Whamcloud - gitweb
LU-14661 lnet: Provide kernel API for adding peers
[fs/lustre-release.git] / lnet / lnet / api-ni.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  */
31
32 #define DEBUG_SUBSYSTEM S_LNET
33
34 #include <linux/ctype.h>
35 #include <linux/log2.h>
36 #include <linux/ktime.h>
37 #include <linux/moduleparam.h>
38 #include <linux/uaccess.h>
39 #ifdef HAVE_SCHED_HEADERS
40 #include <linux/sched/signal.h>
41 #endif
42 #include <lnet/udsp.h>
43 #include <lnet/lib-lnet.h>
44
45 #define D_LNI D_CONSOLE
46
47 /*
48  * initialize ln_api_mutex statically, since it needs to be used in
49  * discovery_set callback. That module parameter callback can be called
50  * before module init completes. The mutex needs to be ready for use then.
51  */
52 struct lnet the_lnet = {
53         .ln_api_mutex = __MUTEX_INITIALIZER(the_lnet.ln_api_mutex),
54 };              /* THE state of the network */
55 EXPORT_SYMBOL(the_lnet);
56
57 static char *ip2nets = "";
58 module_param(ip2nets, charp, 0444);
59 MODULE_PARM_DESC(ip2nets, "LNET network <- IP table");
60
61 static char *networks = "";
62 module_param(networks, charp, 0444);
63 MODULE_PARM_DESC(networks, "local networks");
64
65 static char *routes = "";
66 module_param(routes, charp, 0444);
67 MODULE_PARM_DESC(routes, "routes to non-local networks");
68
69 static int rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
70 module_param(rnet_htable_size, int, 0444);
71 MODULE_PARM_DESC(rnet_htable_size, "size of remote network hash table");
72
73 static int use_tcp_bonding;
74 module_param(use_tcp_bonding, int, 0444);
75 MODULE_PARM_DESC(use_tcp_bonding,
76                  "use_tcp_bonding parameter has been removed");
77
78 unsigned int lnet_numa_range = 0;
79 module_param(lnet_numa_range, uint, 0444);
80 MODULE_PARM_DESC(lnet_numa_range,
81                 "NUMA range to consider during Multi-Rail selection");
82
83 /*
84  * lnet_health_sensitivity determines by how much we decrement the health
85  * value on sending error. The value defaults to 100, which means health
86  * interface health is decremented by 100 points every failure.
87  */
88 unsigned int lnet_health_sensitivity = 100;
89 static int sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp);
90 #ifdef HAVE_KERNEL_PARAM_OPS
91 static struct kernel_param_ops param_ops_health_sensitivity = {
92         .set = sensitivity_set,
93         .get = param_get_int,
94 };
95 #define param_check_health_sensitivity(name, p) \
96                 __param_check(name, p, int)
97 module_param(lnet_health_sensitivity, health_sensitivity, S_IRUGO|S_IWUSR);
98 #else
99 module_param_call(lnet_health_sensitivity, sensitivity_set, param_get_int,
100                   &lnet_health_sensitivity, S_IRUGO|S_IWUSR);
101 #endif
102 MODULE_PARM_DESC(lnet_health_sensitivity,
103                 "Value to decrement the health value by on error");
104
105 /*
106  * lnet_recovery_interval determines how often we should perform recovery
107  * on unhealthy interfaces.
108  */
109 unsigned int lnet_recovery_interval = 1;
110 static int recovery_interval_set(const char *val, cfs_kernel_param_arg_t *kp);
111 #ifdef HAVE_KERNEL_PARAM_OPS
112 static struct kernel_param_ops param_ops_recovery_interval = {
113         .set = recovery_interval_set,
114         .get = param_get_int,
115 };
116 #define param_check_recovery_interval(name, p) \
117                 __param_check(name, p, int)
118 module_param(lnet_recovery_interval, recovery_interval, S_IRUGO|S_IWUSR);
119 #else
120 module_param_call(lnet_recovery_interval, recovery_interval_set, param_get_int,
121                   &lnet_recovery_interval, S_IRUGO|S_IWUSR);
122 #endif
123 MODULE_PARM_DESC(lnet_recovery_interval,
124                 "DEPRECATED - Interval to recover unhealthy interfaces in seconds");
125
126 unsigned int lnet_recovery_limit;
127 module_param(lnet_recovery_limit, uint, 0644);
128 MODULE_PARM_DESC(lnet_recovery_limit,
129                  "How long to attempt recovery of unhealthy peer interfaces in seconds. Set to 0 to allow indefinite recovery");
130
131 static int lnet_interfaces_max = LNET_INTERFACES_MAX_DEFAULT;
132 static int intf_max_set(const char *val, cfs_kernel_param_arg_t *kp);
133
134 static struct kernel_param_ops param_ops_interfaces_max = {
135         .set = intf_max_set,
136         .get = param_get_int,
137 };
138
139 #define param_check_interfaces_max(name, p) \
140                 __param_check(name, p, int)
141
142 #ifdef HAVE_KERNEL_PARAM_OPS
143 module_param(lnet_interfaces_max, interfaces_max, 0644);
144 #else
145 module_param_call(lnet_interfaces_max, intf_max_set, param_get_int,
146                   &param_ops_interfaces_max, 0644);
147 #endif
148 MODULE_PARM_DESC(lnet_interfaces_max,
149                 "Maximum number of interfaces in a node.");
150
151 unsigned lnet_peer_discovery_disabled = 0;
152 static int discovery_set(const char *val, cfs_kernel_param_arg_t *kp);
153
154 static struct kernel_param_ops param_ops_discovery_disabled = {
155         .set = discovery_set,
156         .get = param_get_int,
157 };
158
159 #define param_check_discovery_disabled(name, p) \
160                 __param_check(name, p, int)
161 #ifdef HAVE_KERNEL_PARAM_OPS
162 module_param(lnet_peer_discovery_disabled, discovery_disabled, 0644);
163 #else
164 module_param_call(lnet_peer_discovery_disabled, discovery_set, param_get_int,
165                   &param_ops_discovery_disabled, 0644);
166 #endif
167 MODULE_PARM_DESC(lnet_peer_discovery_disabled,
168                 "Set to 1 to disable peer discovery on this node.");
169
170 unsigned int lnet_drop_asym_route;
171 static int drop_asym_route_set(const char *val, cfs_kernel_param_arg_t *kp);
172
173 static struct kernel_param_ops param_ops_drop_asym_route = {
174         .set = drop_asym_route_set,
175         .get = param_get_int,
176 };
177
178 #define param_check_drop_asym_route(name, p)    \
179         __param_check(name, p, int)
180 #ifdef HAVE_KERNEL_PARAM_OPS
181 module_param(lnet_drop_asym_route, drop_asym_route, 0644);
182 #else
183 module_param_call(lnet_drop_asym_route, drop_asym_route_set, param_get_int,
184                   &param_ops_drop_asym_route, 0644);
185 #endif
186 MODULE_PARM_DESC(lnet_drop_asym_route,
187                  "Set to 1 to drop asymmetrical route messages.");
188
189 #define LNET_TRANSACTION_TIMEOUT_DEFAULT 50
190 unsigned int lnet_transaction_timeout = LNET_TRANSACTION_TIMEOUT_DEFAULT;
191 static int transaction_to_set(const char *val, cfs_kernel_param_arg_t *kp);
192 #ifdef HAVE_KERNEL_PARAM_OPS
193 static struct kernel_param_ops param_ops_transaction_timeout = {
194         .set = transaction_to_set,
195         .get = param_get_int,
196 };
197
198 #define param_check_transaction_timeout(name, p) \
199                 __param_check(name, p, int)
200 module_param(lnet_transaction_timeout, transaction_timeout, S_IRUGO|S_IWUSR);
201 #else
202 module_param_call(lnet_transaction_timeout, transaction_to_set, param_get_int,
203                   &lnet_transaction_timeout, S_IRUGO|S_IWUSR);
204 #endif
205 MODULE_PARM_DESC(lnet_transaction_timeout,
206                 "Maximum number of seconds to wait for a peer response.");
207
208 #define LNET_RETRY_COUNT_DEFAULT 2
209 unsigned int lnet_retry_count = LNET_RETRY_COUNT_DEFAULT;
210 static int retry_count_set(const char *val, cfs_kernel_param_arg_t *kp);
211 #ifdef HAVE_KERNEL_PARAM_OPS
212 static struct kernel_param_ops param_ops_retry_count = {
213         .set = retry_count_set,
214         .get = param_get_int,
215 };
216
217 #define param_check_retry_count(name, p) \
218                 __param_check(name, p, int)
219 module_param(lnet_retry_count, retry_count, S_IRUGO|S_IWUSR);
220 #else
221 module_param_call(lnet_retry_count, retry_count_set, param_get_int,
222                   &lnet_retry_count, S_IRUGO|S_IWUSR);
223 #endif
224 MODULE_PARM_DESC(lnet_retry_count,
225                  "Maximum number of times to retry transmitting a message");
226
227 unsigned int lnet_response_tracking = 3;
228 static int response_tracking_set(const char *val, cfs_kernel_param_arg_t *kp);
229
230 #ifdef HAVE_KERNEL_PARAM_OPS
231 static struct kernel_param_ops param_ops_response_tracking = {
232         .set = response_tracking_set,
233         .get = param_get_int,
234 };
235
236 #define param_check_response_tracking(name, p)  \
237         __param_check(name, p, int)
238 module_param(lnet_response_tracking, response_tracking, 0644);
239 #else
240 module_param_call(lnet_response_tracking, response_tracking_set, param_get_int,
241                   &lnet_response_tracking, 0644);
242 #endif
243 MODULE_PARM_DESC(lnet_response_tracking,
244                  "(0|1|2|3) LNet Internal Only|GET Reply only|PUT ACK only|Full Tracking (default)");
245
246 #define LNET_LND_TIMEOUT_DEFAULT ((LNET_TRANSACTION_TIMEOUT_DEFAULT - 1) / \
247                                   (LNET_RETRY_COUNT_DEFAULT + 1))
248 unsigned int lnet_lnd_timeout = LNET_LND_TIMEOUT_DEFAULT;
249 static void lnet_set_lnd_timeout(void)
250 {
251         lnet_lnd_timeout = (lnet_transaction_timeout - 1) /
252                            (lnet_retry_count + 1);
253 }
254
255 /*
256  * This sequence number keeps track of how many times DLC was used to
257  * update the local NIs. It is incremented when a NI is added or
258  * removed and checked when sending a message to determine if there is
259  * a need to re-run the selection algorithm. See lnet_select_pathway()
260  * for more details on its usage.
261  */
262 static atomic_t lnet_dlc_seq_no = ATOMIC_INIT(0);
263
264 static int lnet_ping(struct lnet_process_id id, signed long timeout,
265                      struct lnet_process_id __user *ids, int n_ids);
266
267 static int lnet_discover(struct lnet_process_id id, __u32 force,
268                          struct lnet_process_id __user *ids, int n_ids);
269
270 static int
271 sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp)
272 {
273         int rc;
274         unsigned *sensitivity = (unsigned *)kp->arg;
275         unsigned long value;
276
277         rc = kstrtoul(val, 0, &value);
278         if (rc) {
279                 CERROR("Invalid module parameter value for 'lnet_health_sensitivity'\n");
280                 return rc;
281         }
282
283         /*
284          * The purpose of locking the api_mutex here is to ensure that
285          * the correct value ends up stored properly.
286          */
287         mutex_lock(&the_lnet.ln_api_mutex);
288
289         if (value > LNET_MAX_HEALTH_VALUE) {
290                 mutex_unlock(&the_lnet.ln_api_mutex);
291                 CERROR("Invalid health value. Maximum: %d value = %lu\n",
292                        LNET_MAX_HEALTH_VALUE, value);
293                 return -EINVAL;
294         }
295
296         if (*sensitivity != 0 && value == 0 && lnet_retry_count != 0) {
297                 lnet_retry_count = 0;
298                 lnet_set_lnd_timeout();
299         }
300
301         *sensitivity = value;
302
303         mutex_unlock(&the_lnet.ln_api_mutex);
304
305         return 0;
306 }
307
308 static int
309 recovery_interval_set(const char *val, cfs_kernel_param_arg_t *kp)
310 {
311         CWARN("'lnet_recovery_interval' has been deprecated\n");
312
313         return 0;
314 }
315
316 static int
317 discovery_set(const char *val, cfs_kernel_param_arg_t *kp)
318 {
319         int rc;
320         unsigned *discovery_off = (unsigned *)kp->arg;
321         unsigned long value;
322         struct lnet_ping_buffer *pbuf;
323
324         rc = kstrtoul(val, 0, &value);
325         if (rc) {
326                 CERROR("Invalid module parameter value for 'lnet_peer_discovery_disabled'\n");
327                 return rc;
328         }
329
330         value = (value) ? 1 : 0;
331
332         /*
333          * The purpose of locking the api_mutex here is to ensure that
334          * the correct value ends up stored properly.
335          */
336         mutex_lock(&the_lnet.ln_api_mutex);
337
338         if (value == *discovery_off) {
339                 mutex_unlock(&the_lnet.ln_api_mutex);
340                 return 0;
341         }
342
343         /*
344          * We still want to set the discovery value even when LNet is not
345          * running. This is the case when LNet is being loaded and we want
346          * the module parameters to take effect. Otherwise if we're
347          * changing the value dynamically, we want to set it after
348          * updating the peers
349          */
350         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
351                 *discovery_off = value;
352                 mutex_unlock(&the_lnet.ln_api_mutex);
353                 return 0;
354         }
355
356         /* tell peers that discovery setting has changed */
357         lnet_net_lock(LNET_LOCK_EX);
358         pbuf = the_lnet.ln_ping_target;
359         if (value)
360                 pbuf->pb_info.pi_features &= ~LNET_PING_FEAT_DISCOVERY;
361         else
362                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
363         lnet_net_unlock(LNET_LOCK_EX);
364
365         /* only send a push when we're turning off discovery */
366         if (*discovery_off <= 0 && value > 0)
367                 lnet_push_update_to_peers(1);
368         *discovery_off = value;
369
370         mutex_unlock(&the_lnet.ln_api_mutex);
371
372         return 0;
373 }
374
375 static int
376 drop_asym_route_set(const char *val, cfs_kernel_param_arg_t *kp)
377 {
378         int rc;
379         unsigned int *drop_asym_route = (unsigned int *)kp->arg;
380         unsigned long value;
381
382         rc = kstrtoul(val, 0, &value);
383         if (rc) {
384                 CERROR("Invalid module parameter value for "
385                        "'lnet_drop_asym_route'\n");
386                 return rc;
387         }
388
389         /*
390          * The purpose of locking the api_mutex here is to ensure that
391          * the correct value ends up stored properly.
392          */
393         mutex_lock(&the_lnet.ln_api_mutex);
394
395         if (value == *drop_asym_route) {
396                 mutex_unlock(&the_lnet.ln_api_mutex);
397                 return 0;
398         }
399
400         *drop_asym_route = value;
401
402         mutex_unlock(&the_lnet.ln_api_mutex);
403
404         return 0;
405 }
406
407 static int
408 transaction_to_set(const char *val, cfs_kernel_param_arg_t *kp)
409 {
410         int rc;
411         unsigned *transaction_to = (unsigned *)kp->arg;
412         unsigned long value;
413
414         rc = kstrtoul(val, 0, &value);
415         if (rc) {
416                 CERROR("Invalid module parameter value for 'lnet_transaction_timeout'\n");
417                 return rc;
418         }
419
420         /*
421          * The purpose of locking the api_mutex here is to ensure that
422          * the correct value ends up stored properly.
423          */
424         mutex_lock(&the_lnet.ln_api_mutex);
425
426         if (value <= lnet_retry_count || value == 0) {
427                 mutex_unlock(&the_lnet.ln_api_mutex);
428                 CERROR("Invalid value for lnet_transaction_timeout (%lu). "
429                        "Has to be greater than lnet_retry_count (%u)\n",
430                        value, lnet_retry_count);
431                 return -EINVAL;
432         }
433
434         if (value == *transaction_to) {
435                 mutex_unlock(&the_lnet.ln_api_mutex);
436                 return 0;
437         }
438
439         *transaction_to = value;
440         /* Update the lnet_lnd_timeout now that we've modified the
441          * transaction timeout
442          */
443         lnet_set_lnd_timeout();
444
445         mutex_unlock(&the_lnet.ln_api_mutex);
446
447         return 0;
448 }
449
450 static int
451 retry_count_set(const char *val, cfs_kernel_param_arg_t *kp)
452 {
453         int rc;
454         unsigned *retry_count = (unsigned *)kp->arg;
455         unsigned long value;
456
457         rc = kstrtoul(val, 0, &value);
458         if (rc) {
459                 CERROR("Invalid module parameter value for 'lnet_retry_count'\n");
460                 return rc;
461         }
462
463         /*
464          * The purpose of locking the api_mutex here is to ensure that
465          * the correct value ends up stored properly.
466          */
467         mutex_lock(&the_lnet.ln_api_mutex);
468
469         if (lnet_health_sensitivity == 0 && value > 0) {
470                 mutex_unlock(&the_lnet.ln_api_mutex);
471                 CERROR("Can not set lnet_retry_count when health feature is turned off\n");
472                 return -EINVAL;
473         }
474
475         if (value > lnet_transaction_timeout) {
476                 mutex_unlock(&the_lnet.ln_api_mutex);
477                 CERROR("Invalid value for lnet_retry_count (%lu). "
478                        "Has to be smaller than lnet_transaction_timeout (%u)\n",
479                        value, lnet_transaction_timeout);
480                 return -EINVAL;
481         }
482
483         *retry_count = value;
484
485         /* Update the lnet_lnd_timeout now that we've modified the
486          * retry count
487          */
488         lnet_set_lnd_timeout();
489
490         mutex_unlock(&the_lnet.ln_api_mutex);
491
492         return 0;
493 }
494
495 static int
496 intf_max_set(const char *val, cfs_kernel_param_arg_t *kp)
497 {
498         int value, rc;
499
500         rc = kstrtoint(val, 0, &value);
501         if (rc) {
502                 CERROR("Invalid module parameter value for 'lnet_interfaces_max'\n");
503                 return rc;
504         }
505
506         if (value < LNET_INTERFACES_MIN) {
507                 CWARN("max interfaces provided are too small, setting to %d\n",
508                       LNET_INTERFACES_MAX_DEFAULT);
509                 value = LNET_INTERFACES_MAX_DEFAULT;
510         }
511
512         *(int *)kp->arg = value;
513
514         return 0;
515 }
516
517 static int
518 response_tracking_set(const char *val, cfs_kernel_param_arg_t *kp)
519 {
520         int rc;
521         unsigned long new_value;
522
523         rc = kstrtoul(val, 0, &new_value);
524         if (rc) {
525                 CERROR("Invalid value for 'lnet_response_tracking'\n");
526                 return -EINVAL;
527         }
528
529         if (new_value < 0 || new_value > 3) {
530                 CWARN("Invalid value (%lu) for 'lnet_response_tracking'\n",
531                       new_value);
532                 return -EINVAL;
533         }
534
535         lnet_response_tracking = new_value;
536
537         return 0;
538 }
539
540 static const char *
541 lnet_get_routes(void)
542 {
543         return routes;
544 }
545
546 static const char *
547 lnet_get_networks(void)
548 {
549         const char *nets;
550         int rc;
551
552         if (*networks != 0 && *ip2nets != 0) {
553                 LCONSOLE_ERROR_MSG(0x101, "Please specify EITHER 'networks' or "
554                                    "'ip2nets' but not both at once\n");
555                 return NULL;
556         }
557
558         if (*ip2nets != 0) {
559                 rc = lnet_parse_ip2nets(&nets, ip2nets);
560                 return (rc == 0) ? nets : NULL;
561         }
562
563         if (*networks != 0)
564                 return networks;
565
566         return "tcp";
567 }
568
569 static void
570 lnet_init_locks(void)
571 {
572         spin_lock_init(&the_lnet.ln_eq_wait_lock);
573         spin_lock_init(&the_lnet.ln_msg_resend_lock);
574         init_completion(&the_lnet.ln_mt_wait_complete);
575         mutex_init(&the_lnet.ln_lnd_mutex);
576 }
577
578 struct kmem_cache *lnet_mes_cachep;        /* MEs kmem_cache */
579 struct kmem_cache *lnet_small_mds_cachep;  /* <= LNET_SMALL_MD_SIZE bytes
580                                             *  MDs kmem_cache */
581 struct kmem_cache *lnet_udsp_cachep;       /* udsp cache */
582 struct kmem_cache *lnet_rspt_cachep;       /* response tracker cache */
583 struct kmem_cache *lnet_msg_cachep;
584
585 static int
586 lnet_slab_setup(void)
587 {
588         /* create specific kmem_cache for MEs and small MDs (i.e., originally
589          * allocated in <size-xxx> kmem_cache).
590          */
591         lnet_mes_cachep = kmem_cache_create("lnet_MEs", sizeof(struct lnet_me),
592                                             0, 0, NULL);
593         if (!lnet_mes_cachep)
594                 return -ENOMEM;
595
596         lnet_small_mds_cachep = kmem_cache_create("lnet_small_MDs",
597                                                   LNET_SMALL_MD_SIZE, 0, 0,
598                                                   NULL);
599         if (!lnet_small_mds_cachep)
600                 return -ENOMEM;
601
602         lnet_udsp_cachep = kmem_cache_create("lnet_udsp",
603                                              sizeof(struct lnet_udsp),
604                                              0, 0, NULL);
605         if (!lnet_udsp_cachep)
606                 return -ENOMEM;
607
608         lnet_rspt_cachep = kmem_cache_create("lnet_rspt", sizeof(struct lnet_rsp_tracker),
609                                             0, 0, NULL);
610         if (!lnet_rspt_cachep)
611                 return -ENOMEM;
612
613         lnet_msg_cachep = kmem_cache_create("lnet_msg", sizeof(struct lnet_msg),
614                                             0, 0, NULL);
615         if (!lnet_msg_cachep)
616                 return -ENOMEM;
617
618         return 0;
619 }
620
621 static void
622 lnet_slab_cleanup(void)
623 {
624         if (lnet_msg_cachep) {
625                 kmem_cache_destroy(lnet_msg_cachep);
626                 lnet_msg_cachep = NULL;
627         }
628
629         if (lnet_rspt_cachep) {
630                 kmem_cache_destroy(lnet_rspt_cachep);
631                 lnet_rspt_cachep = NULL;
632         }
633
634         if (lnet_udsp_cachep) {
635                 kmem_cache_destroy(lnet_udsp_cachep);
636                 lnet_udsp_cachep = NULL;
637         }
638
639         if (lnet_small_mds_cachep) {
640                 kmem_cache_destroy(lnet_small_mds_cachep);
641                 lnet_small_mds_cachep = NULL;
642         }
643
644         if (lnet_mes_cachep) {
645                 kmem_cache_destroy(lnet_mes_cachep);
646                 lnet_mes_cachep = NULL;
647         }
648 }
649
650 static int
651 lnet_create_remote_nets_table(void)
652 {
653         int               i;
654         struct list_head *hash;
655
656         LASSERT(the_lnet.ln_remote_nets_hash == NULL);
657         LASSERT(the_lnet.ln_remote_nets_hbits > 0);
658         CFS_ALLOC_PTR_ARRAY(hash, LNET_REMOTE_NETS_HASH_SIZE);
659         if (hash == NULL) {
660                 CERROR("Failed to create remote nets hash table\n");
661                 return -ENOMEM;
662         }
663
664         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
665                 INIT_LIST_HEAD(&hash[i]);
666         the_lnet.ln_remote_nets_hash = hash;
667         return 0;
668 }
669
670 static void
671 lnet_destroy_remote_nets_table(void)
672 {
673         int i;
674
675         if (the_lnet.ln_remote_nets_hash == NULL)
676                 return;
677
678         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
679                 LASSERT(list_empty(&the_lnet.ln_remote_nets_hash[i]));
680
681         CFS_FREE_PTR_ARRAY(the_lnet.ln_remote_nets_hash,
682                            LNET_REMOTE_NETS_HASH_SIZE);
683         the_lnet.ln_remote_nets_hash = NULL;
684 }
685
686 static void
687 lnet_destroy_locks(void)
688 {
689         if (the_lnet.ln_res_lock != NULL) {
690                 cfs_percpt_lock_free(the_lnet.ln_res_lock);
691                 the_lnet.ln_res_lock = NULL;
692         }
693
694         if (the_lnet.ln_net_lock != NULL) {
695                 cfs_percpt_lock_free(the_lnet.ln_net_lock);
696                 the_lnet.ln_net_lock = NULL;
697         }
698 }
699
700 static int
701 lnet_create_locks(void)
702 {
703         lnet_init_locks();
704
705         the_lnet.ln_res_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
706         if (the_lnet.ln_res_lock == NULL)
707                 goto failed;
708
709         the_lnet.ln_net_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
710         if (the_lnet.ln_net_lock == NULL)
711                 goto failed;
712
713         return 0;
714
715  failed:
716         lnet_destroy_locks();
717         return -ENOMEM;
718 }
719
720 static void lnet_assert_wire_constants(void)
721 {
722         /* Wire protocol assertions generated by 'wirecheck'
723          * running on Linux robert.bartonsoftware.com 2.6.8-1.521
724          * #1 Mon Aug 16 09:01:18 EDT 2004 i686 athlon i386 GNU/Linux
725          * with gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7)
726          */
727
728         /* Constants... */
729         BUILD_BUG_ON(LNET_PROTO_TCP_MAGIC != 0xeebc0ded);
730         BUILD_BUG_ON(LNET_PROTO_TCP_VERSION_MAJOR != 1);
731         BUILD_BUG_ON(LNET_PROTO_TCP_VERSION_MINOR != 0);
732         BUILD_BUG_ON(LNET_MSG_ACK != 0);
733         BUILD_BUG_ON(LNET_MSG_PUT != 1);
734         BUILD_BUG_ON(LNET_MSG_GET != 2);
735         BUILD_BUG_ON(LNET_MSG_REPLY != 3);
736         BUILD_BUG_ON(LNET_MSG_HELLO != 4);
737
738         BUILD_BUG_ON((int)sizeof(lnet_nid_t) != 8);
739         BUILD_BUG_ON((int)sizeof(lnet_pid_t) != 4);
740
741         /* Checks for struct lnet_process_id_packed */
742         BUILD_BUG_ON((int)sizeof(struct lnet_process_id_packed) != 12);
743         BUILD_BUG_ON((int)offsetof(struct lnet_process_id_packed, nid) != 0);
744         BUILD_BUG_ON((int)sizeof(((struct lnet_process_id_packed *)0)->nid) != 8);
745         BUILD_BUG_ON((int)offsetof(struct lnet_process_id_packed, pid) != 8);
746         BUILD_BUG_ON((int)sizeof(((struct lnet_process_id_packed *)0)->pid) != 4);
747
748         /* Checks for struct lnet_handle_wire */
749         BUILD_BUG_ON((int)sizeof(struct lnet_handle_wire) != 16);
750         BUILD_BUG_ON((int)offsetof(struct lnet_handle_wire,
751                                    wh_interface_cookie) != 0);
752         BUILD_BUG_ON((int)sizeof(((struct lnet_handle_wire *)0)->wh_interface_cookie) != 8);
753         BUILD_BUG_ON((int)offsetof(struct lnet_handle_wire,
754                                    wh_object_cookie) != 8);
755         BUILD_BUG_ON((int)sizeof(((struct lnet_handle_wire *)0)->wh_object_cookie) != 8);
756
757         /* Checks for struct struct lnet_magicversion */
758         BUILD_BUG_ON((int)sizeof(struct lnet_magicversion) != 8);
759         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion, magic) != 0);
760         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->magic) != 4);
761         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion, version_major) != 4);
762         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->version_major) != 2);
763         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion,
764                                    version_minor) != 6);
765         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->version_minor) != 2);
766
767         /* Checks for struct struct lnet_hdr */
768         BUILD_BUG_ON((int)sizeof(struct lnet_hdr) != 72);
769         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, dest_nid) != 0);
770         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->dest_nid) != 8);
771         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, src_nid) != 8);
772         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->src_nid) != 8);
773         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, dest_pid) != 16);
774         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->dest_pid) != 4);
775         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, src_pid) != 20);
776         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->src_pid) != 4);
777         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, type) != 24);
778         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->type) != 4);
779         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, payload_length) != 28);
780         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->payload_length) != 4);
781         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg) != 32);
782         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg) != 40);
783
784         /* Ack */
785         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.ack.dst_wmd) != 32);
786         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.ack.dst_wmd) != 16);
787         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.ack.match_bits) != 48);
788         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.ack.match_bits) != 8);
789         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.ack.mlength) != 56);
790         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.ack.mlength) != 4);
791
792         /* Put */
793         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.put.ack_wmd) != 32);
794         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.put.ack_wmd) != 16);
795         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.put.match_bits) != 48);
796         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.put.match_bits) != 8);
797         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.put.hdr_data) != 56);
798         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.put.hdr_data) != 8);
799         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.put.ptl_index) != 64);
800         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.put.ptl_index) != 4);
801         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.put.offset) != 68);
802         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.put.offset) != 4);
803
804         /* Get */
805         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.get.return_wmd) != 32);
806         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.get.return_wmd) != 16);
807         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.get.match_bits) != 48);
808         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.get.match_bits) != 8);
809         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.get.ptl_index) != 56);
810         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.get.ptl_index) != 4);
811         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.get.src_offset) != 60);
812         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.get.src_offset) != 4);
813         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.get.sink_length) != 64);
814         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.get.sink_length) != 4);
815
816         /* Reply */
817         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.reply.dst_wmd) != 32);
818         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.reply.dst_wmd) != 16);
819
820         /* Hello */
821         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.hello.incarnation) != 32);
822         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.hello.incarnation) != 8);
823         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.hello.type) != 40);
824         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.hello.type) != 4);
825
826         /* Checks for struct lnet_ni_status and related constants */
827         BUILD_BUG_ON(LNET_NI_STATUS_INVALID != 0x00000000);
828         BUILD_BUG_ON(LNET_NI_STATUS_UP != 0x15aac0de);
829         BUILD_BUG_ON(LNET_NI_STATUS_DOWN != 0xdeadface);
830
831         /* Checks for struct lnet_ni_status */
832         BUILD_BUG_ON((int)sizeof(struct lnet_ni_status) != 16);
833         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_nid) != 0);
834         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_nid) != 8);
835         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_status) != 8);
836         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_status) != 4);
837         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_unused) != 12);
838         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_unused) != 4);
839
840         /* Checks for struct lnet_ping_info and related constants */
841         BUILD_BUG_ON(LNET_PROTO_PING_MAGIC != 0x70696E67);
842         BUILD_BUG_ON(LNET_PING_FEAT_INVAL != 0);
843         BUILD_BUG_ON(LNET_PING_FEAT_BASE != 1);
844         BUILD_BUG_ON(LNET_PING_FEAT_NI_STATUS != 2);
845         BUILD_BUG_ON(LNET_PING_FEAT_RTE_DISABLED != 4);
846         BUILD_BUG_ON(LNET_PING_FEAT_MULTI_RAIL != 8);
847         BUILD_BUG_ON(LNET_PING_FEAT_DISCOVERY != 16);
848         BUILD_BUG_ON(LNET_PING_FEAT_BITS != 31);
849
850         /* Checks for struct lnet_ping_info */
851         BUILD_BUG_ON((int)sizeof(struct lnet_ping_info) != 16);
852         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_magic) != 0);
853         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_magic) != 4);
854         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_features) != 4);
855         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_features) != 4);
856         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_pid) != 8);
857         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_pid) != 4);
858         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_nnis) != 12);
859         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_nnis) != 4);
860         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_ni) != 16);
861         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_ni) != 0);
862
863         /* Acceptor connection request */
864         BUILD_BUG_ON(LNET_PROTO_ACCEPTOR_VERSION != 1);
865
866         /* Checks for struct lnet_acceptor_connreq */
867         BUILD_BUG_ON((int)sizeof(struct lnet_acceptor_connreq) != 16);
868         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq, acr_magic) != 0);
869         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq *)0)->acr_magic) != 4);
870         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq, acr_version) != 4);
871         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq *)0)->acr_version) != 4);
872         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq, acr_nid) != 8);
873         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq *)0)->acr_nid) != 8);
874
875         /* Checks for struct lnet_counters_common */
876         BUILD_BUG_ON((int)sizeof(struct lnet_counters_common) != 60);
877         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_msgs_alloc) != 0);
878         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_msgs_alloc) != 4);
879         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_msgs_max) != 4);
880         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_msgs_max) != 4);
881         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_errors) != 8);
882         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_errors) != 4);
883         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_send_count) != 12);
884         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_send_count) != 4);
885         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_recv_count) != 16);
886         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_recv_count) != 4);
887         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_route_count) != 20);
888         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_route_count) != 4);
889         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_drop_count) != 24);
890         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_drop_count) != 4);
891         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_send_length) != 28);
892         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_send_length) != 8);
893         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_recv_length) != 36);
894         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_recv_length) != 8);
895         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_route_length) != 44);
896         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_route_length) != 8);
897         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_drop_length) != 52);
898         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_drop_length) != 8);
899 }
900
901 static const struct lnet_lnd *lnet_find_lnd_by_type(__u32 type)
902 {
903         const struct lnet_lnd *lnd;
904
905         /* holding lnd mutex */
906         if (type >= NUM_LNDS)
907                 return NULL;
908         lnd = the_lnet.ln_lnds[type];
909         LASSERT(!lnd || lnd->lnd_type == type);
910
911         return lnd;
912 }
913
914 unsigned int
915 lnet_get_lnd_timeout(void)
916 {
917         return lnet_lnd_timeout;
918 }
919 EXPORT_SYMBOL(lnet_get_lnd_timeout);
920
921 void
922 lnet_register_lnd(const struct lnet_lnd *lnd)
923 {
924         mutex_lock(&the_lnet.ln_lnd_mutex);
925
926         LASSERT(libcfs_isknown_lnd(lnd->lnd_type));
927         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == NULL);
928
929         the_lnet.ln_lnds[lnd->lnd_type] = lnd;
930
931         CDEBUG(D_NET, "%s LND registered\n", libcfs_lnd2str(lnd->lnd_type));
932
933         mutex_unlock(&the_lnet.ln_lnd_mutex);
934 }
935 EXPORT_SYMBOL(lnet_register_lnd);
936
937 void
938 lnet_unregister_lnd(const struct lnet_lnd *lnd)
939 {
940         mutex_lock(&the_lnet.ln_lnd_mutex);
941
942         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == lnd);
943
944         the_lnet.ln_lnds[lnd->lnd_type] = NULL;
945         CDEBUG(D_NET, "%s LND unregistered\n", libcfs_lnd2str(lnd->lnd_type));
946
947         mutex_unlock(&the_lnet.ln_lnd_mutex);
948 }
949 EXPORT_SYMBOL(lnet_unregister_lnd);
950
951 static void
952 lnet_counters_get_common_locked(struct lnet_counters_common *common)
953 {
954         struct lnet_counters *ctr;
955         int i;
956
957         /* FIXME !!! Their is no assert_lnet_net_locked() to ensure this
958          * actually called under the protection of the lnet_net_lock.
959          */
960         memset(common, 0, sizeof(*common));
961
962         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
963                 common->lcc_msgs_max     += ctr->lct_common.lcc_msgs_max;
964                 common->lcc_msgs_alloc   += ctr->lct_common.lcc_msgs_alloc;
965                 common->lcc_errors       += ctr->lct_common.lcc_errors;
966                 common->lcc_send_count   += ctr->lct_common.lcc_send_count;
967                 common->lcc_recv_count   += ctr->lct_common.lcc_recv_count;
968                 common->lcc_route_count  += ctr->lct_common.lcc_route_count;
969                 common->lcc_drop_count   += ctr->lct_common.lcc_drop_count;
970                 common->lcc_send_length  += ctr->lct_common.lcc_send_length;
971                 common->lcc_recv_length  += ctr->lct_common.lcc_recv_length;
972                 common->lcc_route_length += ctr->lct_common.lcc_route_length;
973                 common->lcc_drop_length  += ctr->lct_common.lcc_drop_length;
974         }
975 }
976
977 void
978 lnet_counters_get_common(struct lnet_counters_common *common)
979 {
980         lnet_net_lock(LNET_LOCK_EX);
981         lnet_counters_get_common_locked(common);
982         lnet_net_unlock(LNET_LOCK_EX);
983 }
984 EXPORT_SYMBOL(lnet_counters_get_common);
985
986 int
987 lnet_counters_get(struct lnet_counters *counters)
988 {
989         struct lnet_counters *ctr;
990         struct lnet_counters_health *health = &counters->lct_health;
991         int i, rc = 0;
992
993         memset(counters, 0, sizeof(*counters));
994
995         lnet_net_lock(LNET_LOCK_EX);
996
997         if (the_lnet.ln_state != LNET_STATE_RUNNING)
998                 GOTO(out_unlock, rc = -ENODEV);
999
1000         lnet_counters_get_common_locked(&counters->lct_common);
1001
1002         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
1003                 health->lch_rst_alloc    += ctr->lct_health.lch_rst_alloc;
1004                 health->lch_resend_count += ctr->lct_health.lch_resend_count;
1005                 health->lch_response_timeout_count +=
1006                                 ctr->lct_health.lch_response_timeout_count;
1007                 health->lch_local_interrupt_count +=
1008                                 ctr->lct_health.lch_local_interrupt_count;
1009                 health->lch_local_dropped_count +=
1010                                 ctr->lct_health.lch_local_dropped_count;
1011                 health->lch_local_aborted_count +=
1012                                 ctr->lct_health.lch_local_aborted_count;
1013                 health->lch_local_no_route_count +=
1014                                 ctr->lct_health.lch_local_no_route_count;
1015                 health->lch_local_timeout_count +=
1016                                 ctr->lct_health.lch_local_timeout_count;
1017                 health->lch_local_error_count +=
1018                                 ctr->lct_health.lch_local_error_count;
1019                 health->lch_remote_dropped_count +=
1020                                 ctr->lct_health.lch_remote_dropped_count;
1021                 health->lch_remote_error_count +=
1022                                 ctr->lct_health.lch_remote_error_count;
1023                 health->lch_remote_timeout_count +=
1024                                 ctr->lct_health.lch_remote_timeout_count;
1025                 health->lch_network_timeout_count +=
1026                                 ctr->lct_health.lch_network_timeout_count;
1027         }
1028 out_unlock:
1029         lnet_net_unlock(LNET_LOCK_EX);
1030         return rc;
1031 }
1032 EXPORT_SYMBOL(lnet_counters_get);
1033
1034 void
1035 lnet_counters_reset(void)
1036 {
1037         struct lnet_counters *counters;
1038         int             i;
1039
1040         lnet_net_lock(LNET_LOCK_EX);
1041
1042         if (the_lnet.ln_state != LNET_STATE_RUNNING)
1043                 goto avoid_reset;
1044
1045         cfs_percpt_for_each(counters, i, the_lnet.ln_counters)
1046                 memset(counters, 0, sizeof(struct lnet_counters));
1047 avoid_reset:
1048         lnet_net_unlock(LNET_LOCK_EX);
1049 }
1050
1051 static char *
1052 lnet_res_type2str(int type)
1053 {
1054         switch (type) {
1055         default:
1056                 LBUG();
1057         case LNET_COOKIE_TYPE_MD:
1058                 return "MD";
1059         case LNET_COOKIE_TYPE_ME:
1060                 return "ME";
1061         case LNET_COOKIE_TYPE_EQ:
1062                 return "EQ";
1063         }
1064 }
1065
1066 static void
1067 lnet_res_container_cleanup(struct lnet_res_container *rec)
1068 {
1069         int     count = 0;
1070
1071         if (rec->rec_type == 0) /* not set yet, it's uninitialized */
1072                 return;
1073
1074         while (!list_empty(&rec->rec_active)) {
1075                 struct list_head *e = rec->rec_active.next;
1076
1077                 list_del_init(e);
1078                 if (rec->rec_type == LNET_COOKIE_TYPE_MD) {
1079                         lnet_md_free(list_entry(e, struct lnet_libmd, md_list));
1080
1081                 } else { /* NB: Active MEs should be attached on portals */
1082                         LBUG();
1083                 }
1084                 count++;
1085         }
1086
1087         if (count > 0) {
1088                 /* Found alive MD/ME/EQ, user really should unlink/free
1089                  * all of them before finalize LNet, but if someone didn't,
1090                  * we have to recycle garbage for him */
1091                 CERROR("%d active elements on exit of %s container\n",
1092                        count, lnet_res_type2str(rec->rec_type));
1093         }
1094
1095         if (rec->rec_lh_hash != NULL) {
1096                 CFS_FREE_PTR_ARRAY(rec->rec_lh_hash, LNET_LH_HASH_SIZE);
1097                 rec->rec_lh_hash = NULL;
1098         }
1099
1100         rec->rec_type = 0; /* mark it as finalized */
1101 }
1102
1103 static int
1104 lnet_res_container_setup(struct lnet_res_container *rec, int cpt, int type)
1105 {
1106         int     rc = 0;
1107         int     i;
1108
1109         LASSERT(rec->rec_type == 0);
1110
1111         rec->rec_type = type;
1112         INIT_LIST_HEAD(&rec->rec_active);
1113
1114         rec->rec_lh_cookie = (cpt << LNET_COOKIE_TYPE_BITS) | type;
1115
1116         /* Arbitrary choice of hash table size */
1117         LIBCFS_CPT_ALLOC(rec->rec_lh_hash, lnet_cpt_table(), cpt,
1118                          LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
1119         if (rec->rec_lh_hash == NULL) {
1120                 rc = -ENOMEM;
1121                 goto out;
1122         }
1123
1124         for (i = 0; i < LNET_LH_HASH_SIZE; i++)
1125                 INIT_LIST_HEAD(&rec->rec_lh_hash[i]);
1126
1127         return 0;
1128
1129 out:
1130         CERROR("Failed to setup %s resource container\n",
1131                lnet_res_type2str(type));
1132         lnet_res_container_cleanup(rec);
1133         return rc;
1134 }
1135
1136 static void
1137 lnet_res_containers_destroy(struct lnet_res_container **recs)
1138 {
1139         struct lnet_res_container       *rec;
1140         int                             i;
1141
1142         cfs_percpt_for_each(rec, i, recs)
1143                 lnet_res_container_cleanup(rec);
1144
1145         cfs_percpt_free(recs);
1146 }
1147
1148 static struct lnet_res_container **
1149 lnet_res_containers_create(int type)
1150 {
1151         struct lnet_res_container       **recs;
1152         struct lnet_res_container       *rec;
1153         int                             rc;
1154         int                             i;
1155
1156         recs = cfs_percpt_alloc(lnet_cpt_table(), sizeof(*rec));
1157         if (recs == NULL) {
1158                 CERROR("Failed to allocate %s resource containers\n",
1159                        lnet_res_type2str(type));
1160                 return NULL;
1161         }
1162
1163         cfs_percpt_for_each(rec, i, recs) {
1164                 rc = lnet_res_container_setup(rec, i, type);
1165                 if (rc != 0) {
1166                         lnet_res_containers_destroy(recs);
1167                         return NULL;
1168                 }
1169         }
1170
1171         return recs;
1172 }
1173
1174 struct lnet_libhandle *
1175 lnet_res_lh_lookup(struct lnet_res_container *rec, __u64 cookie)
1176 {
1177         /* ALWAYS called with lnet_res_lock held */
1178         struct list_head        *head;
1179         struct lnet_libhandle   *lh;
1180         unsigned int            hash;
1181
1182         if ((cookie & LNET_COOKIE_MASK) != rec->rec_type)
1183                 return NULL;
1184
1185         hash = cookie >> (LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS);
1186         head = &rec->rec_lh_hash[hash & LNET_LH_HASH_MASK];
1187
1188         list_for_each_entry(lh, head, lh_hash_chain) {
1189                 if (lh->lh_cookie == cookie)
1190                         return lh;
1191         }
1192
1193         return NULL;
1194 }
1195
1196 void
1197 lnet_res_lh_initialize(struct lnet_res_container *rec,
1198                        struct lnet_libhandle *lh)
1199 {
1200         /* ALWAYS called with lnet_res_lock held */
1201         unsigned int    ibits = LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS;
1202         unsigned int    hash;
1203
1204         lh->lh_cookie = rec->rec_lh_cookie;
1205         rec->rec_lh_cookie += 1 << ibits;
1206
1207         hash = (lh->lh_cookie >> ibits) & LNET_LH_HASH_MASK;
1208
1209         list_add(&lh->lh_hash_chain, &rec->rec_lh_hash[hash]);
1210 }
1211
1212 struct list_head **
1213 lnet_create_array_of_queues(void)
1214 {
1215         struct list_head **qs;
1216         struct list_head *q;
1217         int i;
1218
1219         qs = cfs_percpt_alloc(lnet_cpt_table(),
1220                               sizeof(struct list_head));
1221         if (!qs) {
1222                 CERROR("Failed to allocate queues\n");
1223                 return NULL;
1224         }
1225
1226         cfs_percpt_for_each(q, i, qs)
1227                 INIT_LIST_HEAD(q);
1228
1229         return qs;
1230 }
1231
1232 static int lnet_unprepare(void);
1233
1234 static int
1235 lnet_prepare(lnet_pid_t requested_pid)
1236 {
1237         /* Prepare to bring up the network */
1238         struct lnet_res_container **recs;
1239         int                       rc = 0;
1240
1241         if (requested_pid == LNET_PID_ANY) {
1242                 /* Don't instantiate LNET just for me */
1243                 return -ENETDOWN;
1244         }
1245
1246         LASSERT(the_lnet.ln_refcount == 0);
1247
1248         the_lnet.ln_routing = 0;
1249
1250         LASSERT((requested_pid & LNET_PID_USERFLAG) == 0);
1251         the_lnet.ln_pid = requested_pid;
1252
1253         INIT_LIST_HEAD(&the_lnet.ln_test_peers);
1254         INIT_LIST_HEAD(&the_lnet.ln_remote_peer_ni_list);
1255         INIT_LIST_HEAD(&the_lnet.ln_nets);
1256         INIT_LIST_HEAD(&the_lnet.ln_routers);
1257         INIT_LIST_HEAD(&the_lnet.ln_drop_rules);
1258         INIT_LIST_HEAD(&the_lnet.ln_delay_rules);
1259         INIT_LIST_HEAD(&the_lnet.ln_dc_request);
1260         INIT_LIST_HEAD(&the_lnet.ln_dc_working);
1261         INIT_LIST_HEAD(&the_lnet.ln_dc_expired);
1262         INIT_LIST_HEAD(&the_lnet.ln_mt_localNIRecovq);
1263         INIT_LIST_HEAD(&the_lnet.ln_mt_peerNIRecovq);
1264         INIT_LIST_HEAD(&the_lnet.ln_udsp_list);
1265         init_waitqueue_head(&the_lnet.ln_dc_waitq);
1266         the_lnet.ln_mt_handler = NULL;
1267         init_completion(&the_lnet.ln_started);
1268
1269         rc = lnet_slab_setup();
1270         if (rc != 0)
1271                 goto failed;
1272
1273         rc = lnet_create_remote_nets_table();
1274         if (rc != 0)
1275                 goto failed;
1276
1277         /*
1278          * NB the interface cookie in wire handles guards against delayed
1279          * replies and ACKs appearing valid after reboot.
1280          */
1281         the_lnet.ln_interface_cookie = ktime_get_real_ns();
1282
1283         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
1284                                                 sizeof(struct lnet_counters));
1285         if (the_lnet.ln_counters == NULL) {
1286                 CERROR("Failed to allocate counters for LNet\n");
1287                 rc = -ENOMEM;
1288                 goto failed;
1289         }
1290
1291         rc = lnet_peer_tables_create();
1292         if (rc != 0)
1293                 goto failed;
1294
1295         rc = lnet_msg_containers_create();
1296         if (rc != 0)
1297                 goto failed;
1298
1299         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
1300                                       LNET_COOKIE_TYPE_EQ);
1301         if (rc != 0)
1302                 goto failed;
1303
1304         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
1305         if (recs == NULL) {
1306                 rc = -ENOMEM;
1307                 goto failed;
1308         }
1309
1310         the_lnet.ln_md_containers = recs;
1311
1312         rc = lnet_portals_create();
1313         if (rc != 0) {
1314                 CERROR("Failed to create portals for LNet: %d\n", rc);
1315                 goto failed;
1316         }
1317
1318         the_lnet.ln_mt_zombie_rstqs = lnet_create_array_of_queues();
1319         if (!the_lnet.ln_mt_zombie_rstqs) {
1320                 rc = -ENOMEM;
1321                 goto failed;
1322         }
1323
1324         return 0;
1325
1326  failed:
1327         lnet_unprepare();
1328         return rc;
1329 }
1330
1331 static int
1332 lnet_unprepare (void)
1333 {
1334         /* NB no LNET_LOCK since this is the last reference.  All LND instances
1335          * have shut down already, so it is safe to unlink and free all
1336          * descriptors, even those that appear committed to a network op (eg MD
1337          * with non-zero pending count) */
1338
1339         lnet_fail_nid(LNET_NID_ANY, 0);
1340
1341         LASSERT(the_lnet.ln_refcount == 0);
1342         LASSERT(list_empty(&the_lnet.ln_test_peers));
1343         LASSERT(list_empty(&the_lnet.ln_nets));
1344
1345         if (the_lnet.ln_mt_zombie_rstqs) {
1346                 lnet_clean_zombie_rstqs();
1347                 the_lnet.ln_mt_zombie_rstqs = NULL;
1348         }
1349
1350         lnet_assert_handler_unused(the_lnet.ln_mt_handler);
1351         the_lnet.ln_mt_handler = NULL;
1352
1353         lnet_portals_destroy();
1354
1355         if (the_lnet.ln_md_containers != NULL) {
1356                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
1357                 the_lnet.ln_md_containers = NULL;
1358         }
1359
1360         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
1361
1362         lnet_msg_containers_destroy();
1363         lnet_peer_uninit();
1364         lnet_rtrpools_free(0);
1365
1366         if (the_lnet.ln_counters != NULL) {
1367                 cfs_percpt_free(the_lnet.ln_counters);
1368                 the_lnet.ln_counters = NULL;
1369         }
1370         lnet_destroy_remote_nets_table();
1371         lnet_udsp_destroy(true);
1372         lnet_slab_cleanup();
1373
1374         return 0;
1375 }
1376
1377 struct lnet_ni  *
1378 lnet_net2ni_locked(__u32 net_id, int cpt)
1379 {
1380         struct lnet_ni   *ni;
1381         struct lnet_net  *net;
1382
1383         LASSERT(cpt != LNET_LOCK_EX);
1384
1385         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1386                 if (net->net_id == net_id) {
1387                         ni = list_entry(net->net_ni_list.next, struct lnet_ni,
1388                                         ni_netlist);
1389                         return ni;
1390                 }
1391         }
1392
1393         return NULL;
1394 }
1395
1396 struct lnet_ni *
1397 lnet_net2ni_addref(__u32 net)
1398 {
1399         struct lnet_ni *ni;
1400
1401         lnet_net_lock(0);
1402         ni = lnet_net2ni_locked(net, 0);
1403         if (ni)
1404                 lnet_ni_addref_locked(ni, 0);
1405         lnet_net_unlock(0);
1406
1407         return ni;
1408 }
1409 EXPORT_SYMBOL(lnet_net2ni_addref);
1410
1411 struct lnet_net *
1412 lnet_get_net_locked(__u32 net_id)
1413 {
1414         struct lnet_net  *net;
1415
1416         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1417                 if (net->net_id == net_id)
1418                         return net;
1419         }
1420
1421         return NULL;
1422 }
1423
1424 void
1425 lnet_net_clr_pref_rtrs(struct lnet_net *net)
1426 {
1427         struct list_head zombies;
1428         struct lnet_nid_list *ne;
1429         struct lnet_nid_list *tmp;
1430
1431         INIT_LIST_HEAD(&zombies);
1432
1433         lnet_net_lock(LNET_LOCK_EX);
1434         list_splice_init(&net->net_rtr_pref_nids, &zombies);
1435         lnet_net_unlock(LNET_LOCK_EX);
1436
1437         list_for_each_entry_safe(ne, tmp, &zombies, nl_list) {
1438                 list_del_init(&ne->nl_list);
1439                 LIBCFS_FREE(ne, sizeof(*ne));
1440         }
1441 }
1442
1443 int
1444 lnet_net_add_pref_rtr(struct lnet_net *net,
1445                       lnet_nid_t gw_nid)
1446 __must_hold(&the_lnet.ln_api_mutex)
1447 {
1448         struct lnet_nid_list *ne;
1449
1450         /* This function is called with api_mutex held. When the api_mutex
1451          * is held the list can not be modified, as it is only modified as
1452          * a result of applying a UDSP and that happens under api_mutex
1453          * lock.
1454          */
1455         list_for_each_entry(ne, &net->net_rtr_pref_nids, nl_list) {
1456                 if (ne->nl_nid == gw_nid)
1457                         return -EEXIST;
1458         }
1459
1460         LIBCFS_ALLOC(ne, sizeof(*ne));
1461         if (!ne)
1462                 return -ENOMEM;
1463
1464         ne->nl_nid = gw_nid;
1465
1466         /* Lock the cpt to protect against addition and checks in the
1467          * selection algorithm
1468          */
1469         lnet_net_lock(LNET_LOCK_EX);
1470         list_add(&ne->nl_list, &net->net_rtr_pref_nids);
1471         lnet_net_unlock(LNET_LOCK_EX);
1472
1473         return 0;
1474 }
1475
1476 bool
1477 lnet_net_is_pref_rtr_locked(struct lnet_net *net, lnet_nid_t rtr_nid)
1478 {
1479         struct lnet_nid_list *ne;
1480
1481         CDEBUG(D_NET, "%s: rtr pref emtpy: %d\n",
1482                libcfs_net2str(net->net_id),
1483                list_empty(&net->net_rtr_pref_nids));
1484
1485         if (list_empty(&net->net_rtr_pref_nids))
1486                 return false;
1487
1488         list_for_each_entry(ne, &net->net_rtr_pref_nids, nl_list) {
1489                 CDEBUG(D_NET, "Comparing pref %s with gw %s\n",
1490                        libcfs_nid2str(ne->nl_nid),
1491                        libcfs_nid2str(rtr_nid));
1492                 if (rtr_nid == ne->nl_nid)
1493                         return true;
1494         }
1495
1496         return false;
1497 }
1498
1499 unsigned int
1500 lnet_nid_cpt_hash(lnet_nid_t nid, unsigned int number)
1501 {
1502         __u64           key = nid;
1503         unsigned int    val;
1504
1505         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
1506
1507         if (number == 1)
1508                 return 0;
1509
1510         val = hash_long(key, LNET_CPT_BITS);
1511         /* NB: LNET_CP_NUMBER doesn't have to be PO2 */
1512         if (val < number)
1513                 return val;
1514
1515         return (unsigned int)(key + val + (val >> 1)) % number;
1516 }
1517
1518 int
1519 lnet_cpt_of_nid_locked(lnet_nid_t nid, struct lnet_ni *ni)
1520 {
1521         struct lnet_net *net;
1522
1523         /* must called with hold of lnet_net_lock */
1524         if (LNET_CPT_NUMBER == 1)
1525                 return 0; /* the only one */
1526
1527         /*
1528          * If NI is provided then use the CPT identified in the NI cpt
1529          * list if one exists. If one doesn't exist, then that NI is
1530          * associated with all CPTs and it follows that the net it belongs
1531          * to is implicitly associated with all CPTs, so just hash the nid
1532          * and return that.
1533          */
1534         if (ni != NULL) {
1535                 if (ni->ni_cpts != NULL)
1536                         return ni->ni_cpts[lnet_nid_cpt_hash(nid,
1537                                                              ni->ni_ncpts)];
1538                 else
1539                         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1540         }
1541
1542         /* no NI provided so look at the net */
1543         net = lnet_get_net_locked(LNET_NIDNET(nid));
1544
1545         if (net != NULL && net->net_cpts != NULL) {
1546                 return net->net_cpts[lnet_nid_cpt_hash(nid, net->net_ncpts)];
1547         }
1548
1549         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1550 }
1551
1552 int
1553 lnet_cpt_of_nid(lnet_nid_t nid, struct lnet_ni *ni)
1554 {
1555         int     cpt;
1556         int     cpt2;
1557
1558         if (LNET_CPT_NUMBER == 1)
1559                 return 0; /* the only one */
1560
1561         cpt = lnet_net_lock_current();
1562
1563         cpt2 = lnet_cpt_of_nid_locked(nid, ni);
1564
1565         lnet_net_unlock(cpt);
1566
1567         return cpt2;
1568 }
1569 EXPORT_SYMBOL(lnet_cpt_of_nid);
1570
1571 int
1572 lnet_islocalnet_locked(__u32 net_id)
1573 {
1574         struct lnet_net *net;
1575         bool local;
1576
1577         net = lnet_get_net_locked(net_id);
1578
1579         local = net != NULL;
1580
1581         return local;
1582 }
1583
1584 int
1585 lnet_islocalnet(__u32 net_id)
1586 {
1587         int cpt;
1588         bool local;
1589
1590         cpt = lnet_net_lock_current();
1591
1592         local = lnet_islocalnet_locked(net_id);
1593
1594         lnet_net_unlock(cpt);
1595
1596         return local;
1597 }
1598
1599 struct lnet_ni  *
1600 lnet_nid2ni_locked(lnet_nid_t nid, int cpt)
1601 {
1602         struct lnet_net  *net;
1603         struct lnet_ni   *ni;
1604
1605         LASSERT(cpt != LNET_LOCK_EX);
1606
1607         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1608                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1609                         if (ni->ni_nid == nid)
1610                                 return ni;
1611                 }
1612         }
1613
1614         return NULL;
1615 }
1616
1617 struct lnet_ni *
1618 lnet_nid2ni_addref(lnet_nid_t nid)
1619 {
1620         struct lnet_ni *ni;
1621
1622         lnet_net_lock(0);
1623         ni = lnet_nid2ni_locked(nid, 0);
1624         if (ni)
1625                 lnet_ni_addref_locked(ni, 0);
1626         lnet_net_unlock(0);
1627
1628         return ni;
1629 }
1630 EXPORT_SYMBOL(lnet_nid2ni_addref);
1631
1632 int
1633 lnet_islocalnid(lnet_nid_t nid)
1634 {
1635         struct lnet_ni  *ni;
1636         int             cpt;
1637
1638         cpt = lnet_net_lock_current();
1639         ni = lnet_nid2ni_locked(nid, cpt);
1640         lnet_net_unlock(cpt);
1641
1642         return ni != NULL;
1643 }
1644
1645 int
1646 lnet_count_acceptor_nets(void)
1647 {
1648         /* Return the # of NIs that need the acceptor. */
1649         int              count = 0;
1650         struct lnet_net  *net;
1651         int              cpt;
1652
1653         cpt = lnet_net_lock_current();
1654         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1655                 /* all socklnd type networks should have the acceptor
1656                  * thread started */
1657                 if (net->net_lnd->lnd_accept != NULL)
1658                         count++;
1659         }
1660
1661         lnet_net_unlock(cpt);
1662
1663         return count;
1664 }
1665
1666 struct lnet_ping_buffer *
1667 lnet_ping_buffer_alloc(int nnis, gfp_t gfp)
1668 {
1669         struct lnet_ping_buffer *pbuf;
1670
1671         LIBCFS_ALLOC_GFP(pbuf, LNET_PING_BUFFER_SIZE(nnis), gfp);
1672         if (pbuf) {
1673                 pbuf->pb_nnis = nnis;
1674                 pbuf->pb_needs_post = false;
1675                 atomic_set(&pbuf->pb_refcnt, 1);
1676         }
1677
1678         return pbuf;
1679 }
1680
1681 void
1682 lnet_ping_buffer_free(struct lnet_ping_buffer *pbuf)
1683 {
1684         LASSERT(atomic_read(&pbuf->pb_refcnt) == 0);
1685         LIBCFS_FREE(pbuf, LNET_PING_BUFFER_SIZE(pbuf->pb_nnis));
1686 }
1687
1688 static struct lnet_ping_buffer *
1689 lnet_ping_target_create(int nnis)
1690 {
1691         struct lnet_ping_buffer *pbuf;
1692
1693         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1694         if (pbuf == NULL) {
1695                 CERROR("Can't allocate ping source [%d]\n", nnis);
1696                 return NULL;
1697         }
1698
1699         pbuf->pb_info.pi_nnis = nnis;
1700         pbuf->pb_info.pi_pid = the_lnet.ln_pid;
1701         pbuf->pb_info.pi_magic = LNET_PROTO_PING_MAGIC;
1702         pbuf->pb_info.pi_features =
1703                 LNET_PING_FEAT_NI_STATUS | LNET_PING_FEAT_MULTI_RAIL;
1704
1705         return pbuf;
1706 }
1707
1708 static inline int
1709 lnet_get_net_ni_count_locked(struct lnet_net *net)
1710 {
1711         struct lnet_ni  *ni;
1712         int             count = 0;
1713
1714         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1715                 count++;
1716
1717         return count;
1718 }
1719
1720 static inline int
1721 lnet_get_net_ni_count_pre(struct lnet_net *net)
1722 {
1723         struct lnet_ni  *ni;
1724         int             count = 0;
1725
1726         list_for_each_entry(ni, &net->net_ni_added, ni_netlist)
1727                 count++;
1728
1729         return count;
1730 }
1731
1732 static inline int
1733 lnet_get_ni_count(void)
1734 {
1735         struct lnet_ni  *ni;
1736         struct lnet_net *net;
1737         int             count = 0;
1738
1739         lnet_net_lock(0);
1740
1741         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1742                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1743                         count++;
1744         }
1745
1746         lnet_net_unlock(0);
1747
1748         return count;
1749 }
1750
1751 void
1752 lnet_swap_pinginfo(struct lnet_ping_buffer *pbuf)
1753 {
1754         struct lnet_ni_status *stat;
1755         int nnis;
1756         int i;
1757
1758         __swab32s(&pbuf->pb_info.pi_magic);
1759         __swab32s(&pbuf->pb_info.pi_features);
1760         __swab32s(&pbuf->pb_info.pi_pid);
1761         __swab32s(&pbuf->pb_info.pi_nnis);
1762         nnis = pbuf->pb_info.pi_nnis;
1763         if (nnis > pbuf->pb_nnis)
1764                 nnis = pbuf->pb_nnis;
1765         for (i = 0; i < nnis; i++) {
1766                 stat = &pbuf->pb_info.pi_ni[i];
1767                 __swab64s(&stat->ns_nid);
1768                 __swab32s(&stat->ns_status);
1769         }
1770 }
1771
1772 int
1773 lnet_ping_info_validate(struct lnet_ping_info *pinfo)
1774 {
1775         if (!pinfo)
1776                 return -EINVAL;
1777         if (pinfo->pi_magic != LNET_PROTO_PING_MAGIC)
1778                 return -EPROTO;
1779         if (!(pinfo->pi_features & LNET_PING_FEAT_NI_STATUS))
1780                 return -EPROTO;
1781         /* Loopback is guaranteed to be present */
1782         if (pinfo->pi_nnis < 1 || pinfo->pi_nnis > lnet_interfaces_max)
1783                 return -ERANGE;
1784         if (LNET_PING_INFO_LONI(pinfo) != LNET_NID_LO_0)
1785                 return -EPROTO;
1786         return 0;
1787 }
1788
1789 static void
1790 lnet_ping_target_destroy(void)
1791 {
1792         struct lnet_net *net;
1793         struct lnet_ni  *ni;
1794
1795         lnet_net_lock(LNET_LOCK_EX);
1796
1797         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1798                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1799                         lnet_ni_lock(ni);
1800                         ni->ni_status = NULL;
1801                         lnet_ni_unlock(ni);
1802                 }
1803         }
1804
1805         lnet_ping_buffer_decref(the_lnet.ln_ping_target);
1806         the_lnet.ln_ping_target = NULL;
1807
1808         lnet_net_unlock(LNET_LOCK_EX);
1809 }
1810
1811 static void
1812 lnet_ping_target_event_handler(struct lnet_event *event)
1813 {
1814         struct lnet_ping_buffer *pbuf = event->md_user_ptr;
1815
1816         if (event->unlinked)
1817                 lnet_ping_buffer_decref(pbuf);
1818 }
1819
1820 static int
1821 lnet_ping_target_setup(struct lnet_ping_buffer **ppbuf,
1822                        struct lnet_handle_md *ping_mdh,
1823                        int ni_count, bool set_eq)
1824 {
1825         struct lnet_process_id id = {
1826                 .nid = LNET_NID_ANY,
1827                 .pid = LNET_PID_ANY
1828         };
1829         struct lnet_me *me;
1830         struct lnet_md md = { NULL };
1831         int rc;
1832
1833         if (set_eq)
1834                 the_lnet.ln_ping_target_handler =
1835                         lnet_ping_target_event_handler;
1836
1837         *ppbuf = lnet_ping_target_create(ni_count);
1838         if (*ppbuf == NULL) {
1839                 rc = -ENOMEM;
1840                 goto fail_free_eq;
1841         }
1842
1843         /* Ping target ME/MD */
1844         me = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1845                           LNET_PROTO_PING_MATCHBITS, 0,
1846                           LNET_UNLINK, LNET_INS_AFTER);
1847         if (IS_ERR(me)) {
1848                 rc = PTR_ERR(me);
1849                 CERROR("Can't create ping target ME: %d\n", rc);
1850                 goto fail_decref_ping_buffer;
1851         }
1852
1853         /* initialize md content */
1854         md.start     = &(*ppbuf)->pb_info;
1855         md.length    = LNET_PING_INFO_SIZE((*ppbuf)->pb_nnis);
1856         md.threshold = LNET_MD_THRESH_INF;
1857         md.max_size  = 0;
1858         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1859                        LNET_MD_MANAGE_REMOTE;
1860         md.handler   = the_lnet.ln_ping_target_handler;
1861         md.user_ptr  = *ppbuf;
1862
1863         rc = LNetMDAttach(me, &md, LNET_RETAIN, ping_mdh);
1864         if (rc != 0) {
1865                 CERROR("Can't attach ping target MD: %d\n", rc);
1866                 goto fail_decref_ping_buffer;
1867         }
1868         lnet_ping_buffer_addref(*ppbuf);
1869
1870         return 0;
1871
1872 fail_decref_ping_buffer:
1873         LASSERT(atomic_read(&(*ppbuf)->pb_refcnt) == 1);
1874         lnet_ping_buffer_decref(*ppbuf);
1875         *ppbuf = NULL;
1876 fail_free_eq:
1877         return rc;
1878 }
1879
1880 static void
1881 lnet_ping_md_unlink(struct lnet_ping_buffer *pbuf,
1882                     struct lnet_handle_md *ping_mdh)
1883 {
1884         LNetMDUnlink(*ping_mdh);
1885         LNetInvalidateMDHandle(ping_mdh);
1886
1887         /* NB the MD could be busy; this just starts the unlink */
1888         wait_var_event_warning(&pbuf->pb_refcnt,
1889                                atomic_read(&pbuf->pb_refcnt) <= 1,
1890                                "Still waiting for ping data MD to unlink\n");
1891 }
1892
1893 static void
1894 lnet_ping_target_install_locked(struct lnet_ping_buffer *pbuf)
1895 {
1896         struct lnet_ni          *ni;
1897         struct lnet_net         *net;
1898         struct lnet_ni_status *ns;
1899         int                     i;
1900         int                     rc;
1901
1902         i = 0;
1903         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1904                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1905                         LASSERT(i < pbuf->pb_nnis);
1906
1907                         ns = &pbuf->pb_info.pi_ni[i];
1908
1909                         ns->ns_nid = ni->ni_nid;
1910
1911                         lnet_ni_lock(ni);
1912                         ns->ns_status = lnet_ni_get_status_locked(ni);
1913                         ni->ni_status = ns;
1914                         lnet_ni_unlock(ni);
1915
1916                         i++;
1917                 }
1918         }
1919         /*
1920          * We (ab)use the ns_status of the loopback interface to
1921          * transmit the sequence number. The first interface listed
1922          * must be the loopback interface.
1923          */
1924         rc = lnet_ping_info_validate(&pbuf->pb_info);
1925         if (rc) {
1926                 LCONSOLE_EMERG("Invalid ping target: %d\n", rc);
1927                 LBUG();
1928         }
1929         LNET_PING_BUFFER_SEQNO(pbuf) =
1930                 atomic_inc_return(&the_lnet.ln_ping_target_seqno);
1931 }
1932
1933 static void
1934 lnet_ping_target_update(struct lnet_ping_buffer *pbuf,
1935                         struct lnet_handle_md ping_mdh)
1936 {
1937         struct lnet_ping_buffer *old_pbuf = NULL;
1938         struct lnet_handle_md old_ping_md;
1939
1940         /* switch the NIs to point to the new ping info created */
1941         lnet_net_lock(LNET_LOCK_EX);
1942
1943         if (!the_lnet.ln_routing)
1944                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_RTE_DISABLED;
1945         if (!lnet_peer_discovery_disabled)
1946                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
1947
1948         /* Ensure only known feature bits have been set. */
1949         LASSERT(pbuf->pb_info.pi_features & LNET_PING_FEAT_BITS);
1950         LASSERT(!(pbuf->pb_info.pi_features & ~LNET_PING_FEAT_BITS));
1951
1952         lnet_ping_target_install_locked(pbuf);
1953
1954         if (the_lnet.ln_ping_target) {
1955                 old_pbuf = the_lnet.ln_ping_target;
1956                 old_ping_md = the_lnet.ln_ping_target_md;
1957         }
1958         the_lnet.ln_ping_target_md = ping_mdh;
1959         the_lnet.ln_ping_target = pbuf;
1960
1961         lnet_net_unlock(LNET_LOCK_EX);
1962
1963         if (old_pbuf) {
1964                 /* unlink and free the old ping info */
1965                 lnet_ping_md_unlink(old_pbuf, &old_ping_md);
1966                 lnet_ping_buffer_decref(old_pbuf);
1967         }
1968
1969         lnet_push_update_to_peers(0);
1970 }
1971
1972 static void
1973 lnet_ping_target_fini(void)
1974 {
1975         lnet_ping_md_unlink(the_lnet.ln_ping_target,
1976                             &the_lnet.ln_ping_target_md);
1977
1978         lnet_assert_handler_unused(the_lnet.ln_ping_target_handler);
1979         lnet_ping_target_destroy();
1980 }
1981
1982 /* Resize the push target. */
1983 int lnet_push_target_resize(void)
1984 {
1985         struct lnet_handle_md mdh;
1986         struct lnet_handle_md old_mdh;
1987         struct lnet_ping_buffer *pbuf;
1988         struct lnet_ping_buffer *old_pbuf;
1989         int nnis;
1990         int rc;
1991
1992 again:
1993         nnis = the_lnet.ln_push_target_nnis;
1994         if (nnis <= 0) {
1995                 CDEBUG(D_NET, "Invalid nnis %d\n", nnis);
1996                 return -EINVAL;
1997         }
1998
1999         /* NB: lnet_ping_buffer_alloc() sets pbuf refcount to 1. That ref is
2000          * dropped when we need to resize again (see "old_pbuf" below) or when
2001          * LNet is shutdown (see lnet_push_target_fini())
2002          */
2003         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
2004         if (!pbuf) {
2005                 CDEBUG(D_NET, "Can't allocate pbuf for nnis %d\n", nnis);
2006                 return -ENOMEM;
2007         }
2008
2009         rc = lnet_push_target_post(pbuf, &mdh);
2010         if (rc) {
2011                 CDEBUG(D_NET, "Failed to post push target: %d\n", rc);
2012                 lnet_ping_buffer_decref(pbuf);
2013                 return rc;
2014         }
2015
2016         lnet_net_lock(LNET_LOCK_EX);
2017         old_pbuf = the_lnet.ln_push_target;
2018         old_mdh = the_lnet.ln_push_target_md;
2019         the_lnet.ln_push_target = pbuf;
2020         the_lnet.ln_push_target_md = mdh;
2021         lnet_net_unlock(LNET_LOCK_EX);
2022
2023         if (old_pbuf) {
2024                 LNetMDUnlink(old_mdh);
2025                 /* Drop ref set by lnet_ping_buffer_alloc() */
2026                 lnet_ping_buffer_decref(old_pbuf);
2027         }
2028
2029         /* Received another push or reply that requires a larger buffer */
2030         if (nnis < the_lnet.ln_push_target_nnis)
2031                 goto again;
2032
2033         CDEBUG(D_NET, "nnis %d success\n", nnis);
2034         return 0;
2035 }
2036
2037 int lnet_push_target_post(struct lnet_ping_buffer *pbuf,
2038                           struct lnet_handle_md *mdhp)
2039 {
2040         struct lnet_process_id id = { LNET_NID_ANY, LNET_PID_ANY };
2041         struct lnet_md md = { NULL };
2042         struct lnet_me *me;
2043         int rc;
2044
2045         me = LNetMEAttach(LNET_RESERVED_PORTAL, id,
2046                           LNET_PROTO_PING_MATCHBITS, 0,
2047                           LNET_UNLINK, LNET_INS_AFTER);
2048         if (IS_ERR(me)) {
2049                 rc = PTR_ERR(me);
2050                 CERROR("Can't create push target ME: %d\n", rc);
2051                 return rc;
2052         }
2053
2054         pbuf->pb_needs_post = false;
2055
2056         /* This reference is dropped by lnet_push_target_event_handler() */
2057         lnet_ping_buffer_addref(pbuf);
2058
2059         /* initialize md content */
2060         md.start     = &pbuf->pb_info;
2061         md.length    = LNET_PING_INFO_SIZE(pbuf->pb_nnis);
2062         md.threshold = 1;
2063         md.max_size  = 0;
2064         md.options   = LNET_MD_OP_PUT | LNET_MD_TRUNCATE;
2065         md.user_ptr  = pbuf;
2066         md.handler   = the_lnet.ln_push_target_handler;
2067
2068         rc = LNetMDAttach(me, &md, LNET_UNLINK, mdhp);
2069         if (rc) {
2070                 CERROR("Can't attach push MD: %d\n", rc);
2071                 lnet_ping_buffer_decref(pbuf);
2072                 pbuf->pb_needs_post = true;
2073                 return rc;
2074         }
2075
2076         CDEBUG(D_NET, "posted push target %p\n", pbuf);
2077
2078         return 0;
2079 }
2080
2081 static void lnet_push_target_event_handler(struct lnet_event *ev)
2082 {
2083         struct lnet_ping_buffer *pbuf = ev->md_user_ptr;
2084
2085         CDEBUG(D_NET, "type %d status %d unlinked %d\n", ev->type, ev->status,
2086                ev->unlinked);
2087
2088         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
2089                 lnet_swap_pinginfo(pbuf);
2090
2091         if (ev->type == LNET_EVENT_UNLINK) {
2092                 /* Drop ref added by lnet_push_target_post() */
2093                 lnet_ping_buffer_decref(pbuf);
2094                 return;
2095         }
2096
2097         lnet_peer_push_event(ev);
2098         if (ev->unlinked)
2099                 /* Drop ref added by lnet_push_target_post */
2100                 lnet_ping_buffer_decref(pbuf);
2101 }
2102
2103 /* Initialize the push target. */
2104 static int lnet_push_target_init(void)
2105 {
2106         int rc;
2107
2108         if (the_lnet.ln_push_target)
2109                 return -EALREADY;
2110
2111         the_lnet.ln_push_target_handler =
2112                 lnet_push_target_event_handler;
2113
2114         rc = LNetSetLazyPortal(LNET_RESERVED_PORTAL);
2115         LASSERT(rc == 0);
2116
2117         /* Start at the required minimum, we'll enlarge if required. */
2118         the_lnet.ln_push_target_nnis = LNET_INTERFACES_MIN;
2119
2120         rc = lnet_push_target_resize();
2121
2122         if (rc) {
2123                 LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2124                 the_lnet.ln_push_target_handler = NULL;
2125         }
2126
2127         return rc;
2128 }
2129
2130 /* Clean up the push target. */
2131 static void lnet_push_target_fini(void)
2132 {
2133         if (!the_lnet.ln_push_target)
2134                 return;
2135
2136         /* Unlink and invalidate to prevent new references. */
2137         LNetMDUnlink(the_lnet.ln_push_target_md);
2138         LNetInvalidateMDHandle(&the_lnet.ln_push_target_md);
2139
2140         /* Wait for the unlink to complete. */
2141         wait_var_event_warning(&the_lnet.ln_push_target->pb_refcnt,
2142                                atomic_read(&the_lnet.ln_push_target->pb_refcnt) <= 1,
2143                                "Still waiting for ping data MD to unlink\n");
2144
2145         /* Drop ref set by lnet_ping_buffer_alloc() */
2146         lnet_ping_buffer_decref(the_lnet.ln_push_target);
2147         the_lnet.ln_push_target = NULL;
2148         the_lnet.ln_push_target_nnis = 0;
2149
2150         LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2151         lnet_assert_handler_unused(the_lnet.ln_push_target_handler);
2152         the_lnet.ln_push_target_handler = NULL;
2153 }
2154
2155 static int
2156 lnet_ni_tq_credits(struct lnet_ni *ni)
2157 {
2158         int     credits;
2159
2160         LASSERT(ni->ni_ncpts >= 1);
2161
2162         if (ni->ni_ncpts == 1)
2163                 return ni->ni_net->net_tunables.lct_max_tx_credits;
2164
2165         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
2166         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
2167         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
2168
2169         return credits;
2170 }
2171
2172 static void
2173 lnet_ni_unlink_locked(struct lnet_ni *ni)
2174 {
2175         /* move it to zombie list and nobody can find it anymore */
2176         LASSERT(!list_empty(&ni->ni_netlist));
2177         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
2178         lnet_ni_decref_locked(ni, 0);
2179 }
2180
2181 static void
2182 lnet_clear_zombies_nis_locked(struct lnet_net *net)
2183 {
2184         int             i;
2185         int             islo;
2186         struct lnet_ni  *ni;
2187         struct list_head *zombie_list = &net->net_ni_zombie;
2188
2189         /*
2190          * Now wait for the NIs I just nuked to show up on the zombie
2191          * list and shut them down in guaranteed thread context
2192          */
2193         i = 2;
2194         while (!list_empty(zombie_list)) {
2195                 int     *ref;
2196                 int     j;
2197
2198                 ni = list_entry(zombie_list->next,
2199                                 struct lnet_ni, ni_netlist);
2200                 list_del_init(&ni->ni_netlist);
2201                 /* the ni should be in deleting state. If it's not it's
2202                  * a bug */
2203                 LASSERT(ni->ni_state == LNET_NI_STATE_DELETING);
2204                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
2205                         if (*ref == 0)
2206                                 continue;
2207                         /* still busy, add it back to zombie list */
2208                         list_add(&ni->ni_netlist, zombie_list);
2209                         break;
2210                 }
2211
2212                 if (!list_empty(&ni->ni_netlist)) {
2213                         /* Unlock mutex while waiting to allow other
2214                          * threads to read the LNet state and fall through
2215                          * to avoid deadlock
2216                          */
2217                         lnet_net_unlock(LNET_LOCK_EX);
2218                         mutex_unlock(&the_lnet.ln_api_mutex);
2219
2220                         ++i;
2221                         if ((i & (-i)) == i) {
2222                                 CDEBUG(D_WARNING,
2223                                        "Waiting for zombie LNI %s\n",
2224                                        libcfs_nid2str(ni->ni_nid));
2225                         }
2226                         schedule_timeout_uninterruptible(cfs_time_seconds(1));
2227
2228                         mutex_lock(&the_lnet.ln_api_mutex);
2229                         lnet_net_lock(LNET_LOCK_EX);
2230                         continue;
2231                 }
2232
2233                 lnet_net_unlock(LNET_LOCK_EX);
2234
2235                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
2236
2237                 LASSERT(!in_interrupt());
2238                 /* Holding the mutex makes it safe for lnd_shutdown
2239                  * to call module_put(). Module unload cannot finish
2240                  * until lnet_unregister_lnd() completes, and that
2241                  * requires the mutex.
2242                  */
2243                 mutex_lock(&the_lnet.ln_lnd_mutex);
2244                 (net->net_lnd->lnd_shutdown)(ni);
2245                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2246
2247                 if (!islo)
2248                         CDEBUG(D_LNI, "Removed LNI %s\n",
2249                               libcfs_nid2str(ni->ni_nid));
2250
2251                 lnet_ni_free(ni);
2252                 i = 2;
2253                 lnet_net_lock(LNET_LOCK_EX);
2254         }
2255 }
2256
2257 /* shutdown down the NI and release refcount */
2258 static void
2259 lnet_shutdown_lndni(struct lnet_ni *ni)
2260 {
2261         int i;
2262         struct lnet_net *net = ni->ni_net;
2263
2264         lnet_net_lock(LNET_LOCK_EX);
2265         lnet_ni_lock(ni);
2266         ni->ni_state = LNET_NI_STATE_DELETING;
2267         lnet_ni_unlock(ni);
2268         lnet_ni_unlink_locked(ni);
2269         lnet_incr_dlc_seq();
2270         lnet_net_unlock(LNET_LOCK_EX);
2271
2272         /* clear messages for this NI on the lazy portal */
2273         for (i = 0; i < the_lnet.ln_nportals; i++)
2274                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
2275
2276         lnet_net_lock(LNET_LOCK_EX);
2277         lnet_clear_zombies_nis_locked(net);
2278         lnet_net_unlock(LNET_LOCK_EX);
2279 }
2280
2281 static void
2282 lnet_shutdown_lndnet(struct lnet_net *net)
2283 {
2284         struct lnet_ni *ni;
2285
2286         lnet_net_lock(LNET_LOCK_EX);
2287
2288         list_del_init(&net->net_list);
2289
2290         while (!list_empty(&net->net_ni_list)) {
2291                 ni = list_entry(net->net_ni_list.next,
2292                                 struct lnet_ni, ni_netlist);
2293                 lnet_net_unlock(LNET_LOCK_EX);
2294                 lnet_shutdown_lndni(ni);
2295                 lnet_net_lock(LNET_LOCK_EX);
2296         }
2297
2298         lnet_net_unlock(LNET_LOCK_EX);
2299
2300         /* Do peer table cleanup for this net */
2301         lnet_peer_tables_cleanup(net);
2302
2303         lnet_net_free(net);
2304 }
2305
2306 static void
2307 lnet_shutdown_lndnets(void)
2308 {
2309         struct lnet_net *net;
2310         LIST_HEAD(resend);
2311         struct lnet_msg *msg, *tmp;
2312
2313         /* NB called holding the global mutex */
2314
2315         /* All quiet on the API front */
2316         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
2317         LASSERT(the_lnet.ln_refcount == 0);
2318
2319         lnet_net_lock(LNET_LOCK_EX);
2320         the_lnet.ln_state = LNET_STATE_STOPPING;
2321
2322         /*
2323          * move the nets to the zombie list to avoid them being
2324          * picked up for new work. LONET is also included in the
2325          * Nets that will be moved to the zombie list
2326          */
2327         list_splice_init(&the_lnet.ln_nets, &the_lnet.ln_net_zombie);
2328
2329         /* Drop the cached loopback Net. */
2330         if (the_lnet.ln_loni != NULL) {
2331                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2332                 the_lnet.ln_loni = NULL;
2333         }
2334         lnet_net_unlock(LNET_LOCK_EX);
2335
2336         /* iterate through the net zombie list and delete each net */
2337         while (!list_empty(&the_lnet.ln_net_zombie)) {
2338                 net = list_entry(the_lnet.ln_net_zombie.next,
2339                                  struct lnet_net, net_list);
2340                 lnet_shutdown_lndnet(net);
2341         }
2342
2343         spin_lock(&the_lnet.ln_msg_resend_lock);
2344         list_splice(&the_lnet.ln_msg_resend, &resend);
2345         spin_unlock(&the_lnet.ln_msg_resend_lock);
2346
2347         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2348                 list_del_init(&msg->msg_list);
2349                 msg->msg_no_resend = true;
2350                 lnet_finalize(msg, -ECANCELED);
2351         }
2352
2353         lnet_net_lock(LNET_LOCK_EX);
2354         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2355         lnet_net_unlock(LNET_LOCK_EX);
2356 }
2357
2358 static int
2359 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2360 {
2361         int                     rc = -EINVAL;
2362         struct lnet_tx_queue    *tq;
2363         int                     i;
2364         struct lnet_net         *net = ni->ni_net;
2365
2366         mutex_lock(&the_lnet.ln_lnd_mutex);
2367
2368         if (tun) {
2369                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2370                 ni->ni_lnd_tunables_set = true;
2371         }
2372
2373         rc = (net->net_lnd->lnd_startup)(ni);
2374
2375         mutex_unlock(&the_lnet.ln_lnd_mutex);
2376
2377         if (rc != 0) {
2378                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2379                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2380                 goto failed0;
2381         }
2382
2383         lnet_ni_lock(ni);
2384         ni->ni_state = LNET_NI_STATE_ACTIVE;
2385         lnet_ni_unlock(ni);
2386
2387         /* We keep a reference on the loopback net through the loopback NI */
2388         if (net->net_lnd->lnd_type == LOLND) {
2389                 lnet_ni_addref(ni);
2390                 LASSERT(the_lnet.ln_loni == NULL);
2391                 the_lnet.ln_loni = ni;
2392                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2393                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2394                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2395                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2396                 return 0;
2397         }
2398
2399         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2400             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2401                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2402                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2403                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2404                                         "" : "per-peer ");
2405                 /* shutdown the NI since if we get here then it must've already
2406                  * been started
2407                  */
2408                 lnet_shutdown_lndni(ni);
2409                 return -EINVAL;
2410         }
2411
2412         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2413                 tq->tq_credits_min =
2414                 tq->tq_credits_max =
2415                 tq->tq_credits = lnet_ni_tq_credits(ni);
2416         }
2417
2418         atomic_set(&ni->ni_tx_credits,
2419                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2420         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2421
2422         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2423                 libcfs_nid2str(ni->ni_nid),
2424                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2425                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2426                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2427                 ni->ni_net->net_tunables.lct_peer_timeout);
2428
2429         return 0;
2430 failed0:
2431         lnet_ni_free(ni);
2432         return rc;
2433 }
2434
2435 static int
2436 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2437 {
2438         struct lnet_ni *ni;
2439         struct lnet_net *net_l = NULL;
2440         LIST_HEAD(local_ni_list);
2441         int rc;
2442         int ni_count = 0;
2443         __u32 lnd_type;
2444         const struct lnet_lnd  *lnd;
2445         int peer_timeout =
2446                 net->net_tunables.lct_peer_timeout;
2447         int maxtxcredits =
2448                 net->net_tunables.lct_max_tx_credits;
2449         int peerrtrcredits =
2450                 net->net_tunables.lct_peer_rtr_credits;
2451
2452         /*
2453          * make sure that this net is unique. If it isn't then
2454          * we are adding interfaces to an already existing network, and
2455          * 'net' is just a convenient way to pass in the list.
2456          * if it is unique we need to find the LND and load it if
2457          * necessary.
2458          */
2459         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2460                 lnd_type = LNET_NETTYP(net->net_id);
2461
2462                 mutex_lock(&the_lnet.ln_lnd_mutex);
2463                 lnd = lnet_find_lnd_by_type(lnd_type);
2464
2465                 if (lnd == NULL) {
2466                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2467                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2468                         mutex_lock(&the_lnet.ln_lnd_mutex);
2469
2470                         lnd = lnet_find_lnd_by_type(lnd_type);
2471                         if (lnd == NULL) {
2472                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2473                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
2474                                 libcfs_lnd2str(lnd_type),
2475                                 libcfs_lnd2modname(lnd_type), rc);
2476 #ifndef HAVE_MODULE_LOADING_SUPPORT
2477                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
2478                                                 "compiled with kernel module "
2479                                                 "loading support.");
2480 #endif
2481                                 rc = -EINVAL;
2482                                 goto failed0;
2483                         }
2484                 }
2485
2486                 net->net_lnd = lnd;
2487
2488                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2489
2490                 net_l = net;
2491         }
2492
2493         /*
2494          * net_l: if the network being added is unique then net_l
2495          *        will point to that network
2496          *        if the network being added is not unique then
2497          *        net_l points to the existing network.
2498          *
2499          * When we enter the loop below, we'll pick NIs off he
2500          * network beign added and start them up, then add them to
2501          * a local ni list. Once we've successfully started all
2502          * the NIs then we join the local NI list (of started up
2503          * networks) with the net_l->net_ni_list, which should
2504          * point to the correct network to add the new ni list to
2505          *
2506          * If any of the new NIs fail to start up, then we want to
2507          * iterate through the local ni list, which should include
2508          * any NIs which were successfully started up, and shut
2509          * them down.
2510          *
2511          * After than we want to delete the network being added,
2512          * to avoid a memory leak.
2513          */
2514         while (!list_empty(&net->net_ni_added)) {
2515                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
2516                                 ni_netlist);
2517                 list_del_init(&ni->ni_netlist);
2518
2519                 /* make sure that the the NI we're about to start
2520                  * up is actually unique. if it's not fail. */
2521                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2522                                         ni->ni_interface)) {
2523                         rc = -EEXIST;
2524                         goto failed1;
2525                 }
2526
2527                 /* adjust the pointer the parent network, just in case it
2528                  * the net is a duplicate */
2529                 ni->ni_net = net_l;
2530
2531                 rc = lnet_startup_lndni(ni, tun);
2532
2533                 if (rc < 0)
2534                         goto failed1;
2535
2536                 lnet_ni_addref(ni);
2537                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2538
2539                 ni_count++;
2540         }
2541
2542         lnet_net_lock(LNET_LOCK_EX);
2543         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2544         lnet_incr_dlc_seq();
2545         lnet_net_unlock(LNET_LOCK_EX);
2546
2547         /* if the network is not unique then we don't want to keep
2548          * it around after we're done. Free it. Otherwise add that
2549          * net to the global the_lnet.ln_nets */
2550         if (net_l != net && net_l != NULL) {
2551                 /*
2552                  * TODO - note. currently the tunables can not be updated
2553                  * once added
2554                  */
2555                 lnet_net_free(net);
2556         } else {
2557                 /*
2558                  * restore tunables after it has been overwitten by the
2559                  * lnd
2560                  */
2561                 if (peer_timeout != -1)
2562                         net->net_tunables.lct_peer_timeout = peer_timeout;
2563                 if (maxtxcredits != -1)
2564                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2565                 if (peerrtrcredits != -1)
2566                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2567
2568                 lnet_net_lock(LNET_LOCK_EX);
2569                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2570                 lnet_net_unlock(LNET_LOCK_EX);
2571         }
2572
2573         return ni_count;
2574
2575 failed1:
2576         /*
2577          * shutdown the new NIs that are being started up
2578          * free the NET being started
2579          */
2580         while (!list_empty(&local_ni_list)) {
2581                 ni = list_entry(local_ni_list.next, struct lnet_ni,
2582                                 ni_netlist);
2583
2584                 lnet_shutdown_lndni(ni);
2585         }
2586
2587 failed0:
2588         lnet_net_free(net);
2589
2590         return rc;
2591 }
2592
2593 static int
2594 lnet_startup_lndnets(struct list_head *netlist)
2595 {
2596         struct lnet_net         *net;
2597         int                     rc;
2598         int                     ni_count = 0;
2599
2600         /*
2601          * Change to running state before bringing up the LNDs. This
2602          * allows lnet_shutdown_lndnets() to assert that we've passed
2603          * through here.
2604          */
2605         lnet_net_lock(LNET_LOCK_EX);
2606         the_lnet.ln_state = LNET_STATE_RUNNING;
2607         lnet_net_unlock(LNET_LOCK_EX);
2608
2609         while (!list_empty(netlist)) {
2610                 net = list_entry(netlist->next, struct lnet_net, net_list);
2611                 list_del_init(&net->net_list);
2612
2613                 rc = lnet_startup_lndnet(net, NULL);
2614
2615                 if (rc < 0)
2616                         goto failed;
2617
2618                 ni_count += rc;
2619         }
2620
2621         return ni_count;
2622 failed:
2623         lnet_shutdown_lndnets();
2624
2625         return rc;
2626 }
2627
2628 static int lnet_genl_parse_list(struct sk_buff *msg,
2629                                 const struct ln_key_list *data[], u16 idx)
2630 {
2631         const struct ln_key_list *list = data[idx];
2632         const struct ln_key_props *props;
2633         struct nlattr *node;
2634         u16 count;
2635
2636         if (!list)
2637                 return 0;
2638
2639         if (!list->lkl_maxattr)
2640                 return -ERANGE;
2641
2642         props = list->lkl_list;
2643         if (!props)
2644                 return -EINVAL;
2645
2646         node = nla_nest_start(msg, LN_SCALAR_ATTR_LIST);
2647         if (!node)
2648                 return -ENOBUFS;
2649
2650         for (count = 1; count <= list->lkl_maxattr; count++) {
2651                 struct nlattr *key = nla_nest_start(msg, count);
2652
2653                 if (count == 1)
2654                         nla_put_u16(msg, LN_SCALAR_ATTR_LIST_SIZE,
2655                                     list->lkl_maxattr);
2656
2657                 nla_put_u16(msg, LN_SCALAR_ATTR_INDEX, count);
2658                 if (props[count].lkp_values)
2659                         nla_put_string(msg, LN_SCALAR_ATTR_VALUE,
2660                                        props[count].lkp_values);
2661                 if (props[count].lkp_key_format)
2662                         nla_put_u16(msg, LN_SCALAR_ATTR_KEY_FORMAT,
2663                                     props[count].lkp_key_format);
2664                 nla_put_u16(msg, LN_SCALAR_ATTR_NLA_TYPE,
2665                             props[count].lkp_data_type);
2666                 if (props[count].lkp_data_type == NLA_NESTED) {
2667                         int rc;
2668
2669                         rc = lnet_genl_parse_list(msg, data, ++idx);
2670                         if (rc < 0)
2671                                 return rc;
2672                 }
2673
2674                 nla_nest_end(msg, key);
2675         }
2676
2677         nla_nest_end(msg, node);
2678         return 0;
2679 }
2680
2681 int lnet_genl_send_scalar_list(struct sk_buff *msg, u32 portid, u32 seq,
2682                                const struct genl_family *family, int flags,
2683                                u8 cmd, const struct ln_key_list *data[])
2684 {
2685         int rc = 0;
2686         void *hdr;
2687
2688         if (!data[0])
2689                 return -EINVAL;
2690
2691         hdr = genlmsg_put(msg, portid, seq, family, flags, cmd);
2692         if (!hdr)
2693                 GOTO(canceled, rc = -EMSGSIZE);
2694
2695         rc = lnet_genl_parse_list(msg, data, 0);
2696         if (rc < 0)
2697                 GOTO(canceled, rc);
2698
2699         genlmsg_end(msg, hdr);
2700 canceled:
2701         if (rc < 0)
2702                 genlmsg_cancel(msg, hdr);
2703         return rc;
2704 }
2705 EXPORT_SYMBOL(lnet_genl_send_scalar_list);
2706
2707 /**
2708  * Initialize LNet library.
2709  *
2710  * Automatically called at module loading time. Caller has to call
2711  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2712  * latter returned 0. It must be called exactly once.
2713  *
2714  * \retval 0 on success
2715  * \retval -ve on failures.
2716  */
2717 int lnet_lib_init(void)
2718 {
2719         int rc;
2720
2721         lnet_assert_wire_constants();
2722
2723         /* refer to global cfs_cpt_table for now */
2724         the_lnet.ln_cpt_table = cfs_cpt_tab;
2725         the_lnet.ln_cpt_number = cfs_cpt_number(cfs_cpt_tab);
2726
2727         LASSERT(the_lnet.ln_cpt_number > 0);
2728         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2729                 /* we are under risk of consuming all lh_cookie */
2730                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2731                        "please change setting of CPT-table and retry\n",
2732                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2733                 return -E2BIG;
2734         }
2735
2736         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2737                 the_lnet.ln_cpt_bits++;
2738
2739         rc = lnet_create_locks();
2740         if (rc != 0) {
2741                 CERROR("Can't create LNet global locks: %d\n", rc);
2742                 return rc;
2743         }
2744
2745         the_lnet.ln_refcount = 0;
2746         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2747         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2748
2749         /* The hash table size is the number of bits it takes to express the set
2750          * ln_num_routes, minus 1 (better to under estimate than over so we
2751          * don't waste memory). */
2752         if (rnet_htable_size <= 0)
2753                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2754         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2755                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2756         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2757                                            order_base_2(rnet_htable_size) - 1);
2758
2759         /* All LNDs apart from the LOLND are in separate modules.  They
2760          * register themselves when their module loads, and unregister
2761          * themselves when their module is unloaded. */
2762         lnet_register_lnd(&the_lolnd);
2763         return 0;
2764 }
2765
2766 /**
2767  * Finalize LNet library.
2768  *
2769  * \pre lnet_lib_init() called with success.
2770  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2771  *
2772  * As this happens at module-unload, all lnds must already be unloaded,
2773  * so they must already be unregistered.
2774  */
2775 void lnet_lib_exit(void)
2776 {
2777         int i;
2778
2779         LASSERT(the_lnet.ln_refcount == 0);
2780         lnet_unregister_lnd(&the_lolnd);
2781         for (i = 0; i < NUM_LNDS; i++)
2782                 LASSERT(!the_lnet.ln_lnds[i]);
2783         lnet_destroy_locks();
2784 }
2785
2786 /**
2787  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2788  *
2789  * Users must call this function at least once before any other functions.
2790  * For each successful call there must be a corresponding call to
2791  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2792  * ignored.
2793  *
2794  * The PID used by LNet may be different from the one requested.
2795  * See LNetGetId().
2796  *
2797  * \param requested_pid PID requested by the caller.
2798  *
2799  * \return >= 0 on success, and < 0 error code on failures.
2800  */
2801 int
2802 LNetNIInit(lnet_pid_t requested_pid)
2803 {
2804         int                     im_a_router = 0;
2805         int                     rc;
2806         int                     ni_count;
2807         struct lnet_ping_buffer *pbuf;
2808         struct lnet_handle_md   ping_mdh;
2809         LIST_HEAD(net_head);
2810         struct lnet_net         *net;
2811
2812         mutex_lock(&the_lnet.ln_api_mutex);
2813
2814         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2815
2816         if (the_lnet.ln_refcount > 0) {
2817                 rc = the_lnet.ln_refcount++;
2818                 mutex_unlock(&the_lnet.ln_api_mutex);
2819                 return rc;
2820         }
2821
2822         rc = lnet_prepare(requested_pid);
2823         if (rc != 0) {
2824                 mutex_unlock(&the_lnet.ln_api_mutex);
2825                 return rc;
2826         }
2827
2828         /* create a network for Loopback network */
2829         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2830         if (net == NULL) {
2831                 rc = -ENOMEM;
2832                 goto err_empty_list;
2833         }
2834
2835         /* Add in the loopback NI */
2836         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2837                 rc = -ENOMEM;
2838                 goto err_empty_list;
2839         }
2840
2841         if (use_tcp_bonding)
2842                 CWARN("use_tcp_bonding has been removed. Use Multi-Rail and Dynamic Discovery instead, see LU-13641\n");
2843
2844         /* If LNet is being initialized via DLC it is possible
2845          * that the user requests not to load module parameters (ones which
2846          * are supported by DLC) on initialization.  Therefore, make sure not
2847          * to load networks, routes and forwarding from module parameters
2848          * in this case.  On cleanup in case of failure only clean up
2849          * routes if it has been loaded */
2850         if (!the_lnet.ln_nis_from_mod_params) {
2851                 rc = lnet_parse_networks(&net_head, lnet_get_networks());
2852                 if (rc < 0)
2853                         goto err_empty_list;
2854         }
2855
2856         ni_count = lnet_startup_lndnets(&net_head);
2857         if (ni_count < 0) {
2858                 rc = ni_count;
2859                 goto err_empty_list;
2860         }
2861
2862         if (!the_lnet.ln_nis_from_mod_params) {
2863                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2864                 if (rc != 0)
2865                         goto err_shutdown_lndnis;
2866
2867                 rc = lnet_rtrpools_alloc(im_a_router);
2868                 if (rc != 0)
2869                         goto err_destroy_routes;
2870         }
2871
2872         rc = lnet_acceptor_start();
2873         if (rc != 0)
2874                 goto err_destroy_routes;
2875
2876         the_lnet.ln_refcount = 1;
2877         /* Now I may use my own API functions... */
2878
2879         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2880         if (rc != 0)
2881                 goto err_acceptor_stop;
2882
2883         lnet_ping_target_update(pbuf, ping_mdh);
2884
2885         the_lnet.ln_mt_handler = lnet_mt_event_handler;
2886
2887         rc = lnet_push_target_init();
2888         if (rc != 0)
2889                 goto err_stop_ping;
2890
2891         rc = lnet_peer_discovery_start();
2892         if (rc != 0)
2893                 goto err_destroy_push_target;
2894
2895         rc = lnet_monitor_thr_start();
2896         if (rc != 0)
2897                 goto err_stop_discovery_thr;
2898
2899         lnet_fault_init();
2900         lnet_router_debugfs_init();
2901
2902         mutex_unlock(&the_lnet.ln_api_mutex);
2903
2904         complete_all(&the_lnet.ln_started);
2905
2906         /* wait for all routers to start */
2907         lnet_wait_router_start();
2908
2909         return 0;
2910
2911 err_stop_discovery_thr:
2912         lnet_peer_discovery_stop();
2913 err_destroy_push_target:
2914         lnet_push_target_fini();
2915 err_stop_ping:
2916         lnet_ping_target_fini();
2917 err_acceptor_stop:
2918         the_lnet.ln_refcount = 0;
2919         lnet_acceptor_stop();
2920 err_destroy_routes:
2921         if (!the_lnet.ln_nis_from_mod_params)
2922                 lnet_destroy_routes();
2923 err_shutdown_lndnis:
2924         lnet_shutdown_lndnets();
2925 err_empty_list:
2926         lnet_unprepare();
2927         LASSERT(rc < 0);
2928         mutex_unlock(&the_lnet.ln_api_mutex);
2929         while (!list_empty(&net_head)) {
2930                 struct lnet_net *net;
2931
2932                 net = list_entry(net_head.next, struct lnet_net, net_list);
2933                 list_del_init(&net->net_list);
2934                 lnet_net_free(net);
2935         }
2936         return rc;
2937 }
2938 EXPORT_SYMBOL(LNetNIInit);
2939
2940 /**
2941  * Stop LNet interfaces, routing, and forwarding.
2942  *
2943  * Users must call this function once for each successful call to LNetNIInit().
2944  * Once the LNetNIFini() operation has been started, the results of pending
2945  * API operations are undefined.
2946  *
2947  * \return always 0 for current implementation.
2948  */
2949 int
2950 LNetNIFini(void)
2951 {
2952         mutex_lock(&the_lnet.ln_api_mutex);
2953
2954         LASSERT(the_lnet.ln_refcount > 0);
2955
2956         if (the_lnet.ln_refcount != 1) {
2957                 the_lnet.ln_refcount--;
2958         } else {
2959                 LASSERT(!the_lnet.ln_niinit_self);
2960
2961                 lnet_fault_fini();
2962
2963                 lnet_router_debugfs_fini();
2964                 lnet_monitor_thr_stop();
2965                 lnet_peer_discovery_stop();
2966                 lnet_push_target_fini();
2967                 lnet_ping_target_fini();
2968
2969                 /* Teardown fns that use my own API functions BEFORE here */
2970                 the_lnet.ln_refcount = 0;
2971
2972                 lnet_acceptor_stop();
2973                 lnet_destroy_routes();
2974                 lnet_shutdown_lndnets();
2975                 lnet_unprepare();
2976         }
2977
2978         mutex_unlock(&the_lnet.ln_api_mutex);
2979         return 0;
2980 }
2981 EXPORT_SYMBOL(LNetNIFini);
2982
2983 /**
2984  * Grabs the ni data from the ni structure and fills the out
2985  * parameters
2986  *
2987  * \param[in] ni network        interface structure
2988  * \param[out] cfg_ni           NI config information
2989  * \param[out] tun              network and LND tunables
2990  */
2991 static void
2992 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
2993                    struct lnet_ioctl_config_lnd_tunables *tun,
2994                    struct lnet_ioctl_element_stats *stats,
2995                    __u32 tun_size)
2996 {
2997         size_t min_size = 0;
2998         int i;
2999
3000         if (!ni || !cfg_ni || !tun)
3001                 return;
3002
3003         if (ni->ni_interface != NULL) {
3004                 strncpy(cfg_ni->lic_ni_intf,
3005                         ni->ni_interface,
3006                         sizeof(cfg_ni->lic_ni_intf));
3007         }
3008
3009         cfg_ni->lic_nid = ni->ni_nid;
3010         cfg_ni->lic_status = lnet_ni_get_status_locked(ni);
3011         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
3012
3013         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
3014
3015         if (stats) {
3016                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
3017                                                        LNET_STATS_TYPE_SEND);
3018                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
3019                                                        LNET_STATS_TYPE_RECV);
3020                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
3021                                                        LNET_STATS_TYPE_DROP);
3022         }
3023
3024         /*
3025          * tun->lt_tun will always be present, but in order to be
3026          * backwards compatible, we need to deal with the cases when
3027          * tun->lt_tun is smaller than what the kernel has, because it
3028          * comes from an older version of a userspace program, then we'll
3029          * need to copy as much information as we have available space.
3030          */
3031         min_size = tun_size - sizeof(tun->lt_cmn);
3032         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
3033
3034         /* copy over the cpts */
3035         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
3036             ni->ni_cpts == NULL)  {
3037                 for (i = 0; i < ni->ni_ncpts; i++)
3038                         cfg_ni->lic_cpts[i] = i;
3039         } else {
3040                 for (i = 0;
3041                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
3042                      i < LNET_MAX_SHOW_NUM_CPT;
3043                      i++)
3044                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
3045         }
3046         cfg_ni->lic_ncpts = ni->ni_ncpts;
3047 }
3048
3049 /**
3050  * NOTE: This is a legacy function left in the code to be backwards
3051  * compatible with older userspace programs. It should eventually be
3052  * removed.
3053  *
3054  * Grabs the ni data from the ni structure and fills the out
3055  * parameters
3056  *
3057  * \param[in] ni network        interface structure
3058  * \param[out] config           config information
3059  */
3060 static void
3061 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
3062                          struct lnet_ioctl_config_data *config)
3063 {
3064         struct lnet_ioctl_net_config *net_config;
3065         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
3066         size_t min_size, tunable_size = 0;
3067         int i;
3068
3069         if (!ni || !config)
3070                 return;
3071
3072         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
3073         if (!net_config)
3074                 return;
3075
3076         if (!ni->ni_interface)
3077                 return;
3078
3079         strncpy(net_config->ni_interface,
3080                 ni->ni_interface,
3081                 sizeof(net_config->ni_interface));
3082
3083         config->cfg_nid = ni->ni_nid;
3084         config->cfg_config_u.cfg_net.net_peer_timeout =
3085                 ni->ni_net->net_tunables.lct_peer_timeout;
3086         config->cfg_config_u.cfg_net.net_max_tx_credits =
3087                 ni->ni_net->net_tunables.lct_max_tx_credits;
3088         config->cfg_config_u.cfg_net.net_peer_tx_credits =
3089                 ni->ni_net->net_tunables.lct_peer_tx_credits;
3090         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
3091                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
3092
3093         net_config->ni_status = lnet_ni_get_status_locked(ni);
3094
3095         if (ni->ni_cpts) {
3096                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
3097
3098                 for (i = 0; i < num_cpts; i++)
3099                         net_config->ni_cpts[i] = ni->ni_cpts[i];
3100
3101                 config->cfg_ncpts = num_cpts;
3102         }
3103
3104         /*
3105          * See if user land tools sent in a newer and larger version
3106          * of struct lnet_tunables than what the kernel uses.
3107          */
3108         min_size = sizeof(*config) + sizeof(*net_config);
3109
3110         if (config->cfg_hdr.ioc_len > min_size)
3111                 tunable_size = config->cfg_hdr.ioc_len - min_size;
3112
3113         /* Don't copy too much data to user space */
3114         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
3115         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
3116
3117         if (lnd_cfg && min_size) {
3118                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
3119                 config->cfg_config_u.cfg_net.net_interface_count = 1;
3120
3121                 /* Tell user land that kernel side has less data */
3122                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
3123                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
3124                         config->cfg_hdr.ioc_len -= min_size;
3125                 }
3126         }
3127 }
3128
3129 struct lnet_ni *
3130 lnet_get_ni_idx_locked(int idx)
3131 {
3132         struct lnet_ni          *ni;
3133         struct lnet_net         *net;
3134
3135         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3136                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3137                         if (idx-- == 0)
3138                                 return ni;
3139                 }
3140         }
3141
3142         return NULL;
3143 }
3144
3145 int lnet_get_net_healthv_locked(struct lnet_net *net)
3146 {
3147         struct lnet_ni *ni;
3148         int best_healthv = 0;
3149         int healthv, ni_fatal;
3150
3151         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3152                 healthv = atomic_read(&ni->ni_healthv);
3153                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
3154                 if (!ni_fatal && healthv > best_healthv)
3155                         best_healthv = healthv;
3156         }
3157
3158         return best_healthv;
3159 }
3160
3161 struct lnet_ni *
3162 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
3163 {
3164         struct lnet_ni          *ni;
3165         struct lnet_net         *net = mynet;
3166
3167         /*
3168          * It is possible that the net has been cleaned out while there is
3169          * a message being sent. This function accessed the net without
3170          * checking if the list is empty
3171          */
3172         if (prev == NULL) {
3173                 if (net == NULL)
3174                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
3175                                         net_list);
3176                 if (list_empty(&net->net_ni_list))
3177                         return NULL;
3178                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3179                                 ni_netlist);
3180
3181                 return ni;
3182         }
3183
3184         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
3185                 /* if you reached the end of the ni list and the net is
3186                  * specified, then there are no more nis in that net */
3187                 if (net != NULL)
3188                         return NULL;
3189
3190                 /* we reached the end of this net ni list. move to the
3191                  * next net */
3192                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
3193                         /* no more nets and no more NIs. */
3194                         return NULL;
3195
3196                 /* get the next net */
3197                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
3198                                  net_list);
3199                 if (list_empty(&net->net_ni_list))
3200                         return NULL;
3201                 /* get the ni on it */
3202                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3203                                 ni_netlist);
3204
3205                 return ni;
3206         }
3207
3208         if (list_empty(&prev->ni_netlist))
3209                 return NULL;
3210
3211         /* there are more nis left */
3212         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
3213
3214         return ni;
3215 }
3216
3217 int
3218 lnet_get_net_config(struct lnet_ioctl_config_data *config)
3219 {
3220         struct lnet_ni *ni;
3221         int cpt;
3222         int rc = -ENOENT;
3223         int idx = config->cfg_count;
3224
3225         cpt = lnet_net_lock_current();
3226
3227         ni = lnet_get_ni_idx_locked(idx);
3228
3229         if (ni != NULL) {
3230                 rc = 0;
3231                 lnet_ni_lock(ni);
3232                 lnet_fill_ni_info_legacy(ni, config);
3233                 lnet_ni_unlock(ni);
3234         }
3235
3236         lnet_net_unlock(cpt);
3237         return rc;
3238 }
3239
3240 int
3241 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
3242                    struct lnet_ioctl_config_lnd_tunables *tun,
3243                    struct lnet_ioctl_element_stats *stats,
3244                    __u32 tun_size)
3245 {
3246         struct lnet_ni          *ni;
3247         int                     cpt;
3248         int                     rc = -ENOENT;
3249
3250         if (!cfg_ni || !tun || !stats)
3251                 return -EINVAL;
3252
3253         cpt = lnet_net_lock_current();
3254
3255         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
3256
3257         if (ni) {
3258                 rc = 0;
3259                 lnet_ni_lock(ni);
3260                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
3261                 lnet_ni_unlock(ni);
3262         }
3263
3264         lnet_net_unlock(cpt);
3265         return rc;
3266 }
3267
3268 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
3269 {
3270         struct lnet_ni *ni;
3271         int cpt;
3272         int rc = -ENOENT;
3273
3274         if (!msg_stats)
3275                 return -EINVAL;
3276
3277         cpt = lnet_net_lock_current();
3278
3279         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
3280
3281         if (ni) {
3282                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
3283                 rc = 0;
3284         }
3285
3286         lnet_net_unlock(cpt);
3287
3288         return rc;
3289 }
3290
3291 static int lnet_add_net_common(struct lnet_net *net,
3292                                struct lnet_ioctl_config_lnd_tunables *tun)
3293 {
3294         struct lnet_handle_md ping_mdh;
3295         struct lnet_ping_buffer *pbuf;
3296         struct lnet_remotenet *rnet;
3297         struct lnet_ni *ni;
3298         int net_ni_count;
3299         __u32 net_id;
3300         int rc;
3301
3302         lnet_net_lock(LNET_LOCK_EX);
3303         rnet = lnet_find_rnet_locked(net->net_id);
3304         lnet_net_unlock(LNET_LOCK_EX);
3305         /*
3306          * make sure that the net added doesn't invalidate the current
3307          * configuration LNet is keeping
3308          */
3309         if (rnet) {
3310                 CERROR("Adding net %s will invalidate routing configuration\n",
3311                        libcfs_net2str(net->net_id));
3312                 lnet_net_free(net);
3313                 return -EUSERS;
3314         }
3315
3316         /*
3317          * make sure you calculate the correct number of slots in the ping
3318          * buffer. Since the ping info is a flattened list of all the NIs,
3319          * we should allocate enough slots to accomodate the number of NIs
3320          * which will be added.
3321          *
3322          * since ni hasn't been configured yet, use
3323          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
3324          */
3325         net_ni_count = lnet_get_net_ni_count_pre(net);
3326
3327         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3328                                     net_ni_count + lnet_get_ni_count(),
3329                                     false);
3330         if (rc < 0) {
3331                 lnet_net_free(net);
3332                 return rc;
3333         }
3334
3335         if (tun)
3336                 memcpy(&net->net_tunables,
3337                        &tun->lt_cmn, sizeof(net->net_tunables));
3338         else
3339                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3340
3341         net_id = net->net_id;
3342
3343         rc = lnet_startup_lndnet(net,
3344                                  (tun) ? &tun->lt_tun : NULL);
3345         if (rc < 0)
3346                 goto failed;
3347
3348         lnet_net_lock(LNET_LOCK_EX);
3349         net = lnet_get_net_locked(net_id);
3350         LASSERT(net);
3351
3352         /* apply the UDSPs */
3353         rc = lnet_udsp_apply_policies_on_net(net);
3354         if (rc)
3355                 CERROR("Failed to apply UDSPs on local net %s\n",
3356                        libcfs_net2str(net->net_id));
3357
3358         /* At this point we lost track of which NI was just added, so we
3359          * just re-apply the policies on all of the NIs on this net
3360          */
3361         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3362                 rc = lnet_udsp_apply_policies_on_ni(ni);
3363                 if (rc)
3364                         CERROR("Failed to apply UDSPs on ni %s\n",
3365                                libcfs_nid2str(ni->ni_nid));
3366         }
3367         lnet_net_unlock(LNET_LOCK_EX);
3368
3369         /*
3370          * Start the acceptor thread if this is the first network
3371          * being added that requires the thread.
3372          */
3373         if (net->net_lnd->lnd_accept) {
3374                 rc = lnet_acceptor_start();
3375                 if (rc < 0) {
3376                         /* shutdown the net that we just started */
3377                         CERROR("Failed to start up acceptor thread\n");
3378                         lnet_shutdown_lndnet(net);
3379                         goto failed;
3380                 }
3381         }
3382
3383         lnet_net_lock(LNET_LOCK_EX);
3384         lnet_peer_net_added(net);
3385         lnet_net_unlock(LNET_LOCK_EX);
3386
3387         lnet_ping_target_update(pbuf, ping_mdh);
3388
3389         return 0;
3390
3391 failed:
3392         lnet_ping_md_unlink(pbuf, &ping_mdh);
3393         lnet_ping_buffer_decref(pbuf);
3394         return rc;
3395 }
3396
3397 static void
3398 lnet_set_tune_defaults(struct lnet_ioctl_config_lnd_tunables *tun)
3399 {
3400         if (tun) {
3401                 if (!tun->lt_cmn.lct_peer_timeout)
3402                         tun->lt_cmn.lct_peer_timeout = DEFAULT_PEER_TIMEOUT;
3403                 if (!tun->lt_cmn.lct_peer_tx_credits)
3404                         tun->lt_cmn.lct_peer_tx_credits = DEFAULT_PEER_CREDITS;
3405                 if (!tun->lt_cmn.lct_max_tx_credits)
3406                         tun->lt_cmn.lct_max_tx_credits = DEFAULT_CREDITS;
3407         }
3408 }
3409
3410 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3411                                       struct lnet_ioctl_config_lnd_tunables *tun)
3412 {
3413         struct lnet_net *net;
3414         const char *nets;
3415         int rc;
3416         LIST_HEAD(net_head);
3417
3418         rc = lnet_parse_ip2nets(&nets, ip2nets);
3419         if (rc < 0)
3420                 return rc;
3421
3422         rc = lnet_parse_networks(&net_head, nets);
3423         if (rc < 0)
3424                 return rc;
3425
3426         lnet_set_tune_defaults(tun);
3427
3428         mutex_lock(&the_lnet.ln_api_mutex);
3429         while (!list_empty(&net_head)) {
3430                 net = list_entry(net_head.next, struct lnet_net, net_list);
3431                 list_del_init(&net->net_list);
3432                 rc = lnet_add_net_common(net, tun);
3433                 if (rc < 0)
3434                         goto out;
3435         }
3436
3437 out:
3438         mutex_unlock(&the_lnet.ln_api_mutex);
3439
3440         while (!list_empty(&net_head)) {
3441                 net = list_entry(net_head.next, struct lnet_net, net_list);
3442                 list_del_init(&net->net_list);
3443                 lnet_net_free(net);
3444         }
3445         return rc;
3446 }
3447
3448 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
3449 {
3450         struct lnet_net *net;
3451         struct lnet_ni *ni;
3452         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3453         int rc, i;
3454         __u32 net_id, lnd_type;
3455
3456         /* get the tunables if they are available */
3457         if (conf->lic_cfg_hdr.ioc_len >=
3458             sizeof(*conf) + sizeof(*tun))
3459                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3460                         conf->lic_bulk;
3461
3462         /* handle legacy ip2nets from DLC */
3463         if (conf->lic_legacy_ip2nets[0] != '\0')
3464                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3465                                                   tun);
3466
3467         net_id = LNET_NIDNET(conf->lic_nid);
3468         lnd_type = LNET_NETTYP(net_id);
3469
3470         if (!libcfs_isknown_lnd(lnd_type)) {
3471                 CERROR("No valid net and lnd information provided\n");
3472                 return -EINVAL;
3473         }
3474
3475         net = lnet_net_alloc(net_id, NULL);
3476         if (!net)
3477                 return -ENOMEM;
3478
3479         for (i = 0; i < conf->lic_ncpts; i++) {
3480                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
3481                         return -EINVAL;
3482         }
3483
3484         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3485                                        conf->lic_ni_intf);
3486         if (!ni)
3487                 return -ENOMEM;
3488
3489         lnet_set_tune_defaults(tun);
3490
3491         mutex_lock(&the_lnet.ln_api_mutex);
3492
3493         rc = lnet_add_net_common(net, tun);
3494
3495         mutex_unlock(&the_lnet.ln_api_mutex);
3496
3497         return rc;
3498 }
3499
3500 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
3501 {
3502         struct lnet_net  *net;
3503         struct lnet_ni *ni;
3504         __u32 net_id = LNET_NIDNET(conf->lic_nid);
3505         struct lnet_ping_buffer *pbuf;
3506         struct lnet_handle_md  ping_mdh;
3507         int               rc;
3508         int               net_count;
3509         __u32             addr;
3510
3511         /* don't allow userspace to shutdown the LOLND */
3512         if (LNET_NETTYP(net_id) == LOLND)
3513                 return -EINVAL;
3514