Whamcloud - gitweb
LU-9019 lnet: move ping and delay injection to time64_t
[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                 LASSERT(libcfs_isknown_lnd(lnd_type));
1850
1851                 mutex_lock(&the_lnet.ln_lnd_mutex);
1852                 lnd = lnet_find_lnd_by_type(lnd_type);
1853
1854                 if (lnd == NULL) {
1855                         mutex_unlock(&the_lnet.ln_lnd_mutex);
1856                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
1857                         mutex_lock(&the_lnet.ln_lnd_mutex);
1858
1859                         lnd = lnet_find_lnd_by_type(lnd_type);
1860                         if (lnd == NULL) {
1861                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
1862                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
1863                                 libcfs_lnd2str(lnd_type),
1864                                 libcfs_lnd2modname(lnd_type), rc);
1865 #ifndef HAVE_MODULE_LOADING_SUPPORT
1866                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
1867                                                 "compiled with kernel module "
1868                                                 "loading support.");
1869 #endif
1870                                 rc = -EINVAL;
1871                                 goto failed0;
1872                         }
1873                 }
1874
1875                 lnet_net_lock(LNET_LOCK_EX);
1876                 lnd->lnd_refcount++;
1877                 lnet_net_unlock(LNET_LOCK_EX);
1878
1879                 net->net_lnd = lnd;
1880
1881                 mutex_unlock(&the_lnet.ln_lnd_mutex);
1882
1883                 net_l = net;
1884         }
1885
1886         /*
1887          * net_l: if the network being added is unique then net_l
1888          *        will point to that network
1889          *        if the network being added is not unique then
1890          *        net_l points to the existing network.
1891          *
1892          * When we enter the loop below, we'll pick NIs off he
1893          * network beign added and start them up, then add them to
1894          * a local ni list. Once we've successfully started all
1895          * the NIs then we join the local NI list (of started up
1896          * networks) with the net_l->net_ni_list, which should
1897          * point to the correct network to add the new ni list to
1898          *
1899          * If any of the new NIs fail to start up, then we want to
1900          * iterate through the local ni list, which should include
1901          * any NIs which were successfully started up, and shut
1902          * them down.
1903          *
1904          * After than we want to delete the network being added,
1905          * to avoid a memory leak.
1906          */
1907
1908         /*
1909          * When a network uses TCP bonding then all its interfaces
1910          * must be specified when the network is first defined: the
1911          * TCP bonding code doesn't allow for interfaces to be added
1912          * or removed.
1913          */
1914         if (net_l != net && net_l != NULL && use_tcp_bonding &&
1915             LNET_NETTYP(net_l->net_id) == SOCKLND) {
1916                 rc = -EINVAL;
1917                 goto failed0;
1918         }
1919
1920         while (!list_empty(&net->net_ni_added)) {
1921                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
1922                                 ni_netlist);
1923                 list_del_init(&ni->ni_netlist);
1924
1925                 /* make sure that the the NI we're about to start
1926                  * up is actually unique. if it's not fail. */
1927                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
1928                                         ni->ni_interfaces[0])) {
1929                         rc = -EINVAL;
1930                         goto failed1;
1931                 }
1932
1933                 /* adjust the pointer the parent network, just in case it
1934                  * the net is a duplicate */
1935                 ni->ni_net = net_l;
1936
1937                 rc = lnet_startup_lndni(ni, tun);
1938
1939                 LASSERT(ni->ni_net->net_tunables.lct_peer_timeout <= 0 ||
1940                         ni->ni_net->net_lnd->lnd_query != NULL);
1941
1942                 if (rc < 0)
1943                         goto failed1;
1944
1945                 lnet_ni_addref(ni);
1946                 list_add_tail(&ni->ni_netlist, &local_ni_list);
1947
1948                 ni_count++;
1949         }
1950
1951         lnet_net_lock(LNET_LOCK_EX);
1952         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
1953         lnet_incr_dlc_seq();
1954         lnet_net_unlock(LNET_LOCK_EX);
1955
1956         /* if the network is not unique then we don't want to keep
1957          * it around after we're done. Free it. Otherwise add that
1958          * net to the global the_lnet.ln_nets */
1959         if (net_l != net && net_l != NULL) {
1960                 /*
1961                  * TODO - note. currently the tunables can not be updated
1962                  * once added
1963                  */
1964                 lnet_net_free(net);
1965         } else {
1966                 net->net_state = LNET_NET_STATE_ACTIVE;
1967                 /*
1968                  * restore tunables after it has been overwitten by the
1969                  * lnd
1970                  */
1971                 if (peer_timeout != -1)
1972                         net->net_tunables.lct_peer_timeout = peer_timeout;
1973                 if (maxtxcredits != -1)
1974                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
1975                 if (peerrtrcredits != -1)
1976                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
1977
1978                 lnet_net_lock(LNET_LOCK_EX);
1979                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
1980                 lnet_net_unlock(LNET_LOCK_EX);
1981         }
1982
1983         return ni_count;
1984
1985 failed1:
1986         /*
1987          * shutdown the new NIs that are being started up
1988          * free the NET being started
1989          */
1990         while (!list_empty(&local_ni_list)) {
1991                 ni = list_entry(local_ni_list.next, struct lnet_ni,
1992                                 ni_netlist);
1993
1994                 lnet_shutdown_lndni(ni);
1995         }
1996
1997 failed0:
1998         lnet_net_free(net);
1999
2000         return rc;
2001 }
2002
2003 static int
2004 lnet_startup_lndnets(struct list_head *netlist)
2005 {
2006         struct lnet_net         *net;
2007         int                     rc;
2008         int                     ni_count = 0;
2009
2010         /*
2011          * Change to running state before bringing up the LNDs. This
2012          * allows lnet_shutdown_lndnets() to assert that we've passed
2013          * through here.
2014          */
2015         lnet_net_lock(LNET_LOCK_EX);
2016         the_lnet.ln_state = LNET_STATE_RUNNING;
2017         lnet_net_unlock(LNET_LOCK_EX);
2018
2019         while (!list_empty(netlist)) {
2020                 net = list_entry(netlist->next, struct lnet_net, net_list);
2021                 list_del_init(&net->net_list);
2022
2023                 rc = lnet_startup_lndnet(net, NULL);
2024
2025                 if (rc < 0)
2026                         goto failed;
2027
2028                 ni_count += rc;
2029         }
2030
2031         return ni_count;
2032 failed:
2033         lnet_shutdown_lndnets();
2034
2035         return rc;
2036 }
2037
2038 /**
2039  * Initialize LNet library.
2040  *
2041  * Automatically called at module loading time. Caller has to call
2042  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2043  * latter returned 0. It must be called exactly once.
2044  *
2045  * \retval 0 on success
2046  * \retval -ve on failures.
2047  */
2048 int lnet_lib_init(void)
2049 {
2050         int rc;
2051
2052         lnet_assert_wire_constants();
2053
2054         /* refer to global cfs_cpt_table for now */
2055         the_lnet.ln_cpt_table   = cfs_cpt_table;
2056         the_lnet.ln_cpt_number  = cfs_cpt_number(cfs_cpt_table);
2057
2058         LASSERT(the_lnet.ln_cpt_number > 0);
2059         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2060                 /* we are under risk of consuming all lh_cookie */
2061                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2062                        "please change setting of CPT-table and retry\n",
2063                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2064                 return -E2BIG;
2065         }
2066
2067         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2068                 the_lnet.ln_cpt_bits++;
2069
2070         rc = lnet_create_locks();
2071         if (rc != 0) {
2072                 CERROR("Can't create LNet global locks: %d\n", rc);
2073                 return rc;
2074         }
2075
2076         the_lnet.ln_refcount = 0;
2077         LNetInvalidateEQHandle(&the_lnet.ln_rc_eqh);
2078         INIT_LIST_HEAD(&the_lnet.ln_lnds);
2079         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2080         INIT_LIST_HEAD(&the_lnet.ln_rcd_zombie);
2081         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2082         INIT_LIST_HEAD(&the_lnet.ln_rcd_deathrow);
2083
2084         /* The hash table size is the number of bits it takes to express the set
2085          * ln_num_routes, minus 1 (better to under estimate than over so we
2086          * don't waste memory). */
2087         if (rnet_htable_size <= 0)
2088                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2089         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2090                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2091         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2092                                            order_base_2(rnet_htable_size) - 1);
2093
2094         /* All LNDs apart from the LOLND are in separate modules.  They
2095          * register themselves when their module loads, and unregister
2096          * themselves when their module is unloaded. */
2097         lnet_register_lnd(&the_lolnd);
2098         return 0;
2099 }
2100
2101 /**
2102  * Finalize LNet library.
2103  *
2104  * \pre lnet_lib_init() called with success.
2105  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2106  */
2107 void lnet_lib_exit(void)
2108 {
2109         LASSERT(the_lnet.ln_refcount == 0);
2110
2111         while (!list_empty(&the_lnet.ln_lnds))
2112                 lnet_unregister_lnd(list_entry(the_lnet.ln_lnds.next,
2113                                                struct lnet_lnd, lnd_list));
2114         lnet_destroy_locks();
2115 }
2116
2117 /**
2118  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2119  *
2120  * Users must call this function at least once before any other functions.
2121  * For each successful call there must be a corresponding call to
2122  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2123  * ignored.
2124  *
2125  * The PID used by LNet may be different from the one requested.
2126  * See LNetGetId().
2127  *
2128  * \param requested_pid PID requested by the caller.
2129  *
2130  * \return >= 0 on success, and < 0 error code on failures.
2131  */
2132 int
2133 LNetNIInit(lnet_pid_t requested_pid)
2134 {
2135         int                     im_a_router = 0;
2136         int                     rc;
2137         int                     ni_count;
2138         struct lnet_ping_buffer *pbuf;
2139         struct lnet_handle_md   ping_mdh;
2140         struct list_head        net_head;
2141         struct lnet_net         *net;
2142
2143         INIT_LIST_HEAD(&net_head);
2144
2145         mutex_lock(&the_lnet.ln_api_mutex);
2146
2147         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2148
2149         if (the_lnet.ln_refcount > 0) {
2150                 rc = the_lnet.ln_refcount++;
2151                 mutex_unlock(&the_lnet.ln_api_mutex);
2152                 return rc;
2153         }
2154
2155         rc = lnet_prepare(requested_pid);
2156         if (rc != 0) {
2157                 mutex_unlock(&the_lnet.ln_api_mutex);
2158                 return rc;
2159         }
2160
2161         /* create a network for Loopback network */
2162         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2163         if (net == NULL) {
2164                 rc = -ENOMEM;
2165                 goto err_empty_list;
2166         }
2167
2168         /* Add in the loopback NI */
2169         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2170                 rc = -ENOMEM;
2171                 goto err_empty_list;
2172         }
2173
2174         /* If LNet is being initialized via DLC it is possible
2175          * that the user requests not to load module parameters (ones which
2176          * are supported by DLC) on initialization.  Therefore, make sure not
2177          * to load networks, routes and forwarding from module parameters
2178          * in this case.  On cleanup in case of failure only clean up
2179          * routes if it has been loaded */
2180         if (!the_lnet.ln_nis_from_mod_params) {
2181                 rc = lnet_parse_networks(&net_head, lnet_get_networks(),
2182                                          use_tcp_bonding);
2183                 if (rc < 0)
2184                         goto err_empty_list;
2185         }
2186
2187         ni_count = lnet_startup_lndnets(&net_head);
2188         if (ni_count < 0) {
2189                 rc = ni_count;
2190                 goto err_empty_list;
2191         }
2192
2193         if (!the_lnet.ln_nis_from_mod_params) {
2194                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2195                 if (rc != 0)
2196                         goto err_shutdown_lndnis;
2197
2198                 rc = lnet_check_routes();
2199                 if (rc != 0)
2200                         goto err_destroy_routes;
2201
2202                 rc = lnet_rtrpools_alloc(im_a_router);
2203                 if (rc != 0)
2204                         goto err_destroy_routes;
2205         }
2206
2207         rc = lnet_acceptor_start();
2208         if (rc != 0)
2209                 goto err_destroy_routes;
2210
2211         the_lnet.ln_refcount = 1;
2212         /* Now I may use my own API functions... */
2213
2214         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2215         if (rc != 0)
2216                 goto err_acceptor_stop;
2217
2218         lnet_ping_target_update(pbuf, ping_mdh);
2219
2220         rc = lnet_router_checker_start();
2221         if (rc != 0)
2222                 goto err_stop_ping;
2223
2224         rc = lnet_push_target_init();
2225         if (rc != 0)
2226                 goto err_stop_router_checker;
2227
2228         rc = lnet_peer_discovery_start();
2229         if (rc != 0)
2230                 goto err_destroy_push_target;
2231
2232         lnet_fault_init();
2233         lnet_router_debugfs_init();
2234
2235         mutex_unlock(&the_lnet.ln_api_mutex);
2236
2237         return 0;
2238
2239 err_destroy_push_target:
2240         lnet_push_target_fini();
2241 err_stop_router_checker:
2242         lnet_router_checker_stop();
2243 err_stop_ping:
2244         lnet_ping_target_fini();
2245 err_acceptor_stop:
2246         the_lnet.ln_refcount = 0;
2247         lnet_acceptor_stop();
2248 err_destroy_routes:
2249         if (!the_lnet.ln_nis_from_mod_params)
2250                 lnet_destroy_routes();
2251 err_shutdown_lndnis:
2252         lnet_shutdown_lndnets();
2253 err_empty_list:
2254         lnet_unprepare();
2255         LASSERT(rc < 0);
2256         mutex_unlock(&the_lnet.ln_api_mutex);
2257         while (!list_empty(&net_head)) {
2258                 struct lnet_net *net;
2259
2260                 net = list_entry(net_head.next, struct lnet_net, net_list);
2261                 list_del_init(&net->net_list);
2262                 lnet_net_free(net);
2263         }
2264         return rc;
2265 }
2266 EXPORT_SYMBOL(LNetNIInit);
2267
2268 /**
2269  * Stop LNet interfaces, routing, and forwarding.
2270  *
2271  * Users must call this function once for each successful call to LNetNIInit().
2272  * Once the LNetNIFini() operation has been started, the results of pending
2273  * API operations are undefined.
2274  *
2275  * \return always 0 for current implementation.
2276  */
2277 int
2278 LNetNIFini()
2279 {
2280         mutex_lock(&the_lnet.ln_api_mutex);
2281
2282         LASSERT(the_lnet.ln_refcount > 0);
2283
2284         if (the_lnet.ln_refcount != 1) {
2285                 the_lnet.ln_refcount--;
2286         } else {
2287                 LASSERT(!the_lnet.ln_niinit_self);
2288
2289                 lnet_fault_fini();
2290
2291                 lnet_router_debugfs_init();
2292                 lnet_peer_discovery_stop();
2293                 lnet_push_target_fini();
2294                 lnet_router_checker_stop();
2295                 lnet_ping_target_fini();
2296
2297                 /* Teardown fns that use my own API functions BEFORE here */
2298                 the_lnet.ln_refcount = 0;
2299
2300                 lnet_acceptor_stop();
2301                 lnet_destroy_routes();
2302                 lnet_shutdown_lndnets();
2303                 lnet_unprepare();
2304         }
2305
2306         mutex_unlock(&the_lnet.ln_api_mutex);
2307         return 0;
2308 }
2309 EXPORT_SYMBOL(LNetNIFini);
2310
2311 /**
2312  * Grabs the ni data from the ni structure and fills the out
2313  * parameters
2314  *
2315  * \param[in] ni network        interface structure
2316  * \param[out] cfg_ni           NI config information
2317  * \param[out] tun              network and LND tunables
2318  */
2319 static void
2320 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
2321                    struct lnet_ioctl_config_lnd_tunables *tun,
2322                    struct lnet_ioctl_element_stats *stats,
2323                    __u32 tun_size)
2324 {
2325         size_t min_size = 0;
2326         int i;
2327
2328         if (!ni || !cfg_ni || !tun)
2329                 return;
2330
2331         if (ni->ni_interfaces[0] != NULL) {
2332                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2333                         if (ni->ni_interfaces[i] != NULL) {
2334                                 strncpy(cfg_ni->lic_ni_intf[i],
2335                                         ni->ni_interfaces[i],
2336                                         sizeof(cfg_ni->lic_ni_intf[i]));
2337                         }
2338                 }
2339         }
2340
2341         cfg_ni->lic_nid = ni->ni_nid;
2342         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2343                 cfg_ni->lic_status = LNET_NI_STATUS_UP;
2344         else
2345                 cfg_ni->lic_status = ni->ni_status->ns_status;
2346         cfg_ni->lic_tcp_bonding = use_tcp_bonding;
2347         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
2348
2349         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
2350
2351         if (stats) {
2352                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
2353                                                        LNET_STATS_TYPE_SEND);
2354                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
2355                                                        LNET_STATS_TYPE_RECV);
2356                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
2357                                                        LNET_STATS_TYPE_DROP);
2358         }
2359
2360         /*
2361          * tun->lt_tun will always be present, but in order to be
2362          * backwards compatible, we need to deal with the cases when
2363          * tun->lt_tun is smaller than what the kernel has, because it
2364          * comes from an older version of a userspace program, then we'll
2365          * need to copy as much information as we have available space.
2366          */
2367         min_size = tun_size - sizeof(tun->lt_cmn);
2368         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
2369
2370         /* copy over the cpts */
2371         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
2372             ni->ni_cpts == NULL)  {
2373                 for (i = 0; i < ni->ni_ncpts; i++)
2374                         cfg_ni->lic_cpts[i] = i;
2375         } else {
2376                 for (i = 0;
2377                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
2378                      i < LNET_MAX_SHOW_NUM_CPT;
2379                      i++)
2380                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
2381         }
2382         cfg_ni->lic_ncpts = ni->ni_ncpts;
2383 }
2384
2385 /**
2386  * NOTE: This is a legacy function left in the code to be backwards
2387  * compatible with older userspace programs. It should eventually be
2388  * removed.
2389  *
2390  * Grabs the ni data from the ni structure and fills the out
2391  * parameters
2392  *
2393  * \param[in] ni network        interface structure
2394  * \param[out] config           config information
2395  */
2396 static void
2397 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
2398                          struct lnet_ioctl_config_data *config)
2399 {
2400         struct lnet_ioctl_net_config *net_config;
2401         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
2402         size_t min_size, tunable_size = 0;
2403         int i;
2404
2405         if (!ni || !config)
2406                 return;
2407
2408         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
2409         if (!net_config)
2410                 return;
2411
2412         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
2413                      ARRAY_SIZE(net_config->ni_interfaces));
2414
2415         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2416                 if (!ni->ni_interfaces[i])
2417                         break;
2418
2419                 strncpy(net_config->ni_interfaces[i],
2420                         ni->ni_interfaces[i],
2421                         sizeof(net_config->ni_interfaces[i]));
2422         }
2423
2424         config->cfg_nid = ni->ni_nid;
2425         config->cfg_config_u.cfg_net.net_peer_timeout =
2426                 ni->ni_net->net_tunables.lct_peer_timeout;
2427         config->cfg_config_u.cfg_net.net_max_tx_credits =
2428                 ni->ni_net->net_tunables.lct_max_tx_credits;
2429         config->cfg_config_u.cfg_net.net_peer_tx_credits =
2430                 ni->ni_net->net_tunables.lct_peer_tx_credits;
2431         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
2432                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
2433
2434         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2435                 net_config->ni_status = LNET_NI_STATUS_UP;
2436         else
2437                 net_config->ni_status = ni->ni_status->ns_status;
2438
2439         if (ni->ni_cpts) {
2440                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
2441
2442                 for (i = 0; i < num_cpts; i++)
2443                         net_config->ni_cpts[i] = ni->ni_cpts[i];
2444
2445                 config->cfg_ncpts = num_cpts;
2446         }
2447
2448         /*
2449          * See if user land tools sent in a newer and larger version
2450          * of struct lnet_tunables than what the kernel uses.
2451          */
2452         min_size = sizeof(*config) + sizeof(*net_config);
2453
2454         if (config->cfg_hdr.ioc_len > min_size)
2455                 tunable_size = config->cfg_hdr.ioc_len - min_size;
2456
2457         /* Don't copy too much data to user space */
2458         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
2459         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
2460
2461         if (lnd_cfg && min_size) {
2462                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
2463                 config->cfg_config_u.cfg_net.net_interface_count = 1;
2464
2465                 /* Tell user land that kernel side has less data */
2466                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
2467                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
2468                         config->cfg_hdr.ioc_len -= min_size;
2469                 }
2470         }
2471 }
2472
2473 struct lnet_ni *
2474 lnet_get_ni_idx_locked(int idx)
2475 {
2476         struct lnet_ni          *ni;
2477         struct lnet_net         *net;
2478
2479         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2480                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2481                         if (idx-- == 0)
2482                                 return ni;
2483                 }
2484         }
2485
2486         return NULL;
2487 }
2488
2489 struct lnet_ni *
2490 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
2491 {
2492         struct lnet_ni          *ni;
2493         struct lnet_net         *net = mynet;
2494
2495         if (prev == NULL) {
2496                 if (net == NULL)
2497                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
2498                                         net_list);
2499                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2500                                 ni_netlist);
2501
2502                 return ni;
2503         }
2504
2505         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
2506                 /* if you reached the end of the ni list and the net is
2507                  * specified, then there are no more nis in that net */
2508                 if (net != NULL)
2509                         return NULL;
2510
2511                 /* we reached the end of this net ni list. move to the
2512                  * next net */
2513                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
2514                         /* no more nets and no more NIs. */
2515                         return NULL;
2516
2517                 /* get the next net */
2518                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
2519                                  net_list);
2520                 /* get the ni on it */
2521                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2522                                 ni_netlist);
2523
2524                 return ni;
2525         }
2526
2527         /* there are more nis left */
2528         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
2529
2530         return ni;
2531 }
2532
2533 int
2534 lnet_get_net_config(struct lnet_ioctl_config_data *config)
2535 {
2536         struct lnet_ni *ni;
2537         int cpt;
2538         int rc = -ENOENT;
2539         int idx = config->cfg_count;
2540
2541         cpt = lnet_net_lock_current();
2542
2543         ni = lnet_get_ni_idx_locked(idx);
2544
2545         if (ni != NULL) {
2546                 rc = 0;
2547                 lnet_ni_lock(ni);
2548                 lnet_fill_ni_info_legacy(ni, config);
2549                 lnet_ni_unlock(ni);
2550         }
2551
2552         lnet_net_unlock(cpt);
2553         return rc;
2554 }
2555
2556 int
2557 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
2558                    struct lnet_ioctl_config_lnd_tunables *tun,
2559                    struct lnet_ioctl_element_stats *stats,
2560                    __u32 tun_size)
2561 {
2562         struct lnet_ni          *ni;
2563         int                     cpt;
2564         int                     rc = -ENOENT;
2565
2566         if (!cfg_ni || !tun || !stats)
2567                 return -EINVAL;
2568
2569         cpt = lnet_net_lock_current();
2570
2571         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
2572
2573         if (ni) {
2574                 rc = 0;
2575                 lnet_ni_lock(ni);
2576                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
2577                 lnet_ni_unlock(ni);
2578         }
2579
2580         lnet_net_unlock(cpt);
2581         return rc;
2582 }
2583
2584 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
2585 {
2586         struct lnet_ni *ni;
2587         int cpt;
2588         int rc = -ENOENT;
2589
2590         if (!msg_stats)
2591                 return -EINVAL;
2592
2593         cpt = lnet_net_lock_current();
2594
2595         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
2596
2597         if (ni) {
2598                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
2599                 rc = 0;
2600         }
2601
2602         lnet_net_unlock(cpt);
2603
2604         return rc;
2605 }
2606
2607 static int lnet_add_net_common(struct lnet_net *net,
2608                                struct lnet_ioctl_config_lnd_tunables *tun)
2609 {
2610         __u32                   net_id;
2611         struct lnet_ping_buffer *pbuf;
2612         struct lnet_handle_md   ping_mdh;
2613         int                     rc;
2614         struct lnet_remotenet *rnet;
2615         int                     net_ni_count;
2616         int                     num_acceptor_nets;
2617
2618         lnet_net_lock(LNET_LOCK_EX);
2619         rnet = lnet_find_rnet_locked(net->net_id);
2620         lnet_net_unlock(LNET_LOCK_EX);
2621         /*
2622          * make sure that the net added doesn't invalidate the current
2623          * configuration LNet is keeping
2624          */
2625         if (rnet) {
2626                 CERROR("Adding net %s will invalidate routing configuration\n",
2627                        libcfs_net2str(net->net_id));
2628                 lnet_net_free(net);
2629                 return -EUSERS;
2630         }
2631
2632         /*
2633          * make sure you calculate the correct number of slots in the ping
2634          * buffer. Since the ping info is a flattened list of all the NIs,
2635          * we should allocate enough slots to accomodate the number of NIs
2636          * which will be added.
2637          *
2638          * since ni hasn't been configured yet, use
2639          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
2640          */
2641         net_ni_count = lnet_get_net_ni_count_pre(net);
2642
2643         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
2644                                     net_ni_count + lnet_get_ni_count(),
2645                                     false);
2646         if (rc < 0) {
2647                 lnet_net_free(net);
2648                 return rc;
2649         }
2650
2651         if (tun)
2652                 memcpy(&net->net_tunables,
2653                        &tun->lt_cmn, sizeof(net->net_tunables));
2654         else
2655                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
2656
2657         /*
2658          * before starting this network get a count of the current TCP
2659          * networks which require the acceptor thread running. If that
2660          * count is == 0 before we start up this network, then we'd want to
2661          * start up the acceptor thread after starting up this network
2662          */
2663         num_acceptor_nets = lnet_count_acceptor_nets();
2664
2665         net_id = net->net_id;
2666
2667         rc = lnet_startup_lndnet(net,
2668                                  (tun) ? &tun->lt_tun : NULL);
2669         if (rc < 0)
2670                 goto failed;
2671
2672         lnet_net_lock(LNET_LOCK_EX);
2673         net = lnet_get_net_locked(net_id);
2674         lnet_net_unlock(LNET_LOCK_EX);
2675
2676         LASSERT(net);
2677
2678         /*
2679          * Start the acceptor thread if this is the first network
2680          * being added that requires the thread.
2681          */
2682         if (net->net_lnd->lnd_accept && num_acceptor_nets == 0) {
2683                 rc = lnet_acceptor_start();
2684                 if (rc < 0) {
2685                         /* shutdown the net that we just started */
2686                         CERROR("Failed to start up acceptor thread\n");
2687                         lnet_shutdown_lndnet(net);
2688                         goto failed;
2689                 }
2690         }
2691
2692         lnet_net_lock(LNET_LOCK_EX);
2693         lnet_peer_net_added(net);
2694         lnet_net_unlock(LNET_LOCK_EX);
2695
2696         lnet_ping_target_update(pbuf, ping_mdh);
2697
2698         return 0;
2699
2700 failed:
2701         lnet_ping_md_unlink(pbuf, &ping_mdh);
2702         lnet_ping_buffer_decref(pbuf);
2703         return rc;
2704 }
2705
2706 static int lnet_handle_legacy_ip2nets(char *ip2nets,
2707                                       struct lnet_ioctl_config_lnd_tunables *tun)
2708 {
2709         struct lnet_net *net;
2710         char *nets;
2711         int rc;
2712         struct list_head net_head;
2713
2714         INIT_LIST_HEAD(&net_head);
2715
2716         rc = lnet_parse_ip2nets(&nets, ip2nets);
2717         if (rc < 0)
2718                 return rc;
2719
2720         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
2721         if (rc < 0)
2722                 return rc;
2723
2724         mutex_lock(&the_lnet.ln_api_mutex);
2725         while (!list_empty(&net_head)) {
2726                 net = list_entry(net_head.next, struct lnet_net, net_list);
2727                 list_del_init(&net->net_list);
2728                 rc = lnet_add_net_common(net, tun);
2729                 if (rc < 0)
2730                         goto out;
2731         }
2732
2733 out:
2734         mutex_unlock(&the_lnet.ln_api_mutex);
2735
2736         while (!list_empty(&net_head)) {
2737                 net = list_entry(net_head.next, struct lnet_net, net_list);
2738                 list_del_init(&net->net_list);
2739                 lnet_net_free(net);
2740         }
2741         return rc;
2742 }
2743
2744 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
2745 {
2746         struct lnet_net *net;
2747         struct lnet_ni *ni;
2748         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
2749         int rc, i;
2750         __u32 net_id;
2751
2752         /* get the tunables if they are available */
2753         if (conf->lic_cfg_hdr.ioc_len >=
2754             sizeof(*conf) + sizeof(*tun))
2755                 tun = (struct lnet_ioctl_config_lnd_tunables *)
2756                         conf->lic_bulk;
2757
2758         /* handle legacy ip2nets from DLC */
2759         if (conf->lic_legacy_ip2nets[0] != '\0')
2760                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
2761                                                   tun);
2762
2763         net_id = LNET_NIDNET(conf->lic_nid);
2764
2765         net = lnet_net_alloc(net_id, NULL);
2766         if (!net)
2767                 return -ENOMEM;
2768
2769         for (i = 0; i < conf->lic_ncpts; i++) {
2770                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
2771                         return -EINVAL;
2772         }
2773
2774         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
2775                                        conf->lic_ni_intf[0]);
2776         if (!ni)
2777                 return -ENOMEM;
2778
2779         mutex_lock(&the_lnet.ln_api_mutex);
2780
2781         rc = lnet_add_net_common(net, tun);
2782
2783         mutex_unlock(&the_lnet.ln_api_mutex);
2784
2785         return rc;
2786 }
2787
2788 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
2789 {
2790         struct lnet_net  *net;
2791         struct lnet_ni *ni;
2792         __u32 net_id = LNET_NIDNET(conf->lic_nid);
2793         struct lnet_ping_buffer *pbuf;
2794         struct lnet_handle_md  ping_mdh;
2795         int               rc;
2796         int               net_count;
2797         __u32             addr;
2798
2799         /* don't allow userspace to shutdown the LOLND */
2800         if (LNET_NETTYP(net_id) == LOLND)
2801                 return -EINVAL;
2802
2803         mutex_lock(&the_lnet.ln_api_mutex);
2804
2805         lnet_net_lock(0);
2806
2807         net = lnet_get_net_locked(net_id);
2808         if (!net) {
2809                 CERROR("net %s not found\n",
2810                        libcfs_net2str(net_id));
2811                 rc = -ENOENT;
2812                 goto unlock_net;
2813         }
2814
2815         addr = LNET_NIDADDR(conf->lic_nid);
2816         if (addr == 0) {
2817                 /* remove the entire net */
2818                 net_count = lnet_get_net_ni_count_locked(net);
2819
2820                 lnet_net_unlock(0);
2821
2822                 /* create and link a new ping info, before removing the old one */
2823                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
2824                                         lnet_get_ni_count() - net_count,
2825                                         false);
2826                 if (rc != 0)
2827                         goto unlock_api_mutex;
2828
2829                 lnet_shutdown_lndnet(net);
2830
2831                 if (lnet_count_acceptor_nets() == 0)
2832                         lnet_acceptor_stop();
2833
2834                 lnet_ping_target_update(pbuf, ping_mdh);
2835
2836                 goto unlock_api_mutex;
2837         }
2838
2839         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
2840         if (!ni) {
2841                 CERROR("nid %s not found\n",
2842                        libcfs_nid2str(conf->lic_nid));
2843                 rc = -ENOENT;
2844                 goto unlock_net;
2845         }
2846
2847         net_count = lnet_get_net_ni_count_locked(net);
2848
2849         lnet_net_unlock(0);
2850
2851         /* create and link a new ping info, before removing the old one */
2852         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
2853                                   lnet_get_ni_count() - 1, false);
2854         if (rc != 0)
2855                 goto unlock_api_mutex;
2856
2857         lnet_shutdown_lndni(ni);
2858
2859         if (lnet_count_acceptor_nets() == 0)
2860                 lnet_acceptor_stop();
2861
2862         lnet_ping_target_update(pbuf, ping_mdh);
2863
2864         /* check if the net is empty and remove it if it is */
2865         if (net_count == 1)
2866                 lnet_shutdown_lndnet(net);
2867
2868         goto unlock_api_mutex;
2869
2870 unlock_net:
2871         lnet_net_unlock(0);
2872 unlock_api_mutex:
2873         mutex_unlock(&the_lnet.ln_api_mutex);
2874
2875         return rc;
2876 }
2877
2878 /*
2879  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
2880  * They are only expected to be called for unique networks.
2881  * That can be as a result of older DLC library
2882  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
2883  */
2884 int
2885 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
2886 {
2887         struct lnet_net         *net;
2888         struct list_head        net_head;
2889         int                     rc;
2890         struct lnet_ioctl_config_lnd_tunables tun;
2891         char *nets = conf->cfg_config_u.cfg_net.net_intf;
2892
2893         INIT_LIST_HEAD(&net_head);
2894
2895         /* Create a net/ni structures for the network string */
2896         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
2897         if (rc <= 0)
2898                 return rc == 0 ? -EINVAL : rc;
2899
2900         mutex_lock(&the_lnet.ln_api_mutex);
2901
2902         if (rc > 1) {
2903                 rc = -EINVAL; /* only add one network per call */
2904                 goto out_unlock_clean;
2905         }
2906
2907         net = list_entry(net_head.next, struct lnet_net, net_list);
2908         list_del_init(&net->net_list);
2909
2910         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
2911
2912         memset(&tun, 0, sizeof(tun));
2913
2914         tun.lt_cmn.lct_peer_timeout =
2915           conf->cfg_config_u.cfg_net.net_peer_timeout;
2916         tun.lt_cmn.lct_peer_tx_credits =
2917           conf->cfg_config_u.cfg_net.net_peer_tx_credits;
2918         tun.lt_cmn.lct_peer_rtr_credits =
2919           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
2920         tun.lt_cmn.lct_max_tx_credits =
2921           conf->cfg_config_u.cfg_net.net_max_tx_credits;
2922
2923         rc = lnet_add_net_common(net, &tun);
2924
2925 out_unlock_clean:
2926         mutex_unlock(&the_lnet.ln_api_mutex);
2927         while (!list_empty(&net_head)) {
2928                 /* net_head list is empty in success case */
2929                 net = list_entry(net_head.next, struct lnet_net, net_list);
2930                 list_del_init(&net->net_list);
2931                 lnet_net_free(net);
2932         }
2933         return rc;
2934 }
2935
2936 int
2937 lnet_dyn_del_net(__u32 net_id)
2938 {
2939         struct lnet_net  *net;
2940         struct lnet_ping_buffer *pbuf;
2941         struct lnet_handle_md ping_mdh;
2942         int               rc;
2943         int               net_ni_count;
2944
2945         /* don't allow userspace to shutdown the LOLND */
2946         if (LNET_NETTYP(net_id) == LOLND)
2947                 return -EINVAL;
2948
2949         mutex_lock(&the_lnet.ln_api_mutex);
2950
2951         lnet_net_lock(0);
2952
2953         net = lnet_get_net_locked(net_id);
2954         if (net == NULL) {
2955                 lnet_net_unlock(0);
2956                 rc = -EINVAL;
2957                 goto out;
2958         }
2959
2960         net_ni_count = lnet_get_net_ni_count_locked(net);
2961
2962         lnet_net_unlock(0);
2963
2964         /* create and link a new ping info, before removing the old one */
2965         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
2966                                     lnet_get_ni_count() - net_ni_count, false);
2967         if (rc != 0)
2968                 goto out;
2969
2970         lnet_shutdown_lndnet(net);
2971
2972         if (lnet_count_acceptor_nets() == 0)
2973                 lnet_acceptor_stop();
2974
2975         lnet_ping_target_update(pbuf, ping_mdh);
2976
2977 out:
2978         mutex_unlock(&the_lnet.ln_api_mutex);
2979
2980         return rc;
2981 }
2982
2983 void lnet_incr_dlc_seq(void)
2984 {
2985         atomic_inc(&lnet_dlc_seq_no);
2986 }
2987
2988 __u32 lnet_get_dlc_seq_locked(void)
2989 {
2990         return atomic_read(&lnet_dlc_seq_no);
2991 }
2992
2993 /**
2994  * LNet ioctl handler.
2995  *
2996  */
2997 int
2998 LNetCtl(unsigned int cmd, void *arg)
2999 {
3000         struct libcfs_ioctl_data *data = arg;
3001         struct lnet_ioctl_config_data *config;
3002         struct lnet_process_id    id = {0};
3003         struct lnet_ni           *ni;
3004         int                       rc;
3005
3006         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
3007                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
3008
3009         switch (cmd) {
3010         case IOC_LIBCFS_GET_NI:
3011                 rc = LNetGetId(data->ioc_count, &id);
3012                 data->ioc_nid = id.nid;
3013                 return rc;
3014
3015         case IOC_LIBCFS_FAIL_NID:
3016                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
3017
3018         case IOC_LIBCFS_ADD_ROUTE:
3019                 config = arg;
3020
3021                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3022                         return -EINVAL;
3023
3024                 mutex_lock(&the_lnet.ln_api_mutex);
3025                 rc = lnet_add_route(config->cfg_net,
3026                                     config->cfg_config_u.cfg_route.rtr_hop,
3027                                     config->cfg_nid,
3028                                     config->cfg_config_u.cfg_route.
3029                                         rtr_priority);
3030                 if (rc == 0) {
3031                         rc = lnet_check_routes();
3032                         if (rc != 0)
3033                                 lnet_del_route(config->cfg_net,
3034                                                config->cfg_nid);
3035                 }
3036                 mutex_unlock(&the_lnet.ln_api_mutex);
3037                 return rc;
3038
3039         case IOC_LIBCFS_DEL_ROUTE:
3040                 config = arg;
3041
3042                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3043                         return -EINVAL;
3044
3045                 mutex_lock(&the_lnet.ln_api_mutex);
3046                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
3047                 mutex_unlock(&the_lnet.ln_api_mutex);
3048                 return rc;
3049
3050         case IOC_LIBCFS_GET_ROUTE:
3051                 config = arg;
3052
3053                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3054                         return -EINVAL;
3055
3056                 mutex_lock(&the_lnet.ln_api_mutex);
3057                 rc = lnet_get_route(config->cfg_count,
3058                                     &config->cfg_net,
3059                                     &config->cfg_config_u.cfg_route.rtr_hop,
3060                                     &config->cfg_nid,
3061                                     &config->cfg_config_u.cfg_route.rtr_flags,
3062                                     &config->cfg_config_u.cfg_route.
3063                                         rtr_priority);
3064                 mutex_unlock(&the_lnet.ln_api_mutex);
3065                 return rc;
3066
3067         case IOC_LIBCFS_GET_LOCAL_NI: {
3068                 struct lnet_ioctl_config_ni *cfg_ni;
3069                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3070                 struct lnet_ioctl_element_stats *stats;
3071                 __u32 tun_size;
3072
3073                 cfg_ni = arg;
3074
3075                 /* get the tunables if they are available */
3076                 if (cfg_ni->lic_cfg_hdr.ioc_len <
3077                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
3078                         return -EINVAL;
3079
3080                 stats = (struct lnet_ioctl_element_stats *)
3081                         cfg_ni->lic_bulk;
3082                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3083                                 (cfg_ni->lic_bulk + sizeof(*stats));
3084
3085                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
3086                         sizeof(*stats);
3087
3088                 mutex_lock(&the_lnet.ln_api_mutex);
3089                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
3090                 mutex_unlock(&the_lnet.ln_api_mutex);
3091                 return rc;
3092         }
3093
3094         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
3095                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
3096
3097                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
3098                         return -EINVAL;
3099
3100                 mutex_lock(&the_lnet.ln_api_mutex);
3101                 rc = lnet_get_ni_stats(msg_stats);
3102                 mutex_unlock(&the_lnet.ln_api_mutex);
3103
3104                 return rc;
3105         }
3106
3107         case IOC_LIBCFS_GET_NET: {
3108                 size_t total = sizeof(*config) +
3109                                sizeof(struct lnet_ioctl_net_config);
3110                 config = arg;
3111
3112                 if (config->cfg_hdr.ioc_len < total)
3113                         return -EINVAL;
3114
3115                 mutex_lock(&the_lnet.ln_api_mutex);
3116                 rc = lnet_get_net_config(config);
3117                 mutex_unlock(&the_lnet.ln_api_mutex);
3118                 return rc;
3119         }
3120
3121         case IOC_LIBCFS_GET_LNET_STATS:
3122         {
3123                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
3124
3125                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
3126                         return -EINVAL;
3127
3128                 mutex_lock(&the_lnet.ln_api_mutex);
3129                 lnet_counters_get(&lnet_stats->st_cntrs);
3130                 mutex_unlock(&the_lnet.ln_api_mutex);
3131                 return 0;
3132         }
3133
3134         case IOC_LIBCFS_CONFIG_RTR:
3135                 config = arg;
3136
3137                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3138                         return -EINVAL;
3139
3140                 mutex_lock(&the_lnet.ln_api_mutex);
3141                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
3142                         rc = lnet_rtrpools_enable();
3143                         mutex_unlock(&the_lnet.ln_api_mutex);
3144                         return rc;
3145                 }
3146                 lnet_rtrpools_disable();
3147                 mutex_unlock(&the_lnet.ln_api_mutex);
3148                 return 0;
3149
3150         case IOC_LIBCFS_ADD_BUF:
3151                 config = arg;
3152
3153                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3154                         return -EINVAL;
3155
3156                 mutex_lock(&the_lnet.ln_api_mutex);
3157                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
3158                                                 buf_tiny,
3159                                           config->cfg_config_u.cfg_buffers.
3160                                                 buf_small,
3161                                           config->cfg_config_u.cfg_buffers.
3162                                                 buf_large);
3163                 mutex_unlock(&the_lnet.ln_api_mutex);
3164                 return rc;
3165
3166         case IOC_LIBCFS_SET_NUMA_RANGE: {
3167                 struct lnet_ioctl_set_value *numa;
3168                 numa = arg;
3169                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3170                         return -EINVAL;
3171                 lnet_net_lock(LNET_LOCK_EX);
3172                 lnet_numa_range = numa->sv_value;
3173                 lnet_net_unlock(LNET_LOCK_EX);
3174                 return 0;
3175         }
3176
3177         case IOC_LIBCFS_GET_NUMA_RANGE: {
3178                 struct lnet_ioctl_set_value *numa;
3179                 numa = arg;
3180                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3181                         return -EINVAL;
3182                 numa->sv_value = lnet_numa_range;
3183                 return 0;
3184         }
3185
3186         case IOC_LIBCFS_GET_BUF: {
3187                 struct lnet_ioctl_pool_cfg *pool_cfg;
3188                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
3189
3190                 config = arg;
3191
3192                 if (config->cfg_hdr.ioc_len < total)
3193                         return -EINVAL;
3194
3195                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
3196
3197                 mutex_lock(&the_lnet.ln_api_mutex);
3198                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
3199                 mutex_unlock(&the_lnet.ln_api_mutex);
3200                 return rc;
3201         }
3202
3203         case IOC_LIBCFS_ADD_PEER_NI: {
3204                 struct lnet_ioctl_peer_cfg *cfg = arg;
3205
3206                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3207                         return -EINVAL;
3208
3209                 mutex_lock(&the_lnet.ln_api_mutex);
3210                 rc = lnet_add_peer_ni(cfg->prcfg_prim_nid,
3211                                       cfg->prcfg_cfg_nid,
3212                                       cfg->prcfg_mr);
3213                 mutex_unlock(&the_lnet.ln_api_mutex);
3214                 return rc;
3215         }
3216
3217         case IOC_LIBCFS_DEL_PEER_NI: {
3218                 struct lnet_ioctl_peer_cfg *cfg = arg;
3219
3220                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3221                         return -EINVAL;
3222
3223                 mutex_lock(&the_lnet.ln_api_mutex);
3224                 rc = lnet_del_peer_ni(cfg->prcfg_prim_nid,
3225                                       cfg->prcfg_cfg_nid);
3226                 mutex_unlock(&the_lnet.ln_api_mutex);
3227                 return rc;
3228         }
3229
3230         case IOC_LIBCFS_GET_PEER_INFO: {
3231                 struct lnet_ioctl_peer *peer_info = arg;
3232
3233                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
3234                         return -EINVAL;
3235
3236                 mutex_lock(&the_lnet.ln_api_mutex);
3237                 rc = lnet_get_peer_ni_info(
3238                    peer_info->pr_count,
3239                    &peer_info->pr_nid,
3240                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
3241                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
3242                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
3243                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
3244                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
3245                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
3246                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
3247                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
3248                 mutex_unlock(&the_lnet.ln_api_mutex);
3249                 return rc;
3250         }
3251
3252         case IOC_LIBCFS_GET_PEER_NI: {
3253                 struct lnet_ioctl_peer_cfg *cfg = arg;
3254
3255                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3256                         return -EINVAL;
3257
3258                 mutex_lock(&the_lnet.ln_api_mutex);
3259                 rc = lnet_get_peer_info(cfg,
3260                                         (void __user *)cfg->prcfg_bulk);
3261                 mutex_unlock(&the_lnet.ln_api_mutex);
3262                 return rc;
3263         }
3264
3265         case IOC_LIBCFS_GET_PEER_LIST: {
3266                 struct lnet_ioctl_peer_cfg *cfg = arg;
3267
3268                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3269                         return -EINVAL;
3270
3271                 mutex_lock(&the_lnet.ln_api_mutex);
3272                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
3273                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
3274                 mutex_unlock(&the_lnet.ln_api_mutex);
3275                 return rc;
3276         }
3277
3278         case IOC_LIBCFS_NOTIFY_ROUTER: {
3279                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
3280
3281                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
3282                                    deadline);
3283         }
3284
3285         case IOC_LIBCFS_LNET_DIST:
3286                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
3287                 if (rc < 0 && rc != -EHOSTUNREACH)
3288                         return rc;
3289
3290                 data->ioc_u32[0] = rc;
3291                 return 0;
3292
3293         case IOC_LIBCFS_TESTPROTOCOMPAT:
3294                 lnet_net_lock(LNET_LOCK_EX);
3295                 the_lnet.ln_testprotocompat = data->ioc_flags;
3296                 lnet_net_unlock(LNET_LOCK_EX);
3297                 return 0;
3298
3299         case IOC_LIBCFS_LNET_FAULT:
3300                 return lnet_fault_ctl(data->ioc_flags, data);
3301
3302         case IOC_LIBCFS_PING: {
3303                 signed long timeout;
3304
3305                 id.nid = data->ioc_nid;
3306                 id.pid = data->ioc_u32[0];
3307
3308                 /* If timeout is negative then set default of 3 minutes */
3309                 if (((s32)data->ioc_u32[1] <= 0) ||
3310                     data->ioc_u32[1] > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3311                         timeout = msecs_to_jiffies(DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC);
3312                 else
3313                         timeout = msecs_to_jiffies(data->ioc_u32[1]);
3314
3315                 rc = lnet_ping(id, timeout, data->ioc_pbuf1,
3316                                data->ioc_plen1 / sizeof(struct lnet_process_id));
3317
3318                 if (rc < 0)
3319                         return rc;
3320
3321                 data->ioc_count = rc;
3322                 return 0;
3323         }
3324
3325         case IOC_LIBCFS_PING_PEER: {
3326                 struct lnet_ioctl_ping_data *ping = arg;
3327                 struct lnet_peer *lp;
3328                 signed long timeout;
3329
3330                 /* If timeout is negative then set default of 3 minutes */
3331                 if (((s32)ping->op_param) <= 0 ||
3332                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3333                         timeout = msecs_to_jiffies(DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC);
3334                 else
3335                         timeout = msecs_to_jiffies(ping->op_param);
3336
3337                 rc = lnet_ping(ping->ping_id, timeout,
3338                                ping->ping_buf,
3339                                ping->ping_count);
3340                 if (rc < 0)
3341                         return rc;
3342
3343                 mutex_lock(&the_lnet.ln_api_mutex);
3344                 lp = lnet_find_peer(ping->ping_id.nid);
3345                 if (lp) {
3346                         ping->ping_id.nid = lp->lp_primary_nid;
3347                         ping->mr_info = lnet_peer_is_multi_rail(lp);
3348                         lnet_peer_decref_locked(lp);
3349                 }
3350                 mutex_unlock(&the_lnet.ln_api_mutex);
3351
3352                 ping->ping_count = rc;
3353                 return 0;
3354         }
3355
3356         case IOC_LIBCFS_DISCOVER: {
3357                 struct lnet_ioctl_ping_data *discover = arg;
3358                 struct lnet_peer *lp;
3359
3360                 rc = lnet_discover(discover->ping_id, discover->op_param,
3361                                    discover->ping_buf,
3362                                    discover->ping_count);
3363                 if (rc < 0)
3364                         return rc;
3365
3366                 mutex_lock(&the_lnet.ln_api_mutex);
3367                 lp = lnet_find_peer(discover->ping_id.nid);
3368                 if (lp) {
3369                         discover->ping_id.nid = lp->lp_primary_nid;
3370                         discover->mr_info = lnet_peer_is_multi_rail(lp);
3371                         lnet_peer_decref_locked(lp);
3372                 }
3373                 mutex_unlock(&the_lnet.ln_api_mutex);
3374
3375                 discover->ping_count = rc;
3376                 return 0;
3377         }
3378
3379         default:
3380                 ni = lnet_net2ni_addref(data->ioc_net);
3381                 if (ni == NULL)
3382                         return -EINVAL;
3383
3384                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
3385                         rc = -EINVAL;
3386                 else
3387                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
3388
3389                 lnet_ni_decref(ni);
3390                 return rc;
3391         }
3392         /* not reached */
3393 }
3394 EXPORT_SYMBOL(LNetCtl);
3395
3396 void LNetDebugPeer(struct lnet_process_id id)
3397 {
3398         lnet_debug_peer(id.nid);
3399 }
3400 EXPORT_SYMBOL(LNetDebugPeer);
3401
3402 /**
3403  * Determine if the specified peer \a nid is on the local node.
3404  *
3405  * \param nid   peer nid to check
3406  *
3407  * \retval true         If peer NID is on the local node.
3408  * \retval false        If peer NID is not on the local node.
3409  */
3410 bool LNetIsPeerLocal(lnet_nid_t nid)
3411 {
3412         struct lnet_net *net;
3413         struct lnet_ni *ni;
3414         int cpt;
3415
3416         cpt = lnet_net_lock_current();
3417         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3418                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3419                         if (ni->ni_nid == nid) {
3420                                 lnet_net_unlock(cpt);
3421                                 return true;
3422                         }
3423                 }
3424         }
3425         lnet_net_unlock(cpt);
3426
3427         return false;
3428 }
3429 EXPORT_SYMBOL(LNetIsPeerLocal);
3430
3431 /**
3432  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
3433  * Note that all interfaces share a same PID, as requested by LNetNIInit().
3434  *
3435  * \param index Index of the interface to look up.
3436  * \param id On successful return, this location will hold the
3437  * struct lnet_process_id ID of the interface.
3438  *
3439  * \retval 0 If an interface exists at \a index.
3440  * \retval -ENOENT If no interface has been found.
3441  */
3442 int
3443 LNetGetId(unsigned int index, struct lnet_process_id *id)
3444 {
3445         struct lnet_ni   *ni;
3446         struct lnet_net  *net;
3447         int               cpt;
3448         int               rc = -ENOENT;
3449
3450         LASSERT(the_lnet.ln_refcount > 0);
3451
3452         cpt = lnet_net_lock_current();
3453
3454         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3455                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3456                         if (index-- != 0)
3457                                 continue;
3458
3459                         id->nid = ni->ni_nid;
3460                         id->pid = the_lnet.ln_pid;
3461                         rc = 0;
3462                         break;
3463                 }
3464         }
3465
3466         lnet_net_unlock(cpt);
3467         return rc;
3468 }
3469 EXPORT_SYMBOL(LNetGetId);
3470
3471 static int lnet_ping(struct lnet_process_id id, signed long timeout,
3472                      struct lnet_process_id __user *ids, int n_ids)
3473 {
3474         struct lnet_handle_eq eqh;
3475         struct lnet_handle_md mdh;
3476         struct lnet_event event;
3477         struct lnet_md md = { NULL };
3478         int which;
3479         int unlinked = 0;
3480         int replied = 0;
3481         const signed long a_long_time = msecs_to_jiffies(60 * MSEC_PER_SEC);
3482         struct lnet_ping_buffer *pbuf;
3483         struct lnet_process_id tmpid;
3484         int i;
3485         int nob;
3486         int rc;
3487         int rc2;
3488         sigset_t blocked;
3489
3490         /* n_ids limit is arbitrary */
3491         if (n_ids <= 0 || id.nid == LNET_NID_ANY)
3492                 return -EINVAL;
3493
3494         /*
3495          * if the user buffer has more space than the lnet_interfaces_max
3496          * then only fill it up to lnet_interfaces_max
3497          */
3498         if (n_ids > lnet_interfaces_max)
3499                 n_ids = lnet_interfaces_max;
3500
3501         if (id.pid == LNET_PID_ANY)
3502                 id.pid = LNET_PID_LUSTRE;
3503
3504         pbuf = lnet_ping_buffer_alloc(n_ids, GFP_NOFS);
3505         if (!pbuf)
3506                 return -ENOMEM;
3507
3508         /* NB 2 events max (including any unlink event) */
3509         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
3510         if (rc != 0) {
3511                 CERROR("Can't allocate EQ: %d\n", rc);
3512                 goto fail_ping_buffer_decref;
3513         }
3514
3515         /* initialize md content */
3516         md.start     = &pbuf->pb_info;
3517         md.length    = LNET_PING_INFO_SIZE(n_ids);
3518         md.threshold = 2; /* GET/REPLY */
3519         md.max_size  = 0;
3520         md.options   = LNET_MD_TRUNCATE;
3521         md.user_ptr  = NULL;
3522         md.eq_handle = eqh;
3523
3524         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
3525         if (rc != 0) {
3526                 CERROR("Can't bind MD: %d\n", rc);
3527                 goto fail_free_eq;
3528         }
3529
3530         rc = LNetGet(LNET_NID_ANY, mdh, id,
3531                      LNET_RESERVED_PORTAL,
3532                      LNET_PROTO_PING_MATCHBITS, 0);
3533
3534         if (rc != 0) {
3535                 /* Don't CERROR; this could be deliberate! */
3536                 rc2 = LNetMDUnlink(mdh);
3537                 LASSERT(rc2 == 0);
3538
3539                 /* NB must wait for the UNLINK event below... */
3540                 unlinked = 1;
3541                 timeout = a_long_time;
3542         }
3543
3544         do {
3545                 /* MUST block for unlink to complete */
3546                 if (unlinked)
3547                         blocked = cfs_block_allsigs();
3548
3549                 rc2 = LNetEQPoll(&eqh, 1, timeout, &event, &which);
3550
3551                 if (unlinked)
3552                         cfs_restore_sigs(blocked);
3553
3554                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
3555                        (rc2 <= 0) ? -1 : event.type,
3556                        (rc2 <= 0) ? -1 : event.status,
3557                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
3558
3559                 LASSERT(rc2 != -EOVERFLOW);     /* can't miss anything */
3560
3561                 if (rc2 <= 0 || event.status != 0) {
3562                         /* timeout or error */
3563                         if (!replied && rc == 0)
3564                                 rc = (rc2 < 0) ? rc2 :
3565                                      (rc2 == 0) ? -ETIMEDOUT :
3566                                      event.status;
3567
3568                         if (!unlinked) {
3569                                 /* Ensure completion in finite time... */
3570                                 LNetMDUnlink(mdh);
3571                                 /* No assertion (racing with network) */
3572                                 unlinked = 1;
3573                                 timeout = a_long_time;
3574                         } else if (rc2 == 0) {
3575                                 /* timed out waiting for unlink */
3576                                 CWARN("ping %s: late network completion\n",
3577                                       libcfs_id2str(id));
3578                         }
3579                 } else if (event.type == LNET_EVENT_REPLY) {
3580                         replied = 1;
3581                         rc = event.mlength;
3582                 }
3583         } while (rc2 <= 0 || !event.unlinked);
3584
3585         if (!replied) {
3586                 if (rc >= 0)
3587                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
3588                               libcfs_id2str(id));
3589                 rc = -EIO;
3590                 goto fail_free_eq;
3591         }
3592
3593         nob = rc;
3594         LASSERT(nob >= 0 && nob <= LNET_PING_INFO_SIZE(n_ids));
3595
3596         rc = -EPROTO;           /* if I can't parse... */
3597
3598         if (nob < 8) {
3599                 CERROR("%s: ping info too short %d\n",
3600                        libcfs_id2str(id), nob);
3601                 goto fail_free_eq;
3602         }
3603
3604         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
3605                 lnet_swap_pinginfo(pbuf);
3606         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
3607                 CERROR("%s: Unexpected magic %08x\n",
3608                        libcfs_id2str(id), pbuf->pb_info.pi_magic);
3609                 goto fail_free_eq;
3610         }
3611
3612         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
3613                 CERROR("%s: ping w/o NI status: 0x%x\n",
3614                        libcfs_id2str(id), pbuf->pb_info.pi_features);
3615                 goto fail_free_eq;
3616         }
3617
3618         if (nob < LNET_PING_INFO_SIZE(0)) {
3619                 CERROR("%s: Short reply %d(%d min)\n",
3620                        libcfs_id2str(id),
3621                        nob, (int)LNET_PING_INFO_SIZE(0));
3622                 goto fail_free_eq;
3623         }
3624
3625         if (pbuf->pb_info.pi_nnis < n_ids)
3626                 n_ids = pbuf->pb_info.pi_nnis;
3627
3628         if (nob < LNET_PING_INFO_SIZE(n_ids)) {
3629                 CERROR("%s: Short reply %d(%d expected)\n",
3630                        libcfs_id2str(id),
3631                        nob, (int)LNET_PING_INFO_SIZE(n_ids));
3632                 goto fail_free_eq;
3633         }
3634
3635         rc = -EFAULT;           /* if I segv in copy_to_user()... */
3636
3637         memset(&tmpid, 0, sizeof(tmpid));
3638         for (i = 0; i < n_ids; i++) {
3639                 tmpid.pid = pbuf->pb_info.pi_pid;
3640                 tmpid.nid = pbuf->pb_info.pi_ni[i].ns_nid;
3641                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
3642                         goto fail_free_eq;
3643         }
3644         rc = pbuf->pb_info.pi_nnis;
3645
3646  fail_free_eq:
3647         rc2 = LNetEQFree(eqh);
3648         if (rc2 != 0)
3649                 CERROR("rc2 %d\n", rc2);
3650         LASSERT(rc2 == 0);
3651
3652  fail_ping_buffer_decref:
3653         lnet_ping_buffer_decref(pbuf);
3654         return rc;
3655 }
3656
3657 static int
3658 lnet_discover(struct lnet_process_id id, __u32 force,
3659               struct lnet_process_id __user *ids, int n_ids)
3660 {
3661         struct lnet_peer_ni *lpni;
3662         struct lnet_peer_ni *p;
3663         struct lnet_peer *lp;
3664         struct lnet_process_id *buf;
3665         int cpt;
3666         int i;
3667         int rc;
3668         int max_intf = lnet_interfaces_max;
3669         size_t buf_size;
3670
3671         if (n_ids <= 0 ||
3672             id.nid == LNET_NID_ANY)
3673                 return -EINVAL;
3674
3675         if (id.pid == LNET_PID_ANY)
3676                 id.pid = LNET_PID_LUSTRE;
3677
3678         /*
3679          * if the user buffer has more space than the max_intf
3680          * then only fill it up to max_intf
3681          */
3682         if (n_ids > max_intf)
3683                 n_ids = max_intf;
3684
3685         buf_size = n_ids * sizeof(*buf);
3686
3687         LIBCFS_ALLOC(buf, buf_size);
3688         if (!buf)
3689                 return -ENOMEM;
3690
3691         cpt = lnet_net_lock_current();
3692         lpni = lnet_nid2peerni_locked(id.nid, LNET_NID_ANY, cpt);
3693         if (IS_ERR(lpni)) {
3694                 rc = PTR_ERR(lpni);
3695                 goto out;
3696         }
3697
3698         /*
3699          * Clearing the NIDS_UPTODATE flag ensures the peer will
3700          * be discovered, provided discovery has not been disabled.
3701          */
3702         lp = lpni->lpni_peer_net->lpn_peer;
3703         spin_lock(&lp->lp_lock);
3704         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
3705         /* If the force flag is set, force a PING and PUSH as well. */
3706         if (force)
3707                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
3708         spin_unlock(&lp->lp_lock);
3709         rc = lnet_discover_peer_locked(lpni, cpt, true);
3710         if (rc)
3711                 goto out_decref;
3712
3713         /* Peer may have changed. */
3714         lp = lpni->lpni_peer_net->lpn_peer;
3715         if (lp->lp_nnis < n_ids)
3716                 n_ids = lp->lp_nnis;
3717
3718         i = 0;
3719         p = NULL;
3720         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
3721                 buf[i].pid = id.pid;
3722                 buf[i].nid = p->lpni_nid;
3723                 if (++i >= n_ids)
3724                         break;
3725         }
3726
3727         lnet_net_unlock(cpt);
3728
3729         rc = -EFAULT;
3730         if (copy_to_user(ids, buf, n_ids * sizeof(*buf)))
3731                 goto out_relock;
3732         rc = n_ids;
3733 out_relock:
3734         lnet_net_lock(cpt);
3735 out_decref:
3736         lnet_peer_ni_decref_locked(lpni);
3737 out:
3738         lnet_net_unlock(cpt);
3739
3740         LIBCFS_FREE(buf, buf_size);
3741
3742         return rc;
3743 }