Whamcloud - gitweb
LU-56 lnet: container for LNet message
[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_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_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_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 cfs_list_t *
560 lnet_portal_mhash_alloc(void)
561 {
562         cfs_list_t       *mhash;
563         int               i;
564
565         LIBCFS_ALLOC(mhash, sizeof(cfs_list_t) * LNET_PORTAL_HASH_SIZE);
566         if (mhash == NULL)
567                 return NULL;
568
569         for (i = 0; i < LNET_PORTAL_HASH_SIZE; i++)
570                 CFS_INIT_LIST_HEAD(&mhash[i]);
571
572         return mhash;
573 }
574
575 void
576 lnet_portal_mhash_free(cfs_list_t *mhash)
577 {
578         int     i;
579
580         for (i = 0; i < LNET_PORTAL_HASH_SIZE; i++) {
581                 while (!cfs_list_empty(&mhash[i])) {
582                         lnet_me_t *me = cfs_list_entry(mhash[i].next,
583                                                        lnet_me_t, me_list);
584                         CERROR ("Active ME %p on exit portal mhash\n", me);
585                         cfs_list_del(&me->me_list);
586                         lnet_me_free(me);
587                 }
588         }
589         LIBCFS_FREE(mhash, sizeof(cfs_list_t) * LNET_PORTAL_HASH_SIZE);
590 }
591
592 #ifndef __KERNEL__
593 /**
594  * Reserved API - do not use.
595  * Temporary workaround to allow uOSS and test programs force server
596  * mode in userspace. See comments near ln_server_mode_flag in
597  * lnet/lib-types.h */
598
599 void
600 lnet_server_mode() {
601         the_lnet.ln_server_mode_flag = 1;
602 }
603 #endif
604
605 int
606 lnet_prepare(lnet_pid_t requested_pid)
607 {
608         /* Prepare to bring up the network */
609         int               rc = 0;
610         int               i;
611
612         LASSERT (the_lnet.ln_refcount == 0);
613
614         the_lnet.ln_routing = 0;
615
616 #ifdef __KERNEL__
617         LASSERT ((requested_pid & LNET_PID_USERFLAG) == 0);
618         the_lnet.ln_pid = requested_pid;
619 #else
620         if (the_lnet.ln_server_mode_flag) {/* server case (uOSS) */
621                 LASSERT ((requested_pid & LNET_PID_USERFLAG) == 0);
622
623                 if (cfs_curproc_uid())/* Only root can run user-space server */
624                         return -EPERM;
625                 the_lnet.ln_pid = requested_pid;
626
627         } else {/* client case (liblustre) */
628
629                 /* My PID must be unique on this node and flag I'm userspace */
630                 the_lnet.ln_pid = getpid() | LNET_PID_USERFLAG;
631         }
632 #endif
633
634         memset(&the_lnet.ln_counters, 0,
635                sizeof(the_lnet.ln_counters));
636
637         CFS_INIT_LIST_HEAD (&the_lnet.ln_test_peers);
638         CFS_INIT_LIST_HEAD (&the_lnet.ln_nis);
639         CFS_INIT_LIST_HEAD (&the_lnet.ln_zombie_nis);
640         CFS_INIT_LIST_HEAD (&the_lnet.ln_remote_nets);
641         CFS_INIT_LIST_HEAD (&the_lnet.ln_routers);
642
643         the_lnet.ln_interface_cookie = lnet_create_interface_cookie();
644
645         lnet_init_rtrpools();
646
647         rc = lnet_create_peer_table();
648         if (rc != 0)
649                 goto failed0;
650
651         /* NB: we will have instance of message container per CPT soon */
652         rc = lnet_msg_container_setup(&the_lnet.ln_msg_container);
653         if (rc != 0)
654                 goto failed1;
655
656         rc = lnet_res_container_setup(&the_lnet.ln_eq_container,
657                                       LNET_COOKIE_TYPE_EQ, LNET_FL_MAX_EQS,
658                                       sizeof(lnet_eq_t));
659         if (rc != 0) {
660                 CERROR("Failed to create EQ container for LNet: %d\n", rc);
661                 goto failed2;
662         }
663
664         /* NB: we will have instance of ME container per CPT soon */
665         rc = lnet_res_container_setup(&the_lnet.ln_me_container,
666                                       LNET_COOKIE_TYPE_ME, LNET_FL_MAX_MES,
667                                       sizeof(lnet_me_t));
668         if (rc != 0) {
669                 CERROR("Failed to create ME container for LNet: %d\n", rc);
670                 goto failed3;
671         }
672
673         /* NB: we will have instance of MD container per CPT soon */
674         rc = lnet_res_container_setup(&the_lnet.ln_md_container,
675                                       LNET_COOKIE_TYPE_MD, LNET_FL_MAX_MDS,
676                                       sizeof(lnet_libmd_t));
677         if (rc != 0) {
678                 CERROR("Failed to create MD container for LNet: %d\n", rc);
679                 goto failed3;
680         }
681
682         the_lnet.ln_nportals = MAX_PORTALS;
683         LIBCFS_ALLOC(the_lnet.ln_portals,
684                      the_lnet.ln_nportals *
685                      sizeof(*the_lnet.ln_portals));
686         if (the_lnet.ln_portals == NULL) {
687                 rc = -ENOMEM;
688                 goto failed3;
689         }
690
691         for (i = 0; i < the_lnet.ln_nportals; i++) {
692                 CFS_INIT_LIST_HEAD(&(the_lnet.ln_portals[i].ptl_mlist));
693                 CFS_INIT_LIST_HEAD(&(the_lnet.ln_portals[i].ptl_msgq));
694                 the_lnet.ln_portals[i].ptl_options = 0;
695         }
696
697         return 0;
698
699  failed3:
700         /* NB: lnet_res_container_cleanup is safe to call for
701          * uninitialized container */
702         lnet_res_container_cleanup(&the_lnet.ln_md_container);
703         lnet_res_container_cleanup(&the_lnet.ln_me_container);
704         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
705  failed2:
706         lnet_msg_container_cleanup(&the_lnet.ln_msg_container);
707  failed1:
708         lnet_destroy_peer_table();
709  failed0:
710         return rc;
711 }
712
713 int
714 lnet_unprepare (void)
715 {
716         int       idx;
717
718         /* NB no LNET_LOCK since this is the last reference.  All LND instances
719          * have shut down already, so it is safe to unlink and free all
720          * descriptors, even those that appear committed to a network op (eg MD
721          * with non-zero pending count) */
722
723         lnet_fail_nid(LNET_NID_ANY, 0);
724
725         LASSERT (cfs_list_empty(&the_lnet.ln_test_peers));
726         LASSERT (the_lnet.ln_refcount == 0);
727         LASSERT (cfs_list_empty(&the_lnet.ln_nis));
728         LASSERT (cfs_list_empty(&the_lnet.ln_zombie_nis));
729         LASSERT (the_lnet.ln_nzombie_nis == 0);
730
731         for (idx = 0; idx < the_lnet.ln_nportals; idx++) {
732                 lnet_portal_t *ptl = &the_lnet.ln_portals[idx];
733
734                 LASSERT (cfs_list_empty(&ptl->ptl_msgq));
735
736                 while (!cfs_list_empty(&ptl->ptl_mlist)) {
737                         lnet_me_t *me = cfs_list_entry(ptl->ptl_mlist.next,
738                                                        lnet_me_t, me_list);
739                         CERROR ("Active ME %p on exit\n", me);
740                         cfs_list_del (&me->me_list);
741                         lnet_me_free (me);
742                 }
743
744                 if (ptl->ptl_mhash != NULL) {
745                         LASSERT (lnet_portal_is_unique(ptl));
746                         lnet_portal_mhash_free(ptl->ptl_mhash);
747                 }
748         }
749
750         lnet_res_container_cleanup(&the_lnet.ln_md_container);
751         lnet_res_container_cleanup(&the_lnet.ln_me_container);
752         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
753
754         LIBCFS_FREE(the_lnet.ln_portals,
755                     the_lnet.ln_nportals * sizeof(*the_lnet.ln_portals));
756
757         lnet_free_rtrpools();
758         lnet_msg_container_cleanup(&the_lnet.ln_msg_container);
759         lnet_destroy_peer_table();
760
761         return 0;
762 }
763
764 lnet_ni_t  *
765 lnet_net2ni_locked (__u32 net)
766 {
767         cfs_list_t       *tmp;
768         lnet_ni_t        *ni;
769
770         cfs_list_for_each (tmp, &the_lnet.ln_nis) {
771                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
772
773                 if (LNET_NIDNET(ni->ni_nid) == net) {
774                         lnet_ni_addref_locked(ni);
775                         return ni;
776                 }
777         }
778
779         return NULL;
780 }
781
782 int
783 lnet_islocalnet (__u32 net)
784 {
785         lnet_ni_t        *ni;
786
787         LNET_LOCK();
788         ni = lnet_net2ni_locked(net);
789         if (ni != NULL)
790                 lnet_ni_decref_locked(ni);
791         LNET_UNLOCK();
792
793         return ni != NULL;
794 }
795
796 lnet_ni_t  *
797 lnet_nid2ni_locked (lnet_nid_t nid)
798 {
799         cfs_list_t       *tmp;
800         lnet_ni_t        *ni;
801
802         cfs_list_for_each (tmp, &the_lnet.ln_nis) {
803                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
804
805                 if (ni->ni_nid == nid) {
806                         lnet_ni_addref_locked(ni);
807                         return ni;
808                 }
809         }
810
811         return NULL;
812 }
813
814 int
815 lnet_islocalnid (lnet_nid_t nid)
816 {
817         lnet_ni_t     *ni;
818
819         LNET_LOCK();
820         ni = lnet_nid2ni_locked(nid);
821         if (ni != NULL)
822                 lnet_ni_decref_locked(ni);
823         LNET_UNLOCK();
824
825         return ni != NULL;
826 }
827
828 int
829 lnet_count_acceptor_nis (void)
830 {
831         /* Return the # of NIs that need the acceptor. */
832         int            count = 0;
833 #if defined(__KERNEL__) || defined(HAVE_LIBPTHREAD)
834         cfs_list_t    *tmp;
835         lnet_ni_t     *ni;
836
837         LNET_LOCK();
838         cfs_list_for_each (tmp, &the_lnet.ln_nis) {
839                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
840
841                 if (ni->ni_lnd->lnd_accept != NULL)
842                         count++;
843         }
844
845         LNET_UNLOCK();
846
847 #endif /* defined(__KERNEL__) || defined(HAVE_LIBPTHREAD) */
848         return count;
849 }
850
851 void
852 lnet_shutdown_lndnis (void)
853 {
854         int                i;
855         int                islo;
856         lnet_ni_t         *ni;
857
858         /* NB called holding the global mutex */
859
860         /* All quiet on the API front */
861         LASSERT (!the_lnet.ln_shutdown);
862         LASSERT (the_lnet.ln_refcount == 0);
863         LASSERT (cfs_list_empty(&the_lnet.ln_zombie_nis));
864         LASSERT (the_lnet.ln_nzombie_nis == 0);
865         LASSERT (cfs_list_empty(&the_lnet.ln_remote_nets));
866
867         LNET_LOCK();
868         the_lnet.ln_shutdown = 1;               /* flag shutdown */
869
870         /* Unlink NIs from the global table */
871         while (!cfs_list_empty(&the_lnet.ln_nis)) {
872                 ni = cfs_list_entry(the_lnet.ln_nis.next,
873                                     lnet_ni_t, ni_list);
874                 cfs_list_del (&ni->ni_list);
875
876                 the_lnet.ln_nzombie_nis++;
877                 lnet_ni_decref_locked(ni); /* drop ln_nis' ref */
878         }
879
880         /* Drop the cached eqwait NI. */
881         if (the_lnet.ln_eqwaitni != NULL) {
882                 lnet_ni_decref_locked(the_lnet.ln_eqwaitni);
883                 the_lnet.ln_eqwaitni = NULL;
884         }
885
886         /* Drop the cached loopback NI. */
887         if (the_lnet.ln_loni != NULL) {
888                 lnet_ni_decref_locked(the_lnet.ln_loni);
889                 the_lnet.ln_loni = NULL;
890         }
891
892         LNET_UNLOCK();
893
894         /* Clear lazy portals and drop delayed messages which hold refs
895          * on their lnet_msg_t::msg_rxpeer */
896         for (i = 0; i < the_lnet.ln_nportals; i++)
897                 LNetClearLazyPortal(i);
898
899         /* Clear the peer table and wait for all peers to go (they hold refs on
900          * their NIs) */
901         lnet_clear_peer_table();
902
903         LNET_LOCK();
904         /* Now wait for the NI's I just nuked to show up on ln_zombie_nis
905          * and shut them down in guaranteed thread context */
906         i = 2;
907         while (the_lnet.ln_nzombie_nis != 0) {
908
909                 while (cfs_list_empty(&the_lnet.ln_zombie_nis)) {
910                         LNET_UNLOCK();
911                         ++i;
912                         if ((i & (-i)) == i)
913                                 CDEBUG(D_WARNING,"Waiting for %d zombie NIs\n",
914                                        the_lnet.ln_nzombie_nis);
915                         cfs_pause(cfs_time_seconds(1));
916                         LNET_LOCK();
917                 }
918
919                 ni = cfs_list_entry(the_lnet.ln_zombie_nis.next,
920                                     lnet_ni_t, ni_list);
921                 cfs_list_del(&ni->ni_list);
922                 ni->ni_lnd->lnd_refcount--;
923
924                 LNET_UNLOCK();
925
926                 islo = ni->ni_lnd->lnd_type == LOLND;
927
928                 LASSERT (!cfs_in_interrupt ());
929                 (ni->ni_lnd->lnd_shutdown)(ni);
930
931                 /* can't deref lnd anymore now; it might have unregistered
932                  * itself...  */
933
934                 if (!islo)
935                         CDEBUG(D_LNI, "Removed LNI %s\n",
936                                libcfs_nid2str(ni->ni_nid));
937
938                 LIBCFS_FREE(ni, sizeof(*ni));
939
940                 LNET_LOCK();
941                 the_lnet.ln_nzombie_nis--;
942         }
943
944         the_lnet.ln_shutdown = 0;
945         LNET_UNLOCK();
946
947         if (the_lnet.ln_network_tokens != NULL) {
948                 LIBCFS_FREE(the_lnet.ln_network_tokens,
949                             the_lnet.ln_network_tokens_nob);
950                 the_lnet.ln_network_tokens = NULL;
951         }
952 }
953
954 int
955 lnet_startup_lndnis (void)
956 {
957         lnd_t             *lnd;
958         lnet_ni_t         *ni;
959         cfs_list_t         nilist;
960         int                rc = 0;
961         int                lnd_type;
962         int                nicount = 0;
963         char              *nets = lnet_get_networks();
964
965         CFS_INIT_LIST_HEAD(&nilist);
966
967         if (nets == NULL)
968                 goto failed;
969
970         rc = lnet_parse_networks(&nilist, nets);
971         if (rc != 0)
972                 goto failed;
973
974         while (!cfs_list_empty(&nilist)) {
975                 ni = cfs_list_entry(nilist.next, lnet_ni_t, ni_list);
976                 lnd_type = LNET_NETTYP(LNET_NIDNET(ni->ni_nid));
977
978                 LASSERT (libcfs_isknown_lnd(lnd_type));
979
980                 if (lnd_type == CIBLND    ||
981                     lnd_type == OPENIBLND ||
982                     lnd_type == IIBLND    ||
983                     lnd_type == VIBLND) {
984                         CERROR("LND %s obsoleted\n",
985                                libcfs_lnd2str(lnd_type));
986                         goto failed;
987                 }
988
989                 LNET_MUTEX_LOCK(&the_lnet.ln_lnd_mutex);
990                 lnd = lnet_find_lnd_by_type(lnd_type);
991
992 #ifdef __KERNEL__
993                 if (lnd == NULL) {
994                         LNET_MUTEX_UNLOCK(&the_lnet.ln_lnd_mutex);
995                         rc = cfs_request_module("%s",
996                                                 libcfs_lnd2modname(lnd_type));
997                         LNET_MUTEX_LOCK(&the_lnet.ln_lnd_mutex);
998
999                         lnd = lnet_find_lnd_by_type(lnd_type);
1000                         if (lnd == NULL) {
1001                                 LNET_MUTEX_UNLOCK(&the_lnet.ln_lnd_mutex);
1002                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
1003                                        libcfs_lnd2str(lnd_type),
1004                                        libcfs_lnd2modname(lnd_type), rc);
1005 #ifndef HAVE_MODULE_LOADING_SUPPORT
1006                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
1007                                          "compiled with kernel module "
1008                                          "loading support.");
1009 #endif
1010                                 goto failed;
1011                         }
1012                 }
1013 #else
1014                 if (lnd == NULL) {
1015                         LNET_MUTEX_UNLOCK(&the_lnet.ln_lnd_mutex);
1016                         CERROR("LND %s not supported\n",
1017                                libcfs_lnd2str(lnd_type));
1018                         goto failed;
1019                 }
1020 #endif
1021
1022                 ni->ni_refcount = 1;
1023
1024                 LNET_LOCK();
1025                 lnd->lnd_refcount++;
1026                 LNET_UNLOCK();
1027
1028                 ni->ni_lnd = lnd;
1029
1030                 rc = (lnd->lnd_startup)(ni);
1031
1032                 LNET_MUTEX_UNLOCK(&the_lnet.ln_lnd_mutex);
1033
1034                 if (rc != 0) {
1035                         LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s"
1036                                            "\n",
1037                                            rc, libcfs_lnd2str(lnd->lnd_type));
1038                         LNET_LOCK();
1039                         lnd->lnd_refcount--;
1040                         LNET_UNLOCK();
1041                         goto failed;
1042                 }
1043
1044                 LASSERT (ni->ni_peertimeout <= 0 || lnd->lnd_query != NULL);
1045
1046                 cfs_list_del(&ni->ni_list);
1047
1048                 LNET_LOCK();
1049                 cfs_list_add_tail(&ni->ni_list, &the_lnet.ln_nis);
1050                 LNET_UNLOCK();
1051
1052                 if (lnd->lnd_type == LOLND) {
1053                         lnet_ni_addref(ni);
1054                         LASSERT (the_lnet.ln_loni == NULL);
1055                         the_lnet.ln_loni = ni;
1056                         continue;
1057                 }
1058
1059 #ifndef __KERNEL__
1060                 if (lnd->lnd_wait != NULL) {
1061                         if (the_lnet.ln_eqwaitni == NULL) {
1062                                 lnet_ni_addref(ni);
1063                                 the_lnet.ln_eqwaitni = ni;
1064                         }
1065                 } else {
1066 # ifndef HAVE_LIBPTHREAD
1067                         LCONSOLE_ERROR_MSG(0x106, "LND %s not supported in a "
1068                                            "single-threaded runtime\n",
1069                                            libcfs_lnd2str(lnd_type));
1070                         goto failed;
1071 # endif
1072                 }
1073 #endif
1074                 if (ni->ni_peertxcredits == 0 ||
1075                     ni->ni_maxtxcredits == 0) {
1076                         LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
1077                                            libcfs_lnd2str(lnd->lnd_type),
1078                                            ni->ni_peertxcredits == 0 ?
1079                                            "" : "per-peer ");
1080                         goto failed;
1081                 }
1082
1083                 ni->ni_txcredits = ni->ni_mintxcredits = ni->ni_maxtxcredits;
1084
1085                 CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
1086                        libcfs_nid2str(ni->ni_nid),
1087                        ni->ni_peertxcredits, ni->ni_txcredits,
1088                        ni->ni_peerrtrcredits, ni->ni_peertimeout);
1089
1090                 nicount++;
1091         }
1092
1093         if (the_lnet.ln_eqwaitni != NULL && nicount > 1) {
1094                 lnd_type = the_lnet.ln_eqwaitni->ni_lnd->lnd_type;
1095                 LCONSOLE_ERROR_MSG(0x109, "LND %s can only run single-network"
1096                                    "\n",
1097                                    libcfs_lnd2str(lnd_type));
1098                 goto failed;
1099         }
1100
1101         return 0;
1102
1103  failed:
1104         lnet_shutdown_lndnis();
1105
1106         while (!cfs_list_empty(&nilist)) {
1107                 ni = cfs_list_entry(nilist.next, lnet_ni_t, ni_list);
1108                 cfs_list_del(&ni->ni_list);
1109                 LIBCFS_FREE(ni, sizeof(*ni));
1110         }
1111
1112         return -ENETDOWN;
1113 }
1114
1115 /**
1116  * Initialize LNet library.
1117  *
1118  * Only userspace program needs to call this function - it's automatically
1119  * called in the kernel at module loading time. Caller has to call LNetFini()
1120  * after a call to LNetInit(), if and only if the latter returned 0. It must
1121  * be called exactly once.
1122  *
1123  * \return 0 on success, and -ve on failures.
1124  */
1125 int
1126 LNetInit(void)
1127 {
1128         lnet_assert_wire_constants ();
1129         LASSERT (!the_lnet.ln_init);
1130
1131         memset(&the_lnet, 0, sizeof(the_lnet));
1132
1133         lnet_init_locks();
1134         the_lnet.ln_refcount = 0;
1135         the_lnet.ln_init = 1;
1136         LNetInvalidateHandle(&the_lnet.ln_rc_eqh);
1137         CFS_INIT_LIST_HEAD(&the_lnet.ln_lnds);
1138         CFS_INIT_LIST_HEAD(&the_lnet.ln_zombie_rcd);
1139
1140 #ifdef __KERNEL__
1141         /* All LNDs apart from the LOLND are in separate modules.  They
1142          * register themselves when their module loads, and unregister
1143          * themselves when their module is unloaded. */
1144 #else
1145         /* Register LNDs
1146          * NB the order here determines default 'networks=' order */
1147 # ifdef CRAY_XT3
1148         LNET_REGISTER_ULND(the_ptllnd);
1149 # endif
1150 # ifdef HAVE_LIBPTHREAD
1151         LNET_REGISTER_ULND(the_tcplnd);
1152 # endif
1153 #endif
1154         lnet_register_lnd(&the_lolnd);
1155         return 0;
1156 }
1157
1158 /**
1159  * Finalize LNet library.
1160  *
1161  * Only userspace program needs to call this function. It can be called
1162  * at most once.
1163  *
1164  * \pre LNetInit() called with success.
1165  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
1166  */
1167 void
1168 LNetFini(void)
1169 {
1170         LASSERT (the_lnet.ln_init);
1171         LASSERT (the_lnet.ln_refcount == 0);
1172
1173         while (!cfs_list_empty(&the_lnet.ln_lnds))
1174                 lnet_unregister_lnd(cfs_list_entry(the_lnet.ln_lnds.next,
1175                                                    lnd_t, lnd_list));
1176         lnet_fini_locks();
1177
1178         the_lnet.ln_init = 0;
1179 }
1180
1181 /**
1182  * Set LNet PID and start LNet interfaces, routing, and forwarding.
1183  *
1184  * Userspace program should call this after a successful call to LNetInit().
1185  * Users must call this function at least once before any other functions.
1186  * For each successful call there must be a corresponding call to
1187  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
1188  * ignored.
1189  *
1190  * The PID used by LNet may be different from the one requested.
1191  * See LNetGetId().
1192  *
1193  * \param requested_pid PID requested by the caller.
1194  *
1195  * \return >= 0 on success, and < 0 error code on failures.
1196  */
1197 int
1198 LNetNIInit(lnet_pid_t requested_pid)
1199 {
1200         int         im_a_router = 0;
1201         int         rc;
1202
1203         LNET_MUTEX_LOCK(&the_lnet.ln_api_mutex);
1204
1205         LASSERT (the_lnet.ln_init);
1206         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
1207
1208         if (the_lnet.ln_refcount > 0) {
1209                 rc = the_lnet.ln_refcount++;
1210                 goto out;
1211         }
1212
1213         lnet_get_tunables();
1214
1215         if (requested_pid == LNET_PID_ANY) {
1216                 /* Don't instantiate LNET just for me */
1217                 rc = -ENETDOWN;
1218                 goto failed0;
1219         }
1220
1221         rc = lnet_prepare(requested_pid);
1222         if (rc != 0)
1223                 goto failed0;
1224
1225         rc = lnet_startup_lndnis();
1226         if (rc != 0)
1227                 goto failed1;
1228
1229         rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
1230         if (rc != 0)
1231                 goto failed2;
1232
1233         rc = lnet_check_routes();
1234         if (rc != 0)
1235                 goto failed2;
1236
1237         rc = lnet_alloc_rtrpools(im_a_router);
1238         if (rc != 0)
1239                 goto failed2;
1240
1241         rc = lnet_acceptor_start();
1242         if (rc != 0)
1243                 goto failed2;
1244
1245         the_lnet.ln_refcount = 1;
1246         /* Now I may use my own API functions... */
1247
1248         /* NB router checker needs the_lnet.ln_ping_info in
1249          * lnet_router_checker -> lnet_update_ni_status */
1250         rc = lnet_ping_target_init();
1251         if (rc != 0)
1252                 goto failed3;
1253
1254         rc = lnet_router_checker_start();
1255         if (rc != 0)
1256                 goto failed4;
1257
1258         lnet_proc_init();
1259         goto out;
1260
1261  failed4:
1262         lnet_ping_target_fini();
1263  failed3:
1264         the_lnet.ln_refcount = 0;
1265         lnet_acceptor_stop();
1266  failed2:
1267         lnet_destroy_routes();
1268         lnet_shutdown_lndnis();
1269  failed1:
1270         lnet_unprepare();
1271  failed0:
1272         LASSERT (rc < 0);
1273  out:
1274         LNET_MUTEX_UNLOCK(&the_lnet.ln_api_mutex);
1275         return rc;
1276 }
1277
1278 /**
1279  * Stop LNet interfaces, routing, and forwarding.
1280  *
1281  * Users must call this function once for each successful call to LNetNIInit().
1282  * Once the LNetNIFini() operation has been started, the results of pending
1283  * API operations are undefined.
1284  *
1285  * \return always 0 for current implementation.
1286  */
1287 int
1288 LNetNIFini()
1289 {
1290         LNET_MUTEX_LOCK(&the_lnet.ln_api_mutex);
1291
1292         LASSERT (the_lnet.ln_init);
1293         LASSERT (the_lnet.ln_refcount > 0);
1294
1295         if (the_lnet.ln_refcount != 1) {
1296                 the_lnet.ln_refcount--;
1297         } else {
1298                 LASSERT (!the_lnet.ln_niinit_self);
1299
1300                 lnet_proc_fini();
1301                 lnet_router_checker_stop();
1302                 lnet_ping_target_fini();
1303
1304                 /* Teardown fns that use my own API functions BEFORE here */
1305                 the_lnet.ln_refcount = 0;
1306
1307                 lnet_acceptor_stop();
1308                 lnet_destroy_routes();
1309                 lnet_shutdown_lndnis();
1310                 lnet_unprepare();
1311         }
1312
1313         LNET_MUTEX_UNLOCK(&the_lnet.ln_api_mutex);
1314         return 0;
1315 }
1316
1317 /**
1318  * This is an ugly hack to export IOC_LIBCFS_DEBUG_PEER and
1319  * IOC_LIBCFS_PORTALS_COMPATIBILITY commands to users, by tweaking the LNet
1320  * internal ioctl handler.
1321  *
1322  * IOC_LIBCFS_PORTALS_COMPATIBILITY is now deprecated, don't use it.
1323  *
1324  * \param cmd IOC_LIBCFS_DEBUG_PEER to print debugging data about a peer.
1325  * The data will be printed to system console. Don't use it excessively.
1326  * \param arg A pointer to lnet_process_id_t, process ID of the peer.
1327  *
1328  * \return Always return 0 when called by users directly (i.e., not via ioctl).
1329  */
1330 int
1331 LNetCtl(unsigned int cmd, void *arg)
1332 {
1333         struct libcfs_ioctl_data *data = arg;
1334         lnet_process_id_t         id = {0};
1335         lnet_ni_t                *ni;
1336         int                       rc;
1337
1338         LASSERT (the_lnet.ln_init);
1339         LASSERT (the_lnet.ln_refcount > 0);
1340
1341         switch (cmd) {
1342         case IOC_LIBCFS_GET_NI:
1343                 rc = LNetGetId(data->ioc_count, &id);
1344                 data->ioc_nid = id.nid;
1345                 return rc;
1346
1347         case IOC_LIBCFS_FAIL_NID:
1348                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
1349
1350         case IOC_LIBCFS_ADD_ROUTE:
1351                 rc = lnet_add_route(data->ioc_net, data->ioc_count,
1352                                     data->ioc_nid);
1353                 return (rc != 0) ? rc : lnet_check_routes();
1354
1355         case IOC_LIBCFS_DEL_ROUTE:
1356                 return lnet_del_route(data->ioc_net, data->ioc_nid);
1357
1358         case IOC_LIBCFS_GET_ROUTE:
1359                 return lnet_get_route(data->ioc_count,
1360                                       &data->ioc_net, &data->ioc_count,
1361                                       &data->ioc_nid, &data->ioc_flags);
1362         case IOC_LIBCFS_NOTIFY_ROUTER:
1363                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
1364                                    cfs_time_current() -
1365                                    cfs_time_seconds(cfs_time_current_sec() -
1366                                                     (time_t)data->ioc_u64[0]));
1367
1368         case IOC_LIBCFS_PORTALS_COMPATIBILITY:
1369                 /* This can be removed once lustre stops calling it */
1370                 return 0;
1371
1372         case IOC_LIBCFS_LNET_DIST:
1373                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
1374                 if (rc < 0 && rc != -EHOSTUNREACH)
1375                         return rc;
1376
1377                 data->ioc_u32[0] = rc;
1378                 return 0;
1379
1380         case IOC_LIBCFS_TESTPROTOCOMPAT:
1381                 LNET_LOCK();
1382                 the_lnet.ln_testprotocompat = data->ioc_flags;
1383                 LNET_UNLOCK();
1384                 return 0;
1385
1386         case IOC_LIBCFS_PING:
1387                 id.nid = data->ioc_nid;
1388                 id.pid = data->ioc_u32[0];
1389                 rc = lnet_ping(id, data->ioc_u32[1], /* timeout */
1390                                (lnet_process_id_t *)data->ioc_pbuf1,
1391                                data->ioc_plen1/sizeof(lnet_process_id_t));
1392                 if (rc < 0)
1393                         return rc;
1394                 data->ioc_count = rc;
1395                 return 0;
1396
1397         case IOC_LIBCFS_DEBUG_PEER: {
1398                 /* CAVEAT EMPTOR: this one designed for calling directly; not
1399                  * via an ioctl */
1400                 id = *((lnet_process_id_t *) arg);
1401
1402                 lnet_debug_peer(id.nid);
1403
1404                 ni = lnet_net2ni(LNET_NIDNET(id.nid));
1405                 if (ni == NULL) {
1406                         CDEBUG(D_WARNING, "No NI for %s\n", libcfs_id2str(id));
1407                 } else {
1408                         if (ni->ni_lnd->lnd_ctl == NULL) {
1409                                 CDEBUG(D_WARNING, "No ctl for %s\n",
1410                                        libcfs_id2str(id));
1411                         } else {
1412                                 (void)ni->ni_lnd->lnd_ctl(ni, cmd, arg);
1413                         }
1414
1415                         lnet_ni_decref(ni);
1416                 }
1417                 return 0;
1418         }
1419
1420         default:
1421                 ni = lnet_net2ni(data->ioc_net);
1422                 if (ni == NULL)
1423                         return -EINVAL;
1424
1425                 if (ni->ni_lnd->lnd_ctl == NULL)
1426                         rc = -EINVAL;
1427                 else
1428                         rc = ni->ni_lnd->lnd_ctl(ni, cmd, arg);
1429
1430                 lnet_ni_decref(ni);
1431                 return rc;
1432         }
1433         /* not reached */
1434 }
1435
1436 /**
1437  * Retrieve the lnet_process_id_t ID of LNet interface at \a index. Note that
1438  * all interfaces share a same PID, as requested by LNetNIInit().
1439  *
1440  * \param index Index of the interface to look up.
1441  * \param id On successful return, this location will hold the
1442  * lnet_process_id_t ID of the interface.
1443  *
1444  * \retval 0 If an interface exists at \a index.
1445  * \retval -ENOENT If no interface has been found.
1446  */
1447 int
1448 LNetGetId(unsigned int index, lnet_process_id_t *id)
1449 {
1450         lnet_ni_t        *ni;
1451         cfs_list_t       *tmp;
1452         int               rc = -ENOENT;
1453
1454         LASSERT (the_lnet.ln_init);
1455         LASSERT (the_lnet.ln_refcount > 0);
1456
1457         LNET_LOCK();
1458
1459         cfs_list_for_each(tmp, &the_lnet.ln_nis) {
1460                 if (index-- != 0)
1461                         continue;
1462
1463                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
1464
1465                 id->nid = ni->ni_nid;
1466                 id->pid = the_lnet.ln_pid;
1467                 rc = 0;
1468                 break;
1469         }
1470
1471         LNET_UNLOCK();
1472
1473         return rc;
1474 }
1475
1476 /**
1477  * Print a string representation of handle \a h into buffer \a str of
1478  * \a len bytes.
1479  */
1480 void
1481 LNetSnprintHandle(char *str, int len, lnet_handle_any_t h)
1482 {
1483         snprintf(str, len, LPX64, h.cookie);
1484 }
1485
1486 static int
1487 lnet_create_ping_info(void)
1488 {
1489         int               i;
1490         int               n;
1491         int               rc;
1492         unsigned int      infosz;
1493         lnet_ni_t        *ni;
1494         lnet_process_id_t id;
1495         lnet_ping_info_t *pinfo;
1496
1497         for (n = 0; ; n++) {
1498                 rc = LNetGetId(n, &id);
1499                 if (rc == -ENOENT)
1500                         break;
1501
1502                 LASSERT (rc == 0);
1503         }
1504
1505         infosz = offsetof(lnet_ping_info_t, pi_ni[n]);
1506         LIBCFS_ALLOC(pinfo, infosz);
1507         if (pinfo == NULL) {
1508                 CERROR("Can't allocate ping info[%d]\n", n);
1509                 return -ENOMEM;
1510         }
1511
1512         pinfo->pi_nnis    = n;
1513         pinfo->pi_pid     = the_lnet.ln_pid;
1514         pinfo->pi_magic   = LNET_PROTO_PING_MAGIC;
1515         pinfo->pi_version = LNET_PROTO_PING_VERSION;
1516
1517         for (i = 0; i < n; i++) {
1518                 lnet_ni_status_t *ns = &pinfo->pi_ni[i];
1519
1520                 rc = LNetGetId(i, &id);
1521                 LASSERT (rc == 0);
1522
1523                 ns->ns_nid    = id.nid;
1524                 ns->ns_status = LNET_NI_STATUS_UP;
1525
1526                 LNET_LOCK();
1527
1528                 ni = lnet_nid2ni_locked(id.nid);
1529                 LASSERT (ni != NULL);
1530                 LASSERT (ni->ni_status == NULL);
1531                 ni->ni_status = ns;
1532                 lnet_ni_decref_locked(ni);
1533
1534                 LNET_UNLOCK();
1535         }
1536
1537         the_lnet.ln_ping_info = pinfo;
1538         return 0;
1539 }
1540
1541 static void
1542 lnet_destroy_ping_info(void)
1543 {
1544         lnet_ni_t *ni;
1545
1546         LNET_LOCK();
1547
1548         cfs_list_for_each_entry (ni, &the_lnet.ln_nis, ni_list) {
1549                 ni->ni_status = NULL;
1550         }
1551
1552         LNET_UNLOCK();
1553
1554         LIBCFS_FREE(the_lnet.ln_ping_info,
1555                     offsetof(lnet_ping_info_t,
1556                              pi_ni[the_lnet.ln_ping_info->pi_nnis]));
1557         the_lnet.ln_ping_info = NULL;
1558         return;
1559 }
1560
1561 int
1562 lnet_ping_target_init(void)
1563 {
1564         lnet_md_t         md = {0};
1565         lnet_handle_me_t  meh;
1566         lnet_process_id_t id;
1567         int               rc;
1568         int               rc2;
1569         int               infosz;
1570
1571         rc = lnet_create_ping_info();
1572         if (rc != 0)
1573                 return rc;
1574
1575         /* We can have a tiny EQ since we only need to see the unlink event on
1576          * teardown, which by definition is the last one! */
1577         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &the_lnet.ln_ping_target_eq);
1578         if (rc != 0) {
1579                 CERROR("Can't allocate ping EQ: %d\n", rc);
1580                 goto failed_0;
1581         }
1582
1583         memset(&id, 0, sizeof(lnet_process_id_t));
1584         id.nid = LNET_NID_ANY;
1585         id.pid = LNET_PID_ANY;
1586
1587         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1588                           LNET_PROTO_PING_MATCHBITS, 0,
1589                           LNET_UNLINK, LNET_INS_AFTER,
1590                           &meh);
1591         if (rc != 0) {
1592                 CERROR("Can't create ping ME: %d\n", rc);
1593                 goto failed_1;
1594         }
1595
1596         /* initialize md content */
1597         infosz = offsetof(lnet_ping_info_t,
1598                           pi_ni[the_lnet.ln_ping_info->pi_nnis]);
1599         md.start     = the_lnet.ln_ping_info;
1600         md.length    = infosz;
1601         md.threshold = LNET_MD_THRESH_INF;
1602         md.max_size  = 0;
1603         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1604                        LNET_MD_MANAGE_REMOTE;
1605         md.user_ptr  = NULL;
1606         md.eq_handle = the_lnet.ln_ping_target_eq;
1607
1608         rc = LNetMDAttach(meh, md,
1609                           LNET_RETAIN,
1610                           &the_lnet.ln_ping_target_md);
1611         if (rc != 0) {
1612                 CERROR("Can't attach ping MD: %d\n", rc);
1613                 goto failed_2;
1614         }
1615
1616         return 0;
1617
1618  failed_2:
1619         rc2 = LNetMEUnlink(meh);
1620         LASSERT (rc2 == 0);
1621  failed_1:
1622         rc2 = LNetEQFree(the_lnet.ln_ping_target_eq);
1623         LASSERT (rc2 == 0);
1624  failed_0:
1625         lnet_destroy_ping_info();
1626         return rc;
1627 }
1628
1629 void
1630 lnet_ping_target_fini(void)
1631 {
1632         lnet_event_t    event;
1633         int             rc;
1634         int             which;
1635         int             timeout_ms = 1000;
1636         cfs_sigset_t    blocked = cfs_block_allsigs();
1637
1638         LNetMDUnlink(the_lnet.ln_ping_target_md);
1639         /* NB md could be busy; this just starts the unlink */
1640
1641         for (;;) {
1642                 rc = LNetEQPoll(&the_lnet.ln_ping_target_eq, 1,
1643                                 timeout_ms, &event, &which);
1644
1645                 /* I expect overflow... */
1646                 LASSERT (rc >= 0 || rc == -EOVERFLOW);
1647
1648                 if (rc == 0) {
1649                         /* timed out: provide a diagnostic */
1650                         CWARN("Still waiting for ping MD to unlink\n");
1651                         timeout_ms *= 2;
1652                         continue;
1653                 }
1654
1655                 /* Got a valid event */
1656                 if (event.unlinked)
1657                         break;
1658         }
1659
1660         rc = LNetEQFree(the_lnet.ln_ping_target_eq);
1661         LASSERT (rc == 0);
1662         lnet_destroy_ping_info();
1663         cfs_restore_sigs(blocked);
1664 }
1665
1666 int
1667 lnet_ping (lnet_process_id_t id, int timeout_ms, lnet_process_id_t *ids, int n_ids)
1668 {
1669         lnet_handle_eq_t     eqh;
1670         lnet_handle_md_t     mdh;
1671         lnet_event_t         event;
1672         lnet_md_t            md = {0};
1673         int                  which;
1674         int                  unlinked = 0;
1675         int                  replied = 0;
1676         const int            a_long_time = 60000; /* mS */
1677         int                  infosz = offsetof(lnet_ping_info_t, pi_ni[n_ids]);
1678         lnet_ping_info_t    *info;
1679         lnet_process_id_t    tmpid;
1680         int                  i;
1681         int                  nob;
1682         int                  rc;
1683         int                  rc2;
1684         cfs_sigset_t         blocked;
1685
1686         if (n_ids <= 0 ||
1687             id.nid == LNET_NID_ANY ||
1688             timeout_ms > 500000 ||              /* arbitrary limit! */
1689             n_ids > 20)                         /* arbitrary limit! */
1690                 return -EINVAL;
1691
1692         if (id.pid == LNET_PID_ANY)
1693                 id.pid = LUSTRE_SRV_LNET_PID;
1694
1695         LIBCFS_ALLOC(info, infosz);
1696         if (info == NULL)
1697                 return -ENOMEM;
1698
1699         /* NB 2 events max (including any unlink event) */
1700         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
1701         if (rc != 0) {
1702                 CERROR("Can't allocate EQ: %d\n", rc);
1703                 goto out_0;
1704         }
1705
1706         /* initialize md content */
1707         md.start     = info;
1708         md.length    = infosz;
1709         md.threshold = 2; /*GET/REPLY*/
1710         md.max_size  = 0;
1711         md.options   = LNET_MD_TRUNCATE;
1712         md.user_ptr  = NULL;
1713         md.eq_handle = eqh;
1714
1715         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
1716         if (rc != 0) {
1717                 CERROR("Can't bind MD: %d\n", rc);
1718                 goto out_1;
1719         }
1720
1721         rc = LNetGet(LNET_NID_ANY, mdh, id,
1722                      LNET_RESERVED_PORTAL,
1723                      LNET_PROTO_PING_MATCHBITS, 0);
1724
1725         if (rc != 0) {
1726                 /* Don't CERROR; this could be deliberate! */
1727
1728                 rc2 = LNetMDUnlink(mdh);
1729                 LASSERT (rc2 == 0);
1730
1731                 /* NB must wait for the UNLINK event below... */
1732                 unlinked = 1;
1733                 timeout_ms = a_long_time;
1734         }
1735
1736         do {
1737                 /* MUST block for unlink to complete */
1738                 if (unlinked)
1739                         blocked = cfs_block_allsigs();
1740
1741                 rc2 = LNetEQPoll(&eqh, 1, timeout_ms, &event, &which);
1742
1743                 if (unlinked)
1744                         cfs_restore_sigs(blocked);
1745
1746                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
1747                        (rc2 <= 0) ? -1 : event.type,
1748                        (rc2 <= 0) ? -1 : event.status,
1749                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
1750
1751                 LASSERT (rc2 != -EOVERFLOW);     /* can't miss anything */
1752
1753                 if (rc2 <= 0 || event.status != 0) {
1754                         /* timeout or error */
1755                         if (!replied && rc == 0)
1756                                 rc = (rc2 < 0) ? rc2 :
1757                                      (rc2 == 0) ? -ETIMEDOUT :
1758                                      event.status;
1759
1760                         if (!unlinked) {
1761                                 /* Ensure completion in finite time... */
1762                                 LNetMDUnlink(mdh);
1763                                 /* No assertion (racing with network) */
1764                                 unlinked = 1;
1765                                 timeout_ms = a_long_time;
1766                         } else if (rc2 == 0) {
1767                                 /* timed out waiting for unlink */
1768                                 CWARN("ping %s: late network completion\n",
1769                                       libcfs_id2str(id));
1770                         }
1771                 } else if (event.type == LNET_EVENT_REPLY) {
1772                         replied = 1;
1773                         rc = event.mlength;
1774                 }
1775
1776         } while (rc2 <= 0 || !event.unlinked);
1777
1778         if (!replied) {
1779                 if (rc >= 0)
1780                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
1781                               libcfs_id2str(id));
1782                 rc = -EIO;
1783                 goto out_1;
1784         }
1785
1786         nob = rc;
1787         LASSERT (nob >= 0 && nob <= infosz);
1788
1789         rc = -EPROTO;                           /* if I can't parse... */
1790
1791         if (nob < 8) {
1792                 /* can't check magic/version */
1793                 CERROR("%s: ping info too short %d\n",
1794                        libcfs_id2str(id), nob);
1795                 goto out_1;
1796         }
1797
1798         if (info->pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
1799                 lnet_swap_pinginfo(info);
1800         } else if (info->pi_magic != LNET_PROTO_PING_MAGIC) {
1801                 CERROR("%s: Unexpected magic %08x\n", 
1802                        libcfs_id2str(id), info->pi_magic);
1803                 goto out_1;
1804         }
1805
1806         if (info->pi_version != LNET_PROTO_PING_VERSION) {
1807                 CERROR("%s: Unexpected version 0x%x\n",
1808                        libcfs_id2str(id), info->pi_version);
1809                 goto out_1;
1810         }
1811
1812         if (nob < offsetof(lnet_ping_info_t, pi_ni[0])) {
1813                 CERROR("%s: Short reply %d(%d min)\n", libcfs_id2str(id),
1814                        nob, (int)offsetof(lnet_ping_info_t, pi_ni[0]));
1815                 goto out_1;
1816         }
1817
1818         if (info->pi_nnis < n_ids)
1819                 n_ids = info->pi_nnis;
1820
1821         if (nob < offsetof(lnet_ping_info_t, pi_ni[n_ids])) {
1822                 CERROR("%s: Short reply %d(%d expected)\n", libcfs_id2str(id),
1823                        nob, (int)offsetof(lnet_ping_info_t, pi_ni[n_ids]));
1824                 goto out_1;
1825         }
1826
1827         rc = -EFAULT;                           /* If I SEGV... */
1828
1829         for (i = 0; i < n_ids; i++) {
1830                 tmpid.pid = info->pi_pid;
1831                 tmpid.nid = info->pi_ni[i].ns_nid;
1832 #ifdef __KERNEL__
1833                 if (cfs_copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
1834                         goto out_1;
1835 #else
1836                 ids[i] = tmpid;
1837 #endif
1838         }
1839         rc = info->pi_nnis;
1840
1841  out_1:
1842         rc2 = LNetEQFree(eqh);
1843         if (rc2 != 0)
1844                 CERROR("rc2 %d\n", rc2);
1845         LASSERT (rc2 == 0);
1846
1847  out_0:
1848         LIBCFS_FREE(info, infosz);
1849         return rc;
1850 }