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