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