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