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