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