Whamcloud - gitweb
e7f9071f56e8af572857bfadab71eac450835ba2
[fs/lustre-release.git] / lnet / klnds / socklnd / socklnd.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, 2015, 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  * lnet/klnds/socklnd/socklnd.c
37  *
38  * Author: Zach Brown <zab@zabbo.net>
39  * Author: Peter J. Braam <braam@clusterfs.com>
40  * Author: Phil Schwan <phil@clusterfs.com>
41  * Author: Eric Barton <eric@bartonsoftware.com>
42  */
43
44 #include "socklnd.h"
45
46 static lnd_t                   the_ksocklnd;
47 ksock_nal_data_t        ksocknal_data;
48
49 static ksock_interface_t *
50 ksocknal_ip2iface(lnet_ni_t *ni, __u32 ip)
51 {
52         ksock_net_t       *net = ni->ni_data;
53         int                i;
54         ksock_interface_t *iface;
55
56         for (i = 0; i < net->ksnn_ninterfaces; i++) {
57                 LASSERT(i < LNET_MAX_INTERFACES);
58                 iface = &net->ksnn_interfaces[i];
59
60                 if (iface->ksni_ipaddr == ip)
61                         return (iface);
62         }
63
64         return (NULL);
65 }
66
67 static ksock_route_t *
68 ksocknal_create_route (__u32 ipaddr, int port)
69 {
70         ksock_route_t *route;
71
72         LIBCFS_ALLOC (route, sizeof (*route));
73         if (route == NULL)
74                 return (NULL);
75
76         atomic_set (&route->ksnr_refcount, 1);
77         route->ksnr_peer = NULL;
78         route->ksnr_retry_interval = 0;         /* OK to connect at any time */
79         route->ksnr_ipaddr = ipaddr;
80         route->ksnr_port = port;
81         route->ksnr_scheduled = 0;
82         route->ksnr_connecting = 0;
83         route->ksnr_connected = 0;
84         route->ksnr_deleted = 0;
85         route->ksnr_conn_count = 0;
86         route->ksnr_share_count = 0;
87
88         return (route);
89 }
90
91 void
92 ksocknal_destroy_route (ksock_route_t *route)
93 {
94         LASSERT (atomic_read(&route->ksnr_refcount) == 0);
95
96         if (route->ksnr_peer != NULL)
97                 ksocknal_peer_decref(route->ksnr_peer);
98
99         LIBCFS_FREE (route, sizeof (*route));
100 }
101
102 static int
103 ksocknal_create_peer(ksock_peer_t **peerp, lnet_ni_t *ni, lnet_process_id_t id)
104 {
105         int             cpt = lnet_cpt_of_nid(id.nid);
106         ksock_net_t     *net = ni->ni_data;
107         ksock_peer_t    *peer;
108
109         LASSERT(id.nid != LNET_NID_ANY);
110         LASSERT(id.pid != LNET_PID_ANY);
111         LASSERT(!in_interrupt());
112
113         LIBCFS_CPT_ALLOC(peer, lnet_cpt_table(), cpt, sizeof(*peer));
114         if (peer == NULL)
115                 return -ENOMEM;
116
117         peer->ksnp_ni = ni;
118         peer->ksnp_id = id;
119         atomic_set(&peer->ksnp_refcount, 1);    /* 1 ref for caller */
120         peer->ksnp_closing = 0;
121         peer->ksnp_accepting = 0;
122         peer->ksnp_proto = NULL;
123         peer->ksnp_last_alive = 0;
124         peer->ksnp_zc_next_cookie = SOCKNAL_KEEPALIVE_PING + 1;
125
126         INIT_LIST_HEAD(&peer->ksnp_conns);
127         INIT_LIST_HEAD(&peer->ksnp_routes);
128         INIT_LIST_HEAD(&peer->ksnp_tx_queue);
129         INIT_LIST_HEAD(&peer->ksnp_zc_req_list);
130         spin_lock_init(&peer->ksnp_lock);
131
132         spin_lock_bh(&net->ksnn_lock);
133
134         if (net->ksnn_shutdown) {
135                 spin_unlock_bh(&net->ksnn_lock);
136
137                 LIBCFS_FREE(peer, sizeof(*peer));
138                 CERROR("Can't create peer: network shutdown\n");
139                 return -ESHUTDOWN;
140         }
141
142         net->ksnn_npeers++;
143
144         spin_unlock_bh(&net->ksnn_lock);
145
146         *peerp = peer;
147         return 0;
148 }
149
150 void
151 ksocknal_destroy_peer (ksock_peer_t *peer)
152 {
153         ksock_net_t    *net = peer->ksnp_ni->ni_data;
154
155         CDEBUG (D_NET, "peer %s %p deleted\n",
156                 libcfs_id2str(peer->ksnp_id), peer);
157
158         LASSERT(atomic_read(&peer->ksnp_refcount) == 0);
159         LASSERT(peer->ksnp_accepting == 0);
160         LASSERT(list_empty(&peer->ksnp_conns));
161         LASSERT(list_empty(&peer->ksnp_routes));
162         LASSERT(list_empty(&peer->ksnp_tx_queue));
163         LASSERT(list_empty(&peer->ksnp_zc_req_list));
164
165         LIBCFS_FREE(peer, sizeof(*peer));
166
167         /* NB a peer's connections and routes keep a reference on their peer
168          * until they are destroyed, so we can be assured that _all_ state to
169          * do with this peer has been cleaned up when its refcount drops to
170          * zero. */
171         spin_lock_bh(&net->ksnn_lock);
172         net->ksnn_npeers--;
173         spin_unlock_bh(&net->ksnn_lock);
174 }
175
176 ksock_peer_t *
177 ksocknal_find_peer_locked (lnet_ni_t *ni, lnet_process_id_t id)
178 {
179         struct list_head *peer_list = ksocknal_nid2peerlist(id.nid);
180         struct list_head *tmp;
181         ksock_peer_t     *peer;
182
183         list_for_each(tmp, peer_list) {
184
185                 peer = list_entry(tmp, ksock_peer_t, ksnp_list);
186
187                 LASSERT(!peer->ksnp_closing);
188
189                 if (peer->ksnp_ni != ni)
190                         continue;
191
192                 if (peer->ksnp_id.nid != id.nid ||
193                     peer->ksnp_id.pid != id.pid)
194                         continue;
195
196                 CDEBUG(D_NET, "got peer [%p] -> %s (%d)\n",
197                        peer, libcfs_id2str(id),
198                        atomic_read(&peer->ksnp_refcount));
199                 return peer;
200         }
201         return NULL;
202 }
203
204 ksock_peer_t *
205 ksocknal_find_peer (lnet_ni_t *ni, lnet_process_id_t id)
206 {
207         ksock_peer_t     *peer;
208
209         read_lock(&ksocknal_data.ksnd_global_lock);
210         peer = ksocknal_find_peer_locked(ni, id);
211         if (peer != NULL)                       /* +1 ref for caller? */
212                 ksocknal_peer_addref(peer);
213         read_unlock(&ksocknal_data.ksnd_global_lock);
214
215         return (peer);
216 }
217
218 static void
219 ksocknal_unlink_peer_locked (ksock_peer_t *peer)
220 {
221         int                i;
222         __u32              ip;
223         ksock_interface_t *iface;
224
225         for (i = 0; i < peer->ksnp_n_passive_ips; i++) {
226                 LASSERT (i < LNET_MAX_INTERFACES);
227                 ip = peer->ksnp_passive_ips[i];
228
229                 iface = ksocknal_ip2iface(peer->ksnp_ni, ip);
230                 /* All IPs in peer->ksnp_passive_ips[] come from the
231                  * interface list, therefore the call must succeed. */
232                 LASSERT (iface != NULL);
233
234                 CDEBUG(D_NET, "peer=%p iface=%p ksni_nroutes=%d\n",
235                        peer, iface, iface->ksni_nroutes);
236                 iface->ksni_npeers--;
237         }
238
239         LASSERT(list_empty(&peer->ksnp_conns));
240         LASSERT(list_empty(&peer->ksnp_routes));
241         LASSERT(!peer->ksnp_closing);
242         peer->ksnp_closing = 1;
243         list_del(&peer->ksnp_list);
244         /* lose peerlist's ref */
245         ksocknal_peer_decref(peer);
246 }
247
248 static int
249 ksocknal_get_peer_info (lnet_ni_t *ni, int index,
250                         lnet_process_id_t *id, __u32 *myip, __u32 *peer_ip,
251                         int *port, int *conn_count, int *share_count)
252 {
253         ksock_peer_t      *peer;
254         struct list_head  *ptmp;
255         ksock_route_t     *route;
256         struct list_head  *rtmp;
257         int                i;
258         int                j;
259         int                rc = -ENOENT;
260
261         read_lock(&ksocknal_data.ksnd_global_lock);
262
263         for (i = 0; i < ksocknal_data.ksnd_peer_hash_size; i++) {
264                 list_for_each(ptmp, &ksocknal_data.ksnd_peers[i]) {
265                         peer = list_entry(ptmp, ksock_peer_t, ksnp_list);
266
267                         if (peer->ksnp_ni != ni)
268                                 continue;
269
270                         if (peer->ksnp_n_passive_ips == 0 &&
271                             list_empty(&peer->ksnp_routes)) {
272                                 if (index-- > 0)
273                                         continue;
274
275                                 *id = peer->ksnp_id;
276                                 *myip = 0;
277                                 *peer_ip = 0;
278                                 *port = 0;
279                                 *conn_count = 0;
280                                 *share_count = 0;
281                                 rc = 0;
282                                 goto out;
283                         }
284
285                         for (j = 0; j < peer->ksnp_n_passive_ips; j++) {
286                                 if (index-- > 0)
287                                         continue;
288
289                                 *id = peer->ksnp_id;
290                                 *myip = peer->ksnp_passive_ips[j];
291                                 *peer_ip = 0;
292                                 *port = 0;
293                                 *conn_count = 0;
294                                 *share_count = 0;
295                                 rc = 0;
296                                 goto out;
297                         }
298
299                         list_for_each(rtmp, &peer->ksnp_routes) {
300                                 if (index-- > 0)
301                                         continue;
302
303                                 route = list_entry(rtmp, ksock_route_t,
304                                                    ksnr_list);
305
306                                 *id = peer->ksnp_id;
307                                 *myip = route->ksnr_myipaddr;
308                                 *peer_ip = route->ksnr_ipaddr;
309                                 *port = route->ksnr_port;
310                                 *conn_count = route->ksnr_conn_count;
311                                 *share_count = route->ksnr_share_count;
312                                 rc = 0;
313                                 goto out;
314                         }
315                 }
316         }
317 out:
318         read_unlock(&ksocknal_data.ksnd_global_lock);
319         return rc;
320 }
321
322 static void
323 ksocknal_associate_route_conn_locked(ksock_route_t *route, ksock_conn_t *conn)
324 {
325         ksock_peer_t      *peer = route->ksnr_peer;
326         int                type = conn->ksnc_type;
327         ksock_interface_t *iface;
328
329         conn->ksnc_route = route;
330         ksocknal_route_addref(route);
331
332         if (route->ksnr_myipaddr != conn->ksnc_myipaddr) {
333                 if (route->ksnr_myipaddr == 0) {
334                         /* route wasn't bound locally yet (the initial route) */
335                         CDEBUG(D_NET, "Binding %s %pI4h to %pI4h\n",
336                                libcfs_id2str(peer->ksnp_id),
337                                &route->ksnr_ipaddr,
338                                &conn->ksnc_myipaddr);
339                 } else {
340                         CDEBUG(D_NET, "Rebinding %s %pI4h from %pI4h "
341                                "to %pI4h\n", libcfs_id2str(peer->ksnp_id),
342                                &route->ksnr_ipaddr,
343                                &route->ksnr_myipaddr,
344                                &conn->ksnc_myipaddr);
345
346                         iface = ksocknal_ip2iface(route->ksnr_peer->ksnp_ni,
347                                                   route->ksnr_myipaddr);
348                         if (iface != NULL)
349                                 iface->ksni_nroutes--;
350                 }
351                 route->ksnr_myipaddr = conn->ksnc_myipaddr;
352                 iface = ksocknal_ip2iface(route->ksnr_peer->ksnp_ni,
353                                           route->ksnr_myipaddr);
354                 if (iface != NULL)
355                         iface->ksni_nroutes++;
356         }
357
358         route->ksnr_connected |= (1<<type);
359         route->ksnr_conn_count++;
360
361         /* Successful connection => further attempts can
362          * proceed immediately */
363         route->ksnr_retry_interval = 0;
364 }
365
366 static void
367 ksocknal_add_route_locked (ksock_peer_t *peer, ksock_route_t *route)
368 {
369         struct list_head *tmp;
370         ksock_conn_t     *conn;
371         ksock_route_t    *route2;
372
373         LASSERT(!peer->ksnp_closing);
374         LASSERT(route->ksnr_peer == NULL);
375         LASSERT(!route->ksnr_scheduled);
376         LASSERT(!route->ksnr_connecting);
377         LASSERT(route->ksnr_connected == 0);
378
379         /* LASSERT(unique) */
380         list_for_each(tmp, &peer->ksnp_routes) {
381                 route2 = list_entry(tmp, ksock_route_t, ksnr_list);
382
383                 if (route2->ksnr_ipaddr == route->ksnr_ipaddr) {
384                         CERROR("Duplicate route %s %pI4h\n",
385                                libcfs_id2str(peer->ksnp_id),
386                                &route->ksnr_ipaddr);
387                         LBUG();
388                 }
389         }
390
391         route->ksnr_peer = peer;
392         ksocknal_peer_addref(peer);
393         /* peer's routelist takes over my ref on 'route' */
394         list_add_tail(&route->ksnr_list, &peer->ksnp_routes);
395
396         list_for_each(tmp, &peer->ksnp_conns) {
397                 conn = list_entry(tmp, ksock_conn_t, ksnc_list);
398
399                 if (conn->ksnc_ipaddr != route->ksnr_ipaddr)
400                         continue;
401
402                 ksocknal_associate_route_conn_locked(route, conn);
403                 /* keep going (typed routes) */
404         }
405 }
406
407 static void
408 ksocknal_del_route_locked (ksock_route_t *route)
409 {
410         ksock_peer_t      *peer = route->ksnr_peer;
411         ksock_interface_t *iface;
412         ksock_conn_t      *conn;
413         struct list_head  *ctmp;
414         struct list_head  *cnxt;
415
416         LASSERT(!route->ksnr_deleted);
417
418         /* Close associated conns */
419         list_for_each_safe(ctmp, cnxt, &peer->ksnp_conns) {
420                 conn = list_entry(ctmp, ksock_conn_t, ksnc_list);
421
422                 if (conn->ksnc_route != route)
423                         continue;
424
425                 ksocknal_close_conn_locked(conn, 0);
426         }
427
428         if (route->ksnr_myipaddr != 0) {
429                 iface = ksocknal_ip2iface(route->ksnr_peer->ksnp_ni,
430                                           route->ksnr_myipaddr);
431                 if (iface != NULL)
432                         iface->ksni_nroutes--;
433         }
434
435         route->ksnr_deleted = 1;
436         list_del(&route->ksnr_list);
437         ksocknal_route_decref(route);           /* drop peer's ref */
438
439         if (list_empty(&peer->ksnp_routes) &&
440             list_empty(&peer->ksnp_conns)) {
441                 /* I've just removed the last route to a peer with no active
442                  * connections */
443                 ksocknal_unlink_peer_locked(peer);
444         }
445 }
446
447 int
448 ksocknal_add_peer(lnet_ni_t *ni, lnet_process_id_t id, __u32 ipaddr, int port)
449 {
450         struct list_head *tmp;
451         ksock_peer_t     *peer;
452         ksock_peer_t     *peer2;
453         ksock_route_t    *route;
454         ksock_route_t    *route2;
455         int               rc;
456
457         if (id.nid == LNET_NID_ANY ||
458             id.pid == LNET_PID_ANY)
459                 return (-EINVAL);
460
461         /* Have a brand new peer ready... */
462         rc = ksocknal_create_peer(&peer, ni, id);
463         if (rc != 0)
464                 return rc;
465
466         route = ksocknal_create_route (ipaddr, port);
467         if (route == NULL) {
468                 ksocknal_peer_decref(peer);
469                 return (-ENOMEM);
470         }
471
472         write_lock_bh(&ksocknal_data.ksnd_global_lock);
473
474         /* always called with a ref on ni, so shutdown can't have started */
475         LASSERT (((ksock_net_t *) ni->ni_data)->ksnn_shutdown == 0);
476
477         peer2 = ksocknal_find_peer_locked(ni, id);
478         if (peer2 != NULL) {
479                 ksocknal_peer_decref(peer);
480                 peer = peer2;
481         } else {
482                 /* peer table takes my ref on peer */
483                 list_add_tail(&peer->ksnp_list,
484                               ksocknal_nid2peerlist(id.nid));
485         }
486
487         route2 = NULL;
488         list_for_each(tmp, &peer->ksnp_routes) {
489                 route2 = list_entry(tmp, ksock_route_t, ksnr_list);
490
491                 if (route2->ksnr_ipaddr == ipaddr)
492                         break;
493
494                 route2 = NULL;
495         }
496         if (route2 == NULL) {
497                 ksocknal_add_route_locked(peer, route);
498                 route->ksnr_share_count++;
499         } else {
500                 ksocknal_route_decref(route);
501                 route2->ksnr_share_count++;
502         }
503
504         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
505
506         return 0;
507 }
508
509 static void
510 ksocknal_del_peer_locked (ksock_peer_t *peer, __u32 ip)
511 {
512         ksock_conn_t     *conn;
513         ksock_route_t    *route;
514         struct list_head *tmp;
515         struct list_head *nxt;
516         int               nshared;
517
518         LASSERT(!peer->ksnp_closing);
519
520         /* Extra ref prevents peer disappearing until I'm done with it */
521         ksocknal_peer_addref(peer);
522
523         list_for_each_safe(tmp, nxt, &peer->ksnp_routes) {
524                 route = list_entry(tmp, ksock_route_t, ksnr_list);
525
526                 /* no match */
527                 if (!(ip == 0 || route->ksnr_ipaddr == ip))
528                         continue;
529
530                 route->ksnr_share_count = 0;
531                 /* This deletes associated conns too */
532                 ksocknal_del_route_locked(route);
533         }
534
535         nshared = 0;
536         list_for_each_safe(tmp, nxt, &peer->ksnp_routes) {
537                 route = list_entry(tmp, ksock_route_t, ksnr_list);
538                 nshared += route->ksnr_share_count;
539         }
540
541         if (nshared == 0) {
542                 /* remove everything else if there are no explicit entries
543                  * left */
544
545                 list_for_each_safe(tmp, nxt, &peer->ksnp_routes) {
546                         route = list_entry(tmp, ksock_route_t, ksnr_list);
547
548                         /* we should only be removing auto-entries */
549                         LASSERT(route->ksnr_share_count == 0);
550                         ksocknal_del_route_locked(route);
551                 }
552
553                 list_for_each_safe(tmp, nxt, &peer->ksnp_conns) {
554                         conn = list_entry(tmp, ksock_conn_t, ksnc_list);
555
556                         ksocknal_close_conn_locked(conn, 0);
557                 }
558         }
559
560         ksocknal_peer_decref(peer);
561                 /* NB peer unlinks itself when last conn/route is removed */
562 }
563
564 static int
565 ksocknal_del_peer (lnet_ni_t *ni, lnet_process_id_t id, __u32 ip)
566 {
567         struct list_head  zombies = LIST_HEAD_INIT(zombies);
568         struct list_head *ptmp;
569         struct list_head *pnxt;
570         ksock_peer_t     *peer;
571         int               lo;
572         int               hi;
573         int               i;
574         int               rc = -ENOENT;
575
576         write_lock_bh(&ksocknal_data.ksnd_global_lock);
577
578         if (id.nid != LNET_NID_ANY) {
579                 hi = (int)(ksocknal_nid2peerlist(id.nid) -
580                            ksocknal_data.ksnd_peers);
581                 lo = hi;
582         } else {
583                 lo = 0;
584                 hi = ksocknal_data.ksnd_peer_hash_size - 1;
585         }
586
587         for (i = lo; i <= hi; i++) {
588                 list_for_each_safe(ptmp, pnxt,
589                                    &ksocknal_data.ksnd_peers[i]) {
590                         peer = list_entry(ptmp, ksock_peer_t, ksnp_list);
591
592                         if (peer->ksnp_ni != ni)
593                                 continue;
594
595                         if (!((id.nid == LNET_NID_ANY ||
596                                peer->ksnp_id.nid == id.nid) &&
597                               (id.pid == LNET_PID_ANY ||
598                                peer->ksnp_id.pid == id.pid)))
599                                 continue;
600
601                         ksocknal_peer_addref(peer);     /* a ref for me... */
602
603                         ksocknal_del_peer_locked(peer, ip);
604
605                         if (peer->ksnp_closing &&
606                             !list_empty(&peer->ksnp_tx_queue)) {
607                                 LASSERT(list_empty(&peer->ksnp_conns));
608                                 LASSERT(list_empty(&peer->ksnp_routes));
609
610                                 list_splice_init(&peer->ksnp_tx_queue,
611                                                  &zombies);
612                         }
613
614                         ksocknal_peer_decref(peer);     /* ...till here */
615
616                         rc = 0;                         /* matched! */
617                 }
618         }
619
620         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
621
622         ksocknal_txlist_done(ni, &zombies, 1);
623
624         return rc;
625 }
626
627 static ksock_conn_t *
628 ksocknal_get_conn_by_idx (lnet_ni_t *ni, int index)
629 {
630         ksock_peer_t     *peer;
631         struct list_head *ptmp;
632         ksock_conn_t     *conn;
633         struct list_head *ctmp;
634         int               i;
635
636         read_lock(&ksocknal_data.ksnd_global_lock);
637
638         for (i = 0; i < ksocknal_data.ksnd_peer_hash_size; i++) {
639                 list_for_each(ptmp, &ksocknal_data.ksnd_peers[i]) {
640                         peer = list_entry(ptmp, ksock_peer_t, ksnp_list);
641
642                         LASSERT(!peer->ksnp_closing);
643
644                         if (peer->ksnp_ni != ni)
645                                 continue;
646
647                         list_for_each(ctmp, &peer->ksnp_conns) {
648                                 if (index-- > 0)
649                                         continue;
650
651                                 conn = list_entry(ctmp, ksock_conn_t,
652                                                   ksnc_list);
653                                 ksocknal_conn_addref(conn);
654                                 read_unlock(&ksocknal_data. \
655                                             ksnd_global_lock);
656                                 return conn;
657                         }
658                 }
659         }
660
661         read_unlock(&ksocknal_data.ksnd_global_lock);
662         return NULL;
663 }
664
665 static ksock_sched_t *
666 ksocknal_choose_scheduler_locked(unsigned int cpt)
667 {
668         struct ksock_sched_info *info = ksocknal_data.ksnd_sched_info[cpt];
669         ksock_sched_t           *sched;
670         int                     i;
671
672         LASSERT(info->ksi_nthreads > 0);
673
674         sched = &info->ksi_scheds[0];
675         /*
676          * NB: it's safe so far, but info->ksi_nthreads could be changed
677          * at runtime when we have dynamic LNet configuration, then we
678          * need to take care of this.
679          */
680         for (i = 1; i < info->ksi_nthreads; i++) {
681                 if (sched->kss_nconns > info->ksi_scheds[i].kss_nconns)
682                         sched = &info->ksi_scheds[i];
683         }
684
685         return sched;
686 }
687
688 static int
689 ksocknal_local_ipvec (lnet_ni_t *ni, __u32 *ipaddrs)
690 {
691         ksock_net_t       *net = ni->ni_data;
692         int                i;
693         int                nip;
694
695         read_lock(&ksocknal_data.ksnd_global_lock);
696
697         nip = net->ksnn_ninterfaces;
698         LASSERT (nip <= LNET_MAX_INTERFACES);
699
700         /* Only offer interfaces for additional connections if I have
701          * more than one. */
702         if (nip < 2) {
703                 read_unlock(&ksocknal_data.ksnd_global_lock);
704                 return 0;
705         }
706
707         for (i = 0; i < nip; i++) {
708                 ipaddrs[i] = net->ksnn_interfaces[i].ksni_ipaddr;
709                 LASSERT (ipaddrs[i] != 0);
710         }
711
712         read_unlock(&ksocknal_data.ksnd_global_lock);
713         return (nip);
714 }
715
716 static int
717 ksocknal_match_peerip (ksock_interface_t *iface, __u32 *ips, int nips)
718 {
719         int   best_netmatch = 0;
720         int   best_xor      = 0;
721         int   best          = -1;
722         int   this_xor;
723         int   this_netmatch;
724         int   i;
725
726         for (i = 0; i < nips; i++) {
727                 if (ips[i] == 0)
728                         continue;
729
730                 this_xor = (ips[i] ^ iface->ksni_ipaddr);
731                 this_netmatch = ((this_xor & iface->ksni_netmask) == 0) ? 1 : 0;
732
733                 if (!(best < 0 ||
734                       best_netmatch < this_netmatch ||
735                       (best_netmatch == this_netmatch &&
736                        best_xor > this_xor)))
737                         continue;
738
739                 best = i;
740                 best_netmatch = this_netmatch;
741                 best_xor = this_xor;
742         }
743
744         LASSERT (best >= 0);
745         return (best);
746 }
747
748 static int
749 ksocknal_select_ips(ksock_peer_t *peer, __u32 *peerips, int n_peerips)
750 {
751         rwlock_t                *global_lock = &ksocknal_data.ksnd_global_lock;
752         ksock_net_t        *net = peer->ksnp_ni->ni_data;
753         ksock_interface_t  *iface;
754         ksock_interface_t  *best_iface;
755         int                 n_ips;
756         int                 i;
757         int                 j;
758         int                 k;
759         __u32               ip;
760         __u32               xor;
761         int                 this_netmatch;
762         int                 best_netmatch;
763         int                 best_npeers;
764
765         /* CAVEAT EMPTOR: We do all our interface matching with an
766          * exclusive hold of global lock at IRQ priority.  We're only
767          * expecting to be dealing with small numbers of interfaces, so the
768          * O(n**3)-ness shouldn't matter */
769
770         /* Also note that I'm not going to return more than n_peerips
771          * interfaces, even if I have more myself */
772
773         write_lock_bh(global_lock);
774
775         LASSERT (n_peerips <= LNET_MAX_INTERFACES);
776         LASSERT (net->ksnn_ninterfaces <= LNET_MAX_INTERFACES);
777
778         /* Only match interfaces for additional connections
779          * if I have > 1 interface */
780         n_ips = (net->ksnn_ninterfaces < 2) ? 0 :
781                 MIN(n_peerips, net->ksnn_ninterfaces);
782
783         for (i = 0; peer->ksnp_n_passive_ips < n_ips; i++) {
784                 /*              ^ yes really... */
785
786                 /* If we have any new interfaces, first tick off all the
787                  * peer IPs that match old interfaces, then choose new
788                  * interfaces to match the remaining peer IPS.
789                  * We don't forget interfaces we've stopped using; we might
790                  * start using them again... */
791
792                 if (i < peer->ksnp_n_passive_ips) {
793                         /* Old interface. */
794                         ip = peer->ksnp_passive_ips[i];
795                         best_iface = ksocknal_ip2iface(peer->ksnp_ni, ip);
796
797                         /* peer passive ips are kept up to date */
798                         LASSERT(best_iface != NULL);
799                 } else {
800                         /* choose a new interface */
801                         LASSERT (i == peer->ksnp_n_passive_ips);
802
803                         best_iface = NULL;
804                         best_netmatch = 0;
805                         best_npeers = 0;
806
807                         for (j = 0; j < net->ksnn_ninterfaces; j++) {
808                                 iface = &net->ksnn_interfaces[j];
809                                 ip = iface->ksni_ipaddr;
810
811                                 for (k = 0; k < peer->ksnp_n_passive_ips; k++)
812                                         if (peer->ksnp_passive_ips[k] == ip)
813                                                 break;
814
815                                 if (k < peer->ksnp_n_passive_ips) /* using it already */
816                                         continue;
817
818                                 k = ksocknal_match_peerip(iface, peerips, n_peerips);
819                                 xor = (ip ^ peerips[k]);
820                                 this_netmatch = ((xor & iface->ksni_netmask) == 0) ? 1 : 0;
821
822                                 if (!(best_iface == NULL ||
823                                       best_netmatch < this_netmatch ||
824                                       (best_netmatch == this_netmatch &&
825                                        best_npeers > iface->ksni_npeers)))
826                                         continue;
827
828                                 best_iface = iface;
829                                 best_netmatch = this_netmatch;
830                                 best_npeers = iface->ksni_npeers;
831                         }
832
833                         LASSERT(best_iface != NULL);
834
835                         best_iface->ksni_npeers++;
836                         ip = best_iface->ksni_ipaddr;
837                         peer->ksnp_passive_ips[i] = ip;
838                         peer->ksnp_n_passive_ips = i+1;
839                 }
840
841                 /* mark the best matching peer IP used */
842                 j = ksocknal_match_peerip(best_iface, peerips, n_peerips);
843                 peerips[j] = 0;
844         }
845
846         /* Overwrite input peer IP addresses */
847         memcpy(peerips, peer->ksnp_passive_ips, n_ips * sizeof(*peerips));
848
849         write_unlock_bh(global_lock);
850
851         return (n_ips);
852 }
853
854 static void
855 ksocknal_create_routes(ksock_peer_t *peer, int port,
856                        __u32 *peer_ipaddrs, int npeer_ipaddrs)
857 {
858         ksock_route_t           *newroute = NULL;
859         rwlock_t                *global_lock = &ksocknal_data.ksnd_global_lock;
860         lnet_ni_t               *ni = peer->ksnp_ni;
861         ksock_net_t             *net = ni->ni_data;
862         struct list_head        *rtmp;
863         ksock_route_t           *route;
864         ksock_interface_t       *iface;
865         ksock_interface_t       *best_iface;
866         int                     best_netmatch;
867         int                     this_netmatch;
868         int                     best_nroutes;
869         int                     i;
870         int                     j;
871
872         /* CAVEAT EMPTOR: We do all our interface matching with an
873          * exclusive hold of global lock at IRQ priority.  We're only
874          * expecting to be dealing with small numbers of interfaces, so the
875          * O(n**3)-ness here shouldn't matter */
876
877         write_lock_bh(global_lock);
878
879         if (net->ksnn_ninterfaces < 2) {
880                 /* Only create additional connections
881                  * if I have > 1 interface */
882                 write_unlock_bh(global_lock);
883                 return;
884         }
885
886         LASSERT (npeer_ipaddrs <= LNET_MAX_INTERFACES);
887
888         for (i = 0; i < npeer_ipaddrs; i++) {
889                 if (newroute != NULL) {
890                         newroute->ksnr_ipaddr = peer_ipaddrs[i];
891                 } else {
892                         write_unlock_bh(global_lock);
893
894                         newroute = ksocknal_create_route(peer_ipaddrs[i], port);
895                         if (newroute == NULL)
896                                 return;
897
898                         write_lock_bh(global_lock);
899                 }
900
901                 if (peer->ksnp_closing) {
902                         /* peer got closed under me */
903                         break;
904                 }
905
906                 /* Already got a route? */
907                 route = NULL;
908                 list_for_each(rtmp, &peer->ksnp_routes) {
909                         route = list_entry(rtmp, ksock_route_t, ksnr_list);
910
911                         if (route->ksnr_ipaddr == newroute->ksnr_ipaddr)
912                                 break;
913
914                         route = NULL;
915                 }
916                 if (route != NULL)
917                         continue;
918
919                 best_iface = NULL;
920                 best_nroutes = 0;
921                 best_netmatch = 0;
922
923                 LASSERT(net->ksnn_ninterfaces <= LNET_MAX_INTERFACES);
924
925                 /* Select interface to connect from */
926                 for (j = 0; j < net->ksnn_ninterfaces; j++) {
927                         iface = &net->ksnn_interfaces[j];
928
929                         /* Using this interface already? */
930                         list_for_each(rtmp, &peer->ksnp_routes) {
931                                 route = list_entry(rtmp, ksock_route_t,
932                                                    ksnr_list);
933
934                                 if (route->ksnr_myipaddr == iface->ksni_ipaddr)
935                                         break;
936
937                                 route = NULL;
938                         }
939                         if (route != NULL)
940                                 continue;
941
942                         this_netmatch = (((iface->ksni_ipaddr ^
943                                            newroute->ksnr_ipaddr) &
944                                            iface->ksni_netmask) == 0) ? 1 : 0;
945
946                         if (!(best_iface == NULL ||
947                               best_netmatch < this_netmatch ||
948                               (best_netmatch == this_netmatch &&
949                                best_nroutes > iface->ksni_nroutes)))
950                                 continue;
951
952                         best_iface = iface;
953                         best_netmatch = this_netmatch;
954                         best_nroutes = iface->ksni_nroutes;
955                 }
956
957                 if (best_iface == NULL)
958                         continue;
959
960                 newroute->ksnr_myipaddr = best_iface->ksni_ipaddr;
961                 best_iface->ksni_nroutes++;
962
963                 ksocknal_add_route_locked(peer, newroute);
964                 newroute = NULL;
965         }
966
967         write_unlock_bh(global_lock);
968         if (newroute != NULL)
969                 ksocknal_route_decref(newroute);
970 }
971
972 int
973 ksocknal_accept(lnet_ni_t *ni, struct socket *sock)
974 {
975         ksock_connreq_t *cr;
976         int              rc;
977         __u32            peer_ip;
978         int              peer_port;
979
980         rc = lnet_sock_getaddr(sock, true, &peer_ip, &peer_port);
981         LASSERT(rc == 0);               /* we succeeded before */
982
983         LIBCFS_ALLOC(cr, sizeof(*cr));
984         if (cr == NULL) {
985                 LCONSOLE_ERROR_MSG(0x12f, "Dropping connection request from "
986                                    "%pI4h: memory exhausted\n", &peer_ip);
987                 return -ENOMEM;
988         }
989
990         lnet_ni_addref(ni);
991         cr->ksncr_ni   = ni;
992         cr->ksncr_sock = sock;
993
994         spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
995
996         list_add_tail(&cr->ksncr_list, &ksocknal_data.ksnd_connd_connreqs);
997         wake_up(&ksocknal_data.ksnd_connd_waitq);
998
999         spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
1000         return 0;
1001 }
1002
1003 static int
1004 ksocknal_connecting (ksock_peer_t *peer, __u32 ipaddr)
1005 {
1006         ksock_route_t *route;
1007
1008         list_for_each_entry(route, &peer->ksnp_routes, ksnr_list) {
1009                 if (route->ksnr_ipaddr == ipaddr)
1010                         return route->ksnr_connecting;
1011         }
1012         return 0;
1013 }
1014
1015 int
1016 ksocknal_create_conn(lnet_ni_t *ni, ksock_route_t *route,
1017                      struct socket *sock, int type)
1018 {
1019         rwlock_t                *global_lock = &ksocknal_data.ksnd_global_lock;
1020         struct list_head        zombies = LIST_HEAD_INIT(zombies);
1021         lnet_process_id_t       peerid;
1022         struct list_head        *tmp;
1023         __u64              incarnation;
1024         ksock_conn_t      *conn;
1025         ksock_conn_t      *conn2;
1026         ksock_peer_t      *peer = NULL;
1027         ksock_peer_t      *peer2;
1028         ksock_sched_t     *sched;
1029         ksock_hello_msg_t *hello;
1030         int                cpt;
1031         ksock_tx_t        *tx;
1032         ksock_tx_t        *txtmp;
1033         int                rc;
1034         int                active;
1035         char              *warn = NULL;
1036
1037         active = (route != NULL);
1038
1039         LASSERT (active == (type != SOCKLND_CONN_NONE));
1040
1041         LIBCFS_ALLOC(conn, sizeof(*conn));
1042         if (conn == NULL) {
1043                 rc = -ENOMEM;
1044                 goto failed_0;
1045         }
1046
1047         conn->ksnc_peer = NULL;
1048         conn->ksnc_route = NULL;
1049         conn->ksnc_sock = sock;
1050         /* 2 ref, 1 for conn, another extra ref prevents socket
1051          * being closed before establishment of connection */
1052         atomic_set (&conn->ksnc_sock_refcount, 2);
1053         conn->ksnc_type = type;
1054         ksocknal_lib_save_callback(sock, conn);
1055         atomic_set (&conn->ksnc_conn_refcount, 1); /* 1 ref for me */
1056
1057         conn->ksnc_rx_ready = 0;
1058         conn->ksnc_rx_scheduled = 0;
1059
1060         INIT_LIST_HEAD(&conn->ksnc_tx_queue);
1061         conn->ksnc_tx_ready = 0;
1062         conn->ksnc_tx_scheduled = 0;
1063         conn->ksnc_tx_carrier = NULL;
1064         atomic_set (&conn->ksnc_tx_nob, 0);
1065
1066         LIBCFS_ALLOC(hello, offsetof(ksock_hello_msg_t,
1067                                      kshm_ips[LNET_MAX_INTERFACES]));
1068         if (hello == NULL) {
1069                 rc = -ENOMEM;
1070                 goto failed_1;
1071         }
1072
1073         /* stash conn's local and remote addrs */
1074         rc = ksocknal_lib_get_conn_addrs (conn);
1075         if (rc != 0)
1076                 goto failed_1;
1077
1078         /* Find out/confirm peer's NID and connection type and get the
1079          * vector of interfaces she's willing to let me connect to.
1080          * Passive connections use the listener timeout since the peer sends
1081          * eagerly */
1082
1083         if (active) {
1084                 peer = route->ksnr_peer;
1085                 LASSERT(ni == peer->ksnp_ni);
1086
1087                 /* Active connection sends HELLO eagerly */
1088                 hello->kshm_nips = ksocknal_local_ipvec(ni, hello->kshm_ips);
1089                 peerid = peer->ksnp_id;
1090
1091                 write_lock_bh(global_lock);
1092                 conn->ksnc_proto = peer->ksnp_proto;
1093                 write_unlock_bh(global_lock);
1094
1095                 if (conn->ksnc_proto == NULL) {
1096                          conn->ksnc_proto = &ksocknal_protocol_v3x;
1097 #if SOCKNAL_VERSION_DEBUG
1098                          if (*ksocknal_tunables.ksnd_protocol == 2)
1099                                  conn->ksnc_proto = &ksocknal_protocol_v2x;
1100                          else if (*ksocknal_tunables.ksnd_protocol == 1)
1101                                  conn->ksnc_proto = &ksocknal_protocol_v1x;
1102 #endif
1103                 }
1104
1105                 rc = ksocknal_send_hello (ni, conn, peerid.nid, hello);
1106                 if (rc != 0)
1107                         goto failed_1;
1108         } else {
1109                 peerid.nid = LNET_NID_ANY;
1110                 peerid.pid = LNET_PID_ANY;
1111
1112                 /* Passive, get protocol from peer */
1113                 conn->ksnc_proto = NULL;
1114         }
1115
1116         rc = ksocknal_recv_hello (ni, conn, hello, &peerid, &incarnation);
1117         if (rc < 0)
1118                 goto failed_1;
1119
1120         LASSERT (rc == 0 || active);
1121         LASSERT (conn->ksnc_proto != NULL);
1122         LASSERT (peerid.nid != LNET_NID_ANY);
1123
1124         cpt = lnet_cpt_of_nid(peerid.nid);
1125
1126         if (active) {
1127                 ksocknal_peer_addref(peer);
1128                 write_lock_bh(global_lock);
1129         } else {
1130                 rc = ksocknal_create_peer(&peer, ni, peerid);
1131                 if (rc != 0)
1132                         goto failed_1;
1133
1134                 write_lock_bh(global_lock);
1135
1136                 /* called with a ref on ni, so shutdown can't have started */
1137                 LASSERT (((ksock_net_t *) ni->ni_data)->ksnn_shutdown == 0);
1138
1139                 peer2 = ksocknal_find_peer_locked(ni, peerid);
1140                 if (peer2 == NULL) {
1141                         /* NB this puts an "empty" peer in the peer
1142                          * table (which takes my ref) */
1143                         list_add_tail(&peer->ksnp_list,
1144                                       ksocknal_nid2peerlist(peerid.nid));
1145                 } else {
1146                         ksocknal_peer_decref(peer);
1147                         peer = peer2;
1148                 }
1149
1150                 /* +1 ref for me */
1151                 ksocknal_peer_addref(peer);
1152                 peer->ksnp_accepting++;
1153
1154                 /* Am I already connecting to this guy?  Resolve in
1155                  * favour of higher NID... */
1156                 if (peerid.nid < ni->ni_nid &&
1157                     ksocknal_connecting(peer, conn->ksnc_ipaddr)) {
1158                         rc = EALREADY;
1159                         warn = "connection race resolution";
1160                         goto failed_2;
1161                 }
1162         }
1163
1164         if (peer->ksnp_closing ||
1165             (active && route->ksnr_deleted)) {
1166                 /* peer/route got closed under me */
1167                 rc = -ESTALE;
1168                 warn = "peer/route removed";
1169                 goto failed_2;
1170         }
1171
1172         if (peer->ksnp_proto == NULL) {
1173                 /* Never connected before.
1174                  * NB recv_hello may have returned EPROTO to signal my peer
1175                  * wants a different protocol than the one I asked for.
1176                  */
1177                 LASSERT(list_empty(&peer->ksnp_conns));
1178
1179                 peer->ksnp_proto = conn->ksnc_proto;
1180                 peer->ksnp_incarnation = incarnation;
1181         }
1182
1183         if (peer->ksnp_proto != conn->ksnc_proto ||
1184             peer->ksnp_incarnation != incarnation) {
1185                 /* Peer rebooted or I've got the wrong protocol version */
1186                 ksocknal_close_peer_conns_locked(peer, 0, 0);
1187
1188                 peer->ksnp_proto = NULL;
1189                 rc = ESTALE;
1190                 warn = peer->ksnp_incarnation != incarnation ?
1191                        "peer rebooted" :
1192                        "wrong proto version";
1193                 goto failed_2;
1194         }
1195
1196         switch (rc) {
1197         default:
1198                 LBUG();
1199         case 0:
1200                 break;
1201         case EALREADY:
1202                 warn = "lost conn race";
1203                 goto failed_2;
1204         case EPROTO:
1205                 warn = "retry with different protocol version";
1206                 goto failed_2;
1207         }
1208
1209         /* Refuse to duplicate an existing connection, unless this is a
1210          * loopback connection */
1211         if (conn->ksnc_ipaddr != conn->ksnc_myipaddr) {
1212                 list_for_each(tmp, &peer->ksnp_conns) {
1213                         conn2 = list_entry(tmp, ksock_conn_t, ksnc_list);
1214
1215                         if (conn2->ksnc_ipaddr != conn->ksnc_ipaddr ||
1216                             conn2->ksnc_myipaddr != conn->ksnc_myipaddr ||
1217                             conn2->ksnc_type != conn->ksnc_type)
1218                                 continue;
1219
1220                         /* Reply on a passive connection attempt so the peer
1221                          * realises we're connected. */
1222                         LASSERT (rc == 0);
1223                         if (!active)
1224                                 rc = EALREADY;
1225
1226                         warn = "duplicate";
1227                         goto failed_2;
1228                 }
1229         }
1230
1231         /* If the connection created by this route didn't bind to the IP
1232          * address the route connected to, the connection/route matching
1233          * code below probably isn't going to work. */
1234         if (active &&
1235             route->ksnr_ipaddr != conn->ksnc_ipaddr) {
1236                 CERROR("Route %s %pI4h connected to %pI4h\n",
1237                        libcfs_id2str(peer->ksnp_id),
1238                        &route->ksnr_ipaddr,
1239                        &conn->ksnc_ipaddr);
1240         }
1241
1242         /* Search for a route corresponding to the new connection and
1243          * create an association.  This allows incoming connections created
1244          * by routes in my peer to match my own route entries so I don't
1245          * continually create duplicate routes. */
1246         list_for_each(tmp, &peer->ksnp_routes) {
1247                 route = list_entry(tmp, ksock_route_t, ksnr_list);
1248
1249                 if (route->ksnr_ipaddr != conn->ksnc_ipaddr)
1250                         continue;
1251
1252                 ksocknal_associate_route_conn_locked(route, conn);
1253                 break;
1254         }
1255
1256         conn->ksnc_peer = peer;                 /* conn takes my ref on peer */
1257         peer->ksnp_last_alive = cfs_time_current();
1258         peer->ksnp_send_keepalive = 0;
1259         peer->ksnp_error = 0;
1260
1261         sched = ksocknal_choose_scheduler_locked(cpt);
1262         sched->kss_nconns++;
1263         conn->ksnc_scheduler = sched;
1264
1265         conn->ksnc_tx_last_post = cfs_time_current();
1266         /* Set the deadline for the outgoing HELLO to drain */
1267         conn->ksnc_tx_bufnob = sock->sk->sk_wmem_queued;
1268         conn->ksnc_tx_deadline = cfs_time_shift(*ksocknal_tunables.ksnd_timeout);
1269         smp_mb();   /* order with adding to peer's conn list */
1270
1271         list_add(&conn->ksnc_list, &peer->ksnp_conns);
1272         ksocknal_conn_addref(conn);
1273
1274         ksocknal_new_packet(conn, 0);
1275
1276         conn->ksnc_zc_capable = ksocknal_lib_zc_capable(conn);
1277
1278         /* Take packets blocking for this connection. */
1279         list_for_each_entry_safe(tx, txtmp, &peer->ksnp_tx_queue, tx_list) {
1280                 if (conn->ksnc_proto->pro_match_tx(conn, tx, tx->tx_nonblk) ==
1281                     SOCKNAL_MATCH_NO)
1282                         continue;
1283
1284                 list_del(&tx->tx_list);
1285                 ksocknal_queue_tx_locked(tx, conn);
1286         }
1287
1288         write_unlock_bh(global_lock);
1289
1290         /* We've now got a new connection.  Any errors from here on are just
1291          * like "normal" comms errors and we close the connection normally.
1292          * NB (a) we still have to send the reply HELLO for passive
1293          *        connections,
1294          *    (b) normal I/O on the conn is blocked until I setup and call the
1295          *        socket callbacks.
1296          */
1297
1298         CDEBUG(D_NET, "New conn %s p %d.x %pI4h -> %pI4h/%d"
1299                " incarnation:%lld sched[%d:%d]\n",
1300                libcfs_id2str(peerid), conn->ksnc_proto->pro_version,
1301                &conn->ksnc_myipaddr, &conn->ksnc_ipaddr,
1302                conn->ksnc_port, incarnation, cpt,
1303                (int)(sched - &sched->kss_info->ksi_scheds[0]));
1304
1305         if (active) {
1306                 /* additional routes after interface exchange? */
1307                 ksocknal_create_routes(peer, conn->ksnc_port,
1308                                        hello->kshm_ips, hello->kshm_nips);
1309         } else {
1310                 hello->kshm_nips = ksocknal_select_ips(peer, hello->kshm_ips,
1311                                                        hello->kshm_nips);
1312                 rc = ksocknal_send_hello(ni, conn, peerid.nid, hello);
1313         }
1314
1315         LIBCFS_FREE(hello, offsetof(ksock_hello_msg_t,
1316                                     kshm_ips[LNET_MAX_INTERFACES]));
1317
1318         /* setup the socket AFTER I've received hello (it disables
1319          * SO_LINGER).  I might call back to the acceptor who may want
1320          * to send a protocol version response and then close the
1321          * socket; this ensures the socket only tears down after the
1322          * response has been sent. */
1323         if (rc == 0)
1324                 rc = ksocknal_lib_setup_sock(sock);
1325
1326         write_lock_bh(global_lock);
1327
1328         /* NB my callbacks block while I hold ksnd_global_lock */
1329         ksocknal_lib_set_callback(sock, conn);
1330
1331         if (!active)
1332                 peer->ksnp_accepting--;
1333
1334         write_unlock_bh(global_lock);
1335
1336         if (rc != 0) {
1337                 write_lock_bh(global_lock);
1338                 if (!conn->ksnc_closing) {
1339                         /* could be closed by another thread */
1340                         ksocknal_close_conn_locked(conn, rc);
1341                 }
1342                 write_unlock_bh(global_lock);
1343         } else if (ksocknal_connsock_addref(conn) == 0) {
1344                 /* Allow I/O to proceed. */
1345                 ksocknal_read_callback(conn);
1346                 ksocknal_write_callback(conn);
1347                 ksocknal_connsock_decref(conn);
1348         }
1349
1350         ksocknal_connsock_decref(conn);
1351         ksocknal_conn_decref(conn);
1352         return rc;
1353
1354 failed_2:
1355         if (!peer->ksnp_closing &&
1356             list_empty(&peer->ksnp_conns) &&
1357             list_empty(&peer->ksnp_routes)) {
1358                 list_add(&zombies, &peer->ksnp_tx_queue);
1359                 list_del_init(&peer->ksnp_tx_queue);
1360                 ksocknal_unlink_peer_locked(peer);
1361         }
1362
1363         write_unlock_bh(global_lock);
1364
1365         if (warn != NULL) {
1366                 if (rc < 0)
1367                         CERROR("Not creating conn %s type %d: %s\n",
1368                                libcfs_id2str(peerid), conn->ksnc_type, warn);
1369                 else
1370                         CDEBUG(D_NET, "Not creating conn %s type %d: %s\n",
1371                               libcfs_id2str(peerid), conn->ksnc_type, warn);
1372         }
1373
1374         if (!active) {
1375                 if (rc > 0) {
1376                         /* Request retry by replying with CONN_NONE
1377                          * ksnc_proto has been set already */
1378                         conn->ksnc_type = SOCKLND_CONN_NONE;
1379                         hello->kshm_nips = 0;
1380                         ksocknal_send_hello(ni, conn, peerid.nid, hello);
1381                 }
1382
1383                 write_lock_bh(global_lock);
1384                 peer->ksnp_accepting--;
1385                 write_unlock_bh(global_lock);
1386         }
1387
1388         ksocknal_txlist_done(ni, &zombies, 1);
1389         ksocknal_peer_decref(peer);
1390
1391  failed_1:
1392         if (hello != NULL)
1393                 LIBCFS_FREE(hello, offsetof(ksock_hello_msg_t,
1394                                             kshm_ips[LNET_MAX_INTERFACES]));
1395
1396         LIBCFS_FREE(conn, sizeof(*conn));
1397
1398 failed_0:
1399         sock_release(sock);
1400         return rc;
1401 }
1402
1403 void
1404 ksocknal_close_conn_locked (ksock_conn_t *conn, int error)
1405 {
1406         /* This just does the immmediate housekeeping, and queues the
1407          * connection for the reaper to terminate.
1408          * Caller holds ksnd_global_lock exclusively in irq context */
1409         ksock_peer_t      *peer = conn->ksnc_peer;
1410         ksock_route_t     *route;
1411         ksock_conn_t      *conn2;
1412         struct list_head  *tmp;
1413
1414         LASSERT(peer->ksnp_error == 0);
1415         LASSERT(!conn->ksnc_closing);
1416         conn->ksnc_closing = 1;
1417
1418         /* ksnd_deathrow_conns takes over peer's ref */
1419         list_del(&conn->ksnc_list);
1420
1421         route = conn->ksnc_route;
1422         if (route != NULL) {
1423                 /* dissociate conn from route... */
1424                 LASSERT(!route->ksnr_deleted);
1425                 LASSERT((route->ksnr_connected & (1 << conn->ksnc_type)) != 0);
1426
1427                 conn2 = NULL;
1428                 list_for_each(tmp, &peer->ksnp_conns) {
1429                         conn2 = list_entry(tmp, ksock_conn_t, ksnc_list);
1430
1431                         if (conn2->ksnc_route == route &&
1432                             conn2->ksnc_type == conn->ksnc_type)
1433                                 break;
1434
1435                         conn2 = NULL;
1436                 }
1437                 if (conn2 == NULL)
1438                         route->ksnr_connected &= ~(1 << conn->ksnc_type);
1439
1440                 conn->ksnc_route = NULL;
1441
1442                 ksocknal_route_decref(route);   /* drop conn's ref on route */
1443         }
1444
1445         if (list_empty(&peer->ksnp_conns)) {
1446                 /* No more connections to this peer */
1447
1448                 if (!list_empty(&peer->ksnp_tx_queue)) {
1449                                 ksock_tx_t *tx;
1450
1451                         LASSERT(conn->ksnc_proto == &ksocknal_protocol_v3x);
1452
1453                         /* throw them to the last connection...,
1454                          * these TXs will be send to /dev/null by scheduler */
1455                         list_for_each_entry(tx, &peer->ksnp_tx_queue,
1456                                             tx_list)
1457                                 ksocknal_tx_prep(conn, tx);
1458
1459                         spin_lock_bh(&conn->ksnc_scheduler->kss_lock);
1460                         list_splice_init(&peer->ksnp_tx_queue,
1461                                          &conn->ksnc_tx_queue);
1462                         spin_unlock_bh(&conn->ksnc_scheduler->kss_lock);
1463                 }
1464
1465                 /* renegotiate protocol version */
1466                 peer->ksnp_proto = NULL;
1467                 /* stash last conn close reason */
1468                 peer->ksnp_error = error;
1469
1470                 if (list_empty(&peer->ksnp_routes)) {
1471                         /* I've just closed last conn belonging to a
1472                          * peer with no routes to it */
1473                         ksocknal_unlink_peer_locked(peer);
1474                 }
1475         }
1476
1477         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
1478
1479         list_add_tail(&conn->ksnc_list,
1480                       &ksocknal_data.ksnd_deathrow_conns);
1481         wake_up(&ksocknal_data.ksnd_reaper_waitq);
1482
1483         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
1484 }
1485
1486 void
1487 ksocknal_peer_failed (ksock_peer_t *peer)
1488 {
1489         int        notify = 0;
1490         cfs_time_t last_alive = 0;
1491
1492         /* There has been a connection failure or comms error; but I'll only
1493          * tell LNET I think the peer is dead if it's to another kernel and
1494          * there are no connections or connection attempts in existence. */
1495
1496         read_lock(&ksocknal_data.ksnd_global_lock);
1497
1498         if ((peer->ksnp_id.pid & LNET_PID_USERFLAG) == 0 &&
1499              list_empty(&peer->ksnp_conns) &&
1500              peer->ksnp_accepting == 0 &&
1501              ksocknal_find_connecting_route_locked(peer) == NULL) {
1502                 notify = 1;
1503                 last_alive = peer->ksnp_last_alive;
1504         }
1505
1506         read_unlock(&ksocknal_data.ksnd_global_lock);
1507
1508         if (notify)
1509                 lnet_notify(peer->ksnp_ni, peer->ksnp_id.nid, 0,
1510                             last_alive);
1511 }
1512
1513 void
1514 ksocknal_finalize_zcreq(ksock_conn_t *conn)
1515 {
1516         ksock_peer_t     *peer = conn->ksnc_peer;
1517         ksock_tx_t       *tx;
1518         ksock_tx_t       *tmp;
1519         struct list_head  zlist = LIST_HEAD_INIT(zlist);
1520
1521         /* NB safe to finalize TXs because closing of socket will
1522          * abort all buffered data */
1523         LASSERT(conn->ksnc_sock == NULL);
1524
1525         spin_lock(&peer->ksnp_lock);
1526
1527         list_for_each_entry_safe(tx, tmp, &peer->ksnp_zc_req_list, tx_zc_list) {
1528                 if (tx->tx_conn != conn)
1529                         continue;
1530
1531                 LASSERT(tx->tx_msg.ksm_zc_cookies[0] != 0);
1532
1533                 tx->tx_msg.ksm_zc_cookies[0] = 0;
1534                 tx->tx_zc_aborted = 1;  /* mark it as not-acked */
1535                 list_del(&tx->tx_zc_list);
1536                 list_add(&tx->tx_zc_list, &zlist);
1537         }
1538
1539         spin_unlock(&peer->ksnp_lock);
1540
1541         while (!list_empty(&zlist)) {
1542                 tx = list_entry(zlist.next, ksock_tx_t, tx_zc_list);
1543
1544                 list_del(&tx->tx_zc_list);
1545                 ksocknal_tx_decref(tx);
1546         }
1547 }
1548
1549 void
1550 ksocknal_terminate_conn(ksock_conn_t *conn)
1551 {
1552         /* This gets called by the reaper (guaranteed thread context) to
1553          * disengage the socket from its callbacks and close it.
1554          * ksnc_refcount will eventually hit zero, and then the reaper will
1555          * destroy it. */
1556         ksock_peer_t     *peer = conn->ksnc_peer;
1557         ksock_sched_t    *sched = conn->ksnc_scheduler;
1558         int               failed = 0;
1559
1560         LASSERT(conn->ksnc_closing);
1561
1562         /* wake up the scheduler to "send" all remaining packets to /dev/null */
1563         spin_lock_bh(&sched->kss_lock);
1564
1565         /* a closing conn is always ready to tx */
1566         conn->ksnc_tx_ready = 1;
1567
1568         if (!conn->ksnc_tx_scheduled &&
1569             !list_empty(&conn->ksnc_tx_queue)) {
1570                 list_add_tail(&conn->ksnc_tx_list,
1571                                &sched->kss_tx_conns);
1572                 conn->ksnc_tx_scheduled = 1;
1573                 /* extra ref for scheduler */
1574                 ksocknal_conn_addref(conn);
1575
1576                 wake_up (&sched->kss_waitq);
1577         }
1578
1579         spin_unlock_bh(&sched->kss_lock);
1580
1581         /* serialise with callbacks */
1582         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1583
1584         ksocknal_lib_reset_callback(conn->ksnc_sock, conn);
1585
1586         /* OK, so this conn may not be completely disengaged from its
1587          * scheduler yet, but it _has_ committed to terminate... */
1588         conn->ksnc_scheduler->kss_nconns--;
1589
1590         if (peer->ksnp_error != 0) {
1591                 /* peer's last conn closed in error */
1592                 LASSERT(list_empty(&peer->ksnp_conns));
1593                 failed = 1;
1594                 peer->ksnp_error = 0;     /* avoid multiple notifications */
1595         }
1596
1597         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1598
1599         if (failed)
1600                 ksocknal_peer_failed(peer);
1601
1602         /* The socket is closed on the final put; either here, or in
1603          * ksocknal_{send,recv}msg().  Since we set up the linger2 option
1604          * when the connection was established, this will close the socket
1605          * immediately, aborting anything buffered in it. Any hung
1606          * zero-copy transmits will therefore complete in finite time. */
1607         ksocknal_connsock_decref(conn);
1608 }
1609
1610 void
1611 ksocknal_queue_zombie_conn (ksock_conn_t *conn)
1612 {
1613         /* Queue the conn for the reaper to destroy */
1614
1615         LASSERT(atomic_read(&conn->ksnc_conn_refcount) == 0);
1616         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
1617
1618         list_add_tail(&conn->ksnc_list, &ksocknal_data.ksnd_zombie_conns);
1619         wake_up(&ksocknal_data.ksnd_reaper_waitq);
1620
1621         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
1622 }
1623
1624 void
1625 ksocknal_destroy_conn (ksock_conn_t *conn)
1626 {
1627         cfs_time_t      last_rcv;
1628
1629         /* Final coup-de-grace of the reaper */
1630         CDEBUG (D_NET, "connection %p\n", conn);
1631
1632         LASSERT (atomic_read (&conn->ksnc_conn_refcount) == 0);
1633         LASSERT (atomic_read (&conn->ksnc_sock_refcount) == 0);
1634         LASSERT (conn->ksnc_sock == NULL);
1635         LASSERT (conn->ksnc_route == NULL);
1636         LASSERT (!conn->ksnc_tx_scheduled);
1637         LASSERT (!conn->ksnc_rx_scheduled);
1638         LASSERT(list_empty(&conn->ksnc_tx_queue));
1639
1640         /* complete current receive if any */
1641         switch (conn->ksnc_rx_state) {
1642         case SOCKNAL_RX_LNET_PAYLOAD:
1643                 last_rcv = conn->ksnc_rx_deadline -
1644                            cfs_time_seconds(*ksocknal_tunables.ksnd_timeout);
1645                 CERROR("Completing partial receive from %s[%d], "
1646                        "ip %pI4h:%d, with error, wanted: %d, left: %d, "
1647                        "last alive is %ld secs ago\n",
1648                        libcfs_id2str(conn->ksnc_peer->ksnp_id), conn->ksnc_type,
1649                        &conn->ksnc_ipaddr, conn->ksnc_port,
1650                        conn->ksnc_rx_nob_wanted, conn->ksnc_rx_nob_left,
1651                        cfs_duration_sec(cfs_time_sub(cfs_time_current(),
1652                                         last_rcv)));
1653                 lnet_finalize (conn->ksnc_peer->ksnp_ni,
1654                                conn->ksnc_cookie, -EIO);
1655                 break;
1656         case SOCKNAL_RX_LNET_HEADER:
1657                 if (conn->ksnc_rx_started)
1658                         CERROR("Incomplete receive of lnet header from %s, "
1659                                "ip %pI4h:%d, with error, protocol: %d.x.\n",
1660                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1661                                &conn->ksnc_ipaddr, conn->ksnc_port,
1662                                conn->ksnc_proto->pro_version);
1663                 break;
1664         case SOCKNAL_RX_KSM_HEADER:
1665                 if (conn->ksnc_rx_started)
1666                         CERROR("Incomplete receive of ksock message from %s, "
1667                                "ip %pI4h:%d, with error, protocol: %d.x.\n",
1668                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1669                                &conn->ksnc_ipaddr, conn->ksnc_port,
1670                                conn->ksnc_proto->pro_version);
1671                 break;
1672         case SOCKNAL_RX_SLOP:
1673                 if (conn->ksnc_rx_started)
1674                         CERROR("Incomplete receive of slops from %s, "
1675                                "ip %pI4h:%d, with error\n",
1676                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1677                                &conn->ksnc_ipaddr, conn->ksnc_port);
1678                break;
1679         default:
1680                 LBUG ();
1681                 break;
1682         }
1683
1684         ksocknal_peer_decref(conn->ksnc_peer);
1685
1686         LIBCFS_FREE (conn, sizeof (*conn));
1687 }
1688
1689 int
1690 ksocknal_close_peer_conns_locked (ksock_peer_t *peer, __u32 ipaddr, int why)
1691 {
1692         ksock_conn_t       *conn;
1693         struct list_head         *ctmp;
1694         struct list_head         *cnxt;
1695         int                 count = 0;
1696
1697         list_for_each_safe(ctmp, cnxt, &peer->ksnp_conns) {
1698                 conn = list_entry(ctmp, ksock_conn_t, ksnc_list);
1699
1700                 if (ipaddr == 0 ||
1701                     conn->ksnc_ipaddr == ipaddr) {
1702                         count++;
1703                         ksocknal_close_conn_locked (conn, why);
1704                 }
1705         }
1706
1707         return (count);
1708 }
1709
1710 int
1711 ksocknal_close_conn_and_siblings (ksock_conn_t *conn, int why)
1712 {
1713         ksock_peer_t     *peer = conn->ksnc_peer;
1714         __u32             ipaddr = conn->ksnc_ipaddr;
1715         int               count;
1716
1717         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1718
1719         count = ksocknal_close_peer_conns_locked (peer, ipaddr, why);
1720
1721         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1722
1723         return (count);
1724 }
1725
1726 int
1727 ksocknal_close_matching_conns (lnet_process_id_t id, __u32 ipaddr)
1728 {
1729         ksock_peer_t       *peer;
1730         struct list_head         *ptmp;
1731         struct list_head         *pnxt;
1732         int                 lo;
1733         int                 hi;
1734         int                 i;
1735         int                 count = 0;
1736
1737         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1738
1739         if (id.nid != LNET_NID_ANY)
1740                 lo = hi = (int)(ksocknal_nid2peerlist(id.nid) - ksocknal_data.ksnd_peers);
1741         else {
1742                 lo = 0;
1743                 hi = ksocknal_data.ksnd_peer_hash_size - 1;
1744         }
1745
1746         for (i = lo; i <= hi; i++) {
1747                 list_for_each_safe(ptmp, pnxt, &ksocknal_data.ksnd_peers[i]) {
1748
1749                         peer = list_entry(ptmp, ksock_peer_t, ksnp_list);
1750
1751                         if (!((id.nid == LNET_NID_ANY || id.nid == peer->ksnp_id.nid) &&
1752                               (id.pid == LNET_PID_ANY || id.pid == peer->ksnp_id.pid)))
1753                                 continue;
1754
1755                         count += ksocknal_close_peer_conns_locked (peer, ipaddr, 0);
1756                 }
1757         }
1758
1759         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1760
1761         /* wildcards always succeed */
1762         if (id.nid == LNET_NID_ANY || id.pid == LNET_PID_ANY || ipaddr == 0)
1763                 return (0);
1764
1765         return (count == 0 ? -ENOENT : 0);
1766 }
1767
1768 void
1769 ksocknal_notify (lnet_ni_t *ni, lnet_nid_t gw_nid, int alive)
1770 {
1771         /* The router is telling me she's been notified of a change in
1772          * gateway state.... */
1773         lnet_process_id_t  id = {0};
1774
1775         id.nid = gw_nid;
1776         id.pid = LNET_PID_ANY;
1777
1778         CDEBUG (D_NET, "gw %s %s\n", libcfs_nid2str(gw_nid),
1779                 alive ? "up" : "down");
1780
1781         if (!alive) {
1782                 /* If the gateway crashed, close all open connections... */
1783                 ksocknal_close_matching_conns (id, 0);
1784                 return;
1785         }
1786
1787         /* ...otherwise do nothing.  We can only establish new connections
1788          * if we have autroutes, and these connect on demand. */
1789 }
1790
1791 void
1792 ksocknal_query (lnet_ni_t *ni, lnet_nid_t nid, cfs_time_t *when)
1793 {
1794         int                connect = 1;
1795         cfs_time_t         last_alive = 0;
1796         cfs_time_t         now = cfs_time_current();
1797         ksock_peer_t      *peer = NULL;
1798         rwlock_t                *glock = &ksocknal_data.ksnd_global_lock;
1799         lnet_process_id_t  id = {
1800                 .nid = nid,
1801                 .pid = LNET_PID_LUSTRE,
1802         };
1803
1804         read_lock(glock);
1805
1806         peer = ksocknal_find_peer_locked(ni, id);
1807         if (peer != NULL) {
1808                 struct list_head       *tmp;
1809                 ksock_conn_t     *conn;
1810                 int               bufnob;
1811
1812                 list_for_each(tmp, &peer->ksnp_conns) {
1813                         conn = list_entry(tmp, ksock_conn_t, ksnc_list);
1814                         bufnob = conn->ksnc_sock->sk->sk_wmem_queued;
1815
1816                         if (bufnob < conn->ksnc_tx_bufnob) {
1817                                 /* something got ACKed */
1818                                 conn->ksnc_tx_deadline =
1819                                         cfs_time_shift(*ksocknal_tunables.ksnd_timeout);
1820                                 peer->ksnp_last_alive = now;
1821                                 conn->ksnc_tx_bufnob = bufnob;
1822                         }
1823                 }
1824
1825                 last_alive = peer->ksnp_last_alive;
1826                 if (ksocknal_find_connectable_route_locked(peer) == NULL)
1827                         connect = 0;
1828         }
1829
1830         read_unlock(glock);
1831
1832         if (last_alive != 0)
1833                 *when = last_alive;
1834
1835         CDEBUG(D_NET, "Peer %s %p, alive %ld secs ago, connect %d\n",
1836                libcfs_nid2str(nid), peer,
1837                last_alive ? cfs_duration_sec(now - last_alive) : -1,
1838                connect);
1839
1840         if (!connect)
1841                 return;
1842
1843         ksocknal_add_peer(ni, id, LNET_NIDADDR(nid), lnet_acceptor_port());
1844
1845         write_lock_bh(glock);
1846
1847         peer = ksocknal_find_peer_locked(ni, id);
1848         if (peer != NULL)
1849                 ksocknal_launch_all_connections_locked(peer);
1850
1851         write_unlock_bh(glock);
1852         return;
1853 }
1854
1855 static void
1856 ksocknal_push_peer (ksock_peer_t *peer)
1857 {
1858         int               index;
1859         int               i;
1860         struct list_head       *tmp;
1861         ksock_conn_t     *conn;
1862
1863         for (index = 0; ; index++) {
1864                 read_lock(&ksocknal_data.ksnd_global_lock);
1865
1866                 i = 0;
1867                 conn = NULL;
1868
1869                 list_for_each(tmp, &peer->ksnp_conns) {
1870                         if (i++ == index) {
1871                                 conn = list_entry(tmp, ksock_conn_t,
1872                                                        ksnc_list);
1873                                 ksocknal_conn_addref(conn);
1874                                 break;
1875                         }
1876                 }
1877
1878                 read_unlock(&ksocknal_data.ksnd_global_lock);
1879
1880                 if (conn == NULL)
1881                         break;
1882
1883                 ksocknal_lib_push_conn (conn);
1884                 ksocknal_conn_decref(conn);
1885         }
1886 }
1887
1888 static int
1889 ksocknal_push (lnet_ni_t *ni, lnet_process_id_t id)
1890 {
1891         struct list_head *start;
1892         struct list_head *end;
1893         struct list_head *tmp;
1894         int               rc = -ENOENT;
1895         unsigned int      hsize = ksocknal_data.ksnd_peer_hash_size;
1896
1897         if (id.nid == LNET_NID_ANY) {
1898                 start = &ksocknal_data.ksnd_peers[0];
1899                 end = &ksocknal_data.ksnd_peers[hsize - 1];
1900         } else {
1901                 start = end = ksocknal_nid2peerlist(id.nid);
1902         }
1903
1904         for (tmp = start; tmp <= end; tmp++) {
1905                 int     peer_off; /* searching offset in peer hash table */
1906
1907                 for (peer_off = 0; ; peer_off++) {
1908                         ksock_peer_t *peer;
1909                         int           i = 0;
1910
1911                         read_lock(&ksocknal_data.ksnd_global_lock);
1912                         list_for_each_entry(peer, tmp, ksnp_list) {
1913                                 if (!((id.nid == LNET_NID_ANY ||
1914                                        id.nid == peer->ksnp_id.nid) &&
1915                                       (id.pid == LNET_PID_ANY ||
1916                                        id.pid == peer->ksnp_id.pid)))
1917                                         continue;
1918
1919                                 if (i++ == peer_off) {
1920                                         ksocknal_peer_addref(peer);
1921                                         break;
1922                                 }
1923                         }
1924                         read_unlock(&ksocknal_data.ksnd_global_lock);
1925
1926                         if (i == 0) /* no match */
1927                                 break;
1928
1929                         rc = 0;
1930                         ksocknal_push_peer(peer);
1931                         ksocknal_peer_decref(peer);
1932                 }
1933         }
1934         return rc;
1935 }
1936
1937 static int
1938 ksocknal_add_interface(lnet_ni_t *ni, __u32 ipaddress, __u32 netmask)
1939 {
1940         ksock_net_t       *net = ni->ni_data;
1941         ksock_interface_t *iface;
1942         int                rc;
1943         int                i;
1944         int                j;
1945         struct list_head        *ptmp;
1946         ksock_peer_t      *peer;
1947         struct list_head        *rtmp;
1948         ksock_route_t     *route;
1949
1950         if (ipaddress == 0 ||
1951             netmask == 0)
1952                 return (-EINVAL);
1953
1954         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1955
1956         iface = ksocknal_ip2iface(ni, ipaddress);
1957         if (iface != NULL) {
1958                 /* silently ignore dups */
1959                 rc = 0;
1960         } else if (net->ksnn_ninterfaces == LNET_MAX_INTERFACES) {
1961                 rc = -ENOSPC;
1962         } else {
1963                 iface = &net->ksnn_interfaces[net->ksnn_ninterfaces++];
1964
1965                 iface->ksni_ipaddr = ipaddress;
1966                 iface->ksni_netmask = netmask;
1967                 iface->ksni_nroutes = 0;
1968                 iface->ksni_npeers = 0;
1969
1970                 for (i = 0; i < ksocknal_data.ksnd_peer_hash_size; i++) {
1971                         list_for_each(ptmp, &ksocknal_data.ksnd_peers[i]) {
1972                                 peer = list_entry(ptmp, ksock_peer_t,
1973                                                       ksnp_list);
1974
1975                                 for (j = 0; j < peer->ksnp_n_passive_ips; j++)
1976                                         if (peer->ksnp_passive_ips[j] == ipaddress)
1977                                                 iface->ksni_npeers++;
1978
1979                                 list_for_each(rtmp, &peer->ksnp_routes) {
1980                                         route = list_entry(rtmp,
1981                                                                ksock_route_t,
1982                                                                ksnr_list);
1983
1984                                         if (route->ksnr_myipaddr == ipaddress)
1985                                                 iface->ksni_nroutes++;
1986                                 }
1987                         }
1988                 }
1989
1990                 rc = 0;
1991                 /* NB only new connections will pay attention to the new interface! */
1992         }
1993
1994         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1995
1996         return (rc);
1997 }
1998
1999 static void
2000 ksocknal_peer_del_interface_locked(ksock_peer_t *peer, __u32 ipaddr)
2001 {
2002         struct list_head         *tmp;
2003         struct list_head         *nxt;
2004         ksock_route_t      *route;
2005         ksock_conn_t       *conn;
2006         int                 i;
2007         int                 j;
2008
2009         for (i = 0; i < peer->ksnp_n_passive_ips; i++)
2010                 if (peer->ksnp_passive_ips[i] == ipaddr) {
2011                         for (j = i+1; j < peer->ksnp_n_passive_ips; j++)
2012                                 peer->ksnp_passive_ips[j-1] =
2013                                         peer->ksnp_passive_ips[j];
2014                         peer->ksnp_n_passive_ips--;
2015                         break;
2016                 }
2017
2018         list_for_each_safe(tmp, nxt, &peer->ksnp_routes) {
2019                 route = list_entry(tmp, ksock_route_t, ksnr_list);
2020
2021                 if (route->ksnr_myipaddr != ipaddr)
2022                         continue;
2023
2024                 if (route->ksnr_share_count != 0) {
2025                         /* Manually created; keep, but unbind */
2026                         route->ksnr_myipaddr = 0;
2027                 } else {
2028                         ksocknal_del_route_locked(route);
2029                 }
2030         }
2031
2032         list_for_each_safe(tmp, nxt, &peer->ksnp_conns) {
2033                 conn = list_entry(tmp, ksock_conn_t, ksnc_list);
2034
2035                 if (conn->ksnc_myipaddr == ipaddr)
2036                         ksocknal_close_conn_locked (conn, 0);
2037         }
2038 }
2039
2040 static int
2041 ksocknal_del_interface(lnet_ni_t *ni, __u32 ipaddress)
2042 {
2043         ksock_net_t       *net = ni->ni_data;
2044         int                rc = -ENOENT;
2045         struct list_head        *tmp;
2046         struct list_head        *nxt;
2047         ksock_peer_t      *peer;
2048         __u32              this_ip;
2049         int                i;
2050         int                j;
2051
2052         write_lock_bh(&ksocknal_data.ksnd_global_lock);
2053
2054         for (i = 0; i < net->ksnn_ninterfaces; i++) {
2055                 this_ip = net->ksnn_interfaces[i].ksni_ipaddr;
2056
2057                 if (!(ipaddress == 0 ||
2058                       ipaddress == this_ip))
2059                         continue;
2060
2061                 rc = 0;
2062
2063                 for (j = i+1; j < net->ksnn_ninterfaces; j++)
2064                         net->ksnn_interfaces[j-1] =
2065                                 net->ksnn_interfaces[j];
2066
2067                 net->ksnn_ninterfaces--;
2068
2069                 for (j = 0; j < ksocknal_data.ksnd_peer_hash_size; j++) {
2070                         list_for_each_safe(tmp, nxt,
2071                                                &ksocknal_data.ksnd_peers[j]) {
2072                                 peer = list_entry(tmp, ksock_peer_t,
2073                                                       ksnp_list);
2074
2075                                 if (peer->ksnp_ni != ni)
2076                                         continue;
2077
2078                                 ksocknal_peer_del_interface_locked(peer, this_ip);
2079                         }
2080                 }
2081         }
2082
2083         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2084
2085         return (rc);
2086 }
2087
2088 int
2089 ksocknal_ctl(lnet_ni_t *ni, unsigned int cmd, void *arg)
2090 {
2091         lnet_process_id_t id = {0};
2092         struct libcfs_ioctl_data *data = arg;
2093         int rc;
2094
2095         switch(cmd) {
2096         case IOC_LIBCFS_GET_INTERFACE: {
2097                 ksock_net_t       *net = ni->ni_data;
2098                 ksock_interface_t *iface;
2099
2100                 read_lock(&ksocknal_data.ksnd_global_lock);
2101
2102                 if (data->ioc_count >= (__u32)net->ksnn_ninterfaces) {
2103                         rc = -ENOENT;
2104                 } else {
2105                         rc = 0;
2106                         iface = &net->ksnn_interfaces[data->ioc_count];
2107
2108                         data->ioc_u32[0] = iface->ksni_ipaddr;
2109                         data->ioc_u32[1] = iface->ksni_netmask;
2110                         data->ioc_u32[2] = iface->ksni_npeers;
2111                         data->ioc_u32[3] = iface->ksni_nroutes;
2112                 }
2113
2114                 read_unlock(&ksocknal_data.ksnd_global_lock);
2115                 return rc;
2116         }
2117
2118         case IOC_LIBCFS_ADD_INTERFACE:
2119                 return ksocknal_add_interface(ni,
2120                                               data->ioc_u32[0], /* IP address */
2121                                               data->ioc_u32[1]); /* net mask */
2122
2123         case IOC_LIBCFS_DEL_INTERFACE:
2124                 return ksocknal_del_interface(ni,
2125                                               data->ioc_u32[0]); /* IP address */
2126
2127         case IOC_LIBCFS_GET_PEER: {
2128                 __u32            myip = 0;
2129                 __u32            ip = 0;
2130                 int              port = 0;
2131                 int              conn_count = 0;
2132                 int              share_count = 0;
2133
2134                 rc = ksocknal_get_peer_info(ni, data->ioc_count,
2135                                             &id, &myip, &ip, &port,
2136                                             &conn_count,  &share_count);
2137                 if (rc != 0)
2138                         return rc;
2139
2140                 data->ioc_nid    = id.nid;
2141                 data->ioc_count  = share_count;
2142                 data->ioc_u32[0] = ip;
2143                 data->ioc_u32[1] = port;
2144                 data->ioc_u32[2] = myip;
2145                 data->ioc_u32[3] = conn_count;
2146                 data->ioc_u32[4] = id.pid;
2147                 return 0;
2148         }
2149
2150         case IOC_LIBCFS_ADD_PEER:
2151                 id.nid = data->ioc_nid;
2152                 id.pid = LNET_PID_LUSTRE;
2153                 return ksocknal_add_peer (ni, id,
2154                                           data->ioc_u32[0], /* IP */
2155                                           data->ioc_u32[1]); /* port */
2156
2157         case IOC_LIBCFS_DEL_PEER:
2158                 id.nid = data->ioc_nid;
2159                 id.pid = LNET_PID_ANY;
2160                 return ksocknal_del_peer (ni, id,
2161                                           data->ioc_u32[0]); /* IP */
2162
2163         case IOC_LIBCFS_GET_CONN: {
2164                 int           txmem;
2165                 int           rxmem;
2166                 int           nagle;
2167                 ksock_conn_t *conn = ksocknal_get_conn_by_idx (ni, data->ioc_count);
2168
2169                 if (conn == NULL)
2170                         return -ENOENT;
2171
2172                 ksocknal_lib_get_conn_tunables(conn, &txmem, &rxmem, &nagle);
2173
2174                 data->ioc_count  = txmem;
2175                 data->ioc_nid    = conn->ksnc_peer->ksnp_id.nid;
2176                 data->ioc_flags  = nagle;
2177                 data->ioc_u32[0] = conn->ksnc_ipaddr;
2178                 data->ioc_u32[1] = conn->ksnc_port;
2179                 data->ioc_u32[2] = conn->ksnc_myipaddr;
2180                 data->ioc_u32[3] = conn->ksnc_type;
2181                 data->ioc_u32[4] = conn->ksnc_scheduler->kss_info->ksi_cpt;
2182                 data->ioc_u32[5] = rxmem;
2183                 data->ioc_u32[6] = conn->ksnc_peer->ksnp_id.pid;
2184                 ksocknal_conn_decref(conn);
2185                 return 0;
2186         }
2187
2188         case IOC_LIBCFS_CLOSE_CONNECTION:
2189                 id.nid = data->ioc_nid;
2190                 id.pid = LNET_PID_ANY;
2191                 return ksocknal_close_matching_conns (id,
2192                                                       data->ioc_u32[0]);
2193
2194         case IOC_LIBCFS_REGISTER_MYNID:
2195                 /* Ignore if this is a noop */
2196                 if (data->ioc_nid == ni->ni_nid)
2197                         return 0;
2198
2199                 CERROR("obsolete IOC_LIBCFS_REGISTER_MYNID: %s(%s)\n",
2200                        libcfs_nid2str(data->ioc_nid),
2201                        libcfs_nid2str(ni->ni_nid));
2202                 return -EINVAL;
2203
2204         case IOC_LIBCFS_PUSH_CONNECTION:
2205                 id.nid = data->ioc_nid;
2206                 id.pid = LNET_PID_ANY;
2207                 return ksocknal_push(ni, id);
2208
2209         default:
2210                 return -EINVAL;
2211         }
2212         /* not reached */
2213 }
2214
2215 static void
2216 ksocknal_free_buffers (void)
2217 {
2218         LASSERT (atomic_read(&ksocknal_data.ksnd_nactive_txs) == 0);
2219
2220         if (ksocknal_data.ksnd_sched_info != NULL) {
2221                 struct ksock_sched_info *info;
2222                 int                     i;
2223
2224                 cfs_percpt_for_each(info, i, ksocknal_data.ksnd_sched_info) {
2225                         if (info->ksi_scheds != NULL) {
2226                                 LIBCFS_FREE(info->ksi_scheds,
2227                                             info->ksi_nthreads_max *
2228                                             sizeof(info->ksi_scheds[0]));
2229                         }
2230                 }
2231                 cfs_percpt_free(ksocknal_data.ksnd_sched_info);
2232         }
2233
2234         LIBCFS_FREE (ksocknal_data.ksnd_peers,
2235                      sizeof(struct list_head) *
2236                      ksocknal_data.ksnd_peer_hash_size);
2237
2238         spin_lock(&ksocknal_data.ksnd_tx_lock);
2239
2240         if (!list_empty(&ksocknal_data.ksnd_idle_noop_txs)) {
2241                 struct list_head        zlist;
2242                 ksock_tx_t      *tx;
2243
2244                 list_add(&zlist, &ksocknal_data.ksnd_idle_noop_txs);
2245                 list_del_init(&ksocknal_data.ksnd_idle_noop_txs);
2246                 spin_unlock(&ksocknal_data.ksnd_tx_lock);
2247
2248                 while (!list_empty(&zlist)) {
2249                         tx = list_entry(zlist.next, ksock_tx_t, tx_list);
2250                         list_del(&tx->tx_list);
2251                         LIBCFS_FREE(tx, tx->tx_desc_size);
2252                 }
2253         } else {
2254                 spin_unlock(&ksocknal_data.ksnd_tx_lock);
2255         }
2256 }
2257
2258 static void
2259 ksocknal_base_shutdown(void)
2260 {
2261         struct ksock_sched_info *info;
2262         ksock_sched_t           *sched;
2263         int                     i;
2264         int                     j;
2265
2266         CDEBUG(D_MALLOC, "before NAL cleanup: kmem %d\n",
2267                atomic_read (&libcfs_kmemory));
2268         LASSERT (ksocknal_data.ksnd_nnets == 0);
2269
2270         switch (ksocknal_data.ksnd_init) {
2271         default:
2272                 LASSERT (0);
2273
2274         case SOCKNAL_INIT_ALL:
2275         case SOCKNAL_INIT_DATA:
2276                 LASSERT (ksocknal_data.ksnd_peers != NULL);
2277                 for (i = 0; i < ksocknal_data.ksnd_peer_hash_size; i++) {
2278                         LASSERT(list_empty(&ksocknal_data.ksnd_peers[i]));
2279                 }
2280
2281                 LASSERT(list_empty(&ksocknal_data.ksnd_nets));
2282                 LASSERT(list_empty(&ksocknal_data.ksnd_enomem_conns));
2283                 LASSERT(list_empty(&ksocknal_data.ksnd_zombie_conns));
2284                 LASSERT(list_empty(&ksocknal_data.ksnd_connd_connreqs));
2285                 LASSERT(list_empty(&ksocknal_data.ksnd_connd_routes));
2286
2287                 if (ksocknal_data.ksnd_sched_info != NULL) {
2288                         cfs_percpt_for_each(info, i,
2289                                             ksocknal_data.ksnd_sched_info) {
2290                                 if (info->ksi_scheds == NULL)
2291                                         continue;
2292
2293                                 for (j = 0; j < info->ksi_nthreads_max; j++) {
2294
2295                                         sched = &info->ksi_scheds[j];
2296                                         LASSERT(list_empty(&sched->\
2297                                                                kss_tx_conns));
2298                                         LASSERT(list_empty(&sched->\
2299                                                                kss_rx_conns));
2300                                         LASSERT(list_empty(&sched-> \
2301                                                   kss_zombie_noop_txs));
2302                                         LASSERT(sched->kss_nconns == 0);
2303                                 }
2304                         }
2305                 }
2306
2307                 /* flag threads to terminate; wake and wait for them to die */
2308                 ksocknal_data.ksnd_shuttingdown = 1;
2309                 wake_up_all(&ksocknal_data.ksnd_connd_waitq);
2310                 wake_up_all(&ksocknal_data.ksnd_reaper_waitq);
2311
2312                 if (ksocknal_data.ksnd_sched_info != NULL) {
2313                         cfs_percpt_for_each(info, i,
2314                                             ksocknal_data.ksnd_sched_info) {
2315                                 if (info->ksi_scheds == NULL)
2316                                         continue;
2317
2318                                 for (j = 0; j < info->ksi_nthreads_max; j++) {
2319                                         sched = &info->ksi_scheds[j];
2320                                         wake_up_all(&sched->kss_waitq);
2321                                 }
2322                         }
2323                 }
2324
2325                 i = 4;
2326                 read_lock(&ksocknal_data.ksnd_global_lock);
2327                 while (ksocknal_data.ksnd_nthreads != 0) {
2328                         i++;
2329                         /* power of 2? */
2330                         CDEBUG(((i & (-i)) == i) ? D_WARNING : D_NET,
2331                                 "waiting for %d threads to terminate\n",
2332                                 ksocknal_data.ksnd_nthreads);
2333                         read_unlock(&ksocknal_data.ksnd_global_lock);
2334                         set_current_state(TASK_UNINTERRUPTIBLE);
2335                         schedule_timeout(cfs_time_seconds(1));
2336                         read_lock(&ksocknal_data.ksnd_global_lock);
2337                 }
2338                 read_unlock(&ksocknal_data.ksnd_global_lock);
2339
2340                 ksocknal_free_buffers();
2341
2342                 ksocknal_data.ksnd_init = SOCKNAL_INIT_NOTHING;
2343                 break;
2344         }
2345
2346         CDEBUG(D_MALLOC, "after NAL cleanup: kmem %d\n",
2347                atomic_read (&libcfs_kmemory));
2348
2349         module_put(THIS_MODULE);
2350 }
2351
2352 static __u64 ksocknal_new_incarnation(void)
2353 {
2354         struct timeval tv;
2355
2356         /* The incarnation number is the time this module loaded and it
2357          * identifies this particular instance of the socknal.  Hopefully
2358          * we won't be able to reboot more frequently than 1MHz for the
2359          * forseeable future :) */
2360
2361         do_gettimeofday(&tv);
2362
2363         return (((__u64)tv.tv_sec) * 1000000) + tv.tv_usec;
2364 }
2365
2366 static int
2367 ksocknal_base_startup(void)
2368 {
2369         struct ksock_sched_info *info;
2370         int                     rc;
2371         int                     i;
2372
2373         LASSERT (ksocknal_data.ksnd_init == SOCKNAL_INIT_NOTHING);
2374         LASSERT (ksocknal_data.ksnd_nnets == 0);
2375
2376         memset (&ksocknal_data, 0, sizeof (ksocknal_data)); /* zero pointers */
2377
2378         ksocknal_data.ksnd_peer_hash_size = SOCKNAL_PEER_HASH_SIZE;
2379         LIBCFS_ALLOC(ksocknal_data.ksnd_peers,
2380                      sizeof(struct list_head) *
2381                      ksocknal_data.ksnd_peer_hash_size);
2382         if (ksocknal_data.ksnd_peers == NULL)
2383                 return -ENOMEM;
2384
2385         for (i = 0; i < ksocknal_data.ksnd_peer_hash_size; i++)
2386                 INIT_LIST_HEAD(&ksocknal_data.ksnd_peers[i]);
2387
2388         rwlock_init(&ksocknal_data.ksnd_global_lock);
2389         INIT_LIST_HEAD(&ksocknal_data.ksnd_nets);
2390
2391         spin_lock_init(&ksocknal_data.ksnd_reaper_lock);
2392         INIT_LIST_HEAD(&ksocknal_data.ksnd_enomem_conns);
2393         INIT_LIST_HEAD(&ksocknal_data.ksnd_zombie_conns);
2394         INIT_LIST_HEAD(&ksocknal_data.ksnd_deathrow_conns);
2395         init_waitqueue_head(&ksocknal_data.ksnd_reaper_waitq);
2396
2397         spin_lock_init(&ksocknal_data.ksnd_connd_lock);
2398         INIT_LIST_HEAD(&ksocknal_data.ksnd_connd_connreqs);
2399         INIT_LIST_HEAD(&ksocknal_data.ksnd_connd_routes);
2400         init_waitqueue_head(&ksocknal_data.ksnd_connd_waitq);
2401
2402         spin_lock_init(&ksocknal_data.ksnd_tx_lock);
2403         INIT_LIST_HEAD(&ksocknal_data.ksnd_idle_noop_txs);
2404
2405         /* NB memset above zeros whole of ksocknal_data */
2406
2407         /* flag lists/ptrs/locks initialised */
2408         ksocknal_data.ksnd_init = SOCKNAL_INIT_DATA;
2409         try_module_get(THIS_MODULE);
2410
2411         ksocknal_data.ksnd_sched_info = cfs_percpt_alloc(lnet_cpt_table(),
2412                                                          sizeof(*info));
2413         if (ksocknal_data.ksnd_sched_info == NULL)
2414                 goto failed;
2415
2416         cfs_percpt_for_each(info, i, ksocknal_data.ksnd_sched_info) {
2417                 ksock_sched_t   *sched;
2418                 int             nthrs;
2419
2420                 nthrs = cfs_cpt_weight(lnet_cpt_table(), i);
2421                 if (*ksocknal_tunables.ksnd_nscheds > 0) {
2422                         nthrs = min(nthrs, *ksocknal_tunables.ksnd_nscheds);
2423                 } else {
2424                         /* max to half of CPUs, assume another half should be
2425                          * reserved for upper layer modules */
2426                         nthrs = min(max(SOCKNAL_NSCHEDS, nthrs >> 1), nthrs);
2427                 }
2428
2429                 info->ksi_nthreads_max = nthrs;
2430                 info->ksi_cpt = i;
2431
2432                 LIBCFS_CPT_ALLOC(info->ksi_scheds, lnet_cpt_table(), i,
2433                                  info->ksi_nthreads_max * sizeof(*sched));
2434                 if (info->ksi_scheds == NULL)
2435                         goto failed;
2436
2437                 for (; nthrs > 0; nthrs--) {
2438                         sched = &info->ksi_scheds[nthrs - 1];
2439
2440                         sched->kss_info = info;
2441                         spin_lock_init(&sched->kss_lock);
2442                         INIT_LIST_HEAD(&sched->kss_rx_conns);
2443                         INIT_LIST_HEAD(&sched->kss_tx_conns);
2444                         INIT_LIST_HEAD(&sched->kss_zombie_noop_txs);
2445                         init_waitqueue_head(&sched->kss_waitq);
2446                 }
2447         }
2448
2449         ksocknal_data.ksnd_connd_starting         = 0;
2450         ksocknal_data.ksnd_connd_failed_stamp     = 0;
2451         ksocknal_data.ksnd_connd_starting_stamp   = cfs_time_current_sec();
2452         /* must have at least 2 connds to remain responsive to accepts while
2453          * connecting */
2454         if (*ksocknal_tunables.ksnd_nconnds < SOCKNAL_CONND_RESV + 1)
2455                 *ksocknal_tunables.ksnd_nconnds = SOCKNAL_CONND_RESV + 1;
2456
2457         if (*ksocknal_tunables.ksnd_nconnds_max <
2458             *ksocknal_tunables.ksnd_nconnds) {
2459                 ksocknal_tunables.ksnd_nconnds_max =
2460                         ksocknal_tunables.ksnd_nconnds;
2461         }
2462
2463         for (i = 0; i < *ksocknal_tunables.ksnd_nconnds; i++) {
2464                 char name[16];
2465                 spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
2466                 ksocknal_data.ksnd_connd_starting++;
2467                 spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
2468
2469
2470                 snprintf(name, sizeof(name), "socknal_cd%02d", i);
2471                 rc = ksocknal_thread_start(ksocknal_connd,
2472                                            (void *)((uintptr_t)i), name);
2473                 if (rc != 0) {
2474                         spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
2475                         ksocknal_data.ksnd_connd_starting--;
2476                         spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
2477                         CERROR("Can't spawn socknal connd: %d\n", rc);
2478                         goto failed;
2479                 }
2480         }
2481
2482         rc = ksocknal_thread_start(ksocknal_reaper, NULL, "socknal_reaper");
2483         if (rc != 0) {
2484                 CERROR ("Can't spawn socknal reaper: %d\n", rc);
2485                 goto failed;
2486         }
2487
2488         /* flag everything initialised */
2489         ksocknal_data.ksnd_init = SOCKNAL_INIT_ALL;
2490
2491         return 0;
2492
2493  failed:
2494         ksocknal_base_shutdown();
2495         return -ENETDOWN;
2496 }
2497
2498 static void
2499 ksocknal_debug_peerhash (lnet_ni_t *ni)
2500 {
2501         ksock_peer_t    *peer = NULL;
2502         struct list_head        *tmp;
2503         int             i;
2504
2505         read_lock(&ksocknal_data.ksnd_global_lock);
2506
2507         for (i = 0; i < ksocknal_data.ksnd_peer_hash_size; i++) {
2508                 list_for_each(tmp, &ksocknal_data.ksnd_peers[i]) {
2509                         peer = list_entry(tmp, ksock_peer_t, ksnp_list);
2510
2511                         if (peer->ksnp_ni == ni) break;
2512
2513                         peer = NULL;
2514                 }
2515         }
2516
2517         if (peer != NULL) {
2518                 ksock_route_t *route;
2519                 ksock_conn_t  *conn;
2520
2521                 CWARN ("Active peer on shutdown: %s, ref %d, scnt %d, "
2522                        "closing %d, accepting %d, err %d, zcookie %llu, "
2523                        "txq %d, zc_req %d\n", libcfs_id2str(peer->ksnp_id),
2524                        atomic_read(&peer->ksnp_refcount),
2525                        peer->ksnp_sharecount, peer->ksnp_closing,
2526                        peer->ksnp_accepting, peer->ksnp_error,
2527                        peer->ksnp_zc_next_cookie,
2528                        !list_empty(&peer->ksnp_tx_queue),
2529                        !list_empty(&peer->ksnp_zc_req_list));
2530
2531                 list_for_each(tmp, &peer->ksnp_routes) {
2532                         route = list_entry(tmp, ksock_route_t, ksnr_list);
2533                         CWARN ("Route: ref %d, schd %d, conn %d, cnted %d, "
2534                                "del %d\n", atomic_read(&route->ksnr_refcount),
2535                                route->ksnr_scheduled, route->ksnr_connecting,
2536                                route->ksnr_connected, route->ksnr_deleted);
2537                 }
2538
2539                 list_for_each(tmp, &peer->ksnp_conns) {
2540                         conn = list_entry(tmp, ksock_conn_t, ksnc_list);
2541                         CWARN ("Conn: ref %d, sref %d, t %d, c %d\n",
2542                                atomic_read(&conn->ksnc_conn_refcount),
2543                                atomic_read(&conn->ksnc_sock_refcount),
2544                                conn->ksnc_type, conn->ksnc_closing);
2545                 }
2546         }
2547
2548         read_unlock(&ksocknal_data.ksnd_global_lock);
2549         return;
2550 }
2551
2552 void
2553 ksocknal_shutdown (lnet_ni_t *ni)
2554 {
2555         ksock_net_t      *net = ni->ni_data;
2556         int               i;
2557         lnet_process_id_t anyid = {0};
2558
2559         anyid.nid =  LNET_NID_ANY;
2560         anyid.pid =  LNET_PID_ANY;
2561
2562         LASSERT(ksocknal_data.ksnd_init == SOCKNAL_INIT_ALL);
2563         LASSERT(ksocknal_data.ksnd_nnets > 0);
2564
2565         spin_lock_bh(&net->ksnn_lock);
2566         net->ksnn_shutdown = 1;                 /* prevent new peers */
2567         spin_unlock_bh(&net->ksnn_lock);
2568
2569         /* Delete all peers */
2570         ksocknal_del_peer(ni, anyid, 0);
2571
2572         /* Wait for all peer state to clean up */
2573         i = 2;
2574         spin_lock_bh(&net->ksnn_lock);
2575         while (net->ksnn_npeers != 0) {
2576                 spin_unlock_bh(&net->ksnn_lock);
2577
2578                 i++;
2579                 CDEBUG(((i & (-i)) == i) ? D_WARNING : D_NET, /* power of 2? */
2580                        "waiting for %d peers to disconnect\n",
2581                        net->ksnn_npeers);
2582                 set_current_state(TASK_UNINTERRUPTIBLE);
2583                 schedule_timeout(cfs_time_seconds(1));
2584
2585                 ksocknal_debug_peerhash(ni);
2586
2587                 spin_lock_bh(&net->ksnn_lock);
2588         }
2589         spin_unlock_bh(&net->ksnn_lock);
2590
2591         for (i = 0; i < net->ksnn_ninterfaces; i++) {
2592                 LASSERT (net->ksnn_interfaces[i].ksni_npeers == 0);
2593                 LASSERT (net->ksnn_interfaces[i].ksni_nroutes == 0);
2594         }
2595
2596         list_del(&net->ksnn_list);
2597         LIBCFS_FREE(net, sizeof(*net));
2598
2599         ksocknal_data.ksnd_nnets--;
2600         if (ksocknal_data.ksnd_nnets == 0)
2601                 ksocknal_base_shutdown();
2602 }
2603
2604 static int
2605 ksocknal_enumerate_interfaces(ksock_net_t *net)
2606 {
2607         char      **names;
2608         int         i;
2609         int         j;
2610         int         rc;
2611         int         n;
2612
2613         n = lnet_ipif_enumerate(&names);
2614         if (n <= 0) {
2615                 CERROR("Can't enumerate interfaces: %d\n", n);
2616                 return n;
2617         }
2618
2619         for (i = j = 0; i < n; i++) {
2620                 int        up;
2621                 __u32      ip;
2622                 __u32      mask;
2623
2624                 if (!strcmp(names[i], "lo")) /* skip the loopback IF */
2625                         continue;
2626
2627                 rc = lnet_ipif_query(names[i], &up, &ip, &mask);
2628                 if (rc != 0) {
2629                         CWARN("Can't get interface %s info: %d\n",
2630                               names[i], rc);
2631                         continue;
2632                 }
2633
2634                 if (!up) {
2635                         CWARN("Ignoring interface %s (down)\n",
2636                               names[i]);
2637                         continue;
2638                 }
2639
2640                 if (j == LNET_MAX_INTERFACES) {
2641                         CWARN("Ignoring interface %s (too many interfaces)\n",
2642                               names[i]);
2643                         continue;
2644                 }
2645
2646                 net->ksnn_interfaces[j].ksni_ipaddr = ip;
2647                 net->ksnn_interfaces[j].ksni_netmask = mask;
2648                 strlcpy(net->ksnn_interfaces[j].ksni_name,
2649                         names[i], sizeof(net->ksnn_interfaces[j].ksni_name));
2650                 j++;
2651         }
2652
2653         lnet_ipif_free_enumeration(names, n);
2654
2655         if (j == 0)
2656                 CERROR("Can't find any usable interfaces\n");
2657
2658         return j;
2659 }
2660
2661 static int
2662 ksocknal_search_new_ipif(ksock_net_t *net)
2663 {
2664         int     new_ipif = 0;
2665         int     i;
2666
2667         for (i = 0; i < net->ksnn_ninterfaces; i++) {
2668                 char            *ifnam = &net->ksnn_interfaces[i].ksni_name[0];
2669                 char            *colon = strchr(ifnam, ':');
2670                 int             found  = 0;
2671                 ksock_net_t     *tmp;
2672                 int             j;
2673
2674                 if (colon != NULL) /* ignore alias device */
2675                         *colon = 0;
2676
2677                 list_for_each_entry(tmp, &ksocknal_data.ksnd_nets,
2678                                         ksnn_list) {
2679                         for (j = 0; !found && j < tmp->ksnn_ninterfaces; j++) {
2680                                 char *ifnam2 = &tmp->ksnn_interfaces[j].\
2681                                              ksni_name[0];
2682                                 char *colon2 = strchr(ifnam2, ':');
2683
2684                                 if (colon2 != NULL)
2685                                         *colon2 = 0;
2686
2687                                 found = strcmp(ifnam, ifnam2) == 0;
2688                                 if (colon2 != NULL)
2689                                         *colon2 = ':';
2690                         }
2691                         if (found)
2692                                 break;
2693                 }
2694
2695                 new_ipif += !found;
2696                 if (colon != NULL)
2697                         *colon = ':';
2698         }
2699
2700         return new_ipif;
2701 }
2702
2703 static int
2704 ksocknal_start_schedulers(struct ksock_sched_info *info)
2705 {
2706         int     nthrs;
2707         int     rc = 0;
2708         int     i;
2709
2710         if (info->ksi_nthreads == 0) {
2711                 if (*ksocknal_tunables.ksnd_nscheds > 0) {
2712                         nthrs = info->ksi_nthreads_max;
2713                 } else {
2714                         nthrs = cfs_cpt_weight(lnet_cpt_table(),
2715                                                info->ksi_cpt);
2716                         nthrs = min(max(SOCKNAL_NSCHEDS, nthrs >> 1), nthrs);
2717                         nthrs = min(SOCKNAL_NSCHEDS_HIGH, nthrs);
2718                 }
2719                 nthrs = min(nthrs, info->ksi_nthreads_max);
2720         } else {
2721                 LASSERT(info->ksi_nthreads <= info->ksi_nthreads_max);
2722                 /* increase two threads if there is new interface */
2723                 nthrs = min(2, info->ksi_nthreads_max - info->ksi_nthreads);
2724         }
2725
2726         for (i = 0; i < nthrs; i++) {
2727                 long            id;
2728                 char            name[20];
2729                 ksock_sched_t   *sched;
2730                 id = KSOCK_THREAD_ID(info->ksi_cpt, info->ksi_nthreads + i);
2731                 sched = &info->ksi_scheds[KSOCK_THREAD_SID(id)];
2732                 snprintf(name, sizeof(name), "socknal_sd%02d_%02d",
2733                          info->ksi_cpt, (int)(sched - &info->ksi_scheds[0]));
2734
2735                 rc = ksocknal_thread_start(ksocknal_scheduler,
2736                                            (void *)id, name);
2737                 if (rc == 0)
2738                         continue;
2739
2740                 CERROR("Can't spawn thread %d for scheduler[%d]: %d\n",
2741                        info->ksi_cpt, info->ksi_nthreads + i, rc);
2742                 break;
2743         }
2744
2745         info->ksi_nthreads += i;
2746         return rc;
2747 }
2748
2749 static int
2750 ksocknal_net_start_threads(ksock_net_t *net, __u32 *cpts, int ncpts)
2751 {
2752         int     newif = ksocknal_search_new_ipif(net);
2753         int     rc;
2754         int     i;
2755
2756         LASSERT(ncpts > 0 && ncpts <= cfs_cpt_number(lnet_cpt_table()));
2757
2758         for (i = 0; i < ncpts; i++) {
2759                 struct ksock_sched_info *info;
2760                 int cpt = (cpts == NULL) ? i : cpts[i];
2761
2762                 LASSERT(cpt < cfs_cpt_number(lnet_cpt_table()));
2763                 info = ksocknal_data.ksnd_sched_info[cpt];
2764
2765                 if (!newif && info->ksi_nthreads > 0)
2766                         continue;
2767
2768                 rc = ksocknal_start_schedulers(info);
2769                 if (rc != 0)
2770                         return rc;
2771         }
2772         return 0;
2773 }
2774
2775 int
2776 ksocknal_startup (lnet_ni_t *ni)
2777 {
2778         ksock_net_t  *net;
2779         int           rc;
2780         int           i;
2781
2782         LASSERT (ni->ni_lnd == &the_ksocklnd);
2783
2784         if (ksocknal_data.ksnd_init == SOCKNAL_INIT_NOTHING) {
2785                 rc = ksocknal_base_startup();
2786                 if (rc != 0)
2787                         return rc;
2788         }
2789
2790         LIBCFS_ALLOC(net, sizeof(*net));
2791         if (net == NULL)
2792                 goto fail_0;
2793
2794         spin_lock_init(&net->ksnn_lock);
2795         net->ksnn_incarnation = ksocknal_new_incarnation();
2796         ni->ni_data = net;
2797         ni->ni_peertimeout    = *ksocknal_tunables.ksnd_peertimeout;
2798         ni->ni_maxtxcredits   = *ksocknal_tunables.ksnd_credits;
2799         ni->ni_peertxcredits  = *ksocknal_tunables.ksnd_peertxcredits;
2800         ni->ni_peerrtrcredits = *ksocknal_tunables.ksnd_peerrtrcredits;
2801
2802         if (ni->ni_interfaces[0] == NULL) {
2803                 rc = ksocknal_enumerate_interfaces(net);
2804                 if (rc <= 0)
2805                         goto fail_1;
2806
2807                 net->ksnn_ninterfaces = 1;
2808         } else {
2809                 for (i = 0; i < LNET_MAX_INTERFACES; i++) {
2810                         int    up;
2811
2812                         if (ni->ni_interfaces[i] == NULL)
2813                                 break;
2814
2815                         rc = lnet_ipif_query(ni->ni_interfaces[i], &up,
2816                                 &net->ksnn_interfaces[i].ksni_ipaddr,
2817                                 &net->ksnn_interfaces[i].ksni_netmask);
2818
2819                         if (rc != 0) {
2820                                 CERROR("Can't get interface %s info: %d\n",
2821                                        ni->ni_interfaces[i], rc);
2822                                 goto fail_1;
2823                         }
2824
2825                         if (!up) {
2826                                 CERROR("Interface %s is down\n",
2827                                        ni->ni_interfaces[i]);
2828                                 goto fail_1;
2829                         }
2830
2831                         strlcpy(net->ksnn_interfaces[i].ksni_name,
2832                                 ni->ni_interfaces[i],
2833                                 sizeof(net->ksnn_interfaces[i].ksni_name));
2834                 }
2835                 net->ksnn_ninterfaces = i;
2836         }
2837
2838         /* call it before add it to ksocknal_data.ksnd_nets */
2839         rc = ksocknal_net_start_threads(net, ni->ni_cpts, ni->ni_ncpts);
2840         if (rc != 0)
2841                 goto fail_1;
2842
2843         ni->ni_nid = LNET_MKNID(LNET_NIDNET(ni->ni_nid),
2844                                 net->ksnn_interfaces[0].ksni_ipaddr);
2845         list_add(&net->ksnn_list, &ksocknal_data.ksnd_nets);
2846
2847         ksocknal_data.ksnd_nnets++;
2848
2849         return 0;
2850
2851  fail_1:
2852         LIBCFS_FREE(net, sizeof(*net));
2853  fail_0:
2854         if (ksocknal_data.ksnd_nnets == 0)
2855                 ksocknal_base_shutdown();
2856
2857         return -ENETDOWN;
2858 }
2859
2860
2861 static void __exit ksocklnd_exit(void)
2862 {
2863         lnet_unregister_lnd(&the_ksocklnd);
2864 }
2865
2866 static int __init ksocklnd_init(void)
2867 {
2868         int rc;
2869
2870         /* check ksnr_connected/connecting field large enough */
2871         CLASSERT(SOCKLND_CONN_NTYPES <= 4);
2872         CLASSERT(SOCKLND_CONN_ACK == SOCKLND_CONN_BULK_IN);
2873
2874         /* initialize the_ksocklnd */
2875         the_ksocklnd.lnd_type     = SOCKLND;
2876         the_ksocklnd.lnd_startup  = ksocknal_startup;
2877         the_ksocklnd.lnd_shutdown = ksocknal_shutdown;
2878         the_ksocklnd.lnd_ctl      = ksocknal_ctl;
2879         the_ksocklnd.lnd_send     = ksocknal_send;
2880         the_ksocklnd.lnd_recv     = ksocknal_recv;
2881         the_ksocklnd.lnd_notify   = ksocknal_notify;
2882         the_ksocklnd.lnd_query    = ksocknal_query;
2883         the_ksocklnd.lnd_accept   = ksocknal_accept;
2884
2885         rc = ksocknal_tunables_init();
2886         if (rc != 0)
2887                 return rc;
2888
2889         lnet_register_lnd(&the_ksocklnd);
2890
2891         return 0;
2892 }
2893
2894 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
2895 MODULE_DESCRIPTION("TCP Socket LNet Network Driver");
2896 MODULE_VERSION("2.8.0");
2897 MODULE_LICENSE("GPL");
2898
2899 module_init(ksocklnd_init);
2900 module_exit(ksocklnd_exit);