Whamcloud - gitweb
6c0c2678422a681a1dd58be795c73d3fc808f969
[fs/lustre-release.git] / lnet / lnet / router.c
1 /*
2  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
3  *
4  * Copyright (c) 2011, 2017, Intel Corporation.
5  *
6  *   This file is part of Lustre, https://wiki.whamcloud.com/
7  *
8  *   Portals is free software; you can redistribute it and/or
9  *   modify it under the terms of version 2 of the GNU General Public
10  *   License as published by the Free Software Foundation.
11  *
12  *   Portals is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *   GNU General Public License for more details.
16  *
17  *   You should have received a copy of the GNU General Public License
18  *   along with Portals; if not, write to the Free Software
19  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  *
21  */
22
23 #define DEBUG_SUBSYSTEM S_LNET
24 #include <lnet/lib-lnet.h>
25
26 #define LNET_NRB_TINY_MIN       512     /* min value for each CPT */
27 #define LNET_NRB_TINY           (LNET_NRB_TINY_MIN * 4)
28 #define LNET_NRB_SMALL_MIN      4096    /* min value for each CPT */
29 #define LNET_NRB_SMALL          (LNET_NRB_SMALL_MIN * 4)
30 #define LNET_NRB_SMALL_PAGES    1
31 #define LNET_NRB_LARGE_MIN      256     /* min value for each CPT */
32 #define LNET_NRB_LARGE          (LNET_NRB_LARGE_MIN * 4)
33 #define LNET_NRB_LARGE_PAGES    ((LNET_MTU + PAGE_SIZE - 1) >> \
34                                   PAGE_SHIFT)
35
36 static char *forwarding = "";
37 module_param(forwarding, charp, 0444);
38 MODULE_PARM_DESC(forwarding, "Explicitly enable/disable forwarding between networks");
39
40 static int tiny_router_buffers;
41 module_param(tiny_router_buffers, int, 0444);
42 MODULE_PARM_DESC(tiny_router_buffers, "# of 0 payload messages to buffer in the router");
43 static int small_router_buffers;
44 module_param(small_router_buffers, int, 0444);
45 MODULE_PARM_DESC(small_router_buffers, "# of small (1 page) messages to buffer in the router");
46 static int large_router_buffers;
47 module_param(large_router_buffers, int, 0444);
48 MODULE_PARM_DESC(large_router_buffers, "# of large messages to buffer in the router");
49 static int peer_buffer_credits;
50 module_param(peer_buffer_credits, int, 0444);
51 MODULE_PARM_DESC(peer_buffer_credits, "# router buffer credits per peer");
52
53 static int auto_down = 1;
54 module_param(auto_down, int, 0444);
55 MODULE_PARM_DESC(auto_down, "Automatically mark peers down on comms error");
56
57 int
58 lnet_peer_buffer_credits(struct lnet_net *net)
59 {
60         /* NI option overrides LNet default */
61         if (net->net_tunables.lct_peer_rtr_credits > 0)
62                 return net->net_tunables.lct_peer_rtr_credits;
63         if (peer_buffer_credits > 0)
64                 return peer_buffer_credits;
65
66         /* As an approximation, allow this peer the same number of router
67          * buffers as it is allowed outstanding sends */
68         return net->net_tunables.lct_peer_tx_credits;
69 }
70
71 static int check_routers_before_use;
72 module_param(check_routers_before_use, int, 0444);
73 MODULE_PARM_DESC(check_routers_before_use, "Assume routers are down and ping them before use");
74
75 int avoid_asym_router_failure = 1;
76 module_param(avoid_asym_router_failure, int, 0644);
77 MODULE_PARM_DESC(avoid_asym_router_failure, "Avoid asymmetrical router failures (0 to disable)");
78
79 static int dead_router_check_interval = 60;
80 module_param(dead_router_check_interval, int, 0644);
81 MODULE_PARM_DESC(dead_router_check_interval, "Seconds between dead router health checks (<= 0 to disable)");
82
83 static int live_router_check_interval = 60;
84 module_param(live_router_check_interval, int, 0644);
85 MODULE_PARM_DESC(live_router_check_interval, "Seconds between live router health checks (<= 0 to disable)");
86
87 static int router_ping_timeout = 50;
88 module_param(router_ping_timeout, int, 0644);
89 MODULE_PARM_DESC(router_ping_timeout, "Seconds to wait for the reply to a router health query");
90
91 int
92 lnet_peers_start_down(void)
93 {
94         return check_routers_before_use;
95 }
96
97 void
98 lnet_notify_locked(struct lnet_peer_ni *lp, int notifylnd, int alive,
99                    time64_t when)
100 {
101         if (lp->lpni_timestamp > when) { /* out of date information */
102                 CDEBUG(D_NET, "Out of date\n");
103                 return;
104         }
105
106         /*
107          * This function can be called with different cpt locks being
108          * held. lpni_alive_count modification needs to be properly protected.
109          * Significant reads to lpni_alive_count are also protected with
110          * the same lock
111          */
112         spin_lock(&lp->lpni_lock);
113
114         lp->lpni_timestamp = when; /* update timestamp */
115         lp->lpni_ping_deadline = 0;               /* disable ping timeout */
116
117         if (lp->lpni_alive_count != 0 &&          /* got old news */
118             (!lp->lpni_alive) == (!alive)) {      /* new date for old news */
119                 spin_unlock(&lp->lpni_lock);
120                 CDEBUG(D_NET, "Old news\n");
121                 return;
122         }
123
124         /* Flag that notification is outstanding */
125
126         lp->lpni_alive_count++;
127         lp->lpni_alive = (alive) ? 1 : 0;
128         lp->lpni_notify = 1;
129         lp->lpni_notifylnd = notifylnd;
130         if (lp->lpni_alive)
131                 lp->lpni_ping_feats = LNET_PING_FEAT_INVAL; /* reset */
132
133         spin_unlock(&lp->lpni_lock);
134
135         CDEBUG(D_NET, "set %s %d\n", libcfs_nid2str(lp->lpni_nid), alive);
136 }
137
138 /*
139  * This function will always be called with lp->lpni_cpt lock held.
140  */
141 static void
142 lnet_ni_notify_locked(struct lnet_ni *ni, struct lnet_peer_ni *lp)
143 {
144         int alive;
145         int notifylnd;
146
147         /* Notify only in 1 thread at any time to ensure ordered notification.
148          * NB individual events can be missed; the only guarantee is that you
149          * always get the most recent news */
150
151         spin_lock(&lp->lpni_lock);
152
153         if (lp->lpni_notifying || ni == NULL) {
154                 spin_unlock(&lp->lpni_lock);
155                 return;
156         }
157
158         lp->lpni_notifying = 1;
159
160         /*
161          * lp->lpni_notify needs to be protected because it can be set in
162          * lnet_notify_locked().
163          */
164         while (lp->lpni_notify) {
165                 alive     = lp->lpni_alive;
166                 notifylnd = lp->lpni_notifylnd;
167
168                 lp->lpni_notifylnd = 0;
169                 lp->lpni_notify    = 0;
170
171                 if (notifylnd && ni->ni_net->net_lnd->lnd_notify != NULL) {
172                         spin_unlock(&lp->lpni_lock);
173                         lnet_net_unlock(lp->lpni_cpt);
174
175                         /* A new notification could happen now; I'll handle it
176                          * when control returns to me */
177
178                         (ni->ni_net->net_lnd->lnd_notify)(ni, lp->lpni_nid,
179                                                           alive);
180
181                         lnet_net_lock(lp->lpni_cpt);
182                         spin_lock(&lp->lpni_lock);
183                 }
184         }
185
186         lp->lpni_notifying = 0;
187         spin_unlock(&lp->lpni_lock);
188 }
189
190 static void
191 lnet_rtr_addref_locked(struct lnet_peer_ni *lp)
192 {
193         LASSERT(atomic_read(&lp->lpni_refcount) > 0);
194         LASSERT(lp->lpni_rtr_refcount >= 0);
195
196         /* lnet_net_lock must be exclusively locked */
197         lp->lpni_rtr_refcount++;
198         if (lp->lpni_rtr_refcount == 1) {
199                 struct list_head *pos;
200
201                 /* a simple insertion sort */
202                 list_for_each_prev(pos, &the_lnet.ln_routers) {
203                         struct lnet_peer_ni *rtr;
204
205                         rtr = list_entry(pos, struct lnet_peer_ni,
206                                          lpni_rtr_list);
207                         if (rtr->lpni_nid < lp->lpni_nid)
208                                 break;
209                 }
210
211                 list_add(&lp->lpni_rtr_list, pos);
212                 /* addref for the_lnet.ln_routers */
213                 lnet_peer_ni_addref_locked(lp);
214                 the_lnet.ln_routers_version++;
215         }
216 }
217
218 static void
219 lnet_rtr_decref_locked(struct lnet_peer_ni *lp)
220 {
221         LASSERT(atomic_read(&lp->lpni_refcount) > 0);
222         LASSERT(lp->lpni_rtr_refcount > 0);
223
224         /* lnet_net_lock must be exclusively locked */
225         lp->lpni_rtr_refcount--;
226         if (lp->lpni_rtr_refcount == 0) {
227                 LASSERT(list_empty(&lp->lpni_routes));
228
229                 if (lp->lpni_rcd != NULL) {
230                         list_add(&lp->lpni_rcd->rcd_list,
231                                  &the_lnet.ln_rcd_deathrow);
232                         lp->lpni_rcd = NULL;
233                 }
234
235                 list_del(&lp->lpni_rtr_list);
236                 /* decref for the_lnet.ln_routers */
237                 lnet_peer_ni_decref_locked(lp);
238                 the_lnet.ln_routers_version++;
239         }
240 }
241
242 struct lnet_remotenet *
243 lnet_find_rnet_locked(__u32 net)
244 {
245         struct lnet_remotenet *rnet;
246         struct list_head *tmp;
247         struct list_head *rn_list;
248
249         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
250
251         rn_list = lnet_net2rnethash(net);
252         list_for_each(tmp, rn_list) {
253                 rnet = list_entry(tmp, struct lnet_remotenet, lrn_list);
254
255                 if (rnet->lrn_net == net)
256                         return rnet;
257         }
258         return NULL;
259 }
260
261 static void lnet_shuffle_seed(void)
262 {
263         static int seeded;
264         __u32 lnd_type;
265         __u32 seed[2];
266         struct timespec64 ts;
267         struct lnet_ni *ni = NULL;
268
269         if (seeded)
270                 return;
271
272         cfs_get_random_bytes(seed, sizeof(seed));
273
274         /* Nodes with small feet have little entropy
275          * the NID for this node gives the most entropy in the low bits */
276         while ((ni = lnet_get_next_ni_locked(NULL, ni))) {
277                 lnd_type = LNET_NETTYP(LNET_NIDNET(ni->ni_nid));
278
279                 if (lnd_type != LOLND)
280                         seed[0] ^= (LNET_NIDADDR(ni->ni_nid) | lnd_type);
281         }
282
283         ktime_get_ts64(&ts);
284         cfs_srand(ts.tv_sec ^ seed[0], ts.tv_nsec ^ seed[1]);
285         seeded = 1;
286         return;
287 }
288
289 /* NB expects LNET_LOCK held */
290 static void
291 lnet_add_route_to_rnet(struct lnet_remotenet *rnet, struct lnet_route *route)
292 {
293         unsigned int      len = 0;
294         unsigned int      offset = 0;
295         struct list_head *e;
296
297         lnet_shuffle_seed();
298
299         list_for_each(e, &rnet->lrn_routes) {
300                 len++;
301         }
302
303         /* len+1 positions to add a new entry, also prevents division by 0 */
304         offset = cfs_rand() % (len + 1);
305         list_for_each(e, &rnet->lrn_routes) {
306                 if (offset == 0)
307                         break;
308                 offset--;
309         }
310         list_add(&route->lr_list, e);
311         list_add(&route->lr_gwlist, &route->lr_gateway->lpni_routes);
312
313         the_lnet.ln_remote_nets_version++;
314         lnet_rtr_addref_locked(route->lr_gateway);
315 }
316
317 int
318 lnet_add_route(__u32 net, __u32 hops, lnet_nid_t gateway,
319                unsigned int priority)
320 {
321         struct list_head        *e;
322         struct lnet_remotenet   *rnet;
323         struct lnet_remotenet   *rnet2;
324         struct lnet_route               *route;
325         struct lnet_ni          *ni;
326         struct lnet_peer_ni     *lpni;
327         int                     add_route;
328         int                     rc;
329
330         CDEBUG(D_NET, "Add route: net %s hops %d priority %u gw %s\n",
331                libcfs_net2str(net), hops, priority, libcfs_nid2str(gateway));
332
333         if (gateway == LNET_NID_ANY ||
334             LNET_NETTYP(LNET_NIDNET(gateway)) == LOLND ||
335             net == LNET_NIDNET(LNET_NID_ANY) ||
336             LNET_NETTYP(net) == LOLND ||
337             LNET_NIDNET(gateway) == net ||
338             (hops != LNET_UNDEFINED_HOPS && (hops < 1 || hops > 255)))
339                 return -EINVAL;
340
341         if (lnet_islocalnet(net))       /* it's a local network */
342                 return -EEXIST;
343
344         if (!lnet_islocalnet(LNET_NIDNET(gateway))) {
345                 CERROR("Cannot add route with gateway %s. There is no local interface configured on LNet %s\n",
346                        libcfs_nid2str(gateway),
347                        libcfs_net2str(LNET_NIDNET(gateway)));
348                 return -EHOSTUNREACH;
349         }
350
351         /* Assume net, route, all new */
352         LIBCFS_ALLOC(route, sizeof(*route));
353         LIBCFS_ALLOC(rnet, sizeof(*rnet));
354         if (route == NULL || rnet == NULL) {
355                 CERROR("Out of memory creating route %s %d %s\n",
356                        libcfs_net2str(net), hops, libcfs_nid2str(gateway));
357                 if (route != NULL)
358                         LIBCFS_FREE(route, sizeof(*route));
359                 if (rnet != NULL)
360                         LIBCFS_FREE(rnet, sizeof(*rnet));
361                 return -ENOMEM;
362         }
363
364         INIT_LIST_HEAD(&rnet->lrn_routes);
365         rnet->lrn_net = net;
366         route->lr_hops = hops;
367         route->lr_net = net;
368         route->lr_priority = priority;
369
370         lnet_net_lock(LNET_LOCK_EX);
371
372         lpni = lnet_nid2peerni_ex(gateway, LNET_LOCK_EX);
373         if (IS_ERR(lpni)) {
374                 lnet_net_unlock(LNET_LOCK_EX);
375
376                 LIBCFS_FREE(route, sizeof(*route));
377                 LIBCFS_FREE(rnet, sizeof(*rnet));
378
379                 rc = PTR_ERR(lpni);
380                 if (rc == -EHOSTUNREACH) /* gateway is not on a local net. */
381                         return rc;       /* ignore the route entry */
382                 CERROR("Error %d creating route %s %d %s\n", rc,
383                         libcfs_net2str(net), hops,
384                         libcfs_nid2str(gateway));
385                 return rc;
386         }
387         route->lr_gateway = lpni;
388         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
389
390         rnet2 = lnet_find_rnet_locked(net);
391         if (rnet2 == NULL) {
392                 /* new network */
393                 list_add_tail(&rnet->lrn_list, lnet_net2rnethash(net));
394                 rnet2 = rnet;
395         }
396
397         /* Search for a duplicate route (it's a NOOP if it is) */
398         add_route = 1;
399         list_for_each(e, &rnet2->lrn_routes) {
400                 struct lnet_route *route2;
401
402                 route2 = list_entry(e, struct lnet_route, lr_list);
403                 if (route2->lr_gateway == route->lr_gateway) {
404                         add_route = 0;
405                         break;
406                 }
407
408                 /* our lookups must be true */
409                 LASSERT(route2->lr_gateway->lpni_nid != gateway);
410         }
411
412         if (add_route) {
413                 lnet_peer_ni_addref_locked(route->lr_gateway); /* +1 for notify */
414                 lnet_add_route_to_rnet(rnet2, route);
415
416                 ni = lnet_get_next_ni_locked(route->lr_gateway->lpni_net, NULL);
417                 lnet_net_unlock(LNET_LOCK_EX);
418
419                 /* XXX Assume alive */
420                 if (ni->ni_net->net_lnd->lnd_notify != NULL)
421                         (ni->ni_net->net_lnd->lnd_notify)(ni, gateway, 1);
422
423                 lnet_net_lock(LNET_LOCK_EX);
424         }
425
426         /* -1 for notify or !add_route */
427         lnet_peer_ni_decref_locked(route->lr_gateway);
428         lnet_net_unlock(LNET_LOCK_EX);
429
430         rc = 0;
431
432         if (!add_route) {
433                 rc = -EEXIST;
434                 LIBCFS_FREE(route, sizeof(*route));
435         }
436
437         if (rnet != rnet2)
438                 LIBCFS_FREE(rnet, sizeof(*rnet));
439
440         /* kick start the monitor thread to handle the added route */
441         wake_up(&the_lnet.ln_mt_waitq);
442
443         return rc;
444 }
445
446 int
447 lnet_check_routes(void)
448 {
449         struct lnet_remotenet *rnet;
450         struct lnet_route        *route;
451         struct lnet_route        *route2;
452         struct list_head *e1;
453         struct list_head *e2;
454         int               cpt;
455         struct list_head *rn_list;
456         int               i;
457
458         cpt = lnet_net_lock_current();
459
460         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++) {
461                 rn_list = &the_lnet.ln_remote_nets_hash[i];
462                 list_for_each(e1, rn_list) {
463                         rnet = list_entry(e1, struct lnet_remotenet, lrn_list);
464
465                         route2 = NULL;
466                         list_for_each(e2, &rnet->lrn_routes) {
467                                 lnet_nid_t      nid1;
468                                 lnet_nid_t      nid2;
469                                 int             net;
470
471                                 route = list_entry(e2, struct lnet_route,
472                                                    lr_list);
473
474                                 if (route2 == NULL) {
475                                         route2 = route;
476                                         continue;
477                                 }
478
479                                 if (route->lr_gateway->lpni_net ==
480                                     route2->lr_gateway->lpni_net)
481                                         continue;
482
483                                 nid1 = route->lr_gateway->lpni_nid;
484                                 nid2 = route2->lr_gateway->lpni_nid;
485                                 net = rnet->lrn_net;
486
487                                 lnet_net_unlock(cpt);
488
489                                 CERROR("Routes to %s via %s and %s not "
490                                        "supported\n",
491                                        libcfs_net2str(net),
492                                        libcfs_nid2str(nid1),
493                                        libcfs_nid2str(nid2));
494                                 return -EINVAL;
495                         }
496                 }
497         }
498
499         lnet_net_unlock(cpt);
500         return 0;
501 }
502
503 int
504 lnet_del_route(__u32 net, lnet_nid_t gw_nid)
505 {
506         struct lnet_peer_ni     *gateway;
507         struct lnet_remotenet   *rnet;
508         struct lnet_route               *route;
509         struct list_head        *e1;
510         struct list_head        *e2;
511         int                     rc = -ENOENT;
512         struct list_head        *rn_list;
513         int                     idx = 0;
514
515         CDEBUG(D_NET, "Del route: net %s : gw %s\n",
516                libcfs_net2str(net), libcfs_nid2str(gw_nid));
517
518         /* NB Caller may specify either all routes via the given gateway
519          * or a specific route entry actual NIDs) */
520
521         lnet_net_lock(LNET_LOCK_EX);
522         if (net == LNET_NIDNET(LNET_NID_ANY))
523                 rn_list = &the_lnet.ln_remote_nets_hash[0];
524         else
525                 rn_list = lnet_net2rnethash(net);
526
527 again:
528         list_for_each(e1, rn_list) {
529                 rnet = list_entry(e1, struct lnet_remotenet, lrn_list);
530
531                 if (!(net == LNET_NIDNET(LNET_NID_ANY) ||
532                         net == rnet->lrn_net))
533                         continue;
534
535                 list_for_each(e2, &rnet->lrn_routes) {
536                         route = list_entry(e2, struct lnet_route, lr_list);
537
538                         gateway = route->lr_gateway;
539                         if (!(gw_nid == LNET_NID_ANY ||
540                               gw_nid == gateway->lpni_nid))
541                                 continue;
542
543                         list_del(&route->lr_list);
544                         list_del(&route->lr_gwlist);
545                         the_lnet.ln_remote_nets_version++;
546
547                         if (list_empty(&rnet->lrn_routes))
548                                 list_del(&rnet->lrn_list);
549                         else
550                                 rnet = NULL;
551
552                         lnet_rtr_decref_locked(gateway);
553                         lnet_peer_ni_decref_locked(gateway);
554
555                         lnet_net_unlock(LNET_LOCK_EX);
556
557                         LIBCFS_FREE(route, sizeof(*route));
558
559                         if (rnet != NULL)
560                                 LIBCFS_FREE(rnet, sizeof(*rnet));
561
562                         rc = 0;
563                         lnet_net_lock(LNET_LOCK_EX);
564                         goto again;
565                 }
566         }
567
568         if (net == LNET_NIDNET(LNET_NID_ANY) &&
569             ++idx < LNET_REMOTE_NETS_HASH_SIZE) {
570                 rn_list = &the_lnet.ln_remote_nets_hash[idx];
571                 goto again;
572         }
573         lnet_net_unlock(LNET_LOCK_EX);
574
575         return rc;
576 }
577
578 void
579 lnet_destroy_routes (void)
580 {
581         lnet_del_route(LNET_NIDNET(LNET_NID_ANY), LNET_NID_ANY);
582 }
583
584 int lnet_get_rtr_pool_cfg(int cpt, struct lnet_ioctl_pool_cfg *pool_cfg)
585 {
586         struct lnet_rtrbufpool *rbp;
587         int i, rc = -ENOENT, j;
588
589         if (the_lnet.ln_rtrpools == NULL)
590                 return rc;
591
592
593         cfs_percpt_for_each(rbp, i, the_lnet.ln_rtrpools) {
594                 if (i != cpt)
595                         continue;
596
597                 lnet_net_lock(i);
598                 for (j = 0; j < LNET_NRBPOOLS; j++) {
599                         pool_cfg->pl_pools[j].pl_npages = rbp[j].rbp_npages;
600                         pool_cfg->pl_pools[j].pl_nbuffers = rbp[j].rbp_nbuffers;
601                         pool_cfg->pl_pools[j].pl_credits = rbp[j].rbp_credits;
602                         pool_cfg->pl_pools[j].pl_mincredits = rbp[j].rbp_mincredits;
603                 }
604                 lnet_net_unlock(i);
605                 rc = 0;
606                 break;
607         }
608
609         lnet_net_lock(LNET_LOCK_EX);
610         pool_cfg->pl_routing = the_lnet.ln_routing;
611         lnet_net_unlock(LNET_LOCK_EX);
612
613         return rc;
614 }
615
616 int
617 lnet_get_route(int idx, __u32 *net, __u32 *hops,
618                lnet_nid_t *gateway, __u32 *alive, __u32 *priority)
619 {
620         struct list_head *e1;
621         struct list_head *e2;
622         struct lnet_remotenet *rnet;
623         struct lnet_route        *route;
624         int               cpt;
625         int               i;
626         struct list_head *rn_list;
627
628         cpt = lnet_net_lock_current();
629
630         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++) {
631                 rn_list = &the_lnet.ln_remote_nets_hash[i];
632                 list_for_each(e1, rn_list) {
633                         rnet = list_entry(e1, struct lnet_remotenet, lrn_list);
634
635                         list_for_each(e2, &rnet->lrn_routes) {
636                                 route = list_entry(e2, struct lnet_route,
637                                                    lr_list);
638
639                                 if (idx-- == 0) {
640                                         *net      = rnet->lrn_net;
641                                         *hops     = route->lr_hops;
642                                         *priority = route->lr_priority;
643                                         *gateway  = route->lr_gateway->lpni_nid;
644                                         *alive    = lnet_is_route_alive(route);
645                                         lnet_net_unlock(cpt);
646                                         return 0;
647                                 }
648                         }
649                 }
650         }
651
652         lnet_net_unlock(cpt);
653         return -ENOENT;
654 }
655
656 void
657 lnet_swap_pinginfo(struct lnet_ping_buffer *pbuf)
658 {
659         struct lnet_ni_status *stat;
660         int nnis;
661         int i;
662
663         __swab32s(&pbuf->pb_info.pi_magic);
664         __swab32s(&pbuf->pb_info.pi_features);
665         __swab32s(&pbuf->pb_info.pi_pid);
666         __swab32s(&pbuf->pb_info.pi_nnis);
667         nnis = pbuf->pb_info.pi_nnis;
668         if (nnis > pbuf->pb_nnis)
669                 nnis = pbuf->pb_nnis;
670         for (i = 0; i < nnis; i++) {
671                 stat = &pbuf->pb_info.pi_ni[i];
672                 __swab64s(&stat->ns_nid);
673                 __swab32s(&stat->ns_status);
674         }
675         return;
676 }
677
678 /**
679  * parse router-checker pinginfo, record number of down NIs for remote
680  * networks on that router.
681  */
682 static void
683 lnet_parse_rc_info(struct lnet_rc_data *rcd)
684 {
685         struct lnet_ping_buffer *pbuf = rcd->rcd_pingbuffer;
686         struct lnet_peer_ni     *gw   = rcd->rcd_gateway;
687         struct lnet_route               *rte;
688         int                     nnis;
689
690         if (!gw->lpni_alive || !pbuf)
691                 return;
692
693         /*
694          * Protect gw->lpni_ping_feats. This can be set from
695          * lnet_notify_locked with different locks being held
696          */
697         spin_lock(&gw->lpni_lock);
698
699         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
700                 lnet_swap_pinginfo(pbuf);
701
702         /* NB always racing with network! */
703         if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
704                 CDEBUG(D_NET, "%s: Unexpected magic %08x\n",
705                        libcfs_nid2str(gw->lpni_nid), pbuf->pb_info.pi_magic);
706                 gw->lpni_ping_feats = LNET_PING_FEAT_INVAL;
707                 goto out;
708         }
709
710         gw->lpni_ping_feats = pbuf->pb_info.pi_features;
711
712         /* Without NI status info there's nothing more to do. */
713         if ((gw->lpni_ping_feats & LNET_PING_FEAT_NI_STATUS) == 0)
714                 goto out;
715
716         /* Determine the number of NIs for which there is data. */
717         nnis = pbuf->pb_info.pi_nnis;
718         if (pbuf->pb_nnis < nnis) {
719                 if (rcd->rcd_nnis < nnis)
720                         rcd->rcd_nnis = nnis;
721                 nnis = pbuf->pb_nnis;
722         }
723
724         list_for_each_entry(rte, &gw->lpni_routes, lr_gwlist) {
725                 int     down = 0;
726                 int     up = 0;
727                 int     i;
728
729                 /* If routing disabled then the route is down. */
730                 if ((gw->lpni_ping_feats & LNET_PING_FEAT_RTE_DISABLED) != 0) {
731                         rte->lr_downis = 1;
732                         continue;
733                 }
734
735                 for (i = 0; i < nnis; i++) {
736                         struct lnet_ni_status *stat = &pbuf->pb_info.pi_ni[i];
737                         lnet_nid_t       nid = stat->ns_nid;
738
739                         if (nid == LNET_NID_ANY) {
740                                 CDEBUG(D_NET, "%s: unexpected LNET_NID_ANY\n",
741                                        libcfs_nid2str(gw->lpni_nid));
742                                 gw->lpni_ping_feats = LNET_PING_FEAT_INVAL;
743                                 goto out;
744                         }
745
746                         if (LNET_NETTYP(LNET_NIDNET(nid)) == LOLND)
747                                 continue;
748
749                         if (stat->ns_status == LNET_NI_STATUS_DOWN) {
750                                 down++;
751                                 continue;
752                         }
753
754                         if (stat->ns_status == LNET_NI_STATUS_UP) {
755                                 if (LNET_NIDNET(nid) == rte->lr_net) {
756                                         up = 1;
757                                         break;
758                                 }
759                                 continue;
760                         }
761
762                         CDEBUG(D_NET, "%s: Unexpected status 0x%x\n",
763                                libcfs_nid2str(gw->lpni_nid), stat->ns_status);
764                         gw->lpni_ping_feats = LNET_PING_FEAT_INVAL;
765                         goto out;
766                 }
767
768                 if (up) { /* ignore downed NIs if NI for dest network is up */
769                         rte->lr_downis = 0;
770                         continue;
771                 }
772                 /* if @down is zero and this route is single-hop, it means
773                  * we can't find NI for target network */
774                 if (down == 0 && rte->lr_hops == 1)
775                         down = 1;
776
777                 rte->lr_downis = down;
778         }
779 out:
780         spin_unlock(&gw->lpni_lock);
781 }
782
783 static void
784 lnet_router_checker_event(struct lnet_event *event)
785 {
786         struct lnet_rc_data *rcd = event->md.user_ptr;
787         struct lnet_peer_ni *lp;
788
789         LASSERT(rcd != NULL);
790
791         if (event->unlinked) {
792                 LNetInvalidateMDHandle(&rcd->rcd_mdh);
793                 return;
794         }
795
796         LASSERT(event->type == LNET_EVENT_SEND ||
797                 event->type == LNET_EVENT_REPLY);
798
799         lp = rcd->rcd_gateway;
800         LASSERT(lp != NULL);
801
802          /* NB: it's called with holding lnet_res_lock, we have a few
803           * places need to hold both locks at the same time, please take
804           * care of lock ordering */
805         lnet_net_lock(lp->lpni_cpt);
806         if (!lnet_isrouter(lp) || lp->lpni_rcd != rcd) {
807                 /* ignore if no longer a router or rcd is replaced */
808                 goto out;
809         }
810
811         if (event->type == LNET_EVENT_SEND) {
812                 lp->lpni_ping_notsent = 0;
813                 if (event->status == 0)
814                         goto out;
815         }
816
817         /* LNET_EVENT_REPLY */
818         /* A successful REPLY means the router is up.  If _any_ comms
819          * to the router fail I assume it's down (this will happen if
820          * we ping alive routers to try to detect router death before
821          * apps get burned). */
822
823         lnet_notify_locked(lp, 1, !event->status, ktime_get_seconds());
824         /* The router checker will wake up very shortly and do the
825          * actual notification.
826          * XXX If 'lp' stops being a router before then, it will still
827          * have the notification pending!!! */
828
829         if (avoid_asym_router_failure && event->status == 0)
830                 lnet_parse_rc_info(rcd);
831
832  out:
833         lnet_net_unlock(lp->lpni_cpt);
834 }
835
836 static void
837 lnet_wait_known_routerstate(void)
838 {
839         struct lnet_peer_ni *rtr;
840         struct list_head *entry;
841         int all_known;
842
843         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING);
844
845         for (;;) {
846                 int cpt = lnet_net_lock_current();
847
848                 all_known = 1;
849                 list_for_each(entry, &the_lnet.ln_routers) {
850                         rtr = list_entry(entry, struct lnet_peer_ni,
851                                          lpni_rtr_list);
852
853                         spin_lock(&rtr->lpni_lock);
854
855                         if (rtr->lpni_alive_count == 0) {
856                                 all_known = 0;
857                                 spin_unlock(&rtr->lpni_lock);
858                                 break;
859                         }
860                         spin_unlock(&rtr->lpni_lock);
861                 }
862
863                 lnet_net_unlock(cpt);
864
865                 if (all_known)
866                         return;
867
868                 set_current_state(TASK_UNINTERRUPTIBLE);
869                 schedule_timeout(cfs_time_seconds(1));
870         }
871 }
872
873 void
874 lnet_router_ni_update_locked(struct lnet_peer_ni *gw, __u32 net)
875 {
876         struct lnet_route *rte;
877
878         if ((gw->lpni_ping_feats & LNET_PING_FEAT_NI_STATUS) != 0) {
879                 list_for_each_entry(rte, &gw->lpni_routes, lr_gwlist) {
880                         if (rte->lr_net == net) {
881                                 rte->lr_downis = 0;
882                                 break;
883                         }
884                 }
885         }
886 }
887
888 static void
889 lnet_update_ni_status_locked(void)
890 {
891         struct lnet_ni *ni = NULL;
892         time64_t now;
893         time64_t timeout;
894
895         LASSERT(the_lnet.ln_routing);
896
897         timeout = router_ping_timeout +
898                   MAX(live_router_check_interval, dead_router_check_interval);
899
900         now = ktime_get_real_seconds();
901         while ((ni = lnet_get_next_ni_locked(NULL, ni))) {
902                 if (ni->ni_net->net_lnd->lnd_type == LOLND)
903                         continue;
904
905                 if (now < ni->ni_last_alive + timeout)
906                         continue;
907
908                 lnet_ni_lock(ni);
909                 /* re-check with lock */
910                 if (now < ni->ni_last_alive + timeout) {
911                         lnet_ni_unlock(ni);
912                         continue;
913                 }
914
915                 LASSERT(ni->ni_status != NULL);
916
917                 if (ni->ni_status->ns_status != LNET_NI_STATUS_DOWN) {
918                         CDEBUG(D_NET, "NI(%s:%lld) status changed to down\n",
919                                libcfs_nid2str(ni->ni_nid), timeout);
920                         /* NB: so far, this is the only place to set
921                          * NI status to "down" */
922                         ni->ni_status->ns_status = LNET_NI_STATUS_DOWN;
923                 }
924                 lnet_ni_unlock(ni);
925         }
926 }
927
928 static void
929 lnet_destroy_rc_data(struct lnet_rc_data *rcd)
930 {
931         LASSERT(list_empty(&rcd->rcd_list));
932         /* detached from network */
933         LASSERT(LNetMDHandleIsInvalid(rcd->rcd_mdh));
934
935         if (rcd->rcd_gateway != NULL) {
936                 int cpt = rcd->rcd_gateway->lpni_cpt;
937
938                 lnet_net_lock(cpt);
939                 lnet_peer_ni_decref_locked(rcd->rcd_gateway);
940                 lnet_net_unlock(cpt);
941         }
942
943         if (rcd->rcd_pingbuffer != NULL)
944                 lnet_ping_buffer_decref(rcd->rcd_pingbuffer);
945
946         LIBCFS_FREE(rcd, sizeof(*rcd));
947 }
948
949 static struct lnet_rc_data *
950 lnet_update_rc_data_locked(struct lnet_peer_ni *gateway)
951 {
952         struct lnet_handle_md mdh;
953         struct lnet_rc_data *rcd;
954         struct lnet_ping_buffer *pbuf = NULL;
955         int nnis = LNET_INTERFACES_MIN;
956         int rc;
957         int i;
958
959         rcd = gateway->lpni_rcd;
960         if (rcd) {
961                 nnis = rcd->rcd_nnis;
962                 mdh = rcd->rcd_mdh;
963                 LNetInvalidateMDHandle(&rcd->rcd_mdh);
964                 pbuf = rcd->rcd_pingbuffer;
965                 rcd->rcd_pingbuffer = NULL;
966         } else {
967                 LNetInvalidateMDHandle(&mdh);
968         }
969
970         lnet_net_unlock(gateway->lpni_cpt);
971
972         if (rcd) {
973                 LNetMDUnlink(mdh);
974                 lnet_ping_buffer_decref(pbuf);
975         } else {
976                 LIBCFS_ALLOC(rcd, sizeof(*rcd));
977                 if (rcd == NULL)
978                         goto out;
979
980                 LNetInvalidateMDHandle(&rcd->rcd_mdh);
981                 INIT_LIST_HEAD(&rcd->rcd_list);
982                 rcd->rcd_nnis = nnis;
983         }
984
985         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
986         if (pbuf == NULL)
987                 goto out;
988
989         for (i = 0; i < nnis; i++) {
990                 pbuf->pb_info.pi_ni[i].ns_nid = LNET_NID_ANY;
991                 pbuf->pb_info.pi_ni[i].ns_status = LNET_NI_STATUS_INVALID;
992         }
993         rcd->rcd_pingbuffer = pbuf;
994
995         LASSERT(!LNetEQHandleIsInvalid(the_lnet.ln_rc_eqh));
996         rc = LNetMDBind((struct lnet_md){.start     = &pbuf->pb_info,
997                                     .user_ptr  = rcd,
998                                     .length    = LNET_PING_INFO_SIZE(nnis),
999                                     .threshold = LNET_MD_THRESH_INF,
1000                                     .options   = LNET_MD_TRUNCATE,
1001                                     .eq_handle = the_lnet.ln_rc_eqh},
1002                         LNET_UNLINK,
1003                         &rcd->rcd_mdh);
1004         if (rc < 0) {
1005                 CERROR("Can't bind MD: %d\n", rc);
1006                 goto out_ping_buffer_decref;
1007         }
1008         LASSERT(rc == 0);
1009
1010         lnet_net_lock(gateway->lpni_cpt);
1011         /* Check if this is still a router. */
1012         if (!lnet_isrouter(gateway))
1013                 goto out_unlock;
1014         /* Check if someone else installed router data. */
1015         if (gateway->lpni_rcd && gateway->lpni_rcd != rcd)
1016                 goto out_unlock;
1017
1018         /* Install and/or update the router data. */
1019         if (!gateway->lpni_rcd) {
1020                 lnet_peer_ni_addref_locked(gateway);
1021                 rcd->rcd_gateway = gateway;
1022                 gateway->lpni_rcd = rcd;
1023         }
1024         gateway->lpni_ping_notsent = 0;
1025
1026         return rcd;
1027
1028 out_unlock:
1029         lnet_net_unlock(gateway->lpni_cpt);
1030         rc = LNetMDUnlink(mdh);
1031         LASSERT(rc == 0);
1032 out_ping_buffer_decref:
1033         lnet_ping_buffer_decref(pbuf);
1034 out:
1035         if (rcd && rcd != gateway->lpni_rcd)
1036                 lnet_destroy_rc_data(rcd);
1037         lnet_net_lock(gateway->lpni_cpt);
1038         return gateway->lpni_rcd;
1039 }
1040
1041 static int
1042 lnet_router_check_interval(struct lnet_peer_ni *rtr)
1043 {
1044         int secs;
1045
1046         secs = rtr->lpni_alive ? live_router_check_interval :
1047                                dead_router_check_interval;
1048         if (secs < 0)
1049                 secs = 0;
1050
1051         return secs;
1052 }
1053
1054 static void
1055 lnet_ping_router_locked(struct lnet_peer_ni *rtr)
1056 {
1057         struct lnet_rc_data *rcd = NULL;
1058         time64_t now = ktime_get_seconds();
1059         time64_t secs;
1060         struct lnet_ni *ni;
1061
1062         lnet_peer_ni_addref_locked(rtr);
1063
1064         if (rtr->lpni_ping_deadline != 0 && /* ping timed out? */
1065             now >  rtr->lpni_ping_deadline)
1066                 lnet_notify_locked(rtr, 1, 0, now);
1067
1068         /* Run any outstanding notifications */
1069         ni = lnet_get_next_ni_locked(rtr->lpni_net, NULL);
1070         lnet_ni_notify_locked(ni, rtr);
1071
1072         if (!lnet_isrouter(rtr) ||
1073             the_lnet.ln_mt_state != LNET_MT_STATE_RUNNING) {
1074                 /* router table changed or router checker is shutting down */
1075                 lnet_peer_ni_decref_locked(rtr);
1076                 return;
1077         }
1078
1079         rcd = rtr->lpni_rcd;
1080
1081         /*
1082          * The response to the router checker ping could've timed out and
1083          * the mdh might've been invalidated, so we need to update it
1084          * again.
1085          */
1086         if (!rcd || rcd->rcd_nnis > rcd->rcd_pingbuffer->pb_nnis ||
1087             LNetMDHandleIsInvalid(rcd->rcd_mdh))
1088                 rcd = lnet_update_rc_data_locked(rtr);
1089         if (rcd == NULL)
1090                 return;
1091
1092         secs = lnet_router_check_interval(rtr);
1093
1094         CDEBUG(D_NET,
1095                "rtr %s %lld: deadline %lld ping_notsent %d alive %d "
1096                "alive_count %d lpni_ping_timestamp %lld\n",
1097                libcfs_nid2str(rtr->lpni_nid), secs,
1098                rtr->lpni_ping_deadline, rtr->lpni_ping_notsent,
1099                rtr->lpni_alive, rtr->lpni_alive_count, rtr->lpni_ping_timestamp);
1100
1101         if (secs != 0 && !rtr->lpni_ping_notsent &&
1102             now > rtr->lpni_ping_timestamp + secs) {
1103                 int               rc;
1104                 struct lnet_process_id id;
1105                 struct lnet_handle_md mdh;
1106
1107                 id.nid = rtr->lpni_nid;
1108                 id.pid = LNET_PID_LUSTRE;
1109                 CDEBUG(D_NET, "Check: %s\n", libcfs_id2str(id));
1110
1111                 rtr->lpni_ping_notsent   = 1;
1112                 rtr->lpni_ping_timestamp = now;
1113
1114                 mdh = rcd->rcd_mdh;
1115
1116                 if (rtr->lpni_ping_deadline == 0) {
1117                         rtr->lpni_ping_deadline = ktime_get_seconds() +
1118                                                   router_ping_timeout;
1119                 }
1120
1121                 lnet_net_unlock(rtr->lpni_cpt);
1122
1123                 rc = LNetGet(LNET_NID_ANY, mdh, id, LNET_RESERVED_PORTAL,
1124                              LNET_PROTO_PING_MATCHBITS, 0, false);
1125
1126                 lnet_net_lock(rtr->lpni_cpt);
1127                 if (rc != 0)
1128                         rtr->lpni_ping_notsent = 0; /* no event pending */
1129         }
1130
1131         lnet_peer_ni_decref_locked(rtr);
1132         return;
1133 }
1134
1135 int lnet_router_pre_mt_start(void)
1136 {
1137         int rc;
1138
1139         if (check_routers_before_use &&
1140             dead_router_check_interval <= 0) {
1141                 LCONSOLE_ERROR_MSG(0x10a, "'dead_router_check_interval' must be"
1142                                    " set if 'check_routers_before_use' is set"
1143                                    "\n");
1144                 return -EINVAL;
1145         }
1146
1147         rc = LNetEQAlloc(0, lnet_router_checker_event, &the_lnet.ln_rc_eqh);
1148         if (rc != 0) {
1149                 CERROR("Can't allocate EQ(0): %d\n", rc);
1150                 return -ENOMEM;
1151         }
1152
1153         return 0;
1154 }
1155
1156 void lnet_router_post_mt_start(void)
1157 {
1158         if (check_routers_before_use) {
1159                 /* Note that a helpful side-effect of pinging all known routers
1160                  * at startup is that it makes them drop stale connections they
1161                  * may have to a previous instance of me. */
1162                 lnet_wait_known_routerstate();
1163         }
1164 }
1165
1166 void
1167 lnet_router_cleanup(void)
1168 {
1169         int rc;
1170
1171         rc = LNetEQFree(the_lnet.ln_rc_eqh);
1172         LASSERT(rc == 0);
1173         return;
1174 }
1175
1176 void
1177 lnet_prune_rc_data(int wait_unlink)
1178 {
1179         struct lnet_rc_data *rcd;
1180         struct lnet_rc_data *tmp;
1181         struct lnet_peer_ni *lp;
1182         struct list_head head;
1183         int i = 2;
1184
1185         if (likely(the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING &&
1186                    list_empty(&the_lnet.ln_rcd_deathrow) &&
1187                    list_empty(&the_lnet.ln_rcd_zombie)))
1188                 return;
1189
1190         INIT_LIST_HEAD(&head);
1191
1192         lnet_net_lock(LNET_LOCK_EX);
1193
1194         if (the_lnet.ln_mt_state != LNET_MT_STATE_RUNNING) {
1195                 /* router checker is stopping, prune all */
1196                 list_for_each_entry(lp, &the_lnet.ln_routers,
1197                                     lpni_rtr_list) {
1198                         if (lp->lpni_rcd == NULL)
1199                                 continue;
1200
1201                         LASSERT(list_empty(&lp->lpni_rcd->rcd_list));
1202                         list_add(&lp->lpni_rcd->rcd_list,
1203                                  &the_lnet.ln_rcd_deathrow);
1204                         lp->lpni_rcd = NULL;
1205                 }
1206         }
1207
1208         /* unlink all RCDs on deathrow list */
1209         list_splice_init(&the_lnet.ln_rcd_deathrow, &head);
1210
1211         if (!list_empty(&head)) {
1212                 lnet_net_unlock(LNET_LOCK_EX);
1213
1214                 list_for_each_entry(rcd, &head, rcd_list)
1215                         LNetMDUnlink(rcd->rcd_mdh);
1216
1217                 lnet_net_lock(LNET_LOCK_EX);
1218         }
1219
1220         list_splice_init(&head, &the_lnet.ln_rcd_zombie);
1221
1222         /* release all zombie RCDs */
1223         while (!list_empty(&the_lnet.ln_rcd_zombie)) {
1224                 list_for_each_entry_safe(rcd, tmp, &the_lnet.ln_rcd_zombie,
1225                                          rcd_list) {
1226                         if (LNetMDHandleIsInvalid(rcd->rcd_mdh))
1227                                 list_move(&rcd->rcd_list, &head);
1228                 }
1229
1230                 wait_unlink = wait_unlink &&
1231                               !list_empty(&the_lnet.ln_rcd_zombie);
1232
1233                 lnet_net_unlock(LNET_LOCK_EX);
1234
1235                 while (!list_empty(&head)) {
1236                         rcd = list_entry(head.next,
1237                                          struct lnet_rc_data, rcd_list);
1238                         list_del_init(&rcd->rcd_list);
1239                         lnet_destroy_rc_data(rcd);
1240                 }
1241
1242                 if (!wait_unlink)
1243                         return;
1244
1245                 i++;
1246                 CDEBUG(((i & (-i)) == i) ? D_WARNING : D_NET,
1247                        "Waiting for rc buffers to unlink\n");
1248                 set_current_state(TASK_UNINTERRUPTIBLE);
1249                 schedule_timeout(cfs_time_seconds(1) / 4);
1250
1251                 lnet_net_lock(LNET_LOCK_EX);
1252         }
1253
1254         lnet_net_unlock(LNET_LOCK_EX);
1255 }
1256
1257 /*
1258  * This function is called from the monitor thread to check if there are
1259  * any active routers that need to be checked.
1260  */
1261 inline bool
1262 lnet_router_checker_active(void)
1263 {
1264         if (the_lnet.ln_mt_state != LNET_MT_STATE_RUNNING)
1265                 return true;
1266
1267         /* Router Checker thread needs to run when routing is enabled in
1268          * order to call lnet_update_ni_status_locked() */
1269         if (the_lnet.ln_routing)
1270                 return true;
1271
1272         /* if there are routers that need to be cleaned up then do so */
1273         if (!list_empty(&the_lnet.ln_rcd_deathrow) ||
1274             !list_empty(&the_lnet.ln_rcd_zombie))
1275                 return true;
1276
1277         return !list_empty(&the_lnet.ln_routers) &&
1278                 (live_router_check_interval > 0 ||
1279                  dead_router_check_interval > 0);
1280 }
1281
1282 void
1283 lnet_check_routers(void)
1284 {
1285         struct lnet_peer_ni *rtr;
1286         struct list_head *entry;
1287         __u64   version;
1288         int     cpt;
1289         int     cpt2;
1290
1291         cpt = lnet_net_lock_current();
1292 rescan:
1293         version = the_lnet.ln_routers_version;
1294
1295         list_for_each(entry, &the_lnet.ln_routers) {
1296                 rtr = list_entry(entry, struct lnet_peer_ni,
1297                                         lpni_rtr_list);
1298
1299                 cpt2 = rtr->lpni_cpt;
1300                 if (cpt != cpt2) {
1301                         lnet_net_unlock(cpt);
1302                         cpt = cpt2;
1303                         lnet_net_lock(cpt);
1304                         /* the routers list has changed */
1305                         if (version != the_lnet.ln_routers_version)
1306                                 goto rescan;
1307                 }
1308
1309                 lnet_ping_router_locked(rtr);
1310
1311                 /* NB dropped lock */
1312                 if (version != the_lnet.ln_routers_version) {
1313                         /* the routers list has changed */
1314                         goto rescan;
1315                 }
1316         }
1317
1318         if (the_lnet.ln_routing)
1319                 lnet_update_ni_status_locked();
1320
1321         lnet_net_unlock(cpt);
1322
1323         lnet_prune_rc_data(0); /* don't wait for UNLINK */
1324 }
1325
1326 void
1327 lnet_destroy_rtrbuf(struct lnet_rtrbuf *rb, int npages)
1328 {
1329         int sz = offsetof(struct lnet_rtrbuf, rb_kiov[npages]);
1330
1331         while (--npages >= 0)
1332                 __free_page(rb->rb_kiov[npages].kiov_page);
1333
1334         LIBCFS_FREE(rb, sz);
1335 }
1336
1337 static struct lnet_rtrbuf *
1338 lnet_new_rtrbuf(struct lnet_rtrbufpool *rbp, int cpt)
1339 {
1340         int            npages = rbp->rbp_npages;
1341         int            sz = offsetof(struct lnet_rtrbuf, rb_kiov[npages]);
1342         struct page   *page;
1343         struct lnet_rtrbuf *rb;
1344         int            i;
1345
1346         LIBCFS_CPT_ALLOC(rb, lnet_cpt_table(), cpt, sz);
1347         if (rb == NULL)
1348                 return NULL;
1349
1350         rb->rb_pool = rbp;
1351
1352         for (i = 0; i < npages; i++) {
1353                 page = cfs_page_cpt_alloc(lnet_cpt_table(), cpt,
1354                                           GFP_KERNEL | __GFP_ZERO);
1355                 if (page == NULL) {
1356                         while (--i >= 0)
1357                                 __free_page(rb->rb_kiov[i].kiov_page);
1358
1359                         LIBCFS_FREE(rb, sz);
1360                         return NULL;
1361                 }
1362
1363                 rb->rb_kiov[i].kiov_len = PAGE_SIZE;
1364                 rb->rb_kiov[i].kiov_offset = 0;
1365                 rb->rb_kiov[i].kiov_page = page;
1366         }
1367
1368         return rb;
1369 }
1370
1371 static void
1372 lnet_rtrpool_free_bufs(struct lnet_rtrbufpool *rbp, int cpt)
1373 {
1374         int npages = rbp->rbp_npages;
1375         struct lnet_rtrbuf *rb;
1376         struct list_head tmp;
1377
1378         if (rbp->rbp_nbuffers == 0) /* not initialized or already freed */
1379                 return;
1380
1381         INIT_LIST_HEAD(&tmp);
1382
1383         lnet_net_lock(cpt);
1384         list_splice_init(&rbp->rbp_msgs, &tmp);
1385         lnet_drop_routed_msgs_locked(&tmp, cpt);
1386         list_splice_init(&rbp->rbp_bufs, &tmp);
1387         rbp->rbp_req_nbuffers = 0;
1388         rbp->rbp_nbuffers = rbp->rbp_credits = 0;
1389         rbp->rbp_mincredits = 0;
1390         lnet_net_unlock(cpt);
1391
1392         /* Free buffers on the free list. */
1393         while (!list_empty(&tmp)) {
1394                 rb = list_entry(tmp.next, struct lnet_rtrbuf, rb_list);
1395                 list_del(&rb->rb_list);
1396                 lnet_destroy_rtrbuf(rb, npages);
1397         }
1398 }
1399
1400 static int
1401 lnet_rtrpool_adjust_bufs(struct lnet_rtrbufpool *rbp, int nbufs, int cpt)
1402 {
1403         struct list_head rb_list;
1404         struct lnet_rtrbuf *rb;
1405         int             num_rb;
1406         int             num_buffers = 0;
1407         int             old_req_nbufs;
1408         int             npages = rbp->rbp_npages;
1409
1410         lnet_net_lock(cpt);
1411         /* If we are called for less buffers than already in the pool, we
1412          * just lower the req_nbuffers number and excess buffers will be
1413          * thrown away as they are returned to the free list.  Credits
1414          * then get adjusted as well.
1415          * If we already have enough buffers allocated to serve the
1416          * increase requested, then we can treat that the same way as we
1417          * do the decrease. */
1418         num_rb = nbufs - rbp->rbp_nbuffers;
1419         if (nbufs <= rbp->rbp_req_nbuffers || num_rb <= 0) {
1420                 rbp->rbp_req_nbuffers = nbufs;
1421                 lnet_net_unlock(cpt);
1422                 return 0;
1423         }
1424         /* store the older value of rbp_req_nbuffers and then set it to
1425          * the new request to prevent lnet_return_rx_credits_locked() from
1426          * freeing buffers that we need to keep around */
1427         old_req_nbufs = rbp->rbp_req_nbuffers;
1428         rbp->rbp_req_nbuffers = nbufs;
1429         lnet_net_unlock(cpt);
1430
1431         INIT_LIST_HEAD(&rb_list);
1432
1433         /* allocate the buffers on a local list first.  If all buffers are
1434          * allocated successfully then join this list to the rbp buffer
1435          * list.  If not then free all allocated buffers. */
1436         while (num_rb-- > 0) {
1437                 rb = lnet_new_rtrbuf(rbp, cpt);
1438                 if (rb == NULL) {
1439                         CERROR("Failed to allocate %d route bufs of %d pages\n",
1440                                nbufs, npages);
1441
1442                         lnet_net_lock(cpt);
1443                         rbp->rbp_req_nbuffers = old_req_nbufs;
1444                         lnet_net_unlock(cpt);
1445
1446                         goto failed;
1447                 }
1448
1449                 list_add(&rb->rb_list, &rb_list);
1450                 num_buffers++;
1451         }
1452
1453         lnet_net_lock(cpt);
1454
1455         list_splice_tail(&rb_list, &rbp->rbp_bufs);
1456         rbp->rbp_nbuffers += num_buffers;
1457         rbp->rbp_credits += num_buffers;
1458         rbp->rbp_mincredits = rbp->rbp_credits;
1459         /* We need to schedule blocked msg using the newly
1460          * added buffers. */
1461         while (!list_empty(&rbp->rbp_bufs) &&
1462                !list_empty(&rbp->rbp_msgs))
1463                 lnet_schedule_blocked_locked(rbp);
1464
1465         lnet_net_unlock(cpt);
1466
1467         return 0;
1468
1469 failed:
1470         while (!list_empty(&rb_list)) {
1471                 rb = list_entry(rb_list.next, struct lnet_rtrbuf, rb_list);
1472                 list_del(&rb->rb_list);
1473                 lnet_destroy_rtrbuf(rb, npages);
1474         }
1475
1476         return -ENOMEM;
1477 }
1478
1479 static void
1480 lnet_rtrpool_init(struct lnet_rtrbufpool *rbp, int npages)
1481 {
1482         INIT_LIST_HEAD(&rbp->rbp_msgs);
1483         INIT_LIST_HEAD(&rbp->rbp_bufs);
1484
1485         rbp->rbp_npages = npages;
1486         rbp->rbp_credits = 0;
1487         rbp->rbp_mincredits = 0;
1488 }
1489
1490 void
1491 lnet_rtrpools_free(int keep_pools)
1492 {
1493         struct lnet_rtrbufpool *rtrp;
1494         int               i;
1495
1496         if (the_lnet.ln_rtrpools == NULL) /* uninitialized or freed */
1497                 return;
1498
1499         cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1500                 lnet_rtrpool_free_bufs(&rtrp[LNET_TINY_BUF_IDX], i);
1501                 lnet_rtrpool_free_bufs(&rtrp[LNET_SMALL_BUF_IDX], i);
1502                 lnet_rtrpool_free_bufs(&rtrp[LNET_LARGE_BUF_IDX], i);
1503         }
1504
1505         if (!keep_pools) {
1506                 cfs_percpt_free(the_lnet.ln_rtrpools);
1507                 the_lnet.ln_rtrpools = NULL;
1508         }
1509 }
1510
1511 static int
1512 lnet_nrb_tiny_calculate(void)
1513 {
1514         int     nrbs = LNET_NRB_TINY;
1515
1516         if (tiny_router_buffers < 0) {
1517                 LCONSOLE_ERROR_MSG(0x10c,
1518                                    "tiny_router_buffers=%d invalid when "
1519                                    "routing enabled\n", tiny_router_buffers);
1520                 return -EINVAL;
1521         }
1522
1523         if (tiny_router_buffers > 0)
1524                 nrbs = tiny_router_buffers;
1525
1526         nrbs /= LNET_CPT_NUMBER;
1527         return max(nrbs, LNET_NRB_TINY_MIN);
1528 }
1529
1530 static int
1531 lnet_nrb_small_calculate(void)
1532 {
1533         int     nrbs = LNET_NRB_SMALL;
1534
1535         if (small_router_buffers < 0) {
1536                 LCONSOLE_ERROR_MSG(0x10c,
1537                                    "small_router_buffers=%d invalid when "
1538                                    "routing enabled\n", small_router_buffers);
1539                 return -EINVAL;
1540         }
1541
1542         if (small_router_buffers > 0)
1543                 nrbs = small_router_buffers;
1544
1545         nrbs /= LNET_CPT_NUMBER;
1546         return max(nrbs, LNET_NRB_SMALL_MIN);
1547 }
1548
1549 static int
1550 lnet_nrb_large_calculate(void)
1551 {
1552         int     nrbs = LNET_NRB_LARGE;
1553
1554         if (large_router_buffers < 0) {
1555                 LCONSOLE_ERROR_MSG(0x10c,
1556                                    "large_router_buffers=%d invalid when "
1557                                    "routing enabled\n", large_router_buffers);
1558                 return -EINVAL;
1559         }
1560
1561         if (large_router_buffers > 0)
1562                 nrbs = large_router_buffers;
1563
1564         nrbs /= LNET_CPT_NUMBER;
1565         return max(nrbs, LNET_NRB_LARGE_MIN);
1566 }
1567
1568 int
1569 lnet_rtrpools_alloc(int im_a_router)
1570 {
1571         struct lnet_rtrbufpool *rtrp;
1572         int     nrb_tiny;
1573         int     nrb_small;
1574         int     nrb_large;
1575         int     rc;
1576         int     i;
1577
1578         if (!strcmp(forwarding, "")) {
1579                 /* not set either way */
1580                 if (!im_a_router)
1581                         return 0;
1582         } else if (!strcmp(forwarding, "disabled")) {
1583                 /* explicitly disabled */
1584                 return 0;
1585         } else if (!strcmp(forwarding, "enabled")) {
1586                 /* explicitly enabled */
1587         } else {
1588                 LCONSOLE_ERROR_MSG(0x10b, "'forwarding' not set to either "
1589                                    "'enabled' or 'disabled'\n");
1590                 return -EINVAL;
1591         }
1592
1593         nrb_tiny = lnet_nrb_tiny_calculate();
1594         if (nrb_tiny < 0)
1595                 return -EINVAL;
1596
1597         nrb_small = lnet_nrb_small_calculate();
1598         if (nrb_small < 0)
1599                 return -EINVAL;
1600
1601         nrb_large = lnet_nrb_large_calculate();
1602         if (nrb_large < 0)
1603                 return -EINVAL;
1604
1605         the_lnet.ln_rtrpools = cfs_percpt_alloc(lnet_cpt_table(),
1606                                                 LNET_NRBPOOLS *
1607                                                 sizeof(struct lnet_rtrbufpool));
1608         if (the_lnet.ln_rtrpools == NULL) {
1609                 LCONSOLE_ERROR_MSG(0x10c,
1610                                    "Failed to initialize router buffe pool\n");
1611                 return -ENOMEM;
1612         }
1613
1614         cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1615                 lnet_rtrpool_init(&rtrp[LNET_TINY_BUF_IDX], 0);
1616                 rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_TINY_BUF_IDX],
1617                                               nrb_tiny, i);
1618                 if (rc != 0)
1619                         goto failed;
1620
1621                 lnet_rtrpool_init(&rtrp[LNET_SMALL_BUF_IDX],
1622                                   LNET_NRB_SMALL_PAGES);
1623                 rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_SMALL_BUF_IDX],
1624                                               nrb_small, i);
1625                 if (rc != 0)
1626                         goto failed;
1627
1628                 lnet_rtrpool_init(&rtrp[LNET_LARGE_BUF_IDX],
1629                                   LNET_NRB_LARGE_PAGES);
1630                 rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_LARGE_BUF_IDX],
1631                                               nrb_large, i);
1632                 if (rc != 0)
1633                         goto failed;
1634         }
1635
1636         lnet_net_lock(LNET_LOCK_EX);
1637         the_lnet.ln_routing = 1;
1638         lnet_net_unlock(LNET_LOCK_EX);
1639         return 0;
1640
1641  failed:
1642         lnet_rtrpools_free(0);
1643         return rc;
1644 }
1645
1646 static int
1647 lnet_rtrpools_adjust_helper(int tiny, int small, int large)
1648 {
1649         int nrb = 0;
1650         int rc = 0;
1651         int i;
1652         struct lnet_rtrbufpool *rtrp;
1653
1654         /* If the provided values for each buffer pool are different than the
1655          * configured values, we need to take action. */
1656         if (tiny >= 0) {
1657                 tiny_router_buffers = tiny;
1658                 nrb = lnet_nrb_tiny_calculate();
1659                 cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1660                         rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_TINY_BUF_IDX],
1661                                                       nrb, i);
1662                         if (rc != 0)
1663                                 return rc;
1664                 }
1665         }
1666         if (small >= 0) {
1667                 small_router_buffers = small;
1668                 nrb = lnet_nrb_small_calculate();
1669                 cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1670                         rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_SMALL_BUF_IDX],
1671                                                       nrb, i);
1672                         if (rc != 0)
1673                                 return rc;
1674                 }
1675         }
1676         if (large >= 0) {
1677                 large_router_buffers = large;
1678                 nrb = lnet_nrb_large_calculate();
1679                 cfs_percpt_for_each(rtrp, i, the_lnet.ln_rtrpools) {
1680                         rc = lnet_rtrpool_adjust_bufs(&rtrp[LNET_LARGE_BUF_IDX],
1681                                                       nrb, i);
1682                         if (rc != 0)
1683                                 return rc;
1684                 }
1685         }
1686
1687         return 0;
1688 }
1689
1690 int
1691 lnet_rtrpools_adjust(int tiny, int small, int large)
1692 {
1693         /* this function doesn't revert the changes if adding new buffers
1694          * failed.  It's up to the user space caller to revert the
1695          * changes. */
1696
1697         if (!the_lnet.ln_routing)
1698                 return 0;
1699
1700         return lnet_rtrpools_adjust_helper(tiny, small, large);
1701 }
1702
1703 int
1704 lnet_rtrpools_enable(void)
1705 {
1706         int rc = 0;
1707
1708         if (the_lnet.ln_routing)
1709                 return 0;
1710
1711         if (the_lnet.ln_rtrpools == NULL)
1712                 /* If routing is turned off, and we have never
1713                  * initialized the pools before, just call the
1714                  * standard buffer pool allocation routine as
1715                  * if we are just configuring this for the first
1716                  * time. */
1717                 rc = lnet_rtrpools_alloc(1);
1718         else
1719                 rc = lnet_rtrpools_adjust_helper(0, 0, 0);
1720         if (rc != 0)
1721                 return rc;
1722
1723         lnet_net_lock(LNET_LOCK_EX);
1724         the_lnet.ln_routing = 1;
1725
1726         the_lnet.ln_ping_target->pb_info.pi_features &=
1727                 ~LNET_PING_FEAT_RTE_DISABLED;
1728         lnet_net_unlock(LNET_LOCK_EX);
1729
1730         return rc;
1731 }
1732
1733 void
1734 lnet_rtrpools_disable(void)
1735 {
1736         if (!the_lnet.ln_routing)
1737                 return;
1738
1739         lnet_net_lock(LNET_LOCK_EX);
1740         the_lnet.ln_routing = 0;
1741         the_lnet.ln_ping_target->pb_info.pi_features |=
1742                 LNET_PING_FEAT_RTE_DISABLED;
1743
1744         tiny_router_buffers = 0;
1745         small_router_buffers = 0;
1746         large_router_buffers = 0;
1747         lnet_net_unlock(LNET_LOCK_EX);
1748         lnet_rtrpools_free(1);
1749 }
1750
1751 int
1752 lnet_notify(struct lnet_ni *ni, lnet_nid_t nid, int alive, time64_t when)
1753 {
1754         struct lnet_peer_ni *lp = NULL;
1755         time64_t now = ktime_get_seconds();
1756         int cpt = lnet_cpt_of_nid(nid, ni);
1757
1758         LASSERT (!in_interrupt ());
1759
1760         CDEBUG (D_NET, "%s notifying %s: %s\n",
1761                 (ni == NULL) ? "userspace" : libcfs_nid2str(ni->ni_nid),
1762                 libcfs_nid2str(nid),
1763                 alive ? "up" : "down");
1764
1765         if (ni != NULL &&
1766             LNET_NIDNET(ni->ni_nid) != LNET_NIDNET(nid)) {
1767                 CWARN("Ignoring notification of %s %s by %s (different net)\n",
1768                       libcfs_nid2str(nid), alive ? "birth" : "death",
1769                       libcfs_nid2str(ni->ni_nid));
1770                 return -EINVAL;
1771         }
1772
1773         /* can't do predictions... */
1774         if (when > now) {
1775                 CWARN("Ignoring prediction from %s of %s %s "
1776                       "%lld seconds in the future\n",
1777                       (ni == NULL) ? "userspace" : libcfs_nid2str(ni->ni_nid),
1778                       libcfs_nid2str(nid), alive ? "up" : "down", when - now);
1779                 return -EINVAL;
1780         }
1781
1782         if (ni != NULL && !alive &&             /* LND telling me she's down */
1783             !auto_down) {                       /* auto-down disabled */
1784                 CDEBUG(D_NET, "Auto-down disabled\n");
1785                 return 0;
1786         }
1787
1788         lnet_net_lock(cpt);
1789
1790         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
1791                 lnet_net_unlock(cpt);
1792                 return -ESHUTDOWN;
1793         }
1794
1795         lp = lnet_find_peer_ni_locked(nid);
1796         if (lp == NULL) {
1797                 /* nid not found */
1798                 lnet_net_unlock(cpt);
1799                 CDEBUG(D_NET, "%s not found\n", libcfs_nid2str(nid));
1800                 return 0;
1801         }
1802
1803         /*
1804          * It is possible for this function to be called for the same peer
1805          * but with different NIs. We want to synchronize the notification
1806          * between the different calls. So we will use the lpni_cpt to
1807          * grab the net lock.
1808          */
1809         if (lp->lpni_cpt != cpt) {
1810                 lnet_net_unlock(cpt);
1811                 cpt = lp->lpni_cpt;
1812                 lnet_net_lock(cpt);
1813         }
1814
1815         /* We can't fully trust LND on reporting exact peer last_alive
1816          * if he notifies us about dead peer. For example ksocklnd can
1817          * call us with when == _time_when_the_node_was_booted_ if
1818          * no connections were successfully established */
1819         if (ni != NULL && !alive && when < lp->lpni_last_alive)
1820                 when = lp->lpni_last_alive;
1821
1822         lnet_notify_locked(lp, ni == NULL, alive, when);
1823
1824         if (ni != NULL)
1825                 lnet_ni_notify_locked(ni, lp);
1826
1827         lnet_peer_ni_decref_locked(lp);
1828
1829         lnet_net_unlock(cpt);
1830         return 0;
1831 }
1832 EXPORT_SYMBOL(lnet_notify);