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