Whamcloud - gitweb
LU-56 lnet: eliminate a few locking dance in LNet
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, Whamcloud, Inc.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 #define DEBUG_SUBSYSTEM S_LNET
38 #include <lnet/lib-lnet.h>
39
40 #ifdef __KERNEL__
41 #define D_LNI D_CONSOLE
42 #else
43 #define D_LNI D_CONFIG
44 #endif
45
46 lnet_t      the_lnet;                           /* THE state of the network */
47
48 #ifdef __KERNEL__
49
50 static char *ip2nets = "";
51 CFS_MODULE_PARM(ip2nets, "s", charp, 0444,
52                 "LNET network <- IP table");
53
54 static char *networks = "";
55 CFS_MODULE_PARM(networks, "s", charp, 0444,
56                 "local networks");
57
58 static char *routes = "";
59 CFS_MODULE_PARM(routes, "s", charp, 0444,
60                 "routes to non-local networks");
61
62 char *
63 lnet_get_routes(void)
64 {
65         return routes;
66 }
67
68 char *
69 lnet_get_networks(void)
70 {
71         char   *nets;
72         int     rc;
73
74         if (*networks != 0 && *ip2nets != 0) {
75                 LCONSOLE_ERROR_MSG(0x101, "Please specify EITHER 'networks' or "
76                                    "'ip2nets' but not both at once\n");
77                 return NULL;
78         }
79
80         if (*ip2nets != 0) {
81                 rc = lnet_parse_ip2nets(&nets, ip2nets);
82                 return (rc == 0) ? nets : NULL;
83         }
84
85         if (*networks != 0)
86                 return networks;
87
88         return "tcp";
89 }
90
91 void
92 lnet_init_locks(void)
93 {
94         cfs_spin_lock_init (&the_lnet.ln_lock);
95         cfs_waitq_init(&the_lnet.ln_eq_waitq);
96         cfs_mutex_init(&the_lnet.ln_lnd_mutex);
97         cfs_mutex_init(&the_lnet.ln_api_mutex);
98 }
99
100 void
101 lnet_fini_locks(void)
102 {
103 }
104
105 #else
106
107 char *
108 lnet_get_routes(void)
109 {
110         char *str = getenv("LNET_ROUTES");
111
112         return (str == NULL) ? "" : str;
113 }
114
115 char *
116 lnet_get_networks (void)
117 {
118         static char       default_networks[256];
119         char             *networks = getenv ("LNET_NETWORKS");
120         char             *ip2nets  = getenv ("LNET_IP2NETS");
121         char             *str;
122         char             *sep;
123         int               len;
124         int               nob;
125         int               rc;
126         cfs_list_t       *tmp;
127
128 #ifdef NOT_YET
129         if (networks != NULL && ip2nets != NULL) {
130                 LCONSOLE_ERROR_MSG(0x103, "Please set EITHER 'LNET_NETWORKS' or"
131                                    " 'LNET_IP2NETS' but not both at once\n");
132                 return NULL;
133         }
134
135         if (ip2nets != NULL) {
136                 rc = lnet_parse_ip2nets(&networks, ip2nets);
137                 return (rc == 0) ? networks : NULL;
138         }
139 #else
140         SET_BUT_UNUSED(ip2nets);
141         SET_BUT_UNUSED(rc);
142 #endif
143         if (networks != NULL)
144                 return networks;
145
146         /* In userland, the default 'networks=' is the list of known net types */
147
148         len = sizeof(default_networks);
149         str = default_networks;
150         *str = 0;
151         sep = "";
152
153         cfs_list_for_each (tmp, &the_lnet.ln_lnds) {
154                 lnd_t *lnd = cfs_list_entry(tmp, lnd_t, lnd_list);
155
156                 nob = snprintf(str, len, "%s%s", sep,
157                                libcfs_lnd2str(lnd->lnd_type));
158                 len -= nob;
159                 if (len < 0) {
160                         /* overflowed the string; leave it where it was */
161                         *str = 0;
162                         break;
163                 }
164
165                 str += nob;
166                 sep = ",";
167         }
168
169         return default_networks;
170 }
171
172 # ifndef HAVE_LIBPTHREAD
173
174 void lnet_init_locks(void)
175 {
176         the_lnet.ln_lock = 0;
177         the_lnet.ln_lnd_mutex = 0;
178         the_lnet.ln_api_mutex = 0;
179 }
180
181 void lnet_fini_locks(void)
182 {
183         LASSERT (the_lnet.ln_api_mutex == 0);
184         LASSERT (the_lnet.ln_lnd_mutex == 0);
185         LASSERT (the_lnet.ln_lock == 0);
186 }
187
188 # else
189
190 void lnet_init_locks(void)
191 {
192         pthread_cond_init(&the_lnet.ln_eq_cond, NULL);
193         pthread_mutex_init(&the_lnet.ln_lock, NULL);
194         pthread_mutex_init(&the_lnet.ln_lnd_mutex, NULL);
195         pthread_mutex_init(&the_lnet.ln_api_mutex, NULL);
196 }
197
198 void lnet_fini_locks(void)
199 {
200         pthread_mutex_destroy(&the_lnet.ln_api_mutex);
201         pthread_mutex_destroy(&the_lnet.ln_lnd_mutex);
202         pthread_mutex_destroy(&the_lnet.ln_lock);
203         pthread_cond_destroy(&the_lnet.ln_eq_cond);
204 }
205
206 # endif
207 #endif
208
209 void lnet_assert_wire_constants (void)
210 {
211         /* Wire protocol assertions generated by 'wirecheck'
212          * running on Linux robert.bartonsoftware.com 2.6.8-1.521
213          * #1 Mon Aug 16 09:01:18 EDT 2004 i686 athlon i386 GNU/Linux
214          * with gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7) */
215
216         /* Constants... */
217         CLASSERT (LNET_PROTO_TCP_MAGIC == 0xeebc0ded);
218         CLASSERT (LNET_PROTO_TCP_VERSION_MAJOR == 1);
219         CLASSERT (LNET_PROTO_TCP_VERSION_MINOR == 0);
220         CLASSERT (LNET_MSG_ACK == 0);
221         CLASSERT (LNET_MSG_PUT == 1);
222         CLASSERT (LNET_MSG_GET == 2);
223         CLASSERT (LNET_MSG_REPLY == 3);
224         CLASSERT (LNET_MSG_HELLO == 4);
225
226         /* Checks for struct ptl_handle_wire_t */
227         CLASSERT ((int)sizeof(lnet_handle_wire_t) == 16);
228         CLASSERT ((int)offsetof(lnet_handle_wire_t, wh_interface_cookie) == 0);
229         CLASSERT ((int)sizeof(((lnet_handle_wire_t *)0)->wh_interface_cookie) == 8);
230         CLASSERT ((int)offsetof(lnet_handle_wire_t, wh_object_cookie) == 8);
231         CLASSERT ((int)sizeof(((lnet_handle_wire_t *)0)->wh_object_cookie) == 8);
232
233         /* Checks for struct lnet_magicversion_t */
234         CLASSERT ((int)sizeof(lnet_magicversion_t) == 8);
235         CLASSERT ((int)offsetof(lnet_magicversion_t, magic) == 0);
236         CLASSERT ((int)sizeof(((lnet_magicversion_t *)0)->magic) == 4);
237         CLASSERT ((int)offsetof(lnet_magicversion_t, version_major) == 4);
238         CLASSERT ((int)sizeof(((lnet_magicversion_t *)0)->version_major) == 2);
239         CLASSERT ((int)offsetof(lnet_magicversion_t, version_minor) == 6);
240         CLASSERT ((int)sizeof(((lnet_magicversion_t *)0)->version_minor) == 2);
241
242         /* Checks for struct lnet_hdr_t */
243         CLASSERT ((int)sizeof(lnet_hdr_t) == 72);
244         CLASSERT ((int)offsetof(lnet_hdr_t, dest_nid) == 0);
245         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->dest_nid) == 8);
246         CLASSERT ((int)offsetof(lnet_hdr_t, src_nid) == 8);
247         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->src_nid) == 8);
248         CLASSERT ((int)offsetof(lnet_hdr_t, dest_pid) == 16);
249         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->dest_pid) == 4);
250         CLASSERT ((int)offsetof(lnet_hdr_t, src_pid) == 20);
251         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->src_pid) == 4);
252         CLASSERT ((int)offsetof(lnet_hdr_t, type) == 24);
253         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->type) == 4);
254         CLASSERT ((int)offsetof(lnet_hdr_t, payload_length) == 28);
255         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->payload_length) == 4);
256         CLASSERT ((int)offsetof(lnet_hdr_t, msg) == 32);
257         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg) == 40);
258
259         /* Ack */
260         CLASSERT ((int)offsetof(lnet_hdr_t, msg.ack.dst_wmd) == 32);
261         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.ack.dst_wmd) == 16);
262         CLASSERT ((int)offsetof(lnet_hdr_t, msg.ack.match_bits) == 48);
263         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.ack.match_bits) == 8);
264         CLASSERT ((int)offsetof(lnet_hdr_t, msg.ack.mlength) == 56);
265         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.ack.mlength) == 4);
266
267         /* Put */
268         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.ack_wmd) == 32);
269         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.ack_wmd) == 16);
270         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.match_bits) == 48);
271         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.match_bits) == 8);
272         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.hdr_data) == 56);
273         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.hdr_data) == 8);
274         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.ptl_index) == 64);
275         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.ptl_index) == 4);
276         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.offset) == 68);
277         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.offset) == 4);
278
279         /* Get */
280         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.return_wmd) == 32);
281         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.return_wmd) == 16);
282         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.match_bits) == 48);
283         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.match_bits) == 8);
284         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.ptl_index) == 56);
285         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.ptl_index) == 4);
286         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.src_offset) == 60);
287         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.src_offset) == 4);
288         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.sink_length) == 64);
289         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.sink_length) == 4);
290
291         /* Reply */
292         CLASSERT ((int)offsetof(lnet_hdr_t, msg.reply.dst_wmd) == 32);
293         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.reply.dst_wmd) == 16);
294
295         /* Hello */
296         CLASSERT ((int)offsetof(lnet_hdr_t, msg.hello.incarnation) == 32);
297         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.hello.incarnation) == 8);
298         CLASSERT ((int)offsetof(lnet_hdr_t, msg.hello.type) == 40);
299         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.hello.type) == 4);
300 }
301
302 lnd_t *
303 lnet_find_lnd_by_type (int type)
304 {
305         lnd_t              *lnd;
306         cfs_list_t         *tmp;
307
308         /* holding lnd mutex */
309         cfs_list_for_each (tmp, &the_lnet.ln_lnds) {
310                 lnd = cfs_list_entry(tmp, lnd_t, lnd_list);
311
312                 if ((int)lnd->lnd_type == type)
313                         return lnd;
314         }
315
316         return NULL;
317 }
318
319 void
320 lnet_register_lnd (lnd_t *lnd)
321 {
322         LNET_MUTEX_LOCK(&the_lnet.ln_lnd_mutex);
323
324         LASSERT (the_lnet.ln_init);
325         LASSERT (libcfs_isknown_lnd(lnd->lnd_type));
326         LASSERT (lnet_find_lnd_by_type(lnd->lnd_type) == NULL);
327
328         cfs_list_add_tail (&lnd->lnd_list, &the_lnet.ln_lnds);
329         lnd->lnd_refcount = 0;
330
331         CDEBUG(D_NET, "%s LND registered\n", libcfs_lnd2str(lnd->lnd_type));
332
333         LNET_MUTEX_UNLOCK(&the_lnet.ln_lnd_mutex);
334 }
335
336 void
337 lnet_unregister_lnd (lnd_t *lnd)
338 {
339         LNET_MUTEX_LOCK(&the_lnet.ln_lnd_mutex);
340
341         LASSERT (the_lnet.ln_init);
342         LASSERT (lnet_find_lnd_by_type(lnd->lnd_type) == lnd);
343         LASSERT (lnd->lnd_refcount == 0);
344
345         cfs_list_del (&lnd->lnd_list);
346         CDEBUG(D_NET, "%s LND unregistered\n", libcfs_lnd2str(lnd->lnd_type));
347
348         LNET_MUTEX_UNLOCK(&the_lnet.ln_lnd_mutex);
349 }
350
351 #ifdef LNET_USE_LIB_FREELIST
352
353 int
354 lnet_freelist_init (lnet_freelist_t *fl, int n, int size)
355 {
356         char *space;
357
358         LASSERT (n > 0);
359
360         size += offsetof (lnet_freeobj_t, fo_contents);
361
362         LIBCFS_ALLOC(space, n * size);
363         if (space == NULL)
364                 return (-ENOMEM);
365
366         CFS_INIT_LIST_HEAD (&fl->fl_list);
367         fl->fl_objs = space;
368         fl->fl_nobjs = n;
369         fl->fl_objsize = size;
370
371         do
372         {
373                 memset (space, 0, size);
374                 cfs_list_add ((cfs_list_t *)space, &fl->fl_list);
375                 space += size;
376         } while (--n != 0);
377
378         return (0);
379 }
380
381 void
382 lnet_freelist_fini (lnet_freelist_t *fl)
383 {
384         cfs_list_t       *el;
385         int               count;
386
387         if (fl->fl_nobjs == 0)
388                 return;
389
390         count = 0;
391         for (el = fl->fl_list.next; el != &fl->fl_list; el = el->next)
392                 count++;
393
394         LASSERT (count == fl->fl_nobjs);
395
396         LIBCFS_FREE(fl->fl_objs, fl->fl_nobjs * fl->fl_objsize);
397         memset (fl, 0, sizeof (*fl));
398 }
399
400 #endif /* LNET_USE_LIB_FREELIST */
401
402 __u64
403 lnet_create_interface_cookie (void)
404 {
405         /* NB the interface cookie in wire handles guards against delayed
406          * replies and ACKs appearing valid after reboot. Initialisation time,
407          * even if it's only implemented to millisecond resolution is probably
408          * easily good enough. */
409         struct timeval tv;
410         __u64          cookie;
411 #ifndef __KERNEL__
412         int            rc = gettimeofday (&tv, NULL);
413         LASSERT (rc == 0);
414 #else
415         cfs_gettimeofday(&tv);
416 #endif
417         cookie = tv.tv_sec;
418         cookie *= 1000000;
419         cookie += tv.tv_usec;
420         return cookie;
421 }
422
423 static char *
424 lnet_res_type2str(int type)
425 {
426         switch (type) {
427         default:
428                 LBUG();
429         case LNET_COOKIE_TYPE_MD:
430                 return "MD";
431         case LNET_COOKIE_TYPE_ME:
432                 return "ME";
433         case LNET_COOKIE_TYPE_EQ:
434                 return "EQ";
435         }
436 }
437
438 void
439 lnet_res_container_cleanup(struct lnet_res_container *rec)
440 {
441         int     count = 0;
442
443         if (rec->rec_type == 0) /* not set yet, it's a uninitialized */
444                 return;
445
446         while (!cfs_list_empty(&rec->rec_active)) {
447                 cfs_list_t *e = rec->rec_active.next;
448
449                 cfs_list_del_init(e);
450                 if (rec->rec_type == LNET_COOKIE_TYPE_EQ) {
451                         lnet_eq_free(cfs_list_entry(e, lnet_eq_t, eq_list));
452
453                 } else if (rec->rec_type == LNET_COOKIE_TYPE_MD) {
454                         lnet_md_free(cfs_list_entry(e, lnet_libmd_t, md_list));
455
456                 } else { /* NB: Active MEs should be attached on portals */
457                         LBUG();
458                 }
459                 count++;
460         }
461
462         if (count > 0) {
463                 /* Found alive MD/ME/EQ, user really should unlink/free
464                  * all of them before finalize LNet, but if someone didn't,
465                  * we have to recycle garbage for him */
466                 CERROR("%d active elements on exit of %s container\n",
467                        count, lnet_res_type2str(rec->rec_type));
468         }
469
470 #ifdef LNET_USE_LIB_FREELIST
471         lnet_freelist_fini(&rec->rec_freelist);
472 #endif
473         if (rec->rec_lh_hash != NULL) {
474                 LIBCFS_FREE(rec->rec_lh_hash,
475                             LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
476                 rec->rec_lh_hash = NULL;
477         }
478
479         rec->rec_type = 0; /* mark it as finalized */
480 }
481
482 int
483 lnet_res_container_setup(struct lnet_res_container *rec,
484                          int type, int objnum, int objsz)
485 {
486         int     rc = 0;
487         int     i;
488
489         LASSERT(rec->rec_type == 0);
490
491         rec->rec_type = type;
492         CFS_INIT_LIST_HEAD(&rec->rec_active);
493
494 #ifdef LNET_USE_LIB_FREELIST
495         memset(&rec->rec_freelist, 0, sizeof(rec->rec_freelist));
496         rc = lnet_freelist_init(&rec->rec_freelist, objnum, objsz);
497         if (rc != 0)
498                 goto out;
499 #endif
500         rec->rec_lh_cookie = type;
501
502         /* Arbitrary choice of hash table size */
503         LIBCFS_ALLOC(rec->rec_lh_hash,
504                      LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
505         if (rec->rec_lh_hash == NULL) {
506                 rc = -ENOMEM;
507                 goto out;
508         }
509
510         for (i = 0; i < LNET_LH_HASH_SIZE; i++)
511                 CFS_INIT_LIST_HEAD(&rec->rec_lh_hash[i]);
512
513         return 0;
514
515 out:
516         CERROR("Failed to setup %s resource container\n",
517                lnet_res_type2str(type));
518         lnet_res_container_cleanup(rec);
519         return rc;
520 }
521
522 lnet_libhandle_t *
523 lnet_res_lh_lookup(struct lnet_res_container *rec, __u64 cookie)
524 {
525         /* ALWAYS called with lnet_res_lock held */
526         cfs_list_t              *head;
527         lnet_libhandle_t        *lh;
528         unsigned int            hash;
529
530         if ((cookie & (LNET_COOKIE_TYPES - 1)) != rec->rec_type)
531                 return NULL;
532
533         hash = cookie >> LNET_COOKIE_TYPE_BITS;
534         head = &rec->rec_lh_hash[hash & LNET_LH_HASH_MASK];
535
536         cfs_list_for_each_entry(lh, head, lh_hash_chain) {
537                 if (lh->lh_cookie == cookie)
538                         return lh;
539         }
540
541         return NULL;
542 }
543
544 void
545 lnet_res_lh_initialize(struct lnet_res_container *rec, lnet_libhandle_t *lh)
546 {
547         /* ALWAYS called with lnet_res_lock held */
548         unsigned int    ibits = LNET_COOKIE_TYPE_BITS;
549         unsigned int    hash;
550
551         lh->lh_cookie = rec->rec_lh_cookie;
552         rec->rec_lh_cookie += 1 << ibits;
553
554         hash = (lh->lh_cookie >> ibits) & LNET_LH_HASH_MASK;
555
556         cfs_list_add(&lh->lh_hash_chain, &rec->rec_lh_hash[hash]);
557 }
558
559 #ifndef __KERNEL__
560 /**
561  * Reserved API - do not use.
562  * Temporary workaround to allow uOSS and test programs force server
563  * mode in userspace. See comments near ln_server_mode_flag in
564  * lnet/lib-types.h */
565
566 void
567 lnet_server_mode() {
568         the_lnet.ln_server_mode_flag = 1;
569 }
570 #endif
571
572 int
573 lnet_prepare(lnet_pid_t requested_pid)
574 {
575         /* Prepare to bring up the network */
576         int               rc = 0;
577
578         LASSERT (the_lnet.ln_refcount == 0);
579
580         the_lnet.ln_routing = 0;
581
582 #ifdef __KERNEL__
583         LASSERT ((requested_pid & LNET_PID_USERFLAG) == 0);
584         the_lnet.ln_pid = requested_pid;
585 #else
586         if (the_lnet.ln_server_mode_flag) {/* server case (uOSS) */
587                 LASSERT ((requested_pid & LNET_PID_USERFLAG) == 0);
588
589                 if (cfs_curproc_uid())/* Only root can run user-space server */
590                         return -EPERM;
591                 the_lnet.ln_pid = requested_pid;
592
593         } else {/* client case (liblustre) */
594
595                 /* My PID must be unique on this node and flag I'm userspace */
596                 the_lnet.ln_pid = getpid() | LNET_PID_USERFLAG;
597         }
598 #endif
599
600         memset(&the_lnet.ln_counters, 0,
601                sizeof(the_lnet.ln_counters));
602
603         CFS_INIT_LIST_HEAD (&the_lnet.ln_test_peers);
604         CFS_INIT_LIST_HEAD (&the_lnet.ln_nis);
605         CFS_INIT_LIST_HEAD (&the_lnet.ln_zombie_nis);
606         CFS_INIT_LIST_HEAD (&the_lnet.ln_remote_nets);
607         CFS_INIT_LIST_HEAD (&the_lnet.ln_routers);
608
609         the_lnet.ln_interface_cookie = lnet_create_interface_cookie();
610
611         lnet_init_rtrpools();
612
613         rc = lnet_peer_table_create();
614         if (rc != 0)
615                 goto failed0;
616
617         /* NB: we will have instance of message container per CPT soon */
618         rc = lnet_msg_container_setup(&the_lnet.ln_msg_container);
619         if (rc != 0)
620                 goto failed1;
621
622         rc = lnet_res_container_setup(&the_lnet.ln_eq_container,
623                                       LNET_COOKIE_TYPE_EQ, LNET_FL_MAX_EQS,
624                                       sizeof(lnet_eq_t));
625         if (rc != 0) {
626                 CERROR("Failed to create EQ container for LNet: %d\n", rc);
627                 goto failed2;
628         }
629
630         /* NB: we will have instance of ME container per CPT soon */
631         rc = lnet_res_container_setup(&the_lnet.ln_me_container,
632                                       LNET_COOKIE_TYPE_ME, LNET_FL_MAX_MES,
633                                       sizeof(lnet_me_t));
634         if (rc != 0) {
635                 CERROR("Failed to create ME container for LNet: %d\n", rc);
636                 goto failed3;
637         }
638
639         /* NB: we will have instance of MD container per CPT soon */
640         rc = lnet_res_container_setup(&the_lnet.ln_md_container,
641                                       LNET_COOKIE_TYPE_MD, LNET_FL_MAX_MDS,
642                                       sizeof(lnet_libmd_t));
643         if (rc != 0) {
644                 CERROR("Failed to create MD container for LNet: %d\n", rc);
645                 goto failed3;
646         }
647
648         rc = lnet_portals_create();
649         if (rc != 0) {
650                 CERROR("Failed to create portals for LNet: %d\n", rc);
651                 goto failed3;
652         }
653
654         return 0;
655
656  failed3:
657         /* NB: lnet_res_container_cleanup is safe to call for
658          * uninitialized container */
659         lnet_res_container_cleanup(&the_lnet.ln_md_container);
660         lnet_res_container_cleanup(&the_lnet.ln_me_container);
661         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
662  failed2:
663         lnet_msg_container_cleanup(&the_lnet.ln_msg_container);
664  failed1:
665         lnet_peer_table_destroy();
666  failed0:
667         return rc;
668 }
669
670 int
671 lnet_unprepare (void)
672 {
673         /* NB no LNET_LOCK since this is the last reference.  All LND instances
674          * have shut down already, so it is safe to unlink and free all
675          * descriptors, even those that appear committed to a network op (eg MD
676          * with non-zero pending count) */
677
678         lnet_fail_nid(LNET_NID_ANY, 0);
679
680         LASSERT (cfs_list_empty(&the_lnet.ln_test_peers));
681         LASSERT (the_lnet.ln_refcount == 0);
682         LASSERT (cfs_list_empty(&the_lnet.ln_nis));
683         LASSERT (cfs_list_empty(&the_lnet.ln_zombie_nis));
684         LASSERT (the_lnet.ln_nzombie_nis == 0);
685
686         lnet_portals_destroy();
687
688         lnet_res_container_cleanup(&the_lnet.ln_md_container);
689         lnet_res_container_cleanup(&the_lnet.ln_me_container);
690         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
691
692         lnet_free_rtrpools();
693         lnet_msg_container_cleanup(&the_lnet.ln_msg_container);
694         lnet_peer_table_destroy();
695
696         return 0;
697 }
698
699 lnet_ni_t  *
700 lnet_net2ni_locked (__u32 net)
701 {
702         cfs_list_t       *tmp;
703         lnet_ni_t        *ni;
704
705         cfs_list_for_each (tmp, &the_lnet.ln_nis) {
706                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
707
708                 if (LNET_NIDNET(ni->ni_nid) == net) {
709                         lnet_ni_addref_locked(ni);
710                         return ni;
711                 }
712         }
713
714         return NULL;
715 }
716
717 int
718 lnet_islocalnet (__u32 net)
719 {
720         lnet_ni_t        *ni;
721
722         LNET_LOCK();
723         ni = lnet_net2ni_locked(net);
724         if (ni != NULL)
725                 lnet_ni_decref_locked(ni);
726         LNET_UNLOCK();
727
728         return ni != NULL;
729 }
730
731 lnet_ni_t  *
732 lnet_nid2ni_locked (lnet_nid_t nid)
733 {
734         cfs_list_t       *tmp;
735         lnet_ni_t        *ni;
736
737         cfs_list_for_each (tmp, &the_lnet.ln_nis) {
738                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
739
740                 if (ni->ni_nid == nid) {
741                         lnet_ni_addref_locked(ni);
742                         return ni;
743                 }
744         }
745
746         return NULL;
747 }
748
749 int
750 lnet_islocalnid (lnet_nid_t nid)
751 {
752         lnet_ni_t     *ni;
753
754         LNET_LOCK();
755         ni = lnet_nid2ni_locked(nid);
756         if (ni != NULL)
757                 lnet_ni_decref_locked(ni);
758         LNET_UNLOCK();
759
760         return ni != NULL;
761 }
762
763 int
764 lnet_count_acceptor_nis (void)
765 {
766         /* Return the # of NIs that need the acceptor. */
767         int            count = 0;
768 #if defined(__KERNEL__) || defined(HAVE_LIBPTHREAD)
769         cfs_list_t    *tmp;
770         lnet_ni_t     *ni;
771
772         LNET_LOCK();
773         cfs_list_for_each (tmp, &the_lnet.ln_nis) {
774                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
775
776                 if (ni->ni_lnd->lnd_accept != NULL)
777                         count++;
778         }
779
780         LNET_UNLOCK();
781
782 #endif /* defined(__KERNEL__) || defined(HAVE_LIBPTHREAD) */
783         return count;
784 }
785
786 void
787 lnet_shutdown_lndnis (void)
788 {
789         int                i;
790         int                islo;
791         lnet_ni_t         *ni;
792
793         /* NB called holding the global mutex */
794
795         /* All quiet on the API front */
796         LASSERT (!the_lnet.ln_shutdown);
797         LASSERT (the_lnet.ln_refcount == 0);
798         LASSERT (cfs_list_empty(&the_lnet.ln_zombie_nis));
799         LASSERT (the_lnet.ln_nzombie_nis == 0);
800         LASSERT (cfs_list_empty(&the_lnet.ln_remote_nets));
801
802         LNET_LOCK();
803         the_lnet.ln_shutdown = 1;               /* flag shutdown */
804
805         /* Unlink NIs from the global table */
806         while (!cfs_list_empty(&the_lnet.ln_nis)) {
807                 ni = cfs_list_entry(the_lnet.ln_nis.next,
808                                     lnet_ni_t, ni_list);
809                 cfs_list_del (&ni->ni_list);
810
811                 the_lnet.ln_nzombie_nis++;
812                 lnet_ni_decref_locked(ni); /* drop ln_nis' ref */
813         }
814
815         /* Drop the cached eqwait NI. */
816         if (the_lnet.ln_eq_waitni != NULL) {
817                 lnet_ni_decref_locked(the_lnet.ln_eq_waitni);
818                 the_lnet.ln_eq_waitni = NULL;
819         }
820
821         /* Drop the cached loopback NI. */
822         if (the_lnet.ln_loni != NULL) {
823                 lnet_ni_decref_locked(the_lnet.ln_loni);
824                 the_lnet.ln_loni = NULL;
825         }
826
827         LNET_UNLOCK();
828
829         /* Clear lazy portals and drop delayed messages which hold refs
830          * on their lnet_msg_t::msg_rxpeer */
831         for (i = 0; i < the_lnet.ln_nportals; i++)
832                 LNetClearLazyPortal(i);
833
834         /* Clear the peer table and wait for all peers to go (they hold refs on
835          * their NIs) */
836         lnet_peer_table_cleanup();
837
838         LNET_LOCK();
839         /* Now wait for the NI's I just nuked to show up on ln_zombie_nis
840          * and shut them down in guaranteed thread context */
841         i = 2;
842         while (the_lnet.ln_nzombie_nis != 0) {
843
844                 while (cfs_list_empty(&the_lnet.ln_zombie_nis)) {
845                         LNET_UNLOCK();
846                         ++i;
847                         if ((i & (-i)) == i)
848                                 CDEBUG(D_WARNING,"Waiting for %d zombie NIs\n",
849                                        the_lnet.ln_nzombie_nis);
850                         cfs_pause(cfs_time_seconds(1));
851                         LNET_LOCK();
852                 }
853
854                 ni = cfs_list_entry(the_lnet.ln_zombie_nis.next,
855                                     lnet_ni_t, ni_list);
856                 cfs_list_del(&ni->ni_list);
857                 ni->ni_lnd->lnd_refcount--;
858
859                 LNET_UNLOCK();
860
861                 islo = ni->ni_lnd->lnd_type == LOLND;
862
863                 LASSERT (!cfs_in_interrupt ());
864                 (ni->ni_lnd->lnd_shutdown)(ni);
865
866                 /* can't deref lnd anymore now; it might have unregistered
867                  * itself...  */
868
869                 if (!islo)
870                         CDEBUG(D_LNI, "Removed LNI %s\n",
871                                libcfs_nid2str(ni->ni_nid));
872
873                 LIBCFS_FREE(ni, sizeof(*ni));
874
875                 LNET_LOCK();
876                 the_lnet.ln_nzombie_nis--;
877         }
878
879         the_lnet.ln_shutdown = 0;
880         LNET_UNLOCK();
881
882         if (the_lnet.ln_network_tokens != NULL) {
883                 LIBCFS_FREE(the_lnet.ln_network_tokens,
884                             the_lnet.ln_network_tokens_nob);
885                 the_lnet.ln_network_tokens = NULL;
886         }
887 }
888
889 int
890 lnet_startup_lndnis (void)
891 {
892         lnd_t             *lnd;
893         lnet_ni_t         *ni;
894         cfs_list_t         nilist;
895         int                rc = 0;
896         int                lnd_type;
897         int                nicount = 0;
898         char              *nets = lnet_get_networks();
899
900         CFS_INIT_LIST_HEAD(&nilist);
901
902         if (nets == NULL)
903                 goto failed;
904
905         rc = lnet_parse_networks(&nilist, nets);
906         if (rc != 0)
907                 goto failed;
908
909         while (!cfs_list_empty(&nilist)) {
910                 ni = cfs_list_entry(nilist.next, lnet_ni_t, ni_list);
911                 lnd_type = LNET_NETTYP(LNET_NIDNET(ni->ni_nid));
912
913                 LASSERT (libcfs_isknown_lnd(lnd_type));
914
915                 if (lnd_type == CIBLND    ||
916                     lnd_type == OPENIBLND ||
917                     lnd_type == IIBLND    ||
918                     lnd_type == VIBLND) {
919                         CERROR("LND %s obsoleted\n",
920                                libcfs_lnd2str(lnd_type));
921                         goto failed;
922                 }
923
924                 LNET_MUTEX_LOCK(&the_lnet.ln_lnd_mutex);
925                 lnd = lnet_find_lnd_by_type(lnd_type);
926
927 #ifdef __KERNEL__
928                 if (lnd == NULL) {
929                         LNET_MUTEX_UNLOCK(&the_lnet.ln_lnd_mutex);
930                         rc = cfs_request_module("%s",
931                                                 libcfs_lnd2modname(lnd_type));
932                         LNET_MUTEX_LOCK(&the_lnet.ln_lnd_mutex);
933
934                         lnd = lnet_find_lnd_by_type(lnd_type);
935                         if (lnd == NULL) {
936                                 LNET_MUTEX_UNLOCK(&the_lnet.ln_lnd_mutex);
937                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
938                                        libcfs_lnd2str(lnd_type),
939                                        libcfs_lnd2modname(lnd_type), rc);
940 #ifndef HAVE_MODULE_LOADING_SUPPORT
941                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
942                                          "compiled with kernel module "
943                                          "loading support.");
944 #endif
945                                 goto failed;
946                         }
947                 }
948 #else
949                 if (lnd == NULL) {
950                         LNET_MUTEX_UNLOCK(&the_lnet.ln_lnd_mutex);
951                         CERROR("LND %s not supported\n",
952                                libcfs_lnd2str(lnd_type));
953                         goto failed;
954                 }
955 #endif
956
957                 ni->ni_refcount = 1;
958
959                 LNET_LOCK();
960                 lnd->lnd_refcount++;
961                 LNET_UNLOCK();
962
963                 ni->ni_lnd = lnd;
964
965                 rc = (lnd->lnd_startup)(ni);
966
967                 LNET_MUTEX_UNLOCK(&the_lnet.ln_lnd_mutex);
968
969                 if (rc != 0) {
970                         LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s"
971                                            "\n",
972                                            rc, libcfs_lnd2str(lnd->lnd_type));
973                         LNET_LOCK();
974                         lnd->lnd_refcount--;
975                         LNET_UNLOCK();
976                         goto failed;
977                 }
978
979                 LASSERT (ni->ni_peertimeout <= 0 || lnd->lnd_query != NULL);
980
981                 cfs_list_del(&ni->ni_list);
982
983                 LNET_LOCK();
984                 cfs_list_add_tail(&ni->ni_list, &the_lnet.ln_nis);
985                 LNET_UNLOCK();
986
987                 if (lnd->lnd_type == LOLND) {
988                         lnet_ni_addref(ni);
989                         LASSERT (the_lnet.ln_loni == NULL);
990                         the_lnet.ln_loni = ni;
991                         continue;
992                 }
993
994 #ifndef __KERNEL__
995                 if (lnd->lnd_wait != NULL) {
996                         if (the_lnet.ln_eq_waitni == NULL) {
997                                 lnet_ni_addref(ni);
998                                 the_lnet.ln_eq_waitni = ni;
999                         }
1000                 } else {
1001 # ifndef HAVE_LIBPTHREAD
1002                         LCONSOLE_ERROR_MSG(0x106, "LND %s not supported in a "
1003                                            "single-threaded runtime\n",
1004                                            libcfs_lnd2str(lnd_type));
1005                         goto failed;
1006 # endif
1007                 }
1008 #endif
1009                 if (ni->ni_peertxcredits == 0 ||
1010                     ni->ni_maxtxcredits == 0) {
1011                         LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
1012                                            libcfs_lnd2str(lnd->lnd_type),
1013                                            ni->ni_peertxcredits == 0 ?
1014                                            "" : "per-peer ");
1015                         goto failed;
1016                 }
1017
1018                 ni->ni_txcredits = ni->ni_mintxcredits = ni->ni_maxtxcredits;
1019
1020                 CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
1021                        libcfs_nid2str(ni->ni_nid),
1022                        ni->ni_peertxcredits, ni->ni_txcredits,
1023                        ni->ni_peerrtrcredits, ni->ni_peertimeout);
1024
1025                 nicount++;
1026         }
1027
1028         if (the_lnet.ln_eq_waitni != NULL && nicount > 1) {
1029                 lnd_type = the_lnet.ln_eq_waitni->ni_lnd->lnd_type;
1030                 LCONSOLE_ERROR_MSG(0x109, "LND %s can only run single-network"
1031                                    "\n",
1032                                    libcfs_lnd2str(lnd_type));
1033                 goto failed;
1034         }
1035
1036         return 0;
1037
1038  failed:
1039         lnet_shutdown_lndnis();
1040
1041         while (!cfs_list_empty(&nilist)) {
1042                 ni = cfs_list_entry(nilist.next, lnet_ni_t, ni_list);
1043                 cfs_list_del(&ni->ni_list);
1044                 LIBCFS_FREE(ni, sizeof(*ni));
1045         }
1046
1047         return -ENETDOWN;
1048 }
1049
1050 /**
1051  * Initialize LNet library.
1052  *
1053  * Only userspace program needs to call this function - it's automatically
1054  * called in the kernel at module loading time. Caller has to call LNetFini()
1055  * after a call to LNetInit(), if and only if the latter returned 0. It must
1056  * be called exactly once.
1057  *
1058  * \return 0 on success, and -ve on failures.
1059  */
1060 int
1061 LNetInit(void)
1062 {
1063         lnet_assert_wire_constants ();
1064         LASSERT (!the_lnet.ln_init);
1065
1066         memset(&the_lnet, 0, sizeof(the_lnet));
1067
1068         lnet_init_locks();
1069         the_lnet.ln_refcount = 0;
1070         the_lnet.ln_init = 1;
1071         LNetInvalidateHandle(&the_lnet.ln_rc_eqh);
1072         CFS_INIT_LIST_HEAD(&the_lnet.ln_lnds);
1073         CFS_INIT_LIST_HEAD(&the_lnet.ln_rcd_zombie);
1074         CFS_INIT_LIST_HEAD(&the_lnet.ln_rcd_deathrow);
1075
1076 #ifdef __KERNEL__
1077         /* All LNDs apart from the LOLND are in separate modules.  They
1078          * register themselves when their module loads, and unregister
1079          * themselves when their module is unloaded. */
1080 #else
1081         /* Register LNDs
1082          * NB the order here determines default 'networks=' order */
1083 # ifdef CRAY_XT3
1084         LNET_REGISTER_ULND(the_ptllnd);
1085 # endif
1086 # ifdef HAVE_LIBPTHREAD
1087         LNET_REGISTER_ULND(the_tcplnd);
1088 # endif
1089 #endif
1090         lnet_register_lnd(&the_lolnd);
1091         return 0;
1092 }
1093
1094 /**
1095  * Finalize LNet library.
1096  *
1097  * Only userspace program needs to call this function. It can be called
1098  * at most once.
1099  *
1100  * \pre LNetInit() called with success.
1101  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
1102  */
1103 void
1104 LNetFini(void)
1105 {
1106         LASSERT (the_lnet.ln_init);
1107         LASSERT (the_lnet.ln_refcount == 0);
1108
1109         while (!cfs_list_empty(&the_lnet.ln_lnds))
1110                 lnet_unregister_lnd(cfs_list_entry(the_lnet.ln_lnds.next,
1111                                                    lnd_t, lnd_list));
1112         lnet_fini_locks();
1113
1114         the_lnet.ln_init = 0;
1115 }
1116
1117 /**
1118  * Set LNet PID and start LNet interfaces, routing, and forwarding.
1119  *
1120  * Userspace program should call this after a successful call to LNetInit().
1121  * Users must call this function at least once before any other functions.
1122  * For each successful call there must be a corresponding call to
1123  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
1124  * ignored.
1125  *
1126  * The PID used by LNet may be different from the one requested.
1127  * See LNetGetId().
1128  *
1129  * \param requested_pid PID requested by the caller.
1130  *
1131  * \return >= 0 on success, and < 0 error code on failures.
1132  */
1133 int
1134 LNetNIInit(lnet_pid_t requested_pid)
1135 {
1136         int         im_a_router = 0;
1137         int         rc;
1138
1139         LNET_MUTEX_LOCK(&the_lnet.ln_api_mutex);
1140
1141         LASSERT (the_lnet.ln_init);
1142         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
1143
1144         if (the_lnet.ln_refcount > 0) {
1145                 rc = the_lnet.ln_refcount++;
1146                 goto out;
1147         }
1148
1149         lnet_get_tunables();
1150
1151         if (requested_pid == LNET_PID_ANY) {
1152                 /* Don't instantiate LNET just for me */
1153                 rc = -ENETDOWN;
1154                 goto failed0;
1155         }
1156
1157         rc = lnet_prepare(requested_pid);
1158         if (rc != 0)
1159                 goto failed0;
1160
1161         rc = lnet_startup_lndnis();
1162         if (rc != 0)
1163                 goto failed1;
1164
1165         rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
1166         if (rc != 0)
1167                 goto failed2;
1168
1169         rc = lnet_check_routes();
1170         if (rc != 0)
1171                 goto failed2;
1172
1173         rc = lnet_alloc_rtrpools(im_a_router);
1174         if (rc != 0)
1175                 goto failed2;
1176
1177         rc = lnet_acceptor_start();
1178         if (rc != 0)
1179                 goto failed2;
1180
1181         the_lnet.ln_refcount = 1;
1182         /* Now I may use my own API functions... */
1183
1184         /* NB router checker needs the_lnet.ln_ping_info in
1185          * lnet_router_checker -> lnet_update_ni_status_locked */
1186         rc = lnet_ping_target_init();
1187         if (rc != 0)
1188                 goto failed3;
1189
1190         rc = lnet_router_checker_start();
1191         if (rc != 0)
1192                 goto failed4;
1193
1194         lnet_proc_init();
1195         goto out;
1196
1197  failed4:
1198         lnet_ping_target_fini();
1199  failed3:
1200         the_lnet.ln_refcount = 0;
1201         lnet_acceptor_stop();
1202  failed2:
1203         lnet_destroy_routes();
1204         lnet_shutdown_lndnis();
1205  failed1:
1206         lnet_unprepare();
1207  failed0:
1208         LASSERT (rc < 0);
1209  out:
1210         LNET_MUTEX_UNLOCK(&the_lnet.ln_api_mutex);
1211         return rc;
1212 }
1213
1214 /**
1215  * Stop LNet interfaces, routing, and forwarding.
1216  *
1217  * Users must call this function once for each successful call to LNetNIInit().
1218  * Once the LNetNIFini() operation has been started, the results of pending
1219  * API operations are undefined.
1220  *
1221  * \return always 0 for current implementation.
1222  */
1223 int
1224 LNetNIFini()
1225 {
1226         LNET_MUTEX_LOCK(&the_lnet.ln_api_mutex);
1227
1228         LASSERT (the_lnet.ln_init);
1229         LASSERT (the_lnet.ln_refcount > 0);
1230
1231         if (the_lnet.ln_refcount != 1) {
1232                 the_lnet.ln_refcount--;
1233         } else {
1234                 LASSERT (!the_lnet.ln_niinit_self);
1235
1236                 lnet_proc_fini();
1237                 lnet_router_checker_stop();
1238                 lnet_ping_target_fini();
1239
1240                 /* Teardown fns that use my own API functions BEFORE here */
1241                 the_lnet.ln_refcount = 0;
1242
1243                 lnet_acceptor_stop();
1244                 lnet_destroy_routes();
1245                 lnet_shutdown_lndnis();
1246                 lnet_unprepare();
1247         }
1248
1249         LNET_MUTEX_UNLOCK(&the_lnet.ln_api_mutex);
1250         return 0;
1251 }
1252
1253 /**
1254  * This is an ugly hack to export IOC_LIBCFS_DEBUG_PEER and
1255  * IOC_LIBCFS_PORTALS_COMPATIBILITY commands to users, by tweaking the LNet
1256  * internal ioctl handler.
1257  *
1258  * IOC_LIBCFS_PORTALS_COMPATIBILITY is now deprecated, don't use it.
1259  *
1260  * \param cmd IOC_LIBCFS_DEBUG_PEER to print debugging data about a peer.
1261  * The data will be printed to system console. Don't use it excessively.
1262  * \param arg A pointer to lnet_process_id_t, process ID of the peer.
1263  *
1264  * \return Always return 0 when called by users directly (i.e., not via ioctl).
1265  */
1266 int
1267 LNetCtl(unsigned int cmd, void *arg)
1268 {
1269         struct libcfs_ioctl_data *data = arg;
1270         lnet_process_id_t         id = {0};
1271         lnet_ni_t                *ni;
1272         int                       rc;
1273
1274         LASSERT (the_lnet.ln_init);
1275         LASSERT (the_lnet.ln_refcount > 0);
1276
1277         switch (cmd) {
1278         case IOC_LIBCFS_GET_NI:
1279                 rc = LNetGetId(data->ioc_count, &id);
1280                 data->ioc_nid = id.nid;
1281                 return rc;
1282
1283         case IOC_LIBCFS_FAIL_NID:
1284                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
1285
1286         case IOC_LIBCFS_ADD_ROUTE:
1287                 rc = lnet_add_route(data->ioc_net, data->ioc_count,
1288                                     data->ioc_nid);
1289                 return (rc != 0) ? rc : lnet_check_routes();
1290
1291         case IOC_LIBCFS_DEL_ROUTE:
1292                 return lnet_del_route(data->ioc_net, data->ioc_nid);
1293
1294         case IOC_LIBCFS_GET_ROUTE:
1295                 return lnet_get_route(data->ioc_count,
1296                                       &data->ioc_net, &data->ioc_count,
1297                                       &data->ioc_nid, &data->ioc_flags);
1298         case IOC_LIBCFS_NOTIFY_ROUTER:
1299                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
1300                                    cfs_time_current() -
1301                                    cfs_time_seconds(cfs_time_current_sec() -
1302                                                     (time_t)data->ioc_u64[0]));
1303
1304         case IOC_LIBCFS_PORTALS_COMPATIBILITY:
1305                 /* This can be removed once lustre stops calling it */
1306                 return 0;
1307
1308         case IOC_LIBCFS_LNET_DIST:
1309                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
1310                 if (rc < 0 && rc != -EHOSTUNREACH)
1311                         return rc;
1312
1313                 data->ioc_u32[0] = rc;
1314                 return 0;
1315
1316         case IOC_LIBCFS_TESTPROTOCOMPAT:
1317                 LNET_LOCK();
1318                 the_lnet.ln_testprotocompat = data->ioc_flags;
1319                 LNET_UNLOCK();
1320                 return 0;
1321
1322         case IOC_LIBCFS_PING:
1323                 id.nid = data->ioc_nid;
1324                 id.pid = data->ioc_u32[0];
1325                 rc = lnet_ping(id, data->ioc_u32[1], /* timeout */
1326                                (lnet_process_id_t *)data->ioc_pbuf1,
1327                                data->ioc_plen1/sizeof(lnet_process_id_t));
1328                 if (rc < 0)
1329                         return rc;
1330                 data->ioc_count = rc;
1331                 return 0;
1332
1333         case IOC_LIBCFS_DEBUG_PEER: {
1334                 /* CAVEAT EMPTOR: this one designed for calling directly; not
1335                  * via an ioctl */
1336                 id = *((lnet_process_id_t *) arg);
1337
1338                 lnet_debug_peer(id.nid);
1339
1340                 ni = lnet_net2ni(LNET_NIDNET(id.nid));
1341                 if (ni == NULL) {
1342                         CDEBUG(D_WARNING, "No NI for %s\n", libcfs_id2str(id));
1343                 } else {
1344                         if (ni->ni_lnd->lnd_ctl == NULL) {
1345                                 CDEBUG(D_WARNING, "No ctl for %s\n",
1346                                        libcfs_id2str(id));
1347                         } else {
1348                                 (void)ni->ni_lnd->lnd_ctl(ni, cmd, arg);
1349                         }
1350
1351                         lnet_ni_decref(ni);
1352                 }
1353                 return 0;
1354         }
1355
1356         default:
1357                 ni = lnet_net2ni(data->ioc_net);
1358                 if (ni == NULL)
1359                         return -EINVAL;
1360
1361                 if (ni->ni_lnd->lnd_ctl == NULL)
1362                         rc = -EINVAL;
1363                 else
1364                         rc = ni->ni_lnd->lnd_ctl(ni, cmd, arg);
1365
1366                 lnet_ni_decref(ni);
1367                 return rc;
1368         }
1369         /* not reached */
1370 }
1371
1372 /**
1373  * Retrieve the lnet_process_id_t ID of LNet interface at \a index. Note that
1374  * all interfaces share a same PID, as requested by LNetNIInit().
1375  *
1376  * \param index Index of the interface to look up.
1377  * \param id On successful return, this location will hold the
1378  * lnet_process_id_t ID of the interface.
1379  *
1380  * \retval 0 If an interface exists at \a index.
1381  * \retval -ENOENT If no interface has been found.
1382  */
1383 int
1384 LNetGetId(unsigned int index, lnet_process_id_t *id)
1385 {
1386         lnet_ni_t        *ni;
1387         cfs_list_t       *tmp;
1388         int               rc = -ENOENT;
1389
1390         LASSERT (the_lnet.ln_init);
1391         LASSERT (the_lnet.ln_refcount > 0);
1392
1393         LNET_LOCK();
1394
1395         cfs_list_for_each(tmp, &the_lnet.ln_nis) {
1396                 if (index-- != 0)
1397                         continue;
1398
1399                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
1400
1401                 id->nid = ni->ni_nid;
1402                 id->pid = the_lnet.ln_pid;
1403                 rc = 0;
1404                 break;
1405         }
1406
1407         LNET_UNLOCK();
1408
1409         return rc;
1410 }
1411
1412 /**
1413  * Print a string representation of handle \a h into buffer \a str of
1414  * \a len bytes.
1415  */
1416 void
1417 LNetSnprintHandle(char *str, int len, lnet_handle_any_t h)
1418 {
1419         snprintf(str, len, LPX64, h.cookie);
1420 }
1421
1422 static int
1423 lnet_create_ping_info(void)
1424 {
1425         int               i;
1426         int               n;
1427         int               rc;
1428         unsigned int      infosz;
1429         lnet_ni_t        *ni;
1430         lnet_process_id_t id;
1431         lnet_ping_info_t *pinfo;
1432
1433         for (n = 0; ; n++) {
1434                 rc = LNetGetId(n, &id);
1435                 if (rc == -ENOENT)
1436                         break;
1437
1438                 LASSERT (rc == 0);
1439         }
1440
1441         infosz = offsetof(lnet_ping_info_t, pi_ni[n]);
1442         LIBCFS_ALLOC(pinfo, infosz);
1443         if (pinfo == NULL) {
1444                 CERROR("Can't allocate ping info[%d]\n", n);
1445                 return -ENOMEM;
1446         }
1447
1448         pinfo->pi_nnis    = n;
1449         pinfo->pi_pid     = the_lnet.ln_pid;
1450         pinfo->pi_magic   = LNET_PROTO_PING_MAGIC;
1451         pinfo->pi_version = LNET_PROTO_PING_VERSION;
1452
1453         for (i = 0; i < n; i++) {
1454                 lnet_ni_status_t *ns = &pinfo->pi_ni[i];
1455
1456                 rc = LNetGetId(i, &id);
1457                 LASSERT (rc == 0);
1458
1459                 ns->ns_nid    = id.nid;
1460                 ns->ns_status = LNET_NI_STATUS_UP;
1461
1462                 LNET_LOCK();
1463
1464                 ni = lnet_nid2ni_locked(id.nid);
1465                 LASSERT (ni != NULL);
1466                 LASSERT (ni->ni_status == NULL);
1467                 ni->ni_status = ns;
1468                 lnet_ni_decref_locked(ni);
1469
1470                 LNET_UNLOCK();
1471         }
1472
1473         the_lnet.ln_ping_info = pinfo;
1474         return 0;
1475 }
1476
1477 static void
1478 lnet_destroy_ping_info(void)
1479 {
1480         lnet_ni_t *ni;
1481
1482         LNET_LOCK();
1483
1484         cfs_list_for_each_entry (ni, &the_lnet.ln_nis, ni_list) {
1485                 ni->ni_status = NULL;
1486         }
1487
1488         LNET_UNLOCK();
1489
1490         LIBCFS_FREE(the_lnet.ln_ping_info,
1491                     offsetof(lnet_ping_info_t,
1492                              pi_ni[the_lnet.ln_ping_info->pi_nnis]));
1493         the_lnet.ln_ping_info = NULL;
1494         return;
1495 }
1496
1497 int
1498 lnet_ping_target_init(void)
1499 {
1500         lnet_md_t         md = {0};
1501         lnet_handle_me_t  meh;
1502         lnet_process_id_t id;
1503         int               rc;
1504         int               rc2;
1505         int               infosz;
1506
1507         rc = lnet_create_ping_info();
1508         if (rc != 0)
1509                 return rc;
1510
1511         /* We can have a tiny EQ since we only need to see the unlink event on
1512          * teardown, which by definition is the last one! */
1513         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &the_lnet.ln_ping_target_eq);
1514         if (rc != 0) {
1515                 CERROR("Can't allocate ping EQ: %d\n", rc);
1516                 goto failed_0;
1517         }
1518
1519         memset(&id, 0, sizeof(lnet_process_id_t));
1520         id.nid = LNET_NID_ANY;
1521         id.pid = LNET_PID_ANY;
1522
1523         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1524                           LNET_PROTO_PING_MATCHBITS, 0,
1525                           LNET_UNLINK, LNET_INS_AFTER,
1526                           &meh);
1527         if (rc != 0) {
1528                 CERROR("Can't create ping ME: %d\n", rc);
1529                 goto failed_1;
1530         }
1531
1532         /* initialize md content */
1533         infosz = offsetof(lnet_ping_info_t,
1534                           pi_ni[the_lnet.ln_ping_info->pi_nnis]);
1535         md.start     = the_lnet.ln_ping_info;
1536         md.length    = infosz;
1537         md.threshold = LNET_MD_THRESH_INF;
1538         md.max_size  = 0;
1539         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1540                        LNET_MD_MANAGE_REMOTE;
1541         md.user_ptr  = NULL;
1542         md.eq_handle = the_lnet.ln_ping_target_eq;
1543
1544         rc = LNetMDAttach(meh, md,
1545                           LNET_RETAIN,
1546                           &the_lnet.ln_ping_target_md);
1547         if (rc != 0) {
1548                 CERROR("Can't attach ping MD: %d\n", rc);
1549                 goto failed_2;
1550         }
1551
1552         return 0;
1553
1554  failed_2:
1555         rc2 = LNetMEUnlink(meh);
1556         LASSERT (rc2 == 0);
1557  failed_1:
1558         rc2 = LNetEQFree(the_lnet.ln_ping_target_eq);
1559         LASSERT (rc2 == 0);
1560  failed_0:
1561         lnet_destroy_ping_info();
1562         return rc;
1563 }
1564
1565 void
1566 lnet_ping_target_fini(void)
1567 {
1568         lnet_event_t    event;
1569         int             rc;
1570         int             which;
1571         int             timeout_ms = 1000;
1572         cfs_sigset_t    blocked = cfs_block_allsigs();
1573
1574         LNetMDUnlink(the_lnet.ln_ping_target_md);
1575         /* NB md could be busy; this just starts the unlink */
1576
1577         for (;;) {
1578                 rc = LNetEQPoll(&the_lnet.ln_ping_target_eq, 1,
1579                                 timeout_ms, &event, &which);
1580
1581                 /* I expect overflow... */
1582                 LASSERT (rc >= 0 || rc == -EOVERFLOW);
1583
1584                 if (rc == 0) {
1585                         /* timed out: provide a diagnostic */
1586                         CWARN("Still waiting for ping MD to unlink\n");
1587                         timeout_ms *= 2;
1588                         continue;
1589                 }
1590
1591                 /* Got a valid event */
1592                 if (event.unlinked)
1593                         break;
1594         }
1595
1596         rc = LNetEQFree(the_lnet.ln_ping_target_eq);
1597         LASSERT (rc == 0);
1598         lnet_destroy_ping_info();
1599         cfs_restore_sigs(blocked);
1600 }
1601
1602 int
1603 lnet_ping (lnet_process_id_t id, int timeout_ms, lnet_process_id_t *ids, int n_ids)
1604 {
1605         lnet_handle_eq_t     eqh;
1606         lnet_handle_md_t     mdh;
1607         lnet_event_t         event;
1608         lnet_md_t            md = {0};
1609         int                  which;
1610         int                  unlinked = 0;
1611         int                  replied = 0;
1612         const int            a_long_time = 60000; /* mS */
1613         int                  infosz = offsetof(lnet_ping_info_t, pi_ni[n_ids]);
1614         lnet_ping_info_t    *info;
1615         lnet_process_id_t    tmpid;
1616         int                  i;
1617         int                  nob;
1618         int                  rc;
1619         int                  rc2;
1620         cfs_sigset_t         blocked;
1621
1622         if (n_ids <= 0 ||
1623             id.nid == LNET_NID_ANY ||
1624             timeout_ms > 500000 ||              /* arbitrary limit! */
1625             n_ids > 20)                         /* arbitrary limit! */
1626                 return -EINVAL;
1627
1628         if (id.pid == LNET_PID_ANY)
1629                 id.pid = LUSTRE_SRV_LNET_PID;
1630
1631         LIBCFS_ALLOC(info, infosz);
1632         if (info == NULL)
1633                 return -ENOMEM;
1634
1635         /* NB 2 events max (including any unlink event) */
1636         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
1637         if (rc != 0) {
1638                 CERROR("Can't allocate EQ: %d\n", rc);
1639                 goto out_0;
1640         }
1641
1642         /* initialize md content */
1643         md.start     = info;
1644         md.length    = infosz;
1645         md.threshold = 2; /*GET/REPLY*/
1646         md.max_size  = 0;
1647         md.options   = LNET_MD_TRUNCATE;
1648         md.user_ptr  = NULL;
1649         md.eq_handle = eqh;
1650
1651         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
1652         if (rc != 0) {
1653                 CERROR("Can't bind MD: %d\n", rc);
1654                 goto out_1;
1655         }
1656
1657         rc = LNetGet(LNET_NID_ANY, mdh, id,
1658                      LNET_RESERVED_PORTAL,
1659                      LNET_PROTO_PING_MATCHBITS, 0);
1660
1661         if (rc != 0) {
1662                 /* Don't CERROR; this could be deliberate! */
1663
1664                 rc2 = LNetMDUnlink(mdh);
1665                 LASSERT (rc2 == 0);
1666
1667                 /* NB must wait for the UNLINK event below... */
1668                 unlinked = 1;
1669                 timeout_ms = a_long_time;
1670         }
1671
1672         do {
1673                 /* MUST block for unlink to complete */
1674                 if (unlinked)
1675                         blocked = cfs_block_allsigs();
1676
1677                 rc2 = LNetEQPoll(&eqh, 1, timeout_ms, &event, &which);
1678
1679                 if (unlinked)
1680                         cfs_restore_sigs(blocked);
1681
1682                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
1683                        (rc2 <= 0) ? -1 : event.type,
1684                        (rc2 <= 0) ? -1 : event.status,
1685                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
1686
1687                 LASSERT (rc2 != -EOVERFLOW);     /* can't miss anything */
1688
1689                 if (rc2 <= 0 || event.status != 0) {
1690                         /* timeout or error */
1691                         if (!replied && rc == 0)
1692                                 rc = (rc2 < 0) ? rc2 :
1693                                      (rc2 == 0) ? -ETIMEDOUT :
1694                                      event.status;
1695
1696                         if (!unlinked) {
1697                                 /* Ensure completion in finite time... */
1698                                 LNetMDUnlink(mdh);
1699                                 /* No assertion (racing with network) */
1700                                 unlinked = 1;
1701                                 timeout_ms = a_long_time;
1702                         } else if (rc2 == 0) {
1703                                 /* timed out waiting for unlink */
1704                                 CWARN("ping %s: late network completion\n",
1705                                       libcfs_id2str(id));
1706                         }
1707                 } else if (event.type == LNET_EVENT_REPLY) {
1708                         replied = 1;
1709                         rc = event.mlength;
1710                 }
1711
1712         } while (rc2 <= 0 || !event.unlinked);
1713
1714         if (!replied) {
1715                 if (rc >= 0)
1716                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
1717                               libcfs_id2str(id));
1718                 rc = -EIO;
1719                 goto out_1;
1720         }
1721
1722         nob = rc;
1723         LASSERT (nob >= 0 && nob <= infosz);
1724
1725         rc = -EPROTO;                           /* if I can't parse... */
1726
1727         if (nob < 8) {
1728                 /* can't check magic/version */
1729                 CERROR("%s: ping info too short %d\n",
1730                        libcfs_id2str(id), nob);
1731                 goto out_1;
1732         }
1733
1734         if (info->pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
1735                 lnet_swap_pinginfo(info);
1736         } else if (info->pi_magic != LNET_PROTO_PING_MAGIC) {
1737                 CERROR("%s: Unexpected magic %08x\n", 
1738                        libcfs_id2str(id), info->pi_magic);
1739                 goto out_1;
1740         }
1741
1742         if (info->pi_version != LNET_PROTO_PING_VERSION) {
1743                 CERROR("%s: Unexpected version 0x%x\n",
1744                        libcfs_id2str(id), info->pi_version);
1745                 goto out_1;
1746         }
1747
1748         if (nob < offsetof(lnet_ping_info_t, pi_ni[0])) {
1749                 CERROR("%s: Short reply %d(%d min)\n", libcfs_id2str(id),
1750                        nob, (int)offsetof(lnet_ping_info_t, pi_ni[0]));
1751                 goto out_1;
1752         }
1753
1754         if (info->pi_nnis < n_ids)
1755                 n_ids = info->pi_nnis;
1756
1757         if (nob < offsetof(lnet_ping_info_t, pi_ni[n_ids])) {
1758                 CERROR("%s: Short reply %d(%d expected)\n", libcfs_id2str(id),
1759                        nob, (int)offsetof(lnet_ping_info_t, pi_ni[n_ids]));
1760                 goto out_1;
1761         }
1762
1763         rc = -EFAULT;                           /* If I SEGV... */
1764
1765         for (i = 0; i < n_ids; i++) {
1766                 tmpid.pid = info->pi_pid;
1767                 tmpid.nid = info->pi_ni[i].ns_nid;
1768 #ifdef __KERNEL__
1769                 if (cfs_copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
1770                         goto out_1;
1771 #else
1772                 ids[i] = tmpid;
1773 #endif
1774         }
1775         rc = info->pi_nnis;
1776
1777  out_1:
1778         rc2 = LNetEQFree(eqh);
1779         if (rc2 != 0)
1780                 CERROR("rc2 %d\n", rc2);
1781         LASSERT (rc2 == 0);
1782
1783  out_0:
1784         LIBCFS_FREE(info, infosz);
1785         return rc;
1786 }