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