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