Whamcloud - gitweb
LU-6142 lnet: code style cleanups, improve error handling
[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 <lnet/lib-lnet.h>
36
37 #define D_LNI D_CONSOLE
38
39 lnet_t      the_lnet;                           /* THE state of the network */
40 EXPORT_SYMBOL(the_lnet);
41
42 static char *ip2nets = "";
43 module_param(ip2nets, charp, 0444);
44 MODULE_PARM_DESC(ip2nets, "LNET network <- IP table");
45
46 static char *networks = "";
47 module_param(networks, charp, 0444);
48 MODULE_PARM_DESC(networks, "local networks");
49
50 static char *routes = "";
51 module_param(routes, charp, 0444);
52 MODULE_PARM_DESC(routes, "routes to non-local networks");
53
54 static int rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
55 module_param(rnet_htable_size, int, 0444);
56 MODULE_PARM_DESC(rnet_htable_size, "size of remote network hash table");
57
58 static int lnet_ping(lnet_process_id_t id, int timeout_ms,
59                      lnet_process_id_t __user *ids, int n_ids);
60
61 static char *
62 lnet_get_routes(void)
63 {
64         return routes;
65 }
66
67 static char *
68 lnet_get_networks(void)
69 {
70         char   *nets;
71         int     rc;
72
73         if (*networks != 0 && *ip2nets != 0) {
74                 LCONSOLE_ERROR_MSG(0x101, "Please specify EITHER 'networks' or "
75                                    "'ip2nets' but not both at once\n");
76                 return NULL;
77         }
78
79         if (*ip2nets != 0) {
80                 rc = lnet_parse_ip2nets(&nets, ip2nets);
81                 return (rc == 0) ? nets : NULL;
82         }
83
84         if (*networks != 0)
85                 return networks;
86
87         return "tcp";
88 }
89
90 static void
91 lnet_init_locks(void)
92 {
93         spin_lock_init(&the_lnet.ln_eq_wait_lock);
94         init_waitqueue_head(&the_lnet.ln_eq_waitq);
95         init_waitqueue_head(&the_lnet.ln_rc_waitq);
96         mutex_init(&the_lnet.ln_lnd_mutex);
97         mutex_init(&the_lnet.ln_api_mutex);
98 }
99
100 static void
101 lnet_fini_locks(void)
102 {
103 }
104
105 struct kmem_cache *lnet_mes_cachep;        /* MEs kmem_cache */
106 struct kmem_cache *lnet_small_mds_cachep;  /* <= LNET_SMALL_MD_SIZE bytes
107                                             *  MDs kmem_cache */
108
109 static int
110 lnet_descriptor_setup(void)
111 {
112         /* create specific kmem_cache for MEs and small MDs (i.e., originally
113          * allocated in <size-xxx> kmem_cache).
114          */
115         lnet_mes_cachep = kmem_cache_create("lnet_MEs", sizeof(lnet_me_t),
116                                             0, 0, NULL);
117         if (!lnet_mes_cachep)
118                 return -ENOMEM;
119
120         lnet_small_mds_cachep = kmem_cache_create("lnet_small_MDs",
121                                                   LNET_SMALL_MD_SIZE, 0, 0,
122                                                   NULL);
123         if (!lnet_small_mds_cachep)
124                 return -ENOMEM;
125
126         return 0;
127 }
128
129 static void
130 lnet_descriptor_cleanup(void)
131 {
132
133         if (lnet_small_mds_cachep) {
134                 kmem_cache_destroy(lnet_small_mds_cachep);
135                 lnet_small_mds_cachep = NULL;
136         }
137
138         if (lnet_mes_cachep) {
139                 kmem_cache_destroy(lnet_mes_cachep);
140                 lnet_mes_cachep = NULL;
141         }
142 }
143
144 static int
145 lnet_create_remote_nets_table(void)
146 {
147         int               i;
148         struct list_head *hash;
149
150         LASSERT(the_lnet.ln_remote_nets_hash == NULL);
151         LASSERT(the_lnet.ln_remote_nets_hbits > 0);
152         LIBCFS_ALLOC(hash, LNET_REMOTE_NETS_HASH_SIZE * sizeof(*hash));
153         if (hash == NULL) {
154                 CERROR("Failed to create remote nets hash table\n");
155                 return -ENOMEM;
156         }
157
158         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
159                 INIT_LIST_HEAD(&hash[i]);
160         the_lnet.ln_remote_nets_hash = hash;
161         return 0;
162 }
163
164 static void
165 lnet_destroy_remote_nets_table(void)
166 {
167         int i;
168
169         if (the_lnet.ln_remote_nets_hash == NULL)
170                 return;
171
172         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
173                 LASSERT(list_empty(&the_lnet.ln_remote_nets_hash[i]));
174
175         LIBCFS_FREE(the_lnet.ln_remote_nets_hash,
176                     LNET_REMOTE_NETS_HASH_SIZE *
177                     sizeof(the_lnet.ln_remote_nets_hash[0]));
178         the_lnet.ln_remote_nets_hash = NULL;
179 }
180
181 static void
182 lnet_destroy_locks(void)
183 {
184         if (the_lnet.ln_res_lock != NULL) {
185                 cfs_percpt_lock_free(the_lnet.ln_res_lock);
186                 the_lnet.ln_res_lock = NULL;
187         }
188
189         if (the_lnet.ln_net_lock != NULL) {
190                 cfs_percpt_lock_free(the_lnet.ln_net_lock);
191                 the_lnet.ln_net_lock = NULL;
192         }
193
194         lnet_fini_locks();
195 }
196
197 static int
198 lnet_create_locks(void)
199 {
200         lnet_init_locks();
201
202         the_lnet.ln_res_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
203         if (the_lnet.ln_res_lock == NULL)
204                 goto failed;
205
206         the_lnet.ln_net_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
207         if (the_lnet.ln_net_lock == NULL)
208                 goto failed;
209
210         return 0;
211
212  failed:
213         lnet_destroy_locks();
214         return -ENOMEM;
215 }
216
217 static void lnet_assert_wire_constants(void)
218 {
219         /* Wire protocol assertions generated by 'wirecheck'
220          * running on Linux robert.bartonsoftware.com 2.6.8-1.521
221          * #1 Mon Aug 16 09:01:18 EDT 2004 i686 athlon i386 GNU/Linux
222          * with gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7) */
223
224         /* Constants... */
225         CLASSERT(LNET_PROTO_TCP_MAGIC == 0xeebc0ded);
226         CLASSERT(LNET_PROTO_TCP_VERSION_MAJOR == 1);
227         CLASSERT(LNET_PROTO_TCP_VERSION_MINOR == 0);
228         CLASSERT(LNET_MSG_ACK == 0);
229         CLASSERT(LNET_MSG_PUT == 1);
230         CLASSERT(LNET_MSG_GET == 2);
231         CLASSERT(LNET_MSG_REPLY == 3);
232         CLASSERT(LNET_MSG_HELLO == 4);
233
234         /* Checks for struct lnet_handle_wire */
235         CLASSERT((int)sizeof(struct lnet_handle_wire) == 16);
236         CLASSERT((int)offsetof(struct lnet_handle_wire, wh_interface_cookie) == 0);
237         CLASSERT((int)sizeof(((struct lnet_handle_wire *)0)->wh_interface_cookie) == 8);
238         CLASSERT((int)offsetof(struct lnet_handle_wire, wh_object_cookie) == 8);
239         CLASSERT((int)sizeof(((struct lnet_handle_wire *)0)->wh_object_cookie) == 8);
240
241         /* Checks for struct lnet_magicversion_t */
242         CLASSERT((int)sizeof(lnet_magicversion_t) == 8);
243         CLASSERT((int)offsetof(lnet_magicversion_t, magic) == 0);
244         CLASSERT((int)sizeof(((lnet_magicversion_t *)0)->magic) == 4);
245         CLASSERT((int)offsetof(lnet_magicversion_t, version_major) == 4);
246         CLASSERT((int)sizeof(((lnet_magicversion_t *)0)->version_major) == 2);
247         CLASSERT((int)offsetof(lnet_magicversion_t, version_minor) == 6);
248         CLASSERT((int)sizeof(((lnet_magicversion_t *)0)->version_minor) == 2);
249
250         /* Checks for struct lnet_hdr_t */
251         CLASSERT((int)sizeof(lnet_hdr_t) == 72);
252         CLASSERT((int)offsetof(lnet_hdr_t, dest_nid) == 0);
253         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->dest_nid) == 8);
254         CLASSERT((int)offsetof(lnet_hdr_t, src_nid) == 8);
255         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->src_nid) == 8);
256         CLASSERT((int)offsetof(lnet_hdr_t, dest_pid) == 16);
257         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->dest_pid) == 4);
258         CLASSERT((int)offsetof(lnet_hdr_t, src_pid) == 20);
259         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->src_pid) == 4);
260         CLASSERT((int)offsetof(lnet_hdr_t, type) == 24);
261         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->type) == 4);
262         CLASSERT((int)offsetof(lnet_hdr_t, payload_length) == 28);
263         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->payload_length) == 4);
264         CLASSERT((int)offsetof(lnet_hdr_t, msg) == 32);
265         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg) == 40);
266
267         /* Ack */
268         CLASSERT((int)offsetof(lnet_hdr_t, msg.ack.dst_wmd) == 32);
269         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.ack.dst_wmd) == 16);
270         CLASSERT((int)offsetof(lnet_hdr_t, msg.ack.match_bits) == 48);
271         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.ack.match_bits) == 8);
272         CLASSERT((int)offsetof(lnet_hdr_t, msg.ack.mlength) == 56);
273         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.ack.mlength) == 4);
274
275         /* Put */
276         CLASSERT((int)offsetof(lnet_hdr_t, msg.put.ack_wmd) == 32);
277         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.put.ack_wmd) == 16);
278         CLASSERT((int)offsetof(lnet_hdr_t, msg.put.match_bits) == 48);
279         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.put.match_bits) == 8);
280         CLASSERT((int)offsetof(lnet_hdr_t, msg.put.hdr_data) == 56);
281         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.put.hdr_data) == 8);
282         CLASSERT((int)offsetof(lnet_hdr_t, msg.put.ptl_index) == 64);
283         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.put.ptl_index) == 4);
284         CLASSERT((int)offsetof(lnet_hdr_t, msg.put.offset) == 68);
285         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.put.offset) == 4);
286
287         /* Get */
288         CLASSERT((int)offsetof(lnet_hdr_t, msg.get.return_wmd) == 32);
289         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.get.return_wmd) == 16);
290         CLASSERT((int)offsetof(lnet_hdr_t, msg.get.match_bits) == 48);
291         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.get.match_bits) == 8);
292         CLASSERT((int)offsetof(lnet_hdr_t, msg.get.ptl_index) == 56);
293         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.get.ptl_index) == 4);
294         CLASSERT((int)offsetof(lnet_hdr_t, msg.get.src_offset) == 60);
295         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.get.src_offset) == 4);
296         CLASSERT((int)offsetof(lnet_hdr_t, msg.get.sink_length) == 64);
297         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.get.sink_length) == 4);
298
299         /* Reply */
300         CLASSERT((int)offsetof(lnet_hdr_t, msg.reply.dst_wmd) == 32);
301         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.reply.dst_wmd) == 16);
302
303         /* Hello */
304         CLASSERT((int)offsetof(lnet_hdr_t, msg.hello.incarnation) == 32);
305         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.hello.incarnation) == 8);
306         CLASSERT((int)offsetof(lnet_hdr_t, msg.hello.type) == 40);
307         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.hello.type) == 4);
308 }
309
310 static lnd_t *lnet_find_lnd_by_type(__u32 type)
311 {
312         lnd_t            *lnd;
313         struct list_head *tmp;
314
315         /* holding lnd mutex */
316         list_for_each(tmp, &the_lnet.ln_lnds) {
317                 lnd = list_entry(tmp, lnd_t, lnd_list);
318
319                 if (lnd->lnd_type == type)
320                         return lnd;
321         }
322         return NULL;
323 }
324
325 void
326 lnet_register_lnd (lnd_t *lnd)
327 {
328         mutex_lock(&the_lnet.ln_lnd_mutex);
329
330         LASSERT(libcfs_isknown_lnd(lnd->lnd_type));
331         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == NULL);
332
333         list_add_tail(&lnd->lnd_list, &the_lnet.ln_lnds);
334         lnd->lnd_refcount = 0;
335
336         CDEBUG(D_NET, "%s LND registered\n", libcfs_lnd2str(lnd->lnd_type));
337
338         mutex_unlock(&the_lnet.ln_lnd_mutex);
339 }
340 EXPORT_SYMBOL(lnet_register_lnd);
341
342 void
343 lnet_unregister_lnd (lnd_t *lnd)
344 {
345         mutex_lock(&the_lnet.ln_lnd_mutex);
346
347         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == lnd);
348         LASSERT(lnd->lnd_refcount == 0);
349
350         list_del(&lnd->lnd_list);
351         CDEBUG(D_NET, "%s LND unregistered\n", libcfs_lnd2str(lnd->lnd_type));
352
353         mutex_unlock(&the_lnet.ln_lnd_mutex);
354 }
355 EXPORT_SYMBOL(lnet_unregister_lnd);
356
357 void
358 lnet_counters_get(lnet_counters_t *counters)
359 {
360         lnet_counters_t *ctr;
361         int             i;
362
363         memset(counters, 0, sizeof(*counters));
364
365         lnet_net_lock(LNET_LOCK_EX);
366
367         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
368                 counters->msgs_max     += ctr->msgs_max;
369                 counters->msgs_alloc   += ctr->msgs_alloc;
370                 counters->errors       += ctr->errors;
371                 counters->send_count   += ctr->send_count;
372                 counters->recv_count   += ctr->recv_count;
373                 counters->route_count  += ctr->route_count;
374                 counters->drop_count   += ctr->drop_count;
375                 counters->send_length  += ctr->send_length;
376                 counters->recv_length  += ctr->recv_length;
377                 counters->route_length += ctr->route_length;
378                 counters->drop_length  += ctr->drop_length;
379
380         }
381         lnet_net_unlock(LNET_LOCK_EX);
382 }
383 EXPORT_SYMBOL(lnet_counters_get);
384
385 void
386 lnet_counters_reset(void)
387 {
388         lnet_counters_t *counters;
389         int             i;
390
391         lnet_net_lock(LNET_LOCK_EX);
392
393         cfs_percpt_for_each(counters, i, the_lnet.ln_counters)
394                 memset(counters, 0, sizeof(lnet_counters_t));
395
396         lnet_net_unlock(LNET_LOCK_EX);
397 }
398
399 static __u64 lnet_create_interface_cookie(void)
400 {
401         /* NB the interface cookie in wire handles guards against delayed
402          * replies and ACKs appearing valid after reboot. Initialisation time,
403          * even if it's only implemented to millisecond resolution is probably
404          * easily good enough. */
405         struct timeval tv;
406         __u64          cookie;
407         do_gettimeofday(&tv);
408         cookie = tv.tv_sec;
409         cookie *= 1000000;
410         cookie += tv.tv_usec;
411         return cookie;
412 }
413
414 static char *
415 lnet_res_type2str(int type)
416 {
417         switch (type) {
418         default:
419                 LBUG();
420         case LNET_COOKIE_TYPE_MD:
421                 return "MD";
422         case LNET_COOKIE_TYPE_ME:
423                 return "ME";
424         case LNET_COOKIE_TYPE_EQ:
425                 return "EQ";
426         }
427 }
428
429 static void
430 lnet_res_container_cleanup(struct lnet_res_container *rec)
431 {
432         int     count = 0;
433
434         if (rec->rec_type == 0) /* not set yet, it's uninitialized */
435                 return;
436
437         while (!list_empty(&rec->rec_active)) {
438                 struct list_head *e = rec->rec_active.next;
439
440                 list_del_init(e);
441                 if (rec->rec_type == LNET_COOKIE_TYPE_EQ) {
442                         lnet_eq_free(list_entry(e, lnet_eq_t, eq_list));
443
444                 } else if (rec->rec_type == LNET_COOKIE_TYPE_MD) {
445                         lnet_md_free(list_entry(e, lnet_libmd_t, md_list));
446
447                 } else { /* NB: Active MEs should be attached on portals */
448                         LBUG();
449                 }
450                 count++;
451         }
452
453         if (count > 0) {
454                 /* Found alive MD/ME/EQ, user really should unlink/free
455                  * all of them before finalize LNet, but if someone didn't,
456                  * we have to recycle garbage for him */
457                 CERROR("%d active elements on exit of %s container\n",
458                        count, lnet_res_type2str(rec->rec_type));
459         }
460
461         if (rec->rec_lh_hash != NULL) {
462                 LIBCFS_FREE(rec->rec_lh_hash,
463                             LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
464                 rec->rec_lh_hash = NULL;
465         }
466
467         rec->rec_type = 0; /* mark it as finalized */
468 }
469
470 static int
471 lnet_res_container_setup(struct lnet_res_container *rec, int cpt, int type)
472 {
473         int     rc = 0;
474         int     i;
475
476         LASSERT(rec->rec_type == 0);
477
478         rec->rec_type = type;
479         INIT_LIST_HEAD(&rec->rec_active);
480
481         rec->rec_lh_cookie = (cpt << LNET_COOKIE_TYPE_BITS) | type;
482
483         /* Arbitrary choice of hash table size */
484         LIBCFS_CPT_ALLOC(rec->rec_lh_hash, lnet_cpt_table(), cpt,
485                          LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
486         if (rec->rec_lh_hash == NULL) {
487                 rc = -ENOMEM;
488                 goto out;
489         }
490
491         for (i = 0; i < LNET_LH_HASH_SIZE; i++)
492                 INIT_LIST_HEAD(&rec->rec_lh_hash[i]);
493
494         return 0;
495
496 out:
497         CERROR("Failed to setup %s resource container\n",
498                lnet_res_type2str(type));
499         lnet_res_container_cleanup(rec);
500         return rc;
501 }
502
503 static void
504 lnet_res_containers_destroy(struct lnet_res_container **recs)
505 {
506         struct lnet_res_container       *rec;
507         int                             i;
508
509         cfs_percpt_for_each(rec, i, recs)
510                 lnet_res_container_cleanup(rec);
511
512         cfs_percpt_free(recs);
513 }
514
515 static struct lnet_res_container **
516 lnet_res_containers_create(int type)
517 {
518         struct lnet_res_container       **recs;
519         struct lnet_res_container       *rec;
520         int                             rc;
521         int                             i;
522
523         recs = cfs_percpt_alloc(lnet_cpt_table(), sizeof(*rec));
524         if (recs == NULL) {
525                 CERROR("Failed to allocate %s resource containers\n",
526                        lnet_res_type2str(type));
527                 return NULL;
528         }
529
530         cfs_percpt_for_each(rec, i, recs) {
531                 rc = lnet_res_container_setup(rec, i, type);
532                 if (rc != 0) {
533                         lnet_res_containers_destroy(recs);
534                         return NULL;
535                 }
536         }
537
538         return recs;
539 }
540
541 lnet_libhandle_t *
542 lnet_res_lh_lookup(struct lnet_res_container *rec, __u64 cookie)
543 {
544         /* ALWAYS called with lnet_res_lock held */
545         struct list_head        *head;
546         lnet_libhandle_t        *lh;
547         unsigned int            hash;
548
549         if ((cookie & LNET_COOKIE_MASK) != rec->rec_type)
550                 return NULL;
551
552         hash = cookie >> (LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS);
553         head = &rec->rec_lh_hash[hash & LNET_LH_HASH_MASK];
554
555         list_for_each_entry(lh, head, lh_hash_chain) {
556                 if (lh->lh_cookie == cookie)
557                         return lh;
558         }
559
560         return NULL;
561 }
562
563 void
564 lnet_res_lh_initialize(struct lnet_res_container *rec, lnet_libhandle_t *lh)
565 {
566         /* ALWAYS called with lnet_res_lock held */
567         unsigned int    ibits = LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS;
568         unsigned int    hash;
569
570         lh->lh_cookie = rec->rec_lh_cookie;
571         rec->rec_lh_cookie += 1 << ibits;
572
573         hash = (lh->lh_cookie >> ibits) & LNET_LH_HASH_MASK;
574
575         list_add(&lh->lh_hash_chain, &rec->rec_lh_hash[hash]);
576 }
577
578 static int lnet_unprepare(void);
579
580 static int
581 lnet_prepare(lnet_pid_t requested_pid)
582 {
583         /* Prepare to bring up the network */
584         struct lnet_res_container **recs;
585         int                       rc = 0;
586
587         if (requested_pid == LNET_PID_ANY) {
588                 /* Don't instantiate LNET just for me */
589                 return -ENETDOWN;
590         }
591
592         LASSERT(the_lnet.ln_refcount == 0);
593
594         the_lnet.ln_routing = 0;
595
596         LASSERT((requested_pid & LNET_PID_USERFLAG) == 0);
597         the_lnet.ln_pid = requested_pid;
598
599         INIT_LIST_HEAD(&the_lnet.ln_test_peers);
600         INIT_LIST_HEAD(&the_lnet.ln_nis);
601         INIT_LIST_HEAD(&the_lnet.ln_nis_cpt);
602         INIT_LIST_HEAD(&the_lnet.ln_nis_zombie);
603         INIT_LIST_HEAD(&the_lnet.ln_routers);
604         INIT_LIST_HEAD(&the_lnet.ln_drop_rules);
605         INIT_LIST_HEAD(&the_lnet.ln_delay_rules);
606
607         rc = lnet_descriptor_setup();
608         if (rc != 0)
609                 goto failed;
610
611         rc = lnet_create_remote_nets_table();
612         if (rc != 0)
613                 goto failed;
614
615         the_lnet.ln_interface_cookie = lnet_create_interface_cookie();
616
617         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
618                                                 sizeof(lnet_counters_t));
619         if (the_lnet.ln_counters == NULL) {
620                 CERROR("Failed to allocate counters for LNet\n");
621                 rc = -ENOMEM;
622                 goto failed;
623         }
624
625         rc = lnet_peer_tables_create();
626         if (rc != 0)
627                 goto failed;
628
629         rc = lnet_msg_containers_create();
630         if (rc != 0)
631                 goto failed;
632
633         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
634                                       LNET_COOKIE_TYPE_EQ);
635         if (rc != 0)
636                 goto failed;
637
638         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_ME);
639         if (recs == NULL) {
640                 rc = -ENOMEM;
641                 goto failed;
642         }
643
644         the_lnet.ln_me_containers = recs;
645
646         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
647         if (recs == NULL) {
648                 rc = -ENOMEM;
649                 goto failed;
650         }
651
652         the_lnet.ln_md_containers = recs;
653
654         rc = lnet_portals_create();
655         if (rc != 0) {
656                 CERROR("Failed to create portals for LNet: %d\n", rc);
657                 goto failed;
658         }
659
660         return 0;
661
662  failed:
663         lnet_unprepare();
664         return rc;
665 }
666
667 static int
668 lnet_unprepare (void)
669 {
670         /* NB no LNET_LOCK since this is the last reference.  All LND instances
671          * have shut down already, so it is safe to unlink and free all
672          * descriptors, even those that appear committed to a network op (eg MD
673          * with non-zero pending count) */
674
675         lnet_fail_nid(LNET_NID_ANY, 0);
676
677         LASSERT(the_lnet.ln_refcount == 0);
678         LASSERT(list_empty(&the_lnet.ln_test_peers));
679         LASSERT(list_empty(&the_lnet.ln_nis));
680         LASSERT(list_empty(&the_lnet.ln_nis_cpt));
681         LASSERT(list_empty(&the_lnet.ln_nis_zombie));
682
683         lnet_portals_destroy();
684
685         if (the_lnet.ln_md_containers != NULL) {
686                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
687                 the_lnet.ln_md_containers = NULL;
688         }
689
690         if (the_lnet.ln_me_containers != NULL) {
691                 lnet_res_containers_destroy(the_lnet.ln_me_containers);
692                 the_lnet.ln_me_containers = NULL;
693         }
694
695         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
696
697         lnet_msg_containers_destroy();
698         lnet_peer_tables_destroy();
699         lnet_rtrpools_free(0);
700
701         if (the_lnet.ln_counters != NULL) {
702                 cfs_percpt_free(the_lnet.ln_counters);
703                 the_lnet.ln_counters = NULL;
704         }
705         lnet_destroy_remote_nets_table();
706         lnet_descriptor_cleanup();
707
708         return 0;
709 }
710
711 lnet_ni_t  *
712 lnet_net2ni_locked(__u32 net, int cpt)
713 {
714         struct list_head *tmp;
715         lnet_ni_t        *ni;
716
717         LASSERT(cpt != LNET_LOCK_EX);
718
719         list_for_each(tmp, &the_lnet.ln_nis) {
720                 ni = list_entry(tmp, lnet_ni_t, ni_list);
721
722                 if (LNET_NIDNET(ni->ni_nid) == net) {
723                         lnet_ni_addref_locked(ni, cpt);
724                         return ni;
725                 }
726         }
727
728         return NULL;
729 }
730
731 lnet_ni_t *
732 lnet_net2ni(__u32 net)
733 {
734         lnet_ni_t *ni;
735
736         lnet_net_lock(0);
737         ni = lnet_net2ni_locked(net, 0);
738         lnet_net_unlock(0);
739
740         return ni;
741 }
742 EXPORT_SYMBOL(lnet_net2ni);
743
744 static unsigned int
745 lnet_nid_cpt_hash(lnet_nid_t nid, unsigned int number)
746 {
747         __u64           key = nid;
748         unsigned int    val;
749
750         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
751
752         if (number == 1)
753                 return 0;
754
755         val = hash_long(key, LNET_CPT_BITS);
756         /* NB: LNET_CP_NUMBER doesn't have to be PO2 */
757         if (val < number)
758                 return val;
759
760         return (unsigned int)(key + val + (val >> 1)) % number;
761 }
762
763 int
764 lnet_cpt_of_nid_locked(lnet_nid_t nid)
765 {
766         struct lnet_ni *ni;
767
768         /* must called with hold of lnet_net_lock */
769         if (LNET_CPT_NUMBER == 1)
770                 return 0; /* the only one */
771
772         /* take lnet_net_lock(any) would be OK */
773         if (!list_empty(&the_lnet.ln_nis_cpt)) {
774                 list_for_each_entry(ni, &the_lnet.ln_nis_cpt, ni_cptlist) {
775                         if (LNET_NIDNET(ni->ni_nid) != LNET_NIDNET(nid))
776                                 continue;
777
778                         LASSERT(ni->ni_cpts != NULL);
779                         return ni->ni_cpts[lnet_nid_cpt_hash
780                                            (nid, ni->ni_ncpts)];
781                 }
782         }
783
784         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
785 }
786
787 int
788 lnet_cpt_of_nid(lnet_nid_t nid)
789 {
790         int     cpt;
791         int     cpt2;
792
793         if (LNET_CPT_NUMBER == 1)
794                 return 0; /* the only one */
795
796         if (list_empty(&the_lnet.ln_nis_cpt))
797                 return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
798
799         cpt = lnet_net_lock_current();
800         cpt2 = lnet_cpt_of_nid_locked(nid);
801         lnet_net_unlock(cpt);
802
803         return cpt2;
804 }
805 EXPORT_SYMBOL(lnet_cpt_of_nid);
806
807 int
808 lnet_islocalnet(__u32 net)
809 {
810         struct lnet_ni  *ni;
811         int             cpt;
812
813         cpt = lnet_net_lock_current();
814
815         ni = lnet_net2ni_locked(net, cpt);
816         if (ni != NULL)
817                 lnet_ni_decref_locked(ni, cpt);
818
819         lnet_net_unlock(cpt);
820
821         return ni != NULL;
822 }
823
824 lnet_ni_t  *
825 lnet_nid2ni_locked(lnet_nid_t nid, int cpt)
826 {
827         struct lnet_ni   *ni;
828         struct list_head *tmp;
829
830         LASSERT(cpt != LNET_LOCK_EX);
831
832         list_for_each(tmp, &the_lnet.ln_nis) {
833                 ni = list_entry(tmp, lnet_ni_t, ni_list);
834
835                 if (ni->ni_nid == nid) {
836                         lnet_ni_addref_locked(ni, cpt);
837                         return ni;
838                 }
839         }
840
841         return NULL;
842 }
843
844 int
845 lnet_islocalnid(lnet_nid_t nid)
846 {
847         struct lnet_ni  *ni;
848         int             cpt;
849
850         cpt = lnet_net_lock_current();
851         ni = lnet_nid2ni_locked(nid, cpt);
852         if (ni != NULL)
853                 lnet_ni_decref_locked(ni, cpt);
854         lnet_net_unlock(cpt);
855
856         return ni != NULL;
857 }
858
859 int
860 lnet_count_acceptor_nis (void)
861 {
862         /* Return the # of NIs that need the acceptor. */
863         int              count = 0;
864         struct list_head *tmp;
865         struct lnet_ni   *ni;
866         int              cpt;
867
868         cpt = lnet_net_lock_current();
869         list_for_each(tmp, &the_lnet.ln_nis) {
870                 ni = list_entry(tmp, lnet_ni_t, ni_list);
871
872                 if (ni->ni_lnd->lnd_accept != NULL)
873                         count++;
874         }
875
876         lnet_net_unlock(cpt);
877
878         return count;
879 }
880
881 static struct lnet_ping_info *
882 lnet_ping_info_create(int num_ni)
883 {
884         struct lnet_ping_info *ping_info;
885         unsigned int     infosz;
886
887         infosz = offsetof(struct lnet_ping_info, pi_ni[num_ni]);
888         LIBCFS_ALLOC(ping_info, infosz);
889         if (ping_info == NULL) {
890                 CERROR("Can't allocate ping info[%d]\n", num_ni);
891                 return NULL;
892         }
893
894         ping_info->pi_nnis = num_ni;
895         ping_info->pi_pid = the_lnet.ln_pid;
896         ping_info->pi_magic = LNET_PROTO_PING_MAGIC;
897         ping_info->pi_features = LNET_PING_FEAT_NI_STATUS;
898
899         return ping_info;
900 }
901
902 static inline int
903 lnet_get_ni_count(void)
904 {
905         struct lnet_ni *ni;
906         int            count = 0;
907
908         lnet_net_lock(0);
909
910         list_for_each_entry(ni, &the_lnet.ln_nis, ni_list)
911                 count++;
912
913         lnet_net_unlock(0);
914
915         return count;
916 }
917
918 static inline void
919 lnet_ping_info_free(struct lnet_ping_info *pinfo)
920 {
921         LIBCFS_FREE(pinfo,
922                     offsetof(struct lnet_ping_info,
923                              pi_ni[pinfo->pi_nnis]));
924 }
925
926 static void
927 lnet_ping_info_destroy(void)
928 {
929         struct lnet_ni  *ni;
930
931         lnet_net_lock(LNET_LOCK_EX);
932
933         list_for_each_entry(ni, &the_lnet.ln_nis, ni_list) {
934                 lnet_ni_lock(ni);
935                 ni->ni_status = NULL;
936                 lnet_ni_unlock(ni);
937         }
938
939         lnet_ping_info_free(the_lnet.ln_ping_info);
940         the_lnet.ln_ping_info = NULL;
941
942         lnet_net_unlock(LNET_LOCK_EX);
943 }
944
945 static void
946 lnet_ping_event_handler(lnet_event_t *event)
947 {
948         struct lnet_ping_info *pinfo = event->md.user_ptr;
949
950         if (event->unlinked)
951                 pinfo->pi_features = LNET_PING_FEAT_INVAL;
952 }
953
954 static int
955 lnet_ping_info_setup(struct lnet_ping_info **ppinfo, lnet_handle_md_t *md_handle,
956                      int ni_count, bool set_eq)
957 {
958         lnet_handle_me_t  me_handle;
959         lnet_process_id_t id = {LNET_NID_ANY, LNET_PID_ANY};
960         lnet_md_t         md = {NULL};
961         int               rc, rc2;
962
963         if (set_eq) {
964                 rc = LNetEQAlloc(0, lnet_ping_event_handler,
965                                  &the_lnet.ln_ping_target_eq);
966                 if (rc != 0) {
967                         CERROR("Can't allocate ping EQ: %d\n", rc);
968                         return rc;
969                 }
970         }
971
972         *ppinfo = lnet_ping_info_create(ni_count);
973         if (*ppinfo == NULL) {
974                 rc = -ENOMEM;
975                 goto failed_0;
976         }
977
978         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
979                           LNET_PROTO_PING_MATCHBITS, 0,
980                           LNET_UNLINK, LNET_INS_AFTER,
981                           &me_handle);
982         if (rc != 0) {
983                 CERROR("Can't create ping ME: %d\n", rc);
984                 goto failed_1;
985         }
986
987         /* initialize md content */
988         md.start     = *ppinfo;
989         md.length    = offsetof(struct lnet_ping_info,
990                                 pi_ni[(*ppinfo)->pi_nnis]);
991         md.threshold = LNET_MD_THRESH_INF;
992         md.max_size  = 0;
993         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
994                        LNET_MD_MANAGE_REMOTE;
995         md.user_ptr  = NULL;
996         md.eq_handle = the_lnet.ln_ping_target_eq;
997         md.user_ptr = *ppinfo;
998
999         rc = LNetMDAttach(me_handle, md, LNET_RETAIN, md_handle);
1000         if (rc != 0) {
1001                 CERROR("Can't attach ping MD: %d\n", rc);
1002                 goto failed_2;
1003         }
1004
1005         return 0;
1006
1007 failed_2:
1008         rc2 = LNetMEUnlink(me_handle);
1009         LASSERT(rc2 == 0);
1010 failed_1:
1011         lnet_ping_info_free(*ppinfo);
1012         *ppinfo = NULL;
1013 failed_0:
1014         if (set_eq)
1015                 LNetEQFree(the_lnet.ln_ping_target_eq);
1016         return rc;
1017 }
1018
1019 static void
1020 lnet_ping_md_unlink(struct lnet_ping_info *pinfo, lnet_handle_md_t *md_handle)
1021 {
1022         sigset_t        blocked = cfs_block_allsigs();
1023
1024         LNetMDUnlink(*md_handle);
1025         LNetInvalidateHandle(md_handle);
1026
1027         /* NB md could be busy; this just starts the unlink */
1028         while (pinfo->pi_features != LNET_PING_FEAT_INVAL) {
1029                 CDEBUG(D_NET, "Still waiting for ping MD to unlink\n");
1030                 set_current_state(TASK_UNINTERRUPTIBLE);
1031                 schedule_timeout(cfs_time_seconds(1));
1032         }
1033
1034         cfs_restore_sigs(blocked);
1035 }
1036
1037 static void
1038 lnet_ping_info_install_locked(struct lnet_ping_info *ping_info)
1039 {
1040         int                     i;
1041         lnet_ni_t               *ni;
1042         struct lnet_ni_status *ns;
1043
1044         i = 0;
1045         list_for_each_entry(ni, &the_lnet.ln_nis, ni_list) {
1046                 LASSERT(i < ping_info->pi_nnis);
1047
1048                 ns = &ping_info->pi_ni[i];
1049
1050                 ns->ns_nid = ni->ni_nid;
1051
1052                 lnet_ni_lock(ni);
1053                 ns->ns_status = (ni->ni_status != NULL) ?
1054                                 ni->ni_status->ns_status : LNET_NI_STATUS_UP;
1055                 ni->ni_status = ns;
1056                 lnet_ni_unlock(ni);
1057
1058                 i++;
1059         }
1060 }
1061
1062 static void
1063 lnet_ping_target_update(struct lnet_ping_info *pinfo, lnet_handle_md_t md_handle)
1064 {
1065         struct lnet_ping_info *old_pinfo = NULL;
1066         lnet_handle_md_t old_md;
1067
1068         /* switch the NIs to point to the new ping info created */
1069         lnet_net_lock(LNET_LOCK_EX);
1070
1071         if (!the_lnet.ln_routing)
1072                 pinfo->pi_features |= LNET_PING_FEAT_RTE_DISABLED;
1073         lnet_ping_info_install_locked(pinfo);
1074
1075         if (the_lnet.ln_ping_info != NULL) {
1076                 old_pinfo = the_lnet.ln_ping_info;
1077                 old_md = the_lnet.ln_ping_target_md;
1078         }
1079         the_lnet.ln_ping_target_md = md_handle;
1080         the_lnet.ln_ping_info = pinfo;
1081
1082         lnet_net_unlock(LNET_LOCK_EX);
1083
1084         if (old_pinfo != NULL) {
1085                 /* unlink the old ping info */
1086                 lnet_ping_md_unlink(old_pinfo, &old_md);
1087                 lnet_ping_info_free(old_pinfo);
1088         }
1089 }
1090
1091 static void
1092 lnet_ping_target_fini(void)
1093 {
1094         int             rc;
1095
1096         lnet_ping_md_unlink(the_lnet.ln_ping_info,
1097                             &the_lnet.ln_ping_target_md);
1098
1099         rc = LNetEQFree(the_lnet.ln_ping_target_eq);
1100         LASSERT(rc == 0);
1101
1102         lnet_ping_info_destroy();
1103 }
1104
1105 static int
1106 lnet_ni_tq_credits(lnet_ni_t *ni)
1107 {
1108         int     credits;
1109
1110         LASSERT(ni->ni_ncpts >= 1);
1111
1112         if (ni->ni_ncpts == 1)
1113                 return ni->ni_maxtxcredits;
1114
1115         credits = ni->ni_maxtxcredits / ni->ni_ncpts;
1116         credits = max(credits, 8 * ni->ni_peertxcredits);
1117         credits = min(credits, ni->ni_maxtxcredits);
1118
1119         return credits;
1120 }
1121
1122 static void
1123 lnet_ni_unlink_locked(lnet_ni_t *ni)
1124 {
1125         if (!list_empty(&ni->ni_cptlist)) {
1126                 list_del_init(&ni->ni_cptlist);
1127                 lnet_ni_decref_locked(ni, 0);
1128         }
1129
1130         /* move it to zombie list and nobody can find it anymore */
1131         LASSERT(!list_empty(&ni->ni_list));
1132         list_move(&ni->ni_list, &the_lnet.ln_nis_zombie);
1133         lnet_ni_decref_locked(ni, 0);   /* drop ln_nis' ref */
1134 }
1135
1136 static void
1137 lnet_clear_zombies_nis_locked(void)
1138 {
1139         int             i;
1140         int             islo;
1141         lnet_ni_t       *ni;
1142
1143         /* Now wait for the NI's I just nuked to show up on ln_zombie_nis
1144          * and shut them down in guaranteed thread context */
1145         i = 2;
1146         while (!list_empty(&the_lnet.ln_nis_zombie)) {
1147                 int     *ref;
1148                 int     j;
1149
1150                 ni = list_entry(the_lnet.ln_nis_zombie.next,
1151                                 lnet_ni_t, ni_list);
1152                 list_del_init(&ni->ni_list);
1153                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
1154                         if (*ref == 0)
1155                                 continue;
1156                         /* still busy, add it back to zombie list */
1157                         list_add(&ni->ni_list, &the_lnet.ln_nis_zombie);
1158                         break;
1159                 }
1160
1161                 if (!list_empty(&ni->ni_list)) {
1162                         lnet_net_unlock(LNET_LOCK_EX);
1163                         ++i;
1164                         if ((i & (-i)) == i) {
1165                                 CDEBUG(D_WARNING,
1166                                        "Waiting for zombie LNI %s\n",
1167                                        libcfs_nid2str(ni->ni_nid));
1168                         }
1169                         set_current_state(TASK_UNINTERRUPTIBLE);
1170                         schedule_timeout(cfs_time_seconds(1));
1171                         lnet_net_lock(LNET_LOCK_EX);
1172                         continue;
1173                 }
1174
1175                 ni->ni_lnd->lnd_refcount--;
1176                 lnet_net_unlock(LNET_LOCK_EX);
1177
1178                 islo = ni->ni_lnd->lnd_type == LOLND;
1179
1180                 LASSERT(!in_interrupt());
1181                 (ni->ni_lnd->lnd_shutdown)(ni);
1182
1183                 /* can't deref lnd anymore now; it might have unregistered
1184                  * itself...  */
1185
1186                 if (!islo)
1187                         CDEBUG(D_LNI, "Removed LNI %s\n",
1188                               libcfs_nid2str(ni->ni_nid));
1189
1190                 lnet_ni_free(ni);
1191                 i = 2;
1192                 lnet_net_lock(LNET_LOCK_EX);
1193         }
1194 }
1195
1196 static void
1197 lnet_shutdown_lndnis(void)
1198 {
1199         int             i;
1200         lnet_ni_t       *ni;
1201
1202         /* NB called holding the global mutex */
1203
1204         /* All quiet on the API front */
1205         LASSERT(!the_lnet.ln_shutdown);
1206         LASSERT(the_lnet.ln_refcount == 0);
1207         LASSERT(list_empty(&the_lnet.ln_nis_zombie));
1208
1209         lnet_net_lock(LNET_LOCK_EX);
1210         the_lnet.ln_shutdown = 1;       /* flag shutdown */
1211
1212         /* Unlink NIs from the global table */
1213         while (!list_empty(&the_lnet.ln_nis)) {
1214                 ni = list_entry(the_lnet.ln_nis.next,
1215                                 lnet_ni_t, ni_list);
1216                 lnet_ni_unlink_locked(ni);
1217         }
1218
1219         /* Drop the cached loopback NI. */
1220         if (the_lnet.ln_loni != NULL) {
1221                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
1222                 the_lnet.ln_loni = NULL;
1223         }
1224
1225         lnet_net_unlock(LNET_LOCK_EX);
1226
1227         /* Clear lazy portals and drop delayed messages which hold refs
1228          * on their lnet_msg_t::msg_rxpeer */
1229         for (i = 0; i < the_lnet.ln_nportals; i++)
1230                 LNetClearLazyPortal(i);
1231
1232         /* Clear the peer table and wait for all peers to go (they hold refs on
1233          * their NIs) */
1234         lnet_peer_tables_cleanup(NULL);
1235
1236         lnet_net_lock(LNET_LOCK_EX);
1237
1238         lnet_clear_zombies_nis_locked();
1239         the_lnet.ln_shutdown = 0;
1240         lnet_net_unlock(LNET_LOCK_EX);
1241 }
1242
1243 /* shutdown down the NI and release refcount */
1244 static void
1245 lnet_shutdown_lndni(struct lnet_ni *ni)
1246 {
1247         int i;
1248
1249         lnet_net_lock(LNET_LOCK_EX);
1250         lnet_ni_unlink_locked(ni);
1251         lnet_net_unlock(LNET_LOCK_EX);
1252
1253         /* clear messages for this NI on the lazy portal */
1254         for (i = 0; i < the_lnet.ln_nportals; i++)
1255                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
1256
1257         /* Do peer table cleanup for this ni */
1258         lnet_peer_tables_cleanup(ni);
1259
1260         lnet_net_lock(LNET_LOCK_EX);
1261         lnet_clear_zombies_nis_locked();
1262         lnet_net_unlock(LNET_LOCK_EX);
1263 }
1264
1265 static int
1266 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_ioctl_config_data *conf)
1267 {
1268         struct lnet_ioctl_config_lnd_tunables *lnd_tunables = NULL;
1269         int                     rc = -EINVAL;
1270         __u32                   lnd_type;
1271         lnd_t                   *lnd;
1272         struct lnet_tx_queue    *tq;
1273         int                     i;
1274
1275         lnd_type = LNET_NETTYP(LNET_NIDNET(ni->ni_nid));
1276
1277         LASSERT(libcfs_isknown_lnd(lnd_type));
1278
1279         if (lnd_type == CIBLND || lnd_type == OPENIBLND ||
1280             lnd_type == IIBLND || lnd_type == VIBLND) {
1281                 CERROR("LND %s obsoleted\n", libcfs_lnd2str(lnd_type));
1282                 goto failed0;
1283         }
1284
1285         /* Make sure this new NI is unique. */
1286         lnet_net_lock(LNET_LOCK_EX);
1287         rc = lnet_net_unique(LNET_NIDNET(ni->ni_nid), &the_lnet.ln_nis);
1288         lnet_net_unlock(LNET_LOCK_EX);
1289
1290         if (!rc) {
1291                 if (lnd_type == LOLND) {
1292                         lnet_ni_free(ni);
1293                         return 0;
1294                 }
1295
1296                 CERROR("Net %s is not unique\n",
1297                        libcfs_net2str(LNET_NIDNET(ni->ni_nid)));
1298
1299                 rc = -EEXIST;
1300                 goto failed0;
1301         }
1302
1303         mutex_lock(&the_lnet.ln_lnd_mutex);
1304         lnd = lnet_find_lnd_by_type(lnd_type);
1305
1306         if (lnd == NULL) {
1307                 mutex_unlock(&the_lnet.ln_lnd_mutex);
1308                 rc = request_module("%s", libcfs_lnd2modname(lnd_type));
1309                 mutex_lock(&the_lnet.ln_lnd_mutex);
1310
1311                 lnd = lnet_find_lnd_by_type(lnd_type);
1312                 if (lnd == NULL) {
1313                         mutex_unlock(&the_lnet.ln_lnd_mutex);
1314                         CERROR("Can't load LND %s, module %s, rc=%d\n",
1315                                libcfs_lnd2str(lnd_type),
1316                                libcfs_lnd2modname(lnd_type), rc);
1317 #ifndef HAVE_MODULE_LOADING_SUPPORT
1318                         LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
1319                                            "compiled with kernel module "
1320                                            "loading support.");
1321 #endif
1322                         rc = -EINVAL;
1323                         goto failed0;
1324                 }
1325         }
1326
1327         lnet_net_lock(LNET_LOCK_EX);
1328         lnd->lnd_refcount++;
1329         lnet_net_unlock(LNET_LOCK_EX);
1330
1331         ni->ni_lnd = lnd;
1332
1333         if (conf && conf->cfg_hdr.ioc_len > sizeof(*conf))
1334                 lnd_tunables = (struct lnet_ioctl_config_lnd_tunables *)conf->cfg_bulk;
1335
1336         if (lnd_tunables != NULL) {
1337                 LIBCFS_ALLOC(ni->ni_lnd_tunables,
1338                              sizeof(*ni->ni_lnd_tunables));
1339                 if (ni->ni_lnd_tunables == NULL) {
1340                         mutex_unlock(&the_lnet.ln_lnd_mutex);
1341                         rc = -ENOMEM;
1342                         goto failed0;
1343                 }
1344                 memcpy(ni->ni_lnd_tunables, lnd_tunables,
1345                        sizeof(*ni->ni_lnd_tunables));
1346         }
1347
1348         /* If given some LND tunable parameters, parse those now to
1349          * override the values in the NI structure. */
1350         if (conf) {
1351                 if (conf->cfg_config_u.cfg_net.net_peer_rtr_credits >= 0)
1352                         ni->ni_peerrtrcredits =
1353                                 conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
1354                 if (conf->cfg_config_u.cfg_net.net_peer_timeout >= 0)
1355                         ni->ni_peertimeout =
1356                                 conf->cfg_config_u.cfg_net.net_peer_timeout;
1357                 if (conf->cfg_config_u.cfg_net.net_peer_tx_credits >= 0)
1358                         ni->ni_peertxcredits =
1359                                 conf->cfg_config_u.cfg_net.net_peer_tx_credits;
1360                 if (conf->cfg_config_u.cfg_net.net_max_tx_credits >= 0)
1361                         ni->ni_maxtxcredits =
1362                                 conf->cfg_config_u.cfg_net.net_max_tx_credits;
1363         }
1364
1365         rc = (lnd->lnd_startup)(ni);
1366
1367         mutex_unlock(&the_lnet.ln_lnd_mutex);
1368
1369         if (rc != 0) {
1370                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
1371                                    rc, libcfs_lnd2str(lnd->lnd_type));
1372                 lnet_net_lock(LNET_LOCK_EX);
1373                 lnd->lnd_refcount--;
1374                 lnet_net_unlock(LNET_LOCK_EX);
1375                 goto failed0;
1376         }
1377
1378         LASSERT(ni->ni_peertimeout <= 0 || lnd->lnd_query != NULL);
1379
1380         lnet_net_lock(LNET_LOCK_EX);
1381         /* refcount for ln_nis */
1382         lnet_ni_addref_locked(ni, 0);
1383         list_add_tail(&ni->ni_list, &the_lnet.ln_nis);
1384         if (ni->ni_cpts != NULL) {
1385                 lnet_ni_addref_locked(ni, 0);
1386                 list_add_tail(&ni->ni_cptlist, &the_lnet.ln_nis_cpt);
1387         }
1388
1389         lnet_net_unlock(LNET_LOCK_EX);
1390
1391         if (lnd->lnd_type == LOLND) {
1392                 lnet_ni_addref(ni);
1393                 LASSERT(the_lnet.ln_loni == NULL);
1394                 the_lnet.ln_loni = ni;
1395                 return 0;
1396         }
1397
1398         if (ni->ni_peertxcredits == 0 || ni->ni_maxtxcredits == 0) {
1399                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
1400                                    libcfs_lnd2str(lnd->lnd_type),
1401                                    ni->ni_peertxcredits == 0 ?
1402                                         "" : "per-peer ");
1403                 /* shutdown the NI since if we get here then it must've already
1404                  * been started
1405                  */
1406                 lnet_shutdown_lndni(ni);
1407                 return -EINVAL;
1408         }
1409
1410         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
1411                 tq->tq_credits_min =
1412                 tq->tq_credits_max =
1413                 tq->tq_credits = lnet_ni_tq_credits(ni);
1414         }
1415
1416         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
1417                 libcfs_nid2str(ni->ni_nid), ni->ni_peertxcredits,
1418                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
1419                 ni->ni_peerrtrcredits, ni->ni_peertimeout);
1420
1421         return 0;
1422 failed0:
1423         lnet_ni_free(ni);
1424         return rc;
1425 }
1426
1427 static int
1428 lnet_startup_lndnis(struct list_head *nilist)
1429 {
1430         struct lnet_ni          *ni;
1431         int                     rc;
1432         int                     ni_count = 0;
1433
1434         while (!list_empty(nilist)) {
1435                 ni = list_entry(nilist->next, lnet_ni_t, ni_list);
1436                 list_del(&ni->ni_list);
1437                 rc = lnet_startup_lndni(ni, NULL);
1438
1439                 if (rc < 0)
1440                         goto failed;
1441
1442                 ni_count++;
1443         }
1444
1445         return ni_count;
1446 failed:
1447         lnet_shutdown_lndnis();
1448
1449         return rc;
1450 }
1451
1452 /**
1453  * Initialize LNet library.
1454  *
1455  * Automatically called at module loading time. Caller has to call
1456  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
1457  * latter returned 0. It must be called exactly once.
1458  *
1459  * \retval 0 on success
1460  * \retval -ve on failures.
1461  */
1462 int lnet_lib_init(void)
1463 {
1464         int rc;
1465
1466         lnet_assert_wire_constants();
1467
1468         memset(&the_lnet, 0, sizeof(the_lnet));
1469
1470         /* refer to global cfs_cpt_table for now */
1471         the_lnet.ln_cpt_table   = cfs_cpt_table;
1472         the_lnet.ln_cpt_number  = cfs_cpt_number(cfs_cpt_table);
1473
1474         LASSERT(the_lnet.ln_cpt_number > 0);
1475         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
1476                 /* we are under risk of consuming all lh_cookie */
1477                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
1478                        "please change setting of CPT-table and retry\n",
1479                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
1480                 return -E2BIG;
1481         }
1482
1483         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
1484                 the_lnet.ln_cpt_bits++;
1485
1486         rc = lnet_create_locks();
1487         if (rc != 0) {
1488                 CERROR("Can't create LNet global locks: %d\n", rc);
1489                 return rc;
1490         }
1491
1492         the_lnet.ln_refcount = 0;
1493         LNetInvalidateHandle(&the_lnet.ln_rc_eqh);
1494         INIT_LIST_HEAD(&the_lnet.ln_lnds);
1495         INIT_LIST_HEAD(&the_lnet.ln_rcd_zombie);
1496         INIT_LIST_HEAD(&the_lnet.ln_rcd_deathrow);
1497
1498         /* The hash table size is the number of bits it takes to express the set
1499          * ln_num_routes, minus 1 (better to under estimate than over so we
1500          * don't waste memory). */
1501         if (rnet_htable_size <= 0)
1502                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
1503         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
1504                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
1505         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
1506                                            order_base_2(rnet_htable_size) - 1);
1507
1508         /* All LNDs apart from the LOLND are in separate modules.  They
1509          * register themselves when their module loads, and unregister
1510          * themselves when their module is unloaded. */
1511         lnet_register_lnd(&the_lolnd);
1512         return 0;
1513 }
1514
1515 /**
1516  * Finalize LNet library.
1517  *
1518  * \pre lnet_lib_init() called with success.
1519  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
1520  */
1521 void lnet_lib_exit(void)
1522 {
1523         LASSERT(the_lnet.ln_refcount == 0);
1524
1525         while (!list_empty(&the_lnet.ln_lnds))
1526                 lnet_unregister_lnd(list_entry(the_lnet.ln_lnds.next,
1527                                                lnd_t, lnd_list));
1528         lnet_destroy_locks();
1529 }
1530
1531 /**
1532  * Set LNet PID and start LNet interfaces, routing, and forwarding.
1533  *
1534  * Users must call this function at least once before any other functions.
1535  * For each successful call there must be a corresponding call to
1536  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
1537  * ignored.
1538  *
1539  * The PID used by LNet may be different from the one requested.
1540  * See LNetGetId().
1541  *
1542  * \param requested_pid PID requested by the caller.
1543  *
1544  * \return >= 0 on success, and < 0 error code on failures.
1545  */
1546 int
1547 LNetNIInit(lnet_pid_t requested_pid)
1548 {
1549         int                     im_a_router = 0;
1550         int                     rc;
1551         int                     ni_count;
1552         struct lnet_ping_info   *pinfo;
1553         lnet_handle_md_t        md_handle;
1554         struct list_head        net_head;
1555
1556         INIT_LIST_HEAD(&net_head);
1557
1558         mutex_lock(&the_lnet.ln_api_mutex);
1559
1560         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
1561
1562         if (the_lnet.ln_refcount > 0) {
1563                 rc = the_lnet.ln_refcount++;
1564                 mutex_unlock(&the_lnet.ln_api_mutex);
1565                 return rc;
1566         }
1567
1568         rc = lnet_prepare(requested_pid);
1569         if (rc != 0) {
1570                 mutex_unlock(&the_lnet.ln_api_mutex);
1571                 return rc;
1572         }
1573
1574         /* Add in the loopback network */
1575         if (lnet_ni_alloc(LNET_MKNET(LOLND, 0), NULL, &net_head) == NULL) {
1576                 rc = -ENOMEM;
1577                 goto err_empty_list;
1578         }
1579
1580         /* If LNet is being initialized via DLC it is possible
1581          * that the user requests not to load module parameters (ones which
1582          * are supported by DLC) on initialization.  Therefore, make sure not
1583          * to load networks, routes and forwarding from module parameters
1584          * in this case.  On cleanup in case of failure only clean up
1585          * routes if it has been loaded */
1586         if (!the_lnet.ln_nis_from_mod_params) {
1587                 rc = lnet_parse_networks(&net_head,
1588                                          lnet_get_networks());
1589                 if (rc < 0)
1590                         goto err_empty_list;
1591         }
1592
1593         ni_count = lnet_startup_lndnis(&net_head);
1594         if (ni_count < 0) {
1595                 rc = ni_count;
1596                 goto err_empty_list;
1597         }
1598
1599         if (!the_lnet.ln_nis_from_mod_params) {
1600                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
1601                 if (rc != 0)
1602                         goto err_shutdown_lndnis;
1603
1604                 rc = lnet_check_routes();
1605                 if (rc != 0)
1606                         goto err_destroy_routes;
1607
1608                 rc = lnet_rtrpools_alloc(im_a_router);
1609                 if (rc != 0)
1610                         goto err_destroy_routes;
1611         }
1612
1613         rc = lnet_acceptor_start();
1614         if (rc != 0)
1615                 goto err_destroy_routes;
1616
1617         the_lnet.ln_refcount = 1;
1618         /* Now I may use my own API functions... */
1619
1620         rc = lnet_ping_info_setup(&pinfo, &md_handle, ni_count, true);
1621         if (rc != 0)
1622                 goto err_acceptor_stop;
1623
1624         lnet_ping_target_update(pinfo, md_handle);
1625
1626         rc = lnet_router_checker_start();
1627         if (rc != 0)
1628                 goto err_stop_ping;
1629
1630         lnet_fault_init();
1631         lnet_proc_init();
1632
1633         mutex_unlock(&the_lnet.ln_api_mutex);
1634
1635         return 0;
1636
1637 err_stop_ping:
1638         lnet_ping_target_fini();
1639 err_acceptor_stop:
1640         the_lnet.ln_refcount = 0;
1641         lnet_acceptor_stop();
1642 err_destroy_routes:
1643         if (!the_lnet.ln_nis_from_mod_params)
1644                 lnet_destroy_routes();
1645 err_shutdown_lndnis:
1646         lnet_shutdown_lndnis();
1647 err_empty_list:
1648         lnet_unprepare();
1649         LASSERT(rc < 0);
1650         mutex_unlock(&the_lnet.ln_api_mutex);
1651         while (!list_empty(&net_head)) {
1652                 struct lnet_ni *ni;
1653
1654                 ni = list_entry(net_head.next, struct lnet_ni, ni_list);
1655                 list_del_init(&ni->ni_list);
1656                 lnet_ni_free(ni);
1657         }
1658         return rc;
1659 }
1660 EXPORT_SYMBOL(LNetNIInit);
1661
1662 /**
1663  * Stop LNet interfaces, routing, and forwarding.
1664  *
1665  * Users must call this function once for each successful call to LNetNIInit().
1666  * Once the LNetNIFini() operation has been started, the results of pending
1667  * API operations are undefined.
1668  *
1669  * \return always 0 for current implementation.
1670  */
1671 int
1672 LNetNIFini()
1673 {
1674         mutex_lock(&the_lnet.ln_api_mutex);
1675
1676         LASSERT(the_lnet.ln_refcount > 0);
1677
1678         if (the_lnet.ln_refcount != 1) {
1679                 the_lnet.ln_refcount--;
1680         } else {
1681                 LASSERT(!the_lnet.ln_niinit_self);
1682
1683                 lnet_fault_fini();
1684
1685                 lnet_proc_fini();
1686                 lnet_router_checker_stop();
1687                 lnet_ping_target_fini();
1688
1689                 /* Teardown fns that use my own API functions BEFORE here */
1690                 the_lnet.ln_refcount = 0;
1691
1692                 lnet_acceptor_stop();
1693                 lnet_destroy_routes();
1694                 lnet_shutdown_lndnis();
1695                 lnet_unprepare();
1696         }
1697
1698         mutex_unlock(&the_lnet.ln_api_mutex);
1699         return 0;
1700 }
1701 EXPORT_SYMBOL(LNetNIFini);
1702
1703 /**
1704  * Grabs the ni data from the ni structure and fills the out
1705  * parameters
1706  *
1707  * \param[in] ni network        interface structure
1708  * \param[out] cpt_count        the number of cpts the ni is on
1709  * \param[out] nid              Network Interface ID
1710  * \param[out] peer_timeout     NI peer timeout
1711  * \param[out] peer_tx_crdits   NI peer transmit credits
1712  * \param[out] peer_rtr_credits NI peer router credits
1713  * \param[out] max_tx_credits   NI max transmit credit
1714  * \param[out] net_config       Network configuration
1715  */
1716 static void
1717 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_data *config)
1718 {
1719         struct lnet_ioctl_net_config *net_config;
1720         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
1721         size_t min_size, tunable_size = 0;
1722         int i;
1723
1724         if (!ni || !config)
1725                 return;
1726
1727         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
1728         if (!net_config)
1729                 return;
1730
1731         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
1732                      ARRAY_SIZE(net_config->ni_interfaces));
1733
1734         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
1735                 if (!ni->ni_interfaces[i])
1736                         break;
1737
1738                 strncpy(net_config->ni_interfaces[i],
1739                         ni->ni_interfaces[i],
1740                         sizeof(net_config->ni_interfaces[i]));
1741         }
1742
1743         config->cfg_nid = ni->ni_nid;
1744         config->cfg_config_u.cfg_net.net_peer_timeout = ni->ni_peertimeout;
1745         config->cfg_config_u.cfg_net.net_max_tx_credits = ni->ni_maxtxcredits;
1746         config->cfg_config_u.cfg_net.net_peer_tx_credits = ni->ni_peertxcredits;
1747         config->cfg_config_u.cfg_net.net_peer_rtr_credits = ni->ni_peerrtrcredits;
1748
1749         net_config->ni_status = ni->ni_status->ns_status;
1750
1751         if (ni->ni_cpts) {
1752                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
1753
1754                 for (i = 0; i < num_cpts; i++)
1755                         net_config->ni_cpts[i] = ni->ni_cpts[i];
1756
1757                 config->cfg_ncpts = num_cpts;
1758         }
1759
1760         /*
1761          * See if user land tools sent in a newer and larger version
1762          * of struct lnet_tunables than what the kernel uses.
1763          */
1764         min_size = sizeof(*config) + sizeof(*net_config);
1765
1766         if (config->cfg_hdr.ioc_len > min_size)
1767                 tunable_size = config->cfg_hdr.ioc_len - min_size;
1768
1769         /* Don't copy to much data to user space */
1770         min_size = min(tunable_size, sizeof(*ni->ni_lnd_tunables));
1771         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
1772
1773         if (ni->ni_lnd_tunables && lnd_cfg && min_size) {
1774                 memcpy(lnd_cfg, ni->ni_lnd_tunables, min_size);
1775                 config->cfg_config_u.cfg_net.net_interface_count = 1;
1776
1777                 /* Tell user land that kernel side has less data */
1778                 if (tunable_size > sizeof(*ni->ni_lnd_tunables)) {
1779                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
1780                         config->cfg_hdr.ioc_len -= min_size;
1781                 }
1782         }
1783 }
1784
1785 static int
1786 lnet_get_net_config(struct lnet_ioctl_config_data *config)
1787 {
1788         struct lnet_ni *ni;
1789         struct list_head *tmp;
1790         int idx = config->cfg_count;
1791         int rc = -ENOENT;
1792         int cpt, i = 0;
1793
1794         if (unlikely(!config->cfg_bulk))
1795                 return -EINVAL;
1796
1797         cpt = lnet_net_lock_current();
1798
1799         list_for_each(tmp, &the_lnet.ln_nis) {
1800                 if (i++ != idx)
1801                         continue;
1802
1803                 ni = list_entry(tmp, lnet_ni_t, ni_list);
1804                 lnet_ni_lock(ni);
1805                 lnet_fill_ni_info(ni, config);
1806                 lnet_ni_unlock(ni);
1807                 rc = 0;
1808                 break;
1809         }
1810
1811         lnet_net_unlock(cpt);
1812         return rc;
1813 }
1814
1815 int
1816 lnet_dyn_add_ni(lnet_pid_t requested_pid, struct lnet_ioctl_config_data *conf)
1817 {
1818         char                    *nets = conf->cfg_config_u.cfg_net.net_intf;
1819         struct lnet_ping_info   *pinfo;
1820         lnet_handle_md_t        md_handle;
1821         struct lnet_ni          *ni;
1822         struct list_head        net_head;
1823         int                     rc;
1824         lnet_remotenet_t        *rnet;
1825
1826         INIT_LIST_HEAD(&net_head);
1827
1828         /* Create a ni structure for the network string */
1829         rc = lnet_parse_networks(&net_head, nets);
1830         if (rc <= 0)
1831                 return rc == 0 ? -EINVAL : rc;
1832
1833         mutex_lock(&the_lnet.ln_api_mutex);
1834
1835         if (rc > 1) {
1836                 rc = -EINVAL; /* only add one interface per call */
1837                 goto failed0;
1838         }
1839
1840         ni = list_entry(net_head.next, struct lnet_ni, ni_list);
1841
1842         lnet_net_lock(LNET_LOCK_EX);
1843         rnet = lnet_find_net_locked(LNET_NIDNET(ni->ni_nid));
1844         lnet_net_unlock(LNET_LOCK_EX);
1845         /* make sure that the net added doesn't invalidate the current
1846          * configuration LNet is keeping */
1847         if (rnet != NULL) {
1848                 CERROR("Adding net %s will invalidate routing configuration\n",
1849                        nets);
1850                 rc = -EUSERS;
1851                 goto failed0;
1852         }
1853
1854         rc = lnet_ping_info_setup(&pinfo, &md_handle, 1 + lnet_get_ni_count(),
1855                                   false);
1856         if (rc != 0)
1857                 goto failed0;
1858
1859         list_del_init(&ni->ni_list);
1860
1861         rc = lnet_startup_lndni(ni, conf);
1862         if (rc != 0)
1863                 goto failed1;
1864
1865         if (ni->ni_lnd->lnd_accept != NULL) {
1866                 rc = lnet_acceptor_start();
1867                 if (rc < 0) {
1868                         /* shutdown the ni that we just started */
1869                         CERROR("Failed to start up acceptor thread\n");
1870                         lnet_shutdown_lndni(ni);
1871                         goto failed1;
1872                 }
1873         }
1874
1875         lnet_ping_target_update(pinfo, md_handle);
1876         mutex_unlock(&the_lnet.ln_api_mutex);
1877
1878         return 0;
1879
1880 failed1:
1881         lnet_ping_md_unlink(pinfo, &md_handle);
1882         lnet_ping_info_free(pinfo);
1883 failed0:
1884         mutex_unlock(&the_lnet.ln_api_mutex);
1885         while (!list_empty(&net_head)) {
1886                 ni = list_entry(net_head.next, struct lnet_ni, ni_list);
1887                 list_del_init(&ni->ni_list);
1888                 lnet_ni_free(ni);
1889         }
1890         return rc;
1891 }
1892
1893 int
1894 lnet_dyn_del_ni(__u32 net)
1895 {
1896         lnet_ni_t        *ni;
1897         struct lnet_ping_info *pinfo;
1898         lnet_handle_md_t  md_handle;
1899         int               rc;
1900
1901         /* don't allow userspace to shutdown the LOLND */
1902         if (LNET_NETTYP(net) == LOLND)
1903                 return -EINVAL;
1904
1905         mutex_lock(&the_lnet.ln_api_mutex);
1906         /* create and link a new ping info, before removing the old one */
1907         rc = lnet_ping_info_setup(&pinfo, &md_handle,
1908                                   lnet_get_ni_count() - 1, false);
1909         if (rc != 0)
1910                 goto out;
1911
1912         ni = lnet_net2ni(net);
1913         if (ni == NULL) {
1914                 rc = -EINVAL;
1915                 goto failed;
1916         }
1917
1918         /* decrement the reference counter taken by lnet_net2ni() */
1919         lnet_ni_decref_locked(ni, 0);
1920
1921         lnet_shutdown_lndni(ni);
1922
1923         if (lnet_count_acceptor_nis() == 0)
1924                 lnet_acceptor_stop();
1925
1926         lnet_ping_target_update(pinfo, md_handle);
1927         goto out;
1928 failed:
1929         lnet_ping_md_unlink(pinfo, &md_handle);
1930         lnet_ping_info_free(pinfo);
1931 out:
1932         mutex_unlock(&the_lnet.ln_api_mutex);
1933
1934         return rc;
1935 }
1936
1937 /**
1938  * LNet ioctl handler.
1939  *
1940  */
1941 int
1942 LNetCtl(unsigned int cmd, void *arg)
1943 {
1944         struct libcfs_ioctl_data *data = arg;
1945         struct lnet_ioctl_config_data *config;
1946         lnet_process_id_t         id = {0};
1947         lnet_ni_t                *ni;
1948         int                       rc;
1949
1950         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
1951                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
1952
1953         switch (cmd) {
1954         case IOC_LIBCFS_GET_NI:
1955                 rc = LNetGetId(data->ioc_count, &id);
1956                 data->ioc_nid = id.nid;
1957                 return rc;
1958
1959         case IOC_LIBCFS_FAIL_NID:
1960                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
1961
1962         case IOC_LIBCFS_ADD_ROUTE:
1963                 config = arg;
1964
1965                 if (config->cfg_hdr.ioc_len < sizeof(*config))
1966                         return -EINVAL;
1967
1968                 mutex_lock(&the_lnet.ln_api_mutex);
1969                 rc = lnet_add_route(config->cfg_net,
1970                                     config->cfg_config_u.cfg_route.rtr_hop,
1971                                     config->cfg_nid,
1972                                     config->cfg_config_u.cfg_route.
1973                                         rtr_priority);
1974                 if (rc == 0) {
1975                         rc = lnet_check_routes();
1976                         if (rc != 0)
1977                                 lnet_del_route(config->cfg_net,
1978                                                config->cfg_nid);
1979                 }
1980                 mutex_unlock(&the_lnet.ln_api_mutex);
1981                 return rc;
1982
1983         case IOC_LIBCFS_DEL_ROUTE:
1984                 config = arg;
1985
1986                 if (config->cfg_hdr.ioc_len < sizeof(*config))
1987                         return -EINVAL;
1988
1989                 mutex_lock(&the_lnet.ln_api_mutex);
1990                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
1991                 mutex_unlock(&the_lnet.ln_api_mutex);
1992                 return rc;
1993
1994         case IOC_LIBCFS_GET_ROUTE:
1995                 config = arg;
1996
1997                 if (config->cfg_hdr.ioc_len < sizeof(*config))
1998                         return -EINVAL;
1999
2000                 return lnet_get_route(config->cfg_count,
2001                                       &config->cfg_net,
2002                                       &config->cfg_config_u.cfg_route.rtr_hop,
2003                                       &config->cfg_nid,
2004                                       &config->cfg_config_u.cfg_route.rtr_flags,
2005                                       &config->cfg_config_u.cfg_route.
2006                                         rtr_priority);
2007
2008         case IOC_LIBCFS_GET_NET: {
2009                 size_t total = sizeof(*config) +
2010                                sizeof(struct lnet_ioctl_net_config);
2011                 config = arg;
2012
2013                 if (config->cfg_hdr.ioc_len < total)
2014                         return -EINVAL;
2015
2016                 return lnet_get_net_config(config);
2017         }
2018
2019         case IOC_LIBCFS_GET_LNET_STATS:
2020         {
2021                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
2022
2023                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
2024                         return -EINVAL;
2025
2026                 lnet_counters_get(&lnet_stats->st_cntrs);
2027                 return 0;
2028         }
2029
2030         case IOC_LIBCFS_CONFIG_RTR:
2031                 config = arg;
2032
2033                 if (config->cfg_hdr.ioc_len < sizeof(*config))
2034                         return -EINVAL;
2035
2036                 mutex_lock(&the_lnet.ln_api_mutex);
2037                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
2038                         rc = lnet_rtrpools_enable();
2039                         mutex_unlock(&the_lnet.ln_api_mutex);
2040                         return rc;
2041                 }
2042                 lnet_rtrpools_disable();
2043                 mutex_unlock(&the_lnet.ln_api_mutex);
2044                 return 0;
2045
2046         case IOC_LIBCFS_ADD_BUF:
2047                 config = arg;
2048
2049                 if (config->cfg_hdr.ioc_len < sizeof(*config))
2050                         return -EINVAL;
2051
2052                 mutex_lock(&the_lnet.ln_api_mutex);
2053                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
2054                                                 buf_tiny,
2055                                           config->cfg_config_u.cfg_buffers.
2056                                                 buf_small,
2057                                           config->cfg_config_u.cfg_buffers.
2058                                                 buf_large);
2059                 mutex_unlock(&the_lnet.ln_api_mutex);
2060                 return rc;
2061
2062         case IOC_LIBCFS_GET_BUF: {
2063                 struct lnet_ioctl_pool_cfg *pool_cfg;
2064                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
2065
2066                 config = arg;
2067
2068                 if (config->cfg_hdr.ioc_len < total)
2069                         return -EINVAL;
2070
2071                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
2072                 return lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
2073         }
2074
2075         case IOC_LIBCFS_GET_PEER_INFO: {
2076                 struct lnet_ioctl_peer *peer_info = arg;
2077
2078                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
2079                         return -EINVAL;
2080
2081                 return lnet_get_peer_info(
2082                    peer_info->pr_count,
2083                    &peer_info->pr_nid,
2084                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
2085                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
2086                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
2087                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
2088                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
2089                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
2090                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_rtr_credits,
2091                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
2092         }
2093
2094         case IOC_LIBCFS_NOTIFY_ROUTER: {
2095                 unsigned long jiffies_passed;
2096
2097                 jiffies_passed = ktime_get_real_seconds() - data->ioc_u64[0];
2098                 jiffies_passed = cfs_time_seconds(jiffies_passed);
2099
2100                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
2101                                    jiffies - jiffies_passed);
2102         }
2103
2104         case IOC_LIBCFS_LNET_DIST:
2105                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
2106                 if (rc < 0 && rc != -EHOSTUNREACH)
2107                         return rc;
2108
2109                 data->ioc_u32[0] = rc;
2110                 return 0;
2111
2112         case IOC_LIBCFS_TESTPROTOCOMPAT:
2113                 lnet_net_lock(LNET_LOCK_EX);
2114                 the_lnet.ln_testprotocompat = data->ioc_flags;
2115                 lnet_net_unlock(LNET_LOCK_EX);
2116                 return 0;
2117
2118         case IOC_LIBCFS_LNET_FAULT:
2119                 return lnet_fault_ctl(data->ioc_flags, data);
2120
2121         case IOC_LIBCFS_PING:
2122                 id.nid = data->ioc_nid;
2123                 id.pid = data->ioc_u32[0];
2124                 rc = lnet_ping(id, data->ioc_u32[1], /* timeout */
2125                                data->ioc_pbuf1,
2126                                data->ioc_plen1/sizeof(lnet_process_id_t));
2127                 if (rc < 0)
2128                         return rc;
2129                 data->ioc_count = rc;
2130                 return 0;
2131
2132         default:
2133                 ni = lnet_net2ni(data->ioc_net);
2134                 if (ni == NULL)
2135                         return -EINVAL;
2136
2137                 if (ni->ni_lnd->lnd_ctl == NULL)
2138                         rc = -EINVAL;
2139                 else
2140                         rc = ni->ni_lnd->lnd_ctl(ni, cmd, arg);
2141
2142                 lnet_ni_decref(ni);
2143                 return rc;
2144         }
2145         /* not reached */
2146 }
2147 EXPORT_SYMBOL(LNetCtl);
2148
2149 void LNetDebugPeer(lnet_process_id_t id)
2150 {
2151         lnet_debug_peer(id.nid);
2152 }
2153 EXPORT_SYMBOL(LNetDebugPeer);
2154
2155 /**
2156  * Retrieve the lnet_process_id_t ID of LNet interface at \a index. Note that
2157  * all interfaces share a same PID, as requested by LNetNIInit().
2158  *
2159  * \param index Index of the interface to look up.
2160  * \param id On successful return, this location will hold the
2161  * lnet_process_id_t ID of the interface.
2162  *
2163  * \retval 0 If an interface exists at \a index.
2164  * \retval -ENOENT If no interface has been found.
2165  */
2166 int
2167 LNetGetId(unsigned int index, lnet_process_id_t *id)
2168 {
2169         struct lnet_ni   *ni;
2170         struct list_head *tmp;
2171         int               cpt;
2172         int               rc = -ENOENT;
2173
2174         LASSERT(the_lnet.ln_refcount > 0);
2175
2176         cpt = lnet_net_lock_current();
2177
2178         list_for_each(tmp, &the_lnet.ln_nis) {
2179                 if (index-- != 0)
2180                         continue;
2181
2182                 ni = list_entry(tmp, lnet_ni_t, ni_list);
2183
2184                 id->nid = ni->ni_nid;
2185                 id->pid = the_lnet.ln_pid;
2186                 rc = 0;
2187                 break;
2188         }
2189
2190         lnet_net_unlock(cpt);
2191         return rc;
2192 }
2193 EXPORT_SYMBOL(LNetGetId);
2194
2195 /**
2196  * Print a string representation of handle \a h into buffer \a str of
2197  * \a len bytes.
2198  */
2199 void
2200 LNetSnprintHandle(char *str, int len, lnet_handle_any_t h)
2201 {
2202         snprintf(str, len, "%#llx", h.cookie);
2203 }
2204 EXPORT_SYMBOL(LNetSnprintHandle);
2205
2206 static int
2207 lnet_ping(lnet_process_id_t id, int timeout_ms, lnet_process_id_t __user *ids,
2208           int n_ids)
2209 {
2210         lnet_handle_eq_t     eqh;
2211         lnet_handle_md_t     mdh;
2212         lnet_event_t         event;
2213         lnet_md_t            md = { NULL };
2214         int                  which;
2215         int                  unlinked = 0;
2216         int                  replied = 0;
2217         const int            a_long_time = 60000; /* mS */
2218         int                  infosz;
2219         struct lnet_ping_info    *info;
2220         lnet_process_id_t    tmpid;
2221         int                  i;
2222         int                  nob;
2223         int                  rc;
2224         int                  rc2;
2225         sigset_t         blocked;
2226
2227         infosz = offsetof(struct lnet_ping_info, pi_ni[n_ids]);
2228
2229         if (n_ids <= 0 ||
2230             id.nid == LNET_NID_ANY ||
2231             timeout_ms > 500000 ||              /* arbitrary limit! */
2232             n_ids > 20)                         /* arbitrary limit! */
2233                 return -EINVAL;
2234
2235         if (id.pid == LNET_PID_ANY)
2236                 id.pid = LNET_PID_LUSTRE;
2237
2238         LIBCFS_ALLOC(info, infosz);
2239         if (info == NULL)
2240                 return -ENOMEM;
2241
2242         /* NB 2 events max (including any unlink event) */
2243         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
2244         if (rc != 0) {
2245                 CERROR("Can't allocate EQ: %d\n", rc);
2246                 goto out_0;
2247         }
2248
2249         /* initialize md content */
2250         md.start     = info;
2251         md.length    = infosz;
2252         md.threshold = 2; /*GET/REPLY*/
2253         md.max_size  = 0;
2254         md.options   = LNET_MD_TRUNCATE;
2255         md.user_ptr  = NULL;
2256         md.eq_handle = eqh;
2257
2258         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
2259         if (rc != 0) {
2260                 CERROR("Can't bind MD: %d\n", rc);
2261                 goto out_1;
2262         }
2263
2264         rc = LNetGet(LNET_NID_ANY, mdh, id,
2265                      LNET_RESERVED_PORTAL,
2266                      LNET_PROTO_PING_MATCHBITS, 0);
2267
2268         if (rc != 0) {
2269                 /* Don't CERROR; this could be deliberate! */
2270
2271                 rc2 = LNetMDUnlink(mdh);
2272                 LASSERT(rc2 == 0);
2273
2274                 /* NB must wait for the UNLINK event below... */
2275                 unlinked = 1;
2276                 timeout_ms = a_long_time;
2277         }
2278
2279         do {
2280                 /* MUST block for unlink to complete */
2281                 if (unlinked)
2282                         blocked = cfs_block_allsigs();
2283
2284                 rc2 = LNetEQPoll(&eqh, 1, timeout_ms, &event, &which);
2285
2286                 if (unlinked)
2287                         cfs_restore_sigs(blocked);
2288
2289                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
2290                        (rc2 <= 0) ? -1 : event.type,
2291                        (rc2 <= 0) ? -1 : event.status,
2292                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
2293
2294                 LASSERT(rc2 != -EOVERFLOW);     /* can't miss anything */
2295
2296                 if (rc2 <= 0 || event.status != 0) {
2297                         /* timeout or error */
2298                         if (!replied && rc == 0)
2299                                 rc = (rc2 < 0) ? rc2 :
2300                                      (rc2 == 0) ? -ETIMEDOUT :
2301                                      event.status;
2302
2303                         if (!unlinked) {
2304                                 /* Ensure completion in finite time... */
2305                                 LNetMDUnlink(mdh);
2306                                 /* No assertion (racing with network) */
2307                                 unlinked = 1;
2308                                 timeout_ms = a_long_time;
2309                         } else if (rc2 == 0) {
2310                                 /* timed out waiting for unlink */
2311                                 CWARN("ping %s: late network completion\n",
2312                                       libcfs_id2str(id));
2313                         }
2314                 } else if (event.type == LNET_EVENT_REPLY) {
2315                         replied = 1;
2316                         rc = event.mlength;
2317                 }
2318
2319         } while (rc2 <= 0 || !event.unlinked);
2320
2321         if (!replied) {
2322                 if (rc >= 0)
2323                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
2324                               libcfs_id2str(id));
2325                 rc = -EIO;
2326                 goto out_1;
2327         }
2328
2329         nob = rc;
2330         LASSERT(nob >= 0 && nob <= infosz);
2331
2332         rc = -EPROTO;                           /* if I can't parse... */
2333
2334         if (nob < 8) {
2335                 /* can't check magic/version */
2336                 CERROR("%s: ping info too short %d\n",
2337                        libcfs_id2str(id), nob);
2338                 goto out_1;
2339         }
2340
2341         if (info->pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
2342                 lnet_swap_pinginfo(info);
2343         } else if (info->pi_magic != LNET_PROTO_PING_MAGIC) {
2344                 CERROR("%s: Unexpected magic %08x\n",
2345                        libcfs_id2str(id), info->pi_magic);
2346                 goto out_1;
2347         }
2348
2349         if ((info->pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
2350                 CERROR("%s: ping w/o NI status: 0x%x\n",
2351                        libcfs_id2str(id), info->pi_features);
2352                 goto out_1;
2353         }
2354
2355         if (nob < offsetof(struct lnet_ping_info, pi_ni[0])) {
2356                 CERROR("%s: Short reply %d(%d min)\n", libcfs_id2str(id),
2357                        nob, (int)offsetof(struct lnet_ping_info, pi_ni[0]));
2358                 goto out_1;
2359         }
2360
2361         if (info->pi_nnis < n_ids)
2362                 n_ids = info->pi_nnis;
2363
2364         if (nob < offsetof(struct lnet_ping_info, pi_ni[n_ids])) {
2365                 CERROR("%s: Short reply %d(%d expected)\n", libcfs_id2str(id),
2366                        nob, (int)offsetof(struct lnet_ping_info, pi_ni[n_ids]));
2367                 goto out_1;
2368         }
2369
2370         rc = -EFAULT;                           /* If I SEGV... */
2371
2372         memset(&tmpid, 0, sizeof(tmpid));
2373         for (i = 0; i < n_ids; i++) {
2374                 tmpid.pid = info->pi_pid;
2375                 tmpid.nid = info->pi_ni[i].ns_nid;
2376                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
2377                         goto out_1;
2378         }
2379         rc = info->pi_nnis;
2380
2381  out_1:
2382         rc2 = LNetEQFree(eqh);
2383         if (rc2 != 0)
2384                 CERROR("rc2 %d\n", rc2);
2385         LASSERT(rc2 == 0);
2386
2387  out_0:
2388         LIBCFS_FREE(info, infosz);
2389         return rc;
2390 }