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