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