The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netpfil/pf/if_pfsync.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * SPDX-License-Identifier: (BSD-2-Clause-FreeBSD AND ISC)
    3  *
    4  * Copyright (c) 2002 Michael Shalayeff
    5  * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
    6  * All rights reserved.
    7  *
    8  * Redistribution and use in source and binary forms, with or without
    9  * modification, are permitted provided that the following conditions
   10  * are met:
   11  * 1. Redistributions of source code must retain the above copyright
   12  *    notice, this list of conditions and the following disclaimer.
   13  * 2. Redistributions in binary form must reproduce the above copyright
   14  *    notice, this list of conditions and the following disclaimer in the
   15  *    documentation and/or other materials provided with the distribution.
   16  *
   17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   20  * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,
   21  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   23  * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
   25  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
   26  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   27  * THE POSSIBILITY OF SUCH DAMAGE.
   28  */
   29 
   30 /*-
   31  * Copyright (c) 2009 David Gwynne <dlg@openbsd.org>
   32  *
   33  * Permission to use, copy, modify, and distribute this software for any
   34  * purpose with or without fee is hereby granted, provided that the above
   35  * copyright notice and this permission notice appear in all copies.
   36  *
   37  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   38  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   39  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   40  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   41  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   42  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   43  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   44  */
   45 
   46 /*
   47  * $OpenBSD: if_pfsync.c,v 1.110 2009/02/24 05:39:19 dlg Exp $
   48  *
   49  * Revisions picked from OpenBSD after revision 1.110 import:
   50  * 1.119 - don't m_copydata() beyond the len of mbuf in pfsync_input()
   51  * 1.118, 1.124, 1.148, 1.149, 1.151, 1.171 - fixes to bulk updates
   52  * 1.120, 1.175 - use monotonic time_uptime
   53  * 1.122 - reduce number of updates for non-TCP sessions
   54  * 1.125, 1.127 - rewrite merge or stale processing
   55  * 1.128 - cleanups
   56  * 1.146 - bzero() mbuf before sparsely filling it with data
   57  * 1.170 - SIOCSIFMTU checks
   58  * 1.126, 1.142 - deferred packets processing
   59  * 1.173 - correct expire time processing
   60  */
   61 
   62 #include <sys/cdefs.h>
   63 __FBSDID("$FreeBSD$");
   64 
   65 #include "opt_inet.h"
   66 #include "opt_inet6.h"
   67 #include "opt_pf.h"
   68 
   69 #include <sys/param.h>
   70 #include <sys/bus.h>
   71 #include <sys/endian.h>
   72 #include <sys/interrupt.h>
   73 #include <sys/kernel.h>
   74 #include <sys/lock.h>
   75 #include <sys/mbuf.h>
   76 #include <sys/module.h>
   77 #include <sys/mutex.h>
   78 #include <sys/priv.h>
   79 #include <sys/protosw.h>
   80 #include <sys/smp.h>
   81 #include <sys/socket.h>
   82 #include <sys/sockio.h>
   83 #include <sys/sysctl.h>
   84 #include <sys/syslog.h>
   85 
   86 #include <net/bpf.h>
   87 #include <net/if.h>
   88 #include <net/if_var.h>
   89 #include <net/if_clone.h>
   90 #include <net/if_types.h>
   91 #include <net/vnet.h>
   92 #include <net/pfvar.h>
   93 #include <net/if_pfsync.h>
   94 
   95 #include <netinet/if_ether.h>
   96 #include <netinet/in.h>
   97 #include <netinet/in_var.h>
   98 #include <netinet/ip.h>
   99 #include <netinet/ip_carp.h>
  100 #include <netinet/ip_var.h>
  101 #include <netinet/tcp.h>
  102 #include <netinet/tcp_fsm.h>
  103 #include <netinet/tcp_seq.h>
  104 
  105 #define PFSYNC_MINPKT ( \
  106         sizeof(struct ip) + \
  107         sizeof(struct pfsync_header) + \
  108         sizeof(struct pfsync_subheader) )
  109 
  110 struct pfsync_bucket;
  111 
  112 struct pfsync_pkt {
  113         struct ip *ip;
  114         struct in_addr src;
  115         u_int8_t flags;
  116 };
  117 
  118 static int      pfsync_upd_tcp(struct pf_kstate *, struct pfsync_state_peer *,
  119                     struct pfsync_state_peer *);
  120 static int      pfsync_in_clr(struct pfsync_pkt *, struct mbuf *, int, int);
  121 static int      pfsync_in_ins(struct pfsync_pkt *, struct mbuf *, int, int);
  122 static int      pfsync_in_iack(struct pfsync_pkt *, struct mbuf *, int, int);
  123 static int      pfsync_in_upd(struct pfsync_pkt *, struct mbuf *, int, int);
  124 static int      pfsync_in_upd_c(struct pfsync_pkt *, struct mbuf *, int, int);
  125 static int      pfsync_in_ureq(struct pfsync_pkt *, struct mbuf *, int, int);
  126 static int      pfsync_in_del(struct pfsync_pkt *, struct mbuf *, int, int);
  127 static int      pfsync_in_del_c(struct pfsync_pkt *, struct mbuf *, int, int);
  128 static int      pfsync_in_bus(struct pfsync_pkt *, struct mbuf *, int, int);
  129 static int      pfsync_in_tdb(struct pfsync_pkt *, struct mbuf *, int, int);
  130 static int      pfsync_in_eof(struct pfsync_pkt *, struct mbuf *, int, int);
  131 static int      pfsync_in_error(struct pfsync_pkt *, struct mbuf *, int, int);
  132 
  133 static int (*pfsync_acts[])(struct pfsync_pkt *, struct mbuf *, int, int) = {
  134         pfsync_in_clr,                  /* PFSYNC_ACT_CLR */
  135         pfsync_in_ins,                  /* PFSYNC_ACT_INS */
  136         pfsync_in_iack,                 /* PFSYNC_ACT_INS_ACK */
  137         pfsync_in_upd,                  /* PFSYNC_ACT_UPD */
  138         pfsync_in_upd_c,                /* PFSYNC_ACT_UPD_C */
  139         pfsync_in_ureq,                 /* PFSYNC_ACT_UPD_REQ */
  140         pfsync_in_del,                  /* PFSYNC_ACT_DEL */
  141         pfsync_in_del_c,                /* PFSYNC_ACT_DEL_C */
  142         pfsync_in_error,                /* PFSYNC_ACT_INS_F */
  143         pfsync_in_error,                /* PFSYNC_ACT_DEL_F */
  144         pfsync_in_bus,                  /* PFSYNC_ACT_BUS */
  145         pfsync_in_tdb,                  /* PFSYNC_ACT_TDB */
  146         pfsync_in_eof                   /* PFSYNC_ACT_EOF */
  147 };
  148 
  149 struct pfsync_q {
  150         void            (*write)(struct pf_kstate *, void *);
  151         size_t          len;
  152         u_int8_t        action;
  153 };
  154 
  155 /* we have one of these for every PFSYNC_S_ */
  156 static void     pfsync_out_state(struct pf_kstate *, void *);
  157 static void     pfsync_out_iack(struct pf_kstate *, void *);
  158 static void     pfsync_out_upd_c(struct pf_kstate *, void *);
  159 static void     pfsync_out_del(struct pf_kstate *, void *);
  160 
  161 static struct pfsync_q pfsync_qs[] = {
  162         { pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_INS },
  163         { pfsync_out_iack,  sizeof(struct pfsync_ins_ack), PFSYNC_ACT_INS_ACK },
  164         { pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_UPD },
  165         { pfsync_out_upd_c, sizeof(struct pfsync_upd_c),   PFSYNC_ACT_UPD_C },
  166         { pfsync_out_del,   sizeof(struct pfsync_del_c),   PFSYNC_ACT_DEL_C }
  167 };
  168 
  169 static void     pfsync_q_ins(struct pf_kstate *, int, bool);
  170 static void     pfsync_q_del(struct pf_kstate *, bool, struct pfsync_bucket *);
  171 
  172 static void     pfsync_update_state(struct pf_kstate *);
  173 
  174 struct pfsync_upd_req_item {
  175         TAILQ_ENTRY(pfsync_upd_req_item)        ur_entry;
  176         struct pfsync_upd_req                   ur_msg;
  177 };
  178 
  179 struct pfsync_deferral {
  180         struct pfsync_softc             *pd_sc;
  181         TAILQ_ENTRY(pfsync_deferral)    pd_entry;
  182         u_int                           pd_refs;
  183         struct callout                  pd_tmo;
  184 
  185         struct pf_kstate                *pd_st;
  186         struct mbuf                     *pd_m;
  187 };
  188 
  189 struct pfsync_sofct;
  190 
  191 struct pfsync_bucket
  192 {
  193         int                     b_id;
  194         struct pfsync_softc     *b_sc;
  195         struct mtx              b_mtx;
  196         struct callout          b_tmo;
  197         int                     b_flags;
  198 #define PFSYNCF_BUCKET_PUSH     0x00000001
  199 
  200         size_t                  b_len;
  201         TAILQ_HEAD(, pf_kstate)                 b_qs[PFSYNC_S_COUNT];
  202         TAILQ_HEAD(, pfsync_upd_req_item)       b_upd_req_list;
  203         TAILQ_HEAD(, pfsync_deferral)           b_deferrals;
  204         u_int                   b_deferred;
  205         void                    *b_plus;
  206         size_t                  b_pluslen;
  207 
  208         struct  ifaltq b_snd;
  209 };
  210 
  211 struct pfsync_softc {
  212         /* Configuration */
  213         struct ifnet            *sc_ifp;
  214         struct ifnet            *sc_sync_if;
  215         struct ip_moptions      sc_imo;
  216         struct in_addr          sc_sync_peer;
  217         uint32_t                sc_flags;
  218         uint8_t                 sc_maxupdates;
  219         struct ip               sc_template;
  220         struct mtx              sc_mtx;
  221 
  222         /* Queued data */
  223         struct pfsync_bucket    *sc_buckets;
  224 
  225         /* Bulk update info */
  226         struct mtx              sc_bulk_mtx;
  227         uint32_t                sc_ureq_sent;
  228         int                     sc_bulk_tries;
  229         uint32_t                sc_ureq_received;
  230         int                     sc_bulk_hashid;
  231         uint64_t                sc_bulk_stateid;
  232         uint32_t                sc_bulk_creatorid;
  233         struct callout          sc_bulk_tmo;
  234         struct callout          sc_bulkfail_tmo;
  235 };
  236 
  237 #define PFSYNC_LOCK(sc)         mtx_lock(&(sc)->sc_mtx)
  238 #define PFSYNC_UNLOCK(sc)       mtx_unlock(&(sc)->sc_mtx)
  239 #define PFSYNC_LOCK_ASSERT(sc)  mtx_assert(&(sc)->sc_mtx, MA_OWNED)
  240 
  241 #define PFSYNC_BUCKET_LOCK(b)           mtx_lock(&(b)->b_mtx)
  242 #define PFSYNC_BUCKET_UNLOCK(b)         mtx_unlock(&(b)->b_mtx)
  243 #define PFSYNC_BUCKET_LOCK_ASSERT(b)    mtx_assert(&(b)->b_mtx, MA_OWNED)
  244 
  245 #define PFSYNC_BLOCK(sc)        mtx_lock(&(sc)->sc_bulk_mtx)
  246 #define PFSYNC_BUNLOCK(sc)      mtx_unlock(&(sc)->sc_bulk_mtx)
  247 #define PFSYNC_BLOCK_ASSERT(sc) mtx_assert(&(sc)->sc_bulk_mtx, MA_OWNED)
  248 
  249 static const char pfsyncname[] = "pfsync";
  250 static MALLOC_DEFINE(M_PFSYNC, pfsyncname, "pfsync(4) data");
  251 VNET_DEFINE_STATIC(struct pfsync_softc  *, pfsyncif) = NULL;
  252 #define V_pfsyncif              VNET(pfsyncif)
  253 VNET_DEFINE_STATIC(void *, pfsync_swi_cookie) = NULL;
  254 #define V_pfsync_swi_cookie     VNET(pfsync_swi_cookie)
  255 VNET_DEFINE_STATIC(struct intr_event *, pfsync_swi_ie);
  256 #define V_pfsync_swi_ie         VNET(pfsync_swi_ie)
  257 VNET_DEFINE_STATIC(struct pfsyncstats, pfsyncstats);
  258 #define V_pfsyncstats           VNET(pfsyncstats)
  259 VNET_DEFINE_STATIC(int, pfsync_carp_adj) = CARP_MAXSKEW;
  260 #define V_pfsync_carp_adj       VNET(pfsync_carp_adj)
  261 
  262 static void     pfsync_timeout(void *);
  263 static void     pfsync_push(struct pfsync_bucket *);
  264 static void     pfsync_push_all(struct pfsync_softc *);
  265 static void     pfsyncintr(void *);
  266 static int      pfsync_multicast_setup(struct pfsync_softc *, struct ifnet *,
  267                     struct in_mfilter *imf);
  268 static void     pfsync_multicast_cleanup(struct pfsync_softc *);
  269 static void     pfsync_pointers_init(void);
  270 static void     pfsync_pointers_uninit(void);
  271 static int      pfsync_init(void);
  272 static void     pfsync_uninit(void);
  273 
  274 static unsigned long pfsync_buckets;
  275 
  276 SYSCTL_NODE(_net, OID_AUTO, pfsync, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
  277     "PFSYNC");
  278 SYSCTL_STRUCT(_net_pfsync, OID_AUTO, stats, CTLFLAG_VNET | CTLFLAG_RW,
  279     &VNET_NAME(pfsyncstats), pfsyncstats,
  280     "PFSYNC statistics (struct pfsyncstats, net/if_pfsync.h)");
  281 SYSCTL_INT(_net_pfsync, OID_AUTO, carp_demotion_factor, CTLFLAG_VNET | CTLFLAG_RW,
  282     &VNET_NAME(pfsync_carp_adj), 0, "pfsync's CARP demotion factor adjustment");
  283 SYSCTL_ULONG(_net_pfsync, OID_AUTO, pfsync_buckets, CTLFLAG_RDTUN,
  284     &pfsync_buckets, 0, "Number of pfsync hash buckets");
  285 
  286 static int      pfsync_clone_create(struct if_clone *, int, caddr_t);
  287 static void     pfsync_clone_destroy(struct ifnet *);
  288 static int      pfsync_alloc_scrub_memory(struct pfsync_state_peer *,
  289                     struct pf_state_peer *);
  290 static int      pfsyncoutput(struct ifnet *, struct mbuf *,
  291                     const struct sockaddr *, struct route *);
  292 static int      pfsyncioctl(struct ifnet *, u_long, caddr_t);
  293 
  294 static int      pfsync_defer(struct pf_kstate *, struct mbuf *);
  295 static void     pfsync_undefer(struct pfsync_deferral *, int);
  296 static void     pfsync_undefer_state(struct pf_kstate *, int);
  297 static void     pfsync_defer_tmo(void *);
  298 
  299 static void     pfsync_request_update(u_int32_t, u_int64_t);
  300 static bool     pfsync_update_state_req(struct pf_kstate *);
  301 
  302 static void     pfsync_drop(struct pfsync_softc *);
  303 static void     pfsync_sendout(int, int);
  304 static void     pfsync_send_plus(void *, size_t);
  305 
  306 static void     pfsync_bulk_start(void);
  307 static void     pfsync_bulk_status(u_int8_t);
  308 static void     pfsync_bulk_update(void *);
  309 static void     pfsync_bulk_fail(void *);
  310 
  311 static void     pfsync_detach_ifnet(struct ifnet *);
  312 #ifdef IPSEC
  313 static void     pfsync_update_net_tdb(struct pfsync_tdb *);
  314 #endif
  315 static struct pfsync_bucket     *pfsync_get_bucket(struct pfsync_softc *,
  316                     struct pf_kstate *);
  317 
  318 #define PFSYNC_MAX_BULKTRIES    12
  319 #define PFSYNC_DEFER_TIMEOUT    ((20 * hz) / 1000)
  320 
  321 VNET_DEFINE(struct if_clone *, pfsync_cloner);
  322 #define V_pfsync_cloner VNET(pfsync_cloner)
  323 
  324 static int
  325 pfsync_clone_create(struct if_clone *ifc, int unit, caddr_t param)
  326 {
  327         struct pfsync_softc *sc;
  328         struct ifnet *ifp;
  329         struct pfsync_bucket *b;
  330         int c, q;
  331 
  332         if (unit != 0)
  333                 return (EINVAL);
  334 
  335         if (! pfsync_buckets)
  336                 pfsync_buckets = mp_ncpus * 2;
  337 
  338         sc = malloc(sizeof(struct pfsync_softc), M_PFSYNC, M_WAITOK | M_ZERO);
  339         sc->sc_flags |= PFSYNCF_OK;
  340         sc->sc_maxupdates = 128;
  341 
  342         ifp = sc->sc_ifp = if_alloc(IFT_PFSYNC);
  343         if (ifp == NULL) {
  344                 free(sc, M_PFSYNC);
  345                 return (ENOSPC);
  346         }
  347         if_initname(ifp, pfsyncname, unit);
  348         ifp->if_softc = sc;
  349         ifp->if_ioctl = pfsyncioctl;
  350         ifp->if_output = pfsyncoutput;
  351         ifp->if_type = IFT_PFSYNC;
  352         ifp->if_hdrlen = sizeof(struct pfsync_header);
  353         ifp->if_mtu = ETHERMTU;
  354         mtx_init(&sc->sc_mtx, pfsyncname, NULL, MTX_DEF);
  355         mtx_init(&sc->sc_bulk_mtx, "pfsync bulk", NULL, MTX_DEF);
  356         callout_init_mtx(&sc->sc_bulk_tmo, &sc->sc_bulk_mtx, 0);
  357         callout_init_mtx(&sc->sc_bulkfail_tmo, &sc->sc_bulk_mtx, 0);
  358 
  359         if_attach(ifp);
  360 
  361         bpfattach(ifp, DLT_PFSYNC, PFSYNC_HDRLEN);
  362 
  363         sc->sc_buckets = mallocarray(pfsync_buckets, sizeof(*sc->sc_buckets),
  364             M_PFSYNC, M_ZERO | M_WAITOK);
  365         for (c = 0; c < pfsync_buckets; c++) {
  366                 b = &sc->sc_buckets[c];
  367                 mtx_init(&b->b_mtx, "pfsync bucket", NULL, MTX_DEF);
  368 
  369                 b->b_id = c;
  370                 b->b_sc = sc;
  371                 b->b_len = PFSYNC_MINPKT;
  372 
  373                 for (q = 0; q < PFSYNC_S_COUNT; q++)
  374                         TAILQ_INIT(&b->b_qs[q]);
  375 
  376                 TAILQ_INIT(&b->b_upd_req_list);
  377                 TAILQ_INIT(&b->b_deferrals);
  378 
  379                 callout_init(&b->b_tmo, 1);
  380 
  381                 b->b_snd.ifq_maxlen = ifqmaxlen;
  382         }
  383 
  384         V_pfsyncif = sc;
  385 
  386         return (0);
  387 }
  388 
  389 static void
  390 pfsync_clone_destroy(struct ifnet *ifp)
  391 {
  392         struct pfsync_softc *sc = ifp->if_softc;
  393         struct pfsync_bucket *b;
  394         int c;
  395 
  396         for (c = 0; c < pfsync_buckets; c++) {
  397                 b = &sc->sc_buckets[c];
  398                 /*
  399                  * At this stage, everything should have already been
  400                  * cleared by pfsync_uninit(), and we have only to
  401                  * drain callouts.
  402                  */
  403                 while (b->b_deferred > 0) {
  404                         struct pfsync_deferral *pd =
  405                             TAILQ_FIRST(&b->b_deferrals);
  406 
  407                         TAILQ_REMOVE(&b->b_deferrals, pd, pd_entry);
  408                         b->b_deferred--;
  409                         if (callout_stop(&pd->pd_tmo) > 0) {
  410                                 pf_release_state(pd->pd_st);
  411                                 m_freem(pd->pd_m);
  412                                 free(pd, M_PFSYNC);
  413                         } else {
  414                                 pd->pd_refs++;
  415                                 callout_drain(&pd->pd_tmo);
  416                                 free(pd, M_PFSYNC);
  417                         }
  418                 }
  419 
  420                 callout_drain(&b->b_tmo);
  421         }
  422 
  423         callout_drain(&sc->sc_bulkfail_tmo);
  424         callout_drain(&sc->sc_bulk_tmo);
  425 
  426         if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
  427                 (*carp_demote_adj_p)(-V_pfsync_carp_adj, "pfsync destroy");
  428         bpfdetach(ifp);
  429         if_detach(ifp);
  430 
  431         pfsync_drop(sc);
  432 
  433         if_free(ifp);
  434         pfsync_multicast_cleanup(sc);
  435         mtx_destroy(&sc->sc_mtx);
  436         mtx_destroy(&sc->sc_bulk_mtx);
  437 
  438         free(sc->sc_buckets, M_PFSYNC);
  439         free(sc, M_PFSYNC);
  440 
  441         V_pfsyncif = NULL;
  442 }
  443 
  444 static int
  445 pfsync_alloc_scrub_memory(struct pfsync_state_peer *s,
  446     struct pf_state_peer *d)
  447 {
  448         if (s->scrub.scrub_flag && d->scrub == NULL) {
  449                 d->scrub = uma_zalloc(V_pf_state_scrub_z, M_NOWAIT | M_ZERO);
  450                 if (d->scrub == NULL)
  451                         return (ENOMEM);
  452         }
  453 
  454         return (0);
  455 }
  456 
  457 static int
  458 pfsync_state_import(struct pfsync_state *sp, u_int8_t flags)
  459 {
  460         struct pfsync_softc *sc = V_pfsyncif;
  461 #ifndef __NO_STRICT_ALIGNMENT
  462         struct pfsync_state_key key[2];
  463 #endif
  464         struct pfsync_state_key *kw, *ks;
  465         struct pf_kstate        *st = NULL;
  466         struct pf_state_key *skw = NULL, *sks = NULL;
  467         struct pf_krule *r = NULL;
  468         struct pfi_kkif *kif;
  469         int error;
  470 
  471         PF_RULES_RASSERT();
  472 
  473         if (sp->creatorid == 0) {
  474                 if (V_pf_status.debug >= PF_DEBUG_MISC)
  475                         printf("%s: invalid creator id: %08x\n", __func__,
  476                             ntohl(sp->creatorid));
  477                 return (EINVAL);
  478         }
  479 
  480         if ((kif = pfi_kkif_find(sp->ifname)) == NULL) {
  481                 if (V_pf_status.debug >= PF_DEBUG_MISC)
  482                         printf("%s: unknown interface: %s\n", __func__,
  483                             sp->ifname);
  484                 if (flags & PFSYNC_SI_IOCTL)
  485                         return (EINVAL);
  486                 return (0);     /* skip this state */
  487         }
  488 
  489         /*
  490          * If the ruleset checksums match or the state is coming from the ioctl,
  491          * it's safe to associate the state with the rule of that number.
  492          */
  493         if (sp->rule != htonl(-1) && sp->anchor == htonl(-1) &&
  494             (flags & (PFSYNC_SI_IOCTL | PFSYNC_SI_CKSUM)) && ntohl(sp->rule) <
  495             pf_main_ruleset.rules[PF_RULESET_FILTER].active.rcount)
  496                 r = pf_main_ruleset.rules[
  497                     PF_RULESET_FILTER].active.ptr_array[ntohl(sp->rule)];
  498         else
  499                 r = &V_pf_default_rule;
  500 
  501         if ((r->max_states &&
  502             counter_u64_fetch(r->states_cur) >= r->max_states))
  503                 goto cleanup;
  504 
  505         /*
  506          * XXXGL: consider M_WAITOK in ioctl path after.
  507          */
  508         st = pf_alloc_state(M_NOWAIT);
  509         if (__predict_false(st == NULL))
  510                 goto cleanup;
  511 
  512         if ((skw = uma_zalloc(V_pf_state_key_z, M_NOWAIT)) == NULL)
  513                 goto cleanup;
  514 
  515 #ifndef __NO_STRICT_ALIGNMENT
  516         bcopy(&sp->key, key, sizeof(struct pfsync_state_key) * 2);
  517         kw = &key[PF_SK_WIRE];
  518         ks = &key[PF_SK_STACK];
  519 #else
  520         kw = &sp->key[PF_SK_WIRE];
  521         ks = &sp->key[PF_SK_STACK];
  522 #endif
  523 
  524         if (PF_ANEQ(&kw->addr[0], &ks->addr[0], sp->af) ||
  525             PF_ANEQ(&kw->addr[1], &ks->addr[1], sp->af) ||
  526             kw->port[0] != ks->port[0] ||
  527             kw->port[1] != ks->port[1]) {
  528                 sks = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
  529                 if (sks == NULL)
  530                         goto cleanup;
  531         } else
  532                 sks = skw;
  533 
  534         /* allocate memory for scrub info */
  535         if (pfsync_alloc_scrub_memory(&sp->src, &st->src) ||
  536             pfsync_alloc_scrub_memory(&sp->dst, &st->dst))
  537                 goto cleanup;
  538 
  539         /* Copy to state key(s). */
  540         skw->addr[0] = kw->addr[0];
  541         skw->addr[1] = kw->addr[1];
  542         skw->port[0] = kw->port[0];
  543         skw->port[1] = kw->port[1];
  544         skw->proto = sp->proto;
  545         skw->af = sp->af;
  546         if (sks != skw) {
  547                 sks->addr[0] = ks->addr[0];
  548                 sks->addr[1] = ks->addr[1];
  549                 sks->port[0] = ks->port[0];
  550                 sks->port[1] = ks->port[1];
  551                 sks->proto = sp->proto;
  552                 sks->af = sp->af;
  553         }
  554 
  555         /* copy to state */
  556         bcopy(&sp->rt_addr, &st->rt_addr, sizeof(st->rt_addr));
  557         st->creation = time_uptime - ntohl(sp->creation);
  558         st->expire = time_uptime;
  559         if (sp->expire) {
  560                 uint32_t timeout;
  561 
  562                 timeout = r->timeout[sp->timeout];
  563                 if (!timeout)
  564                         timeout = V_pf_default_rule.timeout[sp->timeout];
  565 
  566                 /* sp->expire may have been adaptively scaled by export. */
  567                 st->expire -= timeout - ntohl(sp->expire);
  568         }
  569 
  570         st->direction = sp->direction;
  571         st->log = sp->log;
  572         st->timeout = sp->timeout;
  573         st->state_flags = sp->state_flags;
  574 
  575         st->id = sp->id;
  576         st->creatorid = sp->creatorid;
  577         pf_state_peer_ntoh(&sp->src, &st->src);
  578         pf_state_peer_ntoh(&sp->dst, &st->dst);
  579 
  580         st->rule.ptr = r;
  581         st->nat_rule.ptr = NULL;
  582         st->anchor.ptr = NULL;
  583         st->rt_kif = NULL;
  584 
  585         st->pfsync_time = time_uptime;
  586         st->sync_state = PFSYNC_S_NONE;
  587 
  588         if (!(flags & PFSYNC_SI_IOCTL))
  589                 st->state_flags |= PFSTATE_NOSYNC;
  590 
  591         if ((error = pf_state_insert(kif, kif, skw, sks, st)) != 0)
  592                 goto cleanup_state;
  593 
  594         /* XXX when we have nat_rule/anchors, use STATE_INC_COUNTERS */
  595         counter_u64_add(r->states_cur, 1);
  596         counter_u64_add(r->states_tot, 1);
  597 
  598         if (!(flags & PFSYNC_SI_IOCTL)) {
  599                 st->state_flags &= ~PFSTATE_NOSYNC;
  600                 if (st->state_flags & PFSTATE_ACK) {
  601                         pfsync_q_ins(st, PFSYNC_S_IACK, true);
  602                         pfsync_push_all(sc);
  603                 }
  604         }
  605         st->state_flags &= ~PFSTATE_ACK;
  606         PF_STATE_UNLOCK(st);
  607 
  608         return (0);
  609 
  610 cleanup:
  611         error = ENOMEM;
  612         if (skw == sks)
  613                 sks = NULL;
  614         if (skw != NULL)
  615                 uma_zfree(V_pf_state_key_z, skw);
  616         if (sks != NULL)
  617                 uma_zfree(V_pf_state_key_z, sks);
  618 
  619 cleanup_state:  /* pf_state_insert() frees the state keys. */
  620         if (st) {
  621                 st->timeout = PFTM_UNLINKED; /* appease an assert */
  622                 pf_free_state(st);
  623         }
  624         return (error);
  625 }
  626 
  627 static int
  628 pfsync_input(struct mbuf **mp, int *offp __unused, int proto __unused)
  629 {
  630         struct pfsync_softc *sc = V_pfsyncif;
  631         struct pfsync_pkt pkt;
  632         struct mbuf *m = *mp;
  633         struct ip *ip = mtod(m, struct ip *);
  634         struct pfsync_header *ph;
  635         struct pfsync_subheader subh;
  636 
  637         int offset, len;
  638         int rv;
  639         uint16_t count;
  640 
  641         PF_RULES_RLOCK_TRACKER;
  642 
  643         *mp = NULL;
  644         V_pfsyncstats.pfsyncs_ipackets++;
  645 
  646         /* Verify that we have a sync interface configured. */
  647         if (!sc || !sc->sc_sync_if || !V_pf_status.running ||
  648             (sc->sc_ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
  649                 goto done;
  650 
  651         /* verify that the packet came in on the right interface */
  652         if (sc->sc_sync_if != m->m_pkthdr.rcvif) {
  653                 V_pfsyncstats.pfsyncs_badif++;
  654                 goto done;
  655         }
  656 
  657         if_inc_counter(sc->sc_ifp, IFCOUNTER_IPACKETS, 1);
  658         if_inc_counter(sc->sc_ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len);
  659         /* verify that the IP TTL is 255. */
  660         if (ip->ip_ttl != PFSYNC_DFLTTL) {
  661                 V_pfsyncstats.pfsyncs_badttl++;
  662                 goto done;
  663         }
  664 
  665         offset = ip->ip_hl << 2;
  666         if (m->m_pkthdr.len < offset + sizeof(*ph)) {
  667                 V_pfsyncstats.pfsyncs_hdrops++;
  668                 goto done;
  669         }
  670 
  671         if (offset + sizeof(*ph) > m->m_len) {
  672                 if (m_pullup(m, offset + sizeof(*ph)) == NULL) {
  673                         V_pfsyncstats.pfsyncs_hdrops++;
  674                         return (IPPROTO_DONE);
  675                 }
  676                 ip = mtod(m, struct ip *);
  677         }
  678         ph = (struct pfsync_header *)((char *)ip + offset);
  679 
  680         /* verify the version */
  681         if (ph->version != PFSYNC_VERSION) {
  682                 V_pfsyncstats.pfsyncs_badver++;
  683                 goto done;
  684         }
  685 
  686         len = ntohs(ph->len) + offset;
  687         if (m->m_pkthdr.len < len) {
  688                 V_pfsyncstats.pfsyncs_badlen++;
  689                 goto done;
  690         }
  691 
  692         /* Cheaper to grab this now than having to mess with mbufs later */
  693         pkt.ip = ip;
  694         pkt.src = ip->ip_src;
  695         pkt.flags = 0;
  696 
  697         /*
  698          * Trusting pf_chksum during packet processing, as well as seeking
  699          * in interface name tree, require holding PF_RULES_RLOCK().
  700          */
  701         PF_RULES_RLOCK();
  702         if (!bcmp(&ph->pfcksum, &V_pf_status.pf_chksum, PF_MD5_DIGEST_LENGTH))
  703                 pkt.flags |= PFSYNC_SI_CKSUM;
  704 
  705         offset += sizeof(*ph);
  706         while (offset <= len - sizeof(subh)) {
  707                 m_copydata(m, offset, sizeof(subh), (caddr_t)&subh);
  708                 offset += sizeof(subh);
  709 
  710                 if (subh.action >= PFSYNC_ACT_MAX) {
  711                         V_pfsyncstats.pfsyncs_badact++;
  712                         PF_RULES_RUNLOCK();
  713                         goto done;
  714                 }
  715 
  716                 count = ntohs(subh.count);
  717                 V_pfsyncstats.pfsyncs_iacts[subh.action] += count;
  718                 rv = (*pfsync_acts[subh.action])(&pkt, m, offset, count);
  719                 if (rv == -1) {
  720                         PF_RULES_RUNLOCK();
  721                         return (IPPROTO_DONE);
  722                 }
  723 
  724                 offset += rv;
  725         }
  726         PF_RULES_RUNLOCK();
  727 
  728 done:
  729         m_freem(m);
  730         return (IPPROTO_DONE);
  731 }
  732 
  733 static int
  734 pfsync_in_clr(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
  735 {
  736         struct pfsync_clr *clr;
  737         struct mbuf *mp;
  738         int len = sizeof(*clr) * count;
  739         int i, offp;
  740         u_int32_t creatorid;
  741 
  742         mp = m_pulldown(m, offset, len, &offp);
  743         if (mp == NULL) {
  744                 V_pfsyncstats.pfsyncs_badlen++;
  745                 return (-1);
  746         }
  747         clr = (struct pfsync_clr *)(mp->m_data + offp);
  748 
  749         for (i = 0; i < count; i++) {
  750                 creatorid = clr[i].creatorid;
  751 
  752                 if (clr[i].ifname[0] != '\0' &&
  753                     pfi_kkif_find(clr[i].ifname) == NULL)
  754                         continue;
  755 
  756                 for (int i = 0; i <= pf_hashmask; i++) {
  757                         struct pf_idhash *ih = &V_pf_idhash[i];
  758                         struct pf_kstate *s;
  759 relock:
  760                         PF_HASHROW_LOCK(ih);
  761                         LIST_FOREACH(s, &ih->states, entry) {
  762                                 if (s->creatorid == creatorid) {
  763                                         s->state_flags |= PFSTATE_NOSYNC;
  764                                         pf_unlink_state(s, PF_ENTER_LOCKED);
  765                                         goto relock;
  766                                 }
  767                         }
  768                         PF_HASHROW_UNLOCK(ih);
  769                 }
  770         }
  771 
  772         return (len);
  773 }
  774 
  775 static int
  776 pfsync_in_ins(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
  777 {
  778         struct mbuf *mp;
  779         struct pfsync_state *sa, *sp;
  780         int len = sizeof(*sp) * count;
  781         int i, offp;
  782 
  783         mp = m_pulldown(m, offset, len, &offp);
  784         if (mp == NULL) {
  785                 V_pfsyncstats.pfsyncs_badlen++;
  786                 return (-1);
  787         }
  788         sa = (struct pfsync_state *)(mp->m_data + offp);
  789 
  790         for (i = 0; i < count; i++) {
  791                 sp = &sa[i];
  792 
  793                 /* Check for invalid values. */
  794                 if (sp->timeout >= PFTM_MAX ||
  795                     sp->src.state > PF_TCPS_PROXY_DST ||
  796                     sp->dst.state > PF_TCPS_PROXY_DST ||
  797                     sp->direction > PF_OUT ||
  798                     (sp->af != AF_INET && sp->af != AF_INET6)) {
  799                         if (V_pf_status.debug >= PF_DEBUG_MISC)
  800                                 printf("%s: invalid value\n", __func__);
  801                         V_pfsyncstats.pfsyncs_badval++;
  802                         continue;
  803                 }
  804 
  805                 if (pfsync_state_import(sp, pkt->flags) == ENOMEM)
  806                         /* Drop out, but process the rest of the actions. */
  807                         break;
  808         }
  809 
  810         return (len);
  811 }
  812 
  813 static int
  814 pfsync_in_iack(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
  815 {
  816         struct pfsync_ins_ack *ia, *iaa;
  817         struct pf_kstate *st;
  818 
  819         struct mbuf *mp;
  820         int len = count * sizeof(*ia);
  821         int offp, i;
  822 
  823         mp = m_pulldown(m, offset, len, &offp);
  824         if (mp == NULL) {
  825                 V_pfsyncstats.pfsyncs_badlen++;
  826                 return (-1);
  827         }
  828         iaa = (struct pfsync_ins_ack *)(mp->m_data + offp);
  829 
  830         for (i = 0; i < count; i++) {
  831                 ia = &iaa[i];
  832 
  833                 st = pf_find_state_byid(ia->id, ia->creatorid);
  834                 if (st == NULL)
  835                         continue;
  836 
  837                 if (st->state_flags & PFSTATE_ACK) {
  838                         pfsync_undefer_state(st, 0);
  839                 }
  840                 PF_STATE_UNLOCK(st);
  841         }
  842         /*
  843          * XXX this is not yet implemented, but we know the size of the
  844          * message so we can skip it.
  845          */
  846 
  847         return (count * sizeof(struct pfsync_ins_ack));
  848 }
  849 
  850 static int
  851 pfsync_upd_tcp(struct pf_kstate *st, struct pfsync_state_peer *src,
  852     struct pfsync_state_peer *dst)
  853 {
  854         int sync = 0;
  855 
  856         PF_STATE_LOCK_ASSERT(st);
  857 
  858         /*
  859          * The state should never go backwards except
  860          * for syn-proxy states.  Neither should the
  861          * sequence window slide backwards.
  862          */
  863         if ((st->src.state > src->state &&
  864             (st->src.state < PF_TCPS_PROXY_SRC ||
  865             src->state >= PF_TCPS_PROXY_SRC)) ||
  866 
  867             (st->src.state == src->state &&
  868             SEQ_GT(st->src.seqlo, ntohl(src->seqlo))))
  869                 sync++;
  870         else
  871                 pf_state_peer_ntoh(src, &st->src);
  872 
  873         if ((st->dst.state > dst->state) ||
  874 
  875             (st->dst.state >= TCPS_SYN_SENT &&
  876             SEQ_GT(st->dst.seqlo, ntohl(dst->seqlo))))
  877                 sync++;
  878         else
  879                 pf_state_peer_ntoh(dst, &st->dst);
  880 
  881         return (sync);
  882 }
  883 
  884 static int
  885 pfsync_in_upd(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
  886 {
  887         struct pfsync_softc *sc = V_pfsyncif;
  888         struct pfsync_state *sa, *sp;
  889         struct pf_kstate *st;
  890         int sync;
  891 
  892         struct mbuf *mp;
  893         int len = count * sizeof(*sp);
  894         int offp, i;
  895 
  896         mp = m_pulldown(m, offset, len, &offp);
  897         if (mp == NULL) {
  898                 V_pfsyncstats.pfsyncs_badlen++;
  899                 return (-1);
  900         }
  901         sa = (struct pfsync_state *)(mp->m_data + offp);
  902 
  903         for (i = 0; i < count; i++) {
  904                 sp = &sa[i];
  905 
  906                 /* check for invalid values */
  907                 if (sp->timeout >= PFTM_MAX ||
  908                     sp->src.state > PF_TCPS_PROXY_DST ||
  909                     sp->dst.state > PF_TCPS_PROXY_DST) {
  910                         if (V_pf_status.debug >= PF_DEBUG_MISC) {
  911                                 printf("pfsync_input: PFSYNC_ACT_UPD: "
  912                                     "invalid value\n");
  913                         }
  914                         V_pfsyncstats.pfsyncs_badval++;
  915                         continue;
  916                 }
  917 
  918                 st = pf_find_state_byid(sp->id, sp->creatorid);
  919                 if (st == NULL) {
  920                         /* insert the update */
  921                         if (pfsync_state_import(sp, pkt->flags))
  922                                 V_pfsyncstats.pfsyncs_badstate++;
  923                         continue;
  924                 }
  925 
  926                 if (st->state_flags & PFSTATE_ACK) {
  927                         pfsync_undefer_state(st, 1);
  928                 }
  929 
  930                 if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP)
  931                         sync = pfsync_upd_tcp(st, &sp->src, &sp->dst);
  932                 else {
  933                         sync = 0;
  934 
  935                         /*
  936                          * Non-TCP protocol state machine always go
  937                          * forwards
  938                          */
  939                         if (st->src.state > sp->src.state)
  940                                 sync++;
  941                         else
  942                                 pf_state_peer_ntoh(&sp->src, &st->src);
  943                         if (st->dst.state > sp->dst.state)
  944                                 sync++;
  945                         else
  946                                 pf_state_peer_ntoh(&sp->dst, &st->dst);
  947                 }
  948                 if (sync < 2) {
  949                         pfsync_alloc_scrub_memory(&sp->dst, &st->dst);
  950                         pf_state_peer_ntoh(&sp->dst, &st->dst);
  951                         st->expire = time_uptime;
  952                         st->timeout = sp->timeout;
  953                 }
  954                 st->pfsync_time = time_uptime;
  955 
  956                 if (sync) {
  957                         V_pfsyncstats.pfsyncs_stale++;
  958 
  959                         pfsync_update_state(st);
  960                         PF_STATE_UNLOCK(st);
  961                         pfsync_push_all(sc);
  962                         continue;
  963                 }
  964                 PF_STATE_UNLOCK(st);
  965         }
  966 
  967         return (len);
  968 }
  969 
  970 static int
  971 pfsync_in_upd_c(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
  972 {
  973         struct pfsync_softc *sc = V_pfsyncif;
  974         struct pfsync_upd_c *ua, *up;
  975         struct pf_kstate *st;
  976         int len = count * sizeof(*up);
  977         int sync;
  978         struct mbuf *mp;
  979         int offp, i;
  980 
  981         mp = m_pulldown(m, offset, len, &offp);
  982         if (mp == NULL) {
  983                 V_pfsyncstats.pfsyncs_badlen++;
  984                 return (-1);
  985         }
  986         ua = (struct pfsync_upd_c *)(mp->m_data + offp);
  987 
  988         for (i = 0; i < count; i++) {
  989                 up = &ua[i];
  990 
  991                 /* check for invalid values */
  992                 if (up->timeout >= PFTM_MAX ||
  993                     up->src.state > PF_TCPS_PROXY_DST ||
  994                     up->dst.state > PF_TCPS_PROXY_DST) {
  995                         if (V_pf_status.debug >= PF_DEBUG_MISC) {
  996                                 printf("pfsync_input: "
  997                                     "PFSYNC_ACT_UPD_C: "
  998                                     "invalid value\n");
  999                         }
 1000                         V_pfsyncstats.pfsyncs_badval++;
 1001                         continue;
 1002                 }
 1003 
 1004                 st = pf_find_state_byid(up->id, up->creatorid);
 1005                 if (st == NULL) {
 1006                         /* We don't have this state. Ask for it. */
 1007                         PFSYNC_BUCKET_LOCK(&sc->sc_buckets[0]);
 1008                         pfsync_request_update(up->creatorid, up->id);
 1009                         PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[0]);
 1010                         continue;
 1011                 }
 1012 
 1013                 if (st->state_flags & PFSTATE_ACK) {
 1014                         pfsync_undefer_state(st, 1);
 1015                 }
 1016 
 1017                 if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP)
 1018                         sync = pfsync_upd_tcp(st, &up->src, &up->dst);
 1019                 else {
 1020                         sync = 0;
 1021 
 1022                         /*
 1023                          * Non-TCP protocol state machine always go
 1024                          * forwards
 1025                          */
 1026                         if (st->src.state > up->src.state)
 1027                                 sync++;
 1028                         else
 1029                                 pf_state_peer_ntoh(&up->src, &st->src);
 1030                         if (st->dst.state > up->dst.state)
 1031                                 sync++;
 1032                         else
 1033                                 pf_state_peer_ntoh(&up->dst, &st->dst);
 1034                 }
 1035                 if (sync < 2) {
 1036                         pfsync_alloc_scrub_memory(&up->dst, &st->dst);
 1037                         pf_state_peer_ntoh(&up->dst, &st->dst);
 1038                         st->expire = time_uptime;
 1039                         st->timeout = up->timeout;
 1040                 }
 1041                 st->pfsync_time = time_uptime;
 1042 
 1043                 if (sync) {
 1044                         V_pfsyncstats.pfsyncs_stale++;
 1045 
 1046                         pfsync_update_state(st);
 1047                         PF_STATE_UNLOCK(st);
 1048                         pfsync_push_all(sc);
 1049                         continue;
 1050                 }
 1051                 PF_STATE_UNLOCK(st);
 1052         }
 1053 
 1054         return (len);
 1055 }
 1056 
 1057 static int
 1058 pfsync_in_ureq(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
 1059 {
 1060         struct pfsync_upd_req *ur, *ura;
 1061         struct mbuf *mp;
 1062         int len = count * sizeof(*ur);
 1063         int i, offp;
 1064 
 1065         struct pf_kstate *st;
 1066 
 1067         mp = m_pulldown(m, offset, len, &offp);
 1068         if (mp == NULL) {
 1069                 V_pfsyncstats.pfsyncs_badlen++;
 1070                 return (-1);
 1071         }
 1072         ura = (struct pfsync_upd_req *)(mp->m_data + offp);
 1073 
 1074         for (i = 0; i < count; i++) {
 1075                 ur = &ura[i];
 1076 
 1077                 if (ur->id == 0 && ur->creatorid == 0)
 1078                         pfsync_bulk_start();
 1079                 else {
 1080                         st = pf_find_state_byid(ur->id, ur->creatorid);
 1081                         if (st == NULL) {
 1082                                 V_pfsyncstats.pfsyncs_badstate++;
 1083                                 continue;
 1084                         }
 1085                         if (st->state_flags & PFSTATE_NOSYNC) {
 1086                                 PF_STATE_UNLOCK(st);
 1087                                 continue;
 1088                         }
 1089 
 1090                         pfsync_update_state_req(st);
 1091                         PF_STATE_UNLOCK(st);
 1092                 }
 1093         }
 1094 
 1095         return (len);
 1096 }
 1097 
 1098 static int
 1099 pfsync_in_del(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
 1100 {
 1101         struct mbuf *mp;
 1102         struct pfsync_state *sa, *sp;
 1103         struct pf_kstate *st;
 1104         int len = count * sizeof(*sp);
 1105         int offp, i;
 1106 
 1107         mp = m_pulldown(m, offset, len, &offp);
 1108         if (mp == NULL) {
 1109                 V_pfsyncstats.pfsyncs_badlen++;
 1110                 return (-1);
 1111         }
 1112         sa = (struct pfsync_state *)(mp->m_data + offp);
 1113 
 1114         for (i = 0; i < count; i++) {
 1115                 sp = &sa[i];
 1116 
 1117                 st = pf_find_state_byid(sp->id, sp->creatorid);
 1118                 if (st == NULL) {
 1119                         V_pfsyncstats.pfsyncs_badstate++;
 1120                         continue;
 1121                 }
 1122                 st->state_flags |= PFSTATE_NOSYNC;
 1123                 pf_unlink_state(st, PF_ENTER_LOCKED);
 1124         }
 1125 
 1126         return (len);
 1127 }
 1128 
 1129 static int
 1130 pfsync_in_del_c(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
 1131 {
 1132         struct mbuf *mp;
 1133         struct pfsync_del_c *sa, *sp;
 1134         struct pf_kstate *st;
 1135         int len = count * sizeof(*sp);
 1136         int offp, i;
 1137 
 1138         mp = m_pulldown(m, offset, len, &offp);
 1139         if (mp == NULL) {
 1140                 V_pfsyncstats.pfsyncs_badlen++;
 1141                 return (-1);
 1142         }
 1143         sa = (struct pfsync_del_c *)(mp->m_data + offp);
 1144 
 1145         for (i = 0; i < count; i++) {
 1146                 sp = &sa[i];
 1147 
 1148                 st = pf_find_state_byid(sp->id, sp->creatorid);
 1149                 if (st == NULL) {
 1150                         V_pfsyncstats.pfsyncs_badstate++;
 1151                         continue;
 1152                 }
 1153 
 1154                 st->state_flags |= PFSTATE_NOSYNC;
 1155                 pf_unlink_state(st, PF_ENTER_LOCKED);
 1156         }
 1157 
 1158         return (len);
 1159 }
 1160 
 1161 static int
 1162 pfsync_in_bus(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
 1163 {
 1164         struct pfsync_softc *sc = V_pfsyncif;
 1165         struct pfsync_bus *bus;
 1166         struct mbuf *mp;
 1167         int len = count * sizeof(*bus);
 1168         int offp;
 1169 
 1170         PFSYNC_BLOCK(sc);
 1171 
 1172         /* If we're not waiting for a bulk update, who cares. */
 1173         if (sc->sc_ureq_sent == 0) {
 1174                 PFSYNC_BUNLOCK(sc);
 1175                 return (len);
 1176         }
 1177 
 1178         mp = m_pulldown(m, offset, len, &offp);
 1179         if (mp == NULL) {
 1180                 PFSYNC_BUNLOCK(sc);
 1181                 V_pfsyncstats.pfsyncs_badlen++;
 1182                 return (-1);
 1183         }
 1184         bus = (struct pfsync_bus *)(mp->m_data + offp);
 1185 
 1186         switch (bus->status) {
 1187         case PFSYNC_BUS_START:
 1188                 callout_reset(&sc->sc_bulkfail_tmo, 4 * hz +
 1189                     V_pf_limits[PF_LIMIT_STATES].limit /
 1190                     ((sc->sc_ifp->if_mtu - PFSYNC_MINPKT) /
 1191                     sizeof(struct pfsync_state)),
 1192                     pfsync_bulk_fail, sc);
 1193                 if (V_pf_status.debug >= PF_DEBUG_MISC)
 1194                         printf("pfsync: received bulk update start\n");
 1195                 break;
 1196 
 1197         case PFSYNC_BUS_END:
 1198                 if (time_uptime - ntohl(bus->endtime) >=
 1199                     sc->sc_ureq_sent) {
 1200                         /* that's it, we're happy */
 1201                         sc->sc_ureq_sent = 0;
 1202                         sc->sc_bulk_tries = 0;
 1203                         callout_stop(&sc->sc_bulkfail_tmo);
 1204                         if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
 1205                                 (*carp_demote_adj_p)(-V_pfsync_carp_adj,
 1206                                     "pfsync bulk done");
 1207                         sc->sc_flags |= PFSYNCF_OK;
 1208                         if (V_pf_status.debug >= PF_DEBUG_MISC)
 1209                                 printf("pfsync: received valid "
 1210                                     "bulk update end\n");
 1211                 } else {
 1212                         if (V_pf_status.debug >= PF_DEBUG_MISC)
 1213                                 printf("pfsync: received invalid "
 1214                                     "bulk update end: bad timestamp\n");
 1215                 }
 1216                 break;
 1217         }
 1218         PFSYNC_BUNLOCK(sc);
 1219 
 1220         return (len);
 1221 }
 1222 
 1223 static int
 1224 pfsync_in_tdb(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
 1225 {
 1226         int len = count * sizeof(struct pfsync_tdb);
 1227 
 1228 #if defined(IPSEC)
 1229         struct pfsync_tdb *tp;
 1230         struct mbuf *mp;
 1231         int offp;
 1232         int i;
 1233         int s;
 1234 
 1235         mp = m_pulldown(m, offset, len, &offp);
 1236         if (mp == NULL) {
 1237                 V_pfsyncstats.pfsyncs_badlen++;
 1238                 return (-1);
 1239         }
 1240         tp = (struct pfsync_tdb *)(mp->m_data + offp);
 1241 
 1242         for (i = 0; i < count; i++)
 1243                 pfsync_update_net_tdb(&tp[i]);
 1244 #endif
 1245 
 1246         return (len);
 1247 }
 1248 
 1249 #if defined(IPSEC)
 1250 /* Update an in-kernel tdb. Silently fail if no tdb is found. */
 1251 static void
 1252 pfsync_update_net_tdb(struct pfsync_tdb *pt)
 1253 {
 1254         struct tdb              *tdb;
 1255         int                      s;
 1256 
 1257         /* check for invalid values */
 1258         if (ntohl(pt->spi) <= SPI_RESERVED_MAX ||
 1259             (pt->dst.sa.sa_family != AF_INET &&
 1260             pt->dst.sa.sa_family != AF_INET6))
 1261                 goto bad;
 1262 
 1263         tdb = gettdb(pt->spi, &pt->dst, pt->sproto);
 1264         if (tdb) {
 1265                 pt->rpl = ntohl(pt->rpl);
 1266                 pt->cur_bytes = (unsigned long long)be64toh(pt->cur_bytes);
 1267 
 1268                 /* Neither replay nor byte counter should ever decrease. */
 1269                 if (pt->rpl < tdb->tdb_rpl ||
 1270                     pt->cur_bytes < tdb->tdb_cur_bytes) {
 1271                         goto bad;
 1272                 }
 1273 
 1274                 tdb->tdb_rpl = pt->rpl;
 1275                 tdb->tdb_cur_bytes = pt->cur_bytes;
 1276         }
 1277         return;
 1278 
 1279 bad:
 1280         if (V_pf_status.debug >= PF_DEBUG_MISC)
 1281                 printf("pfsync_insert: PFSYNC_ACT_TDB_UPD: "
 1282                     "invalid value\n");
 1283         V_pfsyncstats.pfsyncs_badstate++;
 1284         return;
 1285 }
 1286 #endif
 1287 
 1288 static int
 1289 pfsync_in_eof(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
 1290 {
 1291         /* check if we are at the right place in the packet */
 1292         if (offset != m->m_pkthdr.len)
 1293                 V_pfsyncstats.pfsyncs_badlen++;
 1294 
 1295         /* we're done. free and let the caller return */
 1296         m_freem(m);
 1297         return (-1);
 1298 }
 1299 
 1300 static int
 1301 pfsync_in_error(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
 1302 {
 1303         V_pfsyncstats.pfsyncs_badact++;
 1304 
 1305         m_freem(m);
 1306         return (-1);
 1307 }
 1308 
 1309 static int
 1310 pfsyncoutput(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
 1311         struct route *rt)
 1312 {
 1313         m_freem(m);
 1314         return (0);
 1315 }
 1316 
 1317 /* ARGSUSED */
 1318 static int
 1319 pfsyncioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
 1320 {
 1321         struct pfsync_softc *sc = ifp->if_softc;
 1322         struct ifreq *ifr = (struct ifreq *)data;
 1323         struct pfsyncreq pfsyncr;
 1324         int error;
 1325         int c;
 1326 
 1327         switch (cmd) {
 1328         case SIOCSIFFLAGS:
 1329                 PFSYNC_LOCK(sc);
 1330                 if (ifp->if_flags & IFF_UP) {
 1331                         ifp->if_drv_flags |= IFF_DRV_RUNNING;
 1332                         PFSYNC_UNLOCK(sc);
 1333                         pfsync_pointers_init();
 1334                 } else {
 1335                         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
 1336                         PFSYNC_UNLOCK(sc);
 1337                         pfsync_pointers_uninit();
 1338                 }
 1339                 break;
 1340         case SIOCSIFMTU:
 1341                 if (!sc->sc_sync_if ||
 1342                     ifr->ifr_mtu <= PFSYNC_MINPKT ||
 1343                     ifr->ifr_mtu > sc->sc_sync_if->if_mtu)
 1344                         return (EINVAL);
 1345                 if (ifr->ifr_mtu < ifp->if_mtu) {
 1346                         for (c = 0; c < pfsync_buckets; c++) {
 1347                                 PFSYNC_BUCKET_LOCK(&sc->sc_buckets[c]);
 1348                                 if (sc->sc_buckets[c].b_len > PFSYNC_MINPKT)
 1349                                         pfsync_sendout(1, c);
 1350                                 PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[c]);
 1351                         }
 1352                 }
 1353                 ifp->if_mtu = ifr->ifr_mtu;
 1354                 break;
 1355         case SIOCGETPFSYNC:
 1356                 bzero(&pfsyncr, sizeof(pfsyncr));
 1357                 PFSYNC_LOCK(sc);
 1358                 if (sc->sc_sync_if) {
 1359                         strlcpy(pfsyncr.pfsyncr_syncdev,
 1360                             sc->sc_sync_if->if_xname, IFNAMSIZ);
 1361                 }
 1362                 pfsyncr.pfsyncr_syncpeer = sc->sc_sync_peer;
 1363                 pfsyncr.pfsyncr_maxupdates = sc->sc_maxupdates;
 1364                 pfsyncr.pfsyncr_defer = sc->sc_flags;
 1365                 PFSYNC_UNLOCK(sc);
 1366                 return (copyout(&pfsyncr, ifr_data_get_ptr(ifr),
 1367                     sizeof(pfsyncr)));
 1368 
 1369         case SIOCSETPFSYNC:
 1370             {
 1371                 struct in_mfilter *imf = NULL;
 1372                 struct ifnet *sifp;
 1373                 struct ip *ip;
 1374 
 1375                 if ((error = priv_check(curthread, PRIV_NETINET_PF)) != 0)
 1376                         return (error);
 1377                 if ((error = copyin(ifr_data_get_ptr(ifr), &pfsyncr,
 1378                     sizeof(pfsyncr))))
 1379                         return (error);
 1380 
 1381                 if (pfsyncr.pfsyncr_maxupdates > 255)
 1382                         return (EINVAL);
 1383 
 1384                 if (pfsyncr.pfsyncr_syncdev[0] == 0)
 1385                         sifp = NULL;
 1386                 else if ((sifp = ifunit_ref(pfsyncr.pfsyncr_syncdev)) == NULL)
 1387                         return (EINVAL);
 1388 
 1389                 if (sifp != NULL && (
 1390                     pfsyncr.pfsyncr_syncpeer.s_addr == 0 ||
 1391                     pfsyncr.pfsyncr_syncpeer.s_addr ==
 1392                     htonl(INADDR_PFSYNC_GROUP)))
 1393                         imf = ip_mfilter_alloc(M_WAITOK, 0, 0);
 1394 
 1395                 PFSYNC_LOCK(sc);
 1396                 if (pfsyncr.pfsyncr_syncpeer.s_addr == 0)
 1397                         sc->sc_sync_peer.s_addr = htonl(INADDR_PFSYNC_GROUP);
 1398                 else
 1399                         sc->sc_sync_peer.s_addr =
 1400                             pfsyncr.pfsyncr_syncpeer.s_addr;
 1401 
 1402                 sc->sc_maxupdates = pfsyncr.pfsyncr_maxupdates;
 1403                 if (pfsyncr.pfsyncr_defer & PFSYNCF_DEFER) {
 1404                         sc->sc_flags |= PFSYNCF_DEFER;
 1405                         V_pfsync_defer_ptr = pfsync_defer;
 1406                 } else {
 1407                         sc->sc_flags &= ~PFSYNCF_DEFER;
 1408                         V_pfsync_defer_ptr = NULL;
 1409                 }
 1410 
 1411                 if (sifp == NULL) {
 1412                         if (sc->sc_sync_if)
 1413                                 if_rele(sc->sc_sync_if);
 1414                         sc->sc_sync_if = NULL;
 1415                         pfsync_multicast_cleanup(sc);
 1416                         PFSYNC_UNLOCK(sc);
 1417                         break;
 1418                 }
 1419 
 1420                 for (c = 0; c < pfsync_buckets; c++) {
 1421                         PFSYNC_BUCKET_LOCK(&sc->sc_buckets[c]);
 1422                         if (sc->sc_buckets[c].b_len > PFSYNC_MINPKT &&
 1423                             (sifp->if_mtu < sc->sc_ifp->if_mtu ||
 1424                             (sc->sc_sync_if != NULL &&
 1425                             sifp->if_mtu < sc->sc_sync_if->if_mtu) ||
 1426                             sifp->if_mtu < MCLBYTES - sizeof(struct ip)))
 1427                                 pfsync_sendout(1, c);
 1428                         PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[c]);
 1429                 }
 1430 
 1431                 pfsync_multicast_cleanup(sc);
 1432 
 1433                 if (sc->sc_sync_peer.s_addr == htonl(INADDR_PFSYNC_GROUP)) {
 1434                         error = pfsync_multicast_setup(sc, sifp, imf);
 1435                         if (error) {
 1436                                 if_rele(sifp);
 1437                                 ip_mfilter_free(imf);
 1438                                 PFSYNC_UNLOCK(sc);
 1439                                 return (error);
 1440                         }
 1441                 }
 1442                 if (sc->sc_sync_if)
 1443                         if_rele(sc->sc_sync_if);
 1444                 sc->sc_sync_if = sifp;
 1445 
 1446                 ip = &sc->sc_template;
 1447                 bzero(ip, sizeof(*ip));
 1448                 ip->ip_v = IPVERSION;
 1449                 ip->ip_hl = sizeof(sc->sc_template) >> 2;
 1450                 ip->ip_tos = IPTOS_LOWDELAY;
 1451                 /* len and id are set later. */
 1452                 ip->ip_off = htons(IP_DF);
 1453                 ip->ip_ttl = PFSYNC_DFLTTL;
 1454                 ip->ip_p = IPPROTO_PFSYNC;
 1455                 ip->ip_src.s_addr = INADDR_ANY;
 1456                 ip->ip_dst.s_addr = sc->sc_sync_peer.s_addr;
 1457 
 1458                 /* Request a full state table update. */
 1459                 if ((sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
 1460                         (*carp_demote_adj_p)(V_pfsync_carp_adj,
 1461                             "pfsync bulk start");
 1462                 sc->sc_flags &= ~PFSYNCF_OK;
 1463                 if (V_pf_status.debug >= PF_DEBUG_MISC)
 1464                         printf("pfsync: requesting bulk update\n");
 1465                 PFSYNC_UNLOCK(sc);
 1466                 PFSYNC_BUCKET_LOCK(&sc->sc_buckets[0]);
 1467                 pfsync_request_update(0, 0);
 1468                 PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[0]);
 1469                 PFSYNC_BLOCK(sc);
 1470                 sc->sc_ureq_sent = time_uptime;
 1471                 callout_reset(&sc->sc_bulkfail_tmo, 5 * hz, pfsync_bulk_fail,
 1472                     sc);
 1473                 PFSYNC_BUNLOCK(sc);
 1474 
 1475                 break;
 1476             }
 1477         default:
 1478                 return (ENOTTY);
 1479         }
 1480 
 1481         return (0);
 1482 }
 1483 
 1484 static void
 1485 pfsync_out_state(struct pf_kstate *st, void *buf)
 1486 {
 1487         struct pfsync_state *sp = buf;
 1488 
 1489         pfsync_state_export(sp, st);
 1490 }
 1491 
 1492 static void
 1493 pfsync_out_iack(struct pf_kstate *st, void *buf)
 1494 {
 1495         struct pfsync_ins_ack *iack = buf;
 1496 
 1497         iack->id = st->id;
 1498         iack->creatorid = st->creatorid;
 1499 }
 1500 
 1501 static void
 1502 pfsync_out_upd_c(struct pf_kstate *st, void *buf)
 1503 {
 1504         struct pfsync_upd_c *up = buf;
 1505 
 1506         bzero(up, sizeof(*up));
 1507         up->id = st->id;
 1508         pf_state_peer_hton(&st->src, &up->src);
 1509         pf_state_peer_hton(&st->dst, &up->dst);
 1510         up->creatorid = st->creatorid;
 1511         up->timeout = st->timeout;
 1512 }
 1513 
 1514 static void
 1515 pfsync_out_del(struct pf_kstate *st, void *buf)
 1516 {
 1517         struct pfsync_del_c *dp = buf;
 1518 
 1519         dp->id = st->id;
 1520         dp->creatorid = st->creatorid;
 1521         st->state_flags |= PFSTATE_NOSYNC;
 1522 }
 1523 
 1524 static void
 1525 pfsync_drop(struct pfsync_softc *sc)
 1526 {
 1527         struct pf_kstate *st, *next;
 1528         struct pfsync_upd_req_item *ur;
 1529         struct pfsync_bucket *b;
 1530         int c, q;
 1531 
 1532         for (c = 0; c < pfsync_buckets; c++) {
 1533                 b = &sc->sc_buckets[c];
 1534                 for (q = 0; q < PFSYNC_S_COUNT; q++) {
 1535                         if (TAILQ_EMPTY(&b->b_qs[q]))
 1536                                 continue;
 1537 
 1538                         TAILQ_FOREACH_SAFE(st, &b->b_qs[q], sync_list, next) {
 1539                                 KASSERT(st->sync_state == q,
 1540                                         ("%s: st->sync_state == q",
 1541                                                 __func__));
 1542                                 st->sync_state = PFSYNC_S_NONE;
 1543                                 pf_release_state(st);
 1544                         }
 1545                         TAILQ_INIT(&b->b_qs[q]);
 1546                 }
 1547 
 1548                 while ((ur = TAILQ_FIRST(&b->b_upd_req_list)) != NULL) {
 1549                         TAILQ_REMOVE(&b->b_upd_req_list, ur, ur_entry);
 1550                         free(ur, M_PFSYNC);
 1551                 }
 1552 
 1553                 b->b_len = PFSYNC_MINPKT;
 1554                 b->b_plus = NULL;
 1555         }
 1556 }
 1557 
 1558 static void
 1559 pfsync_sendout(int schedswi, int c)
 1560 {
 1561         struct pfsync_softc *sc = V_pfsyncif;
 1562         struct ifnet *ifp = sc->sc_ifp;
 1563         struct mbuf *m;
 1564         struct ip *ip;
 1565         struct pfsync_header *ph;
 1566         struct pfsync_subheader *subh;
 1567         struct pf_kstate *st, *st_next;
 1568         struct pfsync_upd_req_item *ur;
 1569         struct pfsync_bucket *b = &sc->sc_buckets[c];
 1570         int offset;
 1571         int q, count = 0;
 1572 
 1573         KASSERT(sc != NULL, ("%s: null sc", __func__));
 1574         KASSERT(b->b_len > PFSYNC_MINPKT,
 1575             ("%s: sc_len %zu", __func__, b->b_len));
 1576         PFSYNC_BUCKET_LOCK_ASSERT(b);
 1577 
 1578         if (ifp->if_bpf == NULL && sc->sc_sync_if == NULL) {
 1579                 pfsync_drop(sc);
 1580                 return;
 1581         }
 1582 
 1583         m = m_get2(max_linkhdr + b->b_len, M_NOWAIT, MT_DATA, M_PKTHDR);
 1584         if (m == NULL) {
 1585                 if_inc_counter(sc->sc_ifp, IFCOUNTER_OERRORS, 1);
 1586                 V_pfsyncstats.pfsyncs_onomem++;
 1587                 return;
 1588         }
 1589         m->m_data += max_linkhdr;
 1590         m->m_len = m->m_pkthdr.len = b->b_len;
 1591 
 1592         /* build the ip header */
 1593         ip = (struct ip *)m->m_data;
 1594         bcopy(&sc->sc_template, ip, sizeof(*ip));
 1595         offset = sizeof(*ip);
 1596 
 1597         ip->ip_len = htons(m->m_pkthdr.len);
 1598         ip_fillid(ip);
 1599 
 1600         /* build the pfsync header */
 1601         ph = (struct pfsync_header *)(m->m_data + offset);
 1602         bzero(ph, sizeof(*ph));
 1603         offset += sizeof(*ph);
 1604 
 1605         ph->version = PFSYNC_VERSION;
 1606         ph->len = htons(b->b_len - sizeof(*ip));
 1607         bcopy(V_pf_status.pf_chksum, ph->pfcksum, PF_MD5_DIGEST_LENGTH);
 1608 
 1609         /* walk the queues */
 1610         for (q = 0; q < PFSYNC_S_COUNT; q++) {
 1611                 if (TAILQ_EMPTY(&b->b_qs[q]))
 1612                         continue;
 1613 
 1614                 subh = (struct pfsync_subheader *)(m->m_data + offset);
 1615                 offset += sizeof(*subh);
 1616 
 1617                 count = 0;
 1618                 TAILQ_FOREACH_SAFE(st, &b->b_qs[q], sync_list, st_next) {
 1619                         KASSERT(st->sync_state == q,
 1620                                 ("%s: st->sync_state == q",
 1621                                         __func__));
 1622                         /*
 1623                          * XXXGL: some of write methods do unlocked reads
 1624                          * of state data :(
 1625                          */
 1626                         pfsync_qs[q].write(st, m->m_data + offset);
 1627                         offset += pfsync_qs[q].len;
 1628                         st->sync_state = PFSYNC_S_NONE;
 1629                         pf_release_state(st);
 1630                         count++;
 1631                 }
 1632                 TAILQ_INIT(&b->b_qs[q]);
 1633 
 1634                 bzero(subh, sizeof(*subh));
 1635                 subh->action = pfsync_qs[q].action;
 1636                 subh->count = htons(count);
 1637                 V_pfsyncstats.pfsyncs_oacts[pfsync_qs[q].action] += count;
 1638         }
 1639 
 1640         if (!TAILQ_EMPTY(&b->b_upd_req_list)) {
 1641                 subh = (struct pfsync_subheader *)(m->m_data + offset);
 1642                 offset += sizeof(*subh);
 1643 
 1644                 count = 0;
 1645                 while ((ur = TAILQ_FIRST(&b->b_upd_req_list)) != NULL) {
 1646                         TAILQ_REMOVE(&b->b_upd_req_list, ur, ur_entry);
 1647 
 1648                         bcopy(&ur->ur_msg, m->m_data + offset,
 1649                             sizeof(ur->ur_msg));
 1650                         offset += sizeof(ur->ur_msg);
 1651                         free(ur, M_PFSYNC);
 1652                         count++;
 1653                 }
 1654 
 1655                 bzero(subh, sizeof(*subh));
 1656                 subh->action = PFSYNC_ACT_UPD_REQ;
 1657                 subh->count = htons(count);
 1658                 V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_UPD_REQ] += count;
 1659         }
 1660 
 1661         /* has someone built a custom region for us to add? */
 1662         if (b->b_plus != NULL) {
 1663                 bcopy(b->b_plus, m->m_data + offset, b->b_pluslen);
 1664                 offset += b->b_pluslen;
 1665 
 1666                 b->b_plus = NULL;
 1667         }
 1668 
 1669         subh = (struct pfsync_subheader *)(m->m_data + offset);
 1670         offset += sizeof(*subh);
 1671 
 1672         bzero(subh, sizeof(*subh));
 1673         subh->action = PFSYNC_ACT_EOF;
 1674         subh->count = htons(1);
 1675         V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_EOF]++;
 1676 
 1677         /* we're done, let's put it on the wire */
 1678         if (ifp->if_bpf) {
 1679                 m->m_data += sizeof(*ip);
 1680                 m->m_len = m->m_pkthdr.len = b->b_len - sizeof(*ip);
 1681                 BPF_MTAP(ifp, m);
 1682                 m->m_data -= sizeof(*ip);
 1683                 m->m_len = m->m_pkthdr.len = b->b_len;
 1684         }
 1685 
 1686         if (sc->sc_sync_if == NULL) {
 1687                 b->b_len = PFSYNC_MINPKT;
 1688                 m_freem(m);
 1689                 return;
 1690         }
 1691 
 1692         if_inc_counter(sc->sc_ifp, IFCOUNTER_OPACKETS, 1);
 1693         if_inc_counter(sc->sc_ifp, IFCOUNTER_OBYTES, m->m_pkthdr.len);
 1694         b->b_len = PFSYNC_MINPKT;
 1695 
 1696         if (!_IF_QFULL(&b->b_snd))
 1697                 _IF_ENQUEUE(&b->b_snd, m);
 1698         else {
 1699                 m_freem(m);
 1700                 if_inc_counter(sc->sc_ifp, IFCOUNTER_OQDROPS, 1);
 1701         }
 1702         if (schedswi)
 1703                 swi_sched(V_pfsync_swi_cookie, 0);
 1704 }
 1705 
 1706 static void
 1707 pfsync_insert_state(struct pf_kstate *st)
 1708 {
 1709         struct pfsync_softc *sc = V_pfsyncif;
 1710         struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
 1711 
 1712         if (st->state_flags & PFSTATE_NOSYNC)
 1713                 return;
 1714 
 1715         if ((st->rule.ptr->rule_flag & PFRULE_NOSYNC) ||
 1716             st->key[PF_SK_WIRE]->proto == IPPROTO_PFSYNC) {
 1717                 st->state_flags |= PFSTATE_NOSYNC;
 1718                 return;
 1719         }
 1720 
 1721         KASSERT(st->sync_state == PFSYNC_S_NONE,
 1722                 ("%s: st->sync_state %u", __func__, st->sync_state));
 1723 
 1724         PFSYNC_BUCKET_LOCK(b);
 1725         if (b->b_len == PFSYNC_MINPKT)
 1726                 callout_reset(&b->b_tmo, 1 * hz, pfsync_timeout, b);
 1727 
 1728         pfsync_q_ins(st, PFSYNC_S_INS, true);
 1729         PFSYNC_BUCKET_UNLOCK(b);
 1730 
 1731         st->sync_updates = 0;
 1732 }
 1733 
 1734 static int
 1735 pfsync_defer(struct pf_kstate *st, struct mbuf *m)
 1736 {
 1737         struct pfsync_softc *sc = V_pfsyncif;
 1738         struct pfsync_deferral *pd;
 1739         struct pfsync_bucket *b;
 1740 
 1741         if (m->m_flags & (M_BCAST|M_MCAST))
 1742                 return (0);
 1743 
 1744         if (sc == NULL)
 1745                 return (0);
 1746 
 1747         b = pfsync_get_bucket(sc, st);
 1748 
 1749         PFSYNC_LOCK(sc);
 1750 
 1751         if (!(sc->sc_ifp->if_drv_flags & IFF_DRV_RUNNING) ||
 1752             !(sc->sc_flags & PFSYNCF_DEFER)) {
 1753                 PFSYNC_UNLOCK(sc);
 1754                 return (0);
 1755         }
 1756 
 1757         PFSYNC_BUCKET_LOCK(b);
 1758         PFSYNC_UNLOCK(sc);
 1759 
 1760         if (b->b_deferred >= 128)
 1761                 pfsync_undefer(TAILQ_FIRST(&b->b_deferrals), 0);
 1762 
 1763         pd = malloc(sizeof(*pd), M_PFSYNC, M_NOWAIT);
 1764         if (pd == NULL) {
 1765                 PFSYNC_BUCKET_UNLOCK(b);
 1766                 return (0);
 1767         }
 1768         b->b_deferred++;
 1769 
 1770         m->m_flags |= M_SKIP_FIREWALL;
 1771         st->state_flags |= PFSTATE_ACK;
 1772 
 1773         pd->pd_sc = sc;
 1774         pd->pd_refs = 0;
 1775         pd->pd_st = st;
 1776         pf_ref_state(st);
 1777         pd->pd_m = m;
 1778 
 1779         TAILQ_INSERT_TAIL(&b->b_deferrals, pd, pd_entry);
 1780         callout_init_mtx(&pd->pd_tmo, &b->b_mtx, CALLOUT_RETURNUNLOCKED);
 1781         callout_reset(&pd->pd_tmo, PFSYNC_DEFER_TIMEOUT, pfsync_defer_tmo, pd);
 1782 
 1783         pfsync_push(b);
 1784         PFSYNC_BUCKET_UNLOCK(b);
 1785 
 1786         return (1);
 1787 }
 1788 
 1789 static void
 1790 pfsync_undefer(struct pfsync_deferral *pd, int drop)
 1791 {
 1792         struct pfsync_softc *sc = pd->pd_sc;
 1793         struct mbuf *m = pd->pd_m;
 1794         struct pf_kstate *st = pd->pd_st;
 1795         struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
 1796 
 1797         PFSYNC_BUCKET_LOCK_ASSERT(b);
 1798 
 1799         TAILQ_REMOVE(&b->b_deferrals, pd, pd_entry);
 1800         b->b_deferred--;
 1801         pd->pd_st->state_flags &= ~PFSTATE_ACK; /* XXX: locking! */
 1802         free(pd, M_PFSYNC);
 1803         pf_release_state(st);
 1804 
 1805         if (drop)
 1806                 m_freem(m);
 1807         else {
 1808                 _IF_ENQUEUE(&b->b_snd, m);
 1809                 pfsync_push(b);
 1810         }
 1811 }
 1812 
 1813 static void
 1814 pfsync_defer_tmo(void *arg)
 1815 {
 1816         struct epoch_tracker et;
 1817         struct pfsync_deferral *pd = arg;
 1818         struct pfsync_softc *sc = pd->pd_sc;
 1819         struct mbuf *m = pd->pd_m;
 1820         struct pf_kstate *st = pd->pd_st;
 1821         struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
 1822 
 1823         PFSYNC_BUCKET_LOCK_ASSERT(b);
 1824 
 1825         if (sc->sc_sync_if == NULL)
 1826                 return;
 1827 
 1828         NET_EPOCH_ENTER(et);
 1829         CURVNET_SET(sc->sc_sync_if->if_vnet);
 1830 
 1831         TAILQ_REMOVE(&b->b_deferrals, pd, pd_entry);
 1832         b->b_deferred--;
 1833         pd->pd_st->state_flags &= ~PFSTATE_ACK; /* XXX: locking! */
 1834         if (pd->pd_refs == 0)
 1835                 free(pd, M_PFSYNC);
 1836         PFSYNC_BUCKET_UNLOCK(b);
 1837 
 1838         ip_output(m, NULL, NULL, 0, NULL, NULL);
 1839 
 1840         pf_release_state(st);
 1841 
 1842         CURVNET_RESTORE();
 1843         NET_EPOCH_EXIT(et);
 1844 }
 1845 
 1846 static void
 1847 pfsync_undefer_state(struct pf_kstate *st, int drop)
 1848 {
 1849         struct pfsync_softc *sc = V_pfsyncif;
 1850         struct pfsync_deferral *pd;
 1851         struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
 1852 
 1853         PFSYNC_BUCKET_LOCK(b);
 1854 
 1855         TAILQ_FOREACH(pd, &b->b_deferrals, pd_entry) {
 1856                  if (pd->pd_st == st) {
 1857                         if (callout_stop(&pd->pd_tmo) > 0)
 1858                                 pfsync_undefer(pd, drop);
 1859 
 1860                         PFSYNC_BUCKET_UNLOCK(b);
 1861                         return;
 1862                 }
 1863         }
 1864         PFSYNC_BUCKET_UNLOCK(b);
 1865 
 1866         panic("%s: unable to find deferred state", __func__);
 1867 }
 1868 
 1869 static struct pfsync_bucket*
 1870 pfsync_get_bucket(struct pfsync_softc *sc, struct pf_kstate *st)
 1871 {
 1872         int c = PF_IDHASH(st) % pfsync_buckets;
 1873         return &sc->sc_buckets[c];
 1874 }
 1875 
 1876 static void
 1877 pfsync_update_state(struct pf_kstate *st)
 1878 {
 1879         struct pfsync_softc *sc = V_pfsyncif;
 1880         bool sync = false, ref = true;
 1881         struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
 1882 
 1883         PF_STATE_LOCK_ASSERT(st);
 1884         PFSYNC_BUCKET_LOCK(b);
 1885 
 1886         if (st->state_flags & PFSTATE_ACK)
 1887                 pfsync_undefer_state(st, 0);
 1888         if (st->state_flags & PFSTATE_NOSYNC) {
 1889                 if (st->sync_state != PFSYNC_S_NONE)
 1890                         pfsync_q_del(st, true, b);
 1891                 PFSYNC_BUCKET_UNLOCK(b);
 1892                 return;
 1893         }
 1894 
 1895         if (b->b_len == PFSYNC_MINPKT)
 1896                 callout_reset(&b->b_tmo, 1 * hz, pfsync_timeout, b);
 1897 
 1898         switch (st->sync_state) {
 1899         case PFSYNC_S_UPD_C:
 1900         case PFSYNC_S_UPD:
 1901         case PFSYNC_S_INS:
 1902                 /* we're already handling it */
 1903 
 1904                 if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP) {
 1905                         st->sync_updates++;
 1906                         if (st->sync_updates >= sc->sc_maxupdates)
 1907                                 sync = true;
 1908                 }
 1909                 break;
 1910 
 1911         case PFSYNC_S_IACK:
 1912                 pfsync_q_del(st, false, b);
 1913                 ref = false;
 1914                 /* FALLTHROUGH */
 1915 
 1916         case PFSYNC_S_NONE:
 1917                 pfsync_q_ins(st, PFSYNC_S_UPD_C, ref);
 1918                 st->sync_updates = 0;
 1919                 break;
 1920 
 1921         default:
 1922                 panic("%s: unexpected sync state %d", __func__, st->sync_state);
 1923         }
 1924 
 1925         if (sync || (time_uptime - st->pfsync_time) < 2)
 1926                 pfsync_push(b);
 1927 
 1928         PFSYNC_BUCKET_UNLOCK(b);
 1929 }
 1930 
 1931 static void
 1932 pfsync_request_update(u_int32_t creatorid, u_int64_t id)
 1933 {
 1934         struct pfsync_softc *sc = V_pfsyncif;
 1935         struct pfsync_bucket *b = &sc->sc_buckets[0];
 1936         struct pfsync_upd_req_item *item;
 1937         size_t nlen = sizeof(struct pfsync_upd_req);
 1938 
 1939         PFSYNC_BUCKET_LOCK_ASSERT(b);
 1940 
 1941         /*
 1942          * This code does a bit to prevent multiple update requests for the
 1943          * same state being generated. It searches current subheader queue,
 1944          * but it doesn't lookup into queue of already packed datagrams.
 1945          */
 1946         TAILQ_FOREACH(item, &b->b_upd_req_list, ur_entry)
 1947                 if (item->ur_msg.id == id &&
 1948                     item->ur_msg.creatorid == creatorid)
 1949                         return;
 1950 
 1951         item = malloc(sizeof(*item), M_PFSYNC, M_NOWAIT);
 1952         if (item == NULL)
 1953                 return; /* XXX stats */
 1954 
 1955         item->ur_msg.id = id;
 1956         item->ur_msg.creatorid = creatorid;
 1957 
 1958         if (TAILQ_EMPTY(&b->b_upd_req_list))
 1959                 nlen += sizeof(struct pfsync_subheader);
 1960 
 1961         if (b->b_len + nlen > sc->sc_ifp->if_mtu) {
 1962                 pfsync_sendout(0, 0);
 1963 
 1964                 nlen = sizeof(struct pfsync_subheader) +
 1965                     sizeof(struct pfsync_upd_req);
 1966         }
 1967 
 1968         TAILQ_INSERT_TAIL(&b->b_upd_req_list, item, ur_entry);
 1969         b->b_len += nlen;
 1970 
 1971         pfsync_push(b);
 1972 }
 1973 
 1974 static bool
 1975 pfsync_update_state_req(struct pf_kstate *st)
 1976 {
 1977         struct pfsync_softc *sc = V_pfsyncif;
 1978         bool ref = true, full = false;
 1979         struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
 1980 
 1981         PF_STATE_LOCK_ASSERT(st);
 1982         PFSYNC_BUCKET_LOCK(b);
 1983 
 1984         if (st->state_flags & PFSTATE_NOSYNC) {
 1985                 if (st->sync_state != PFSYNC_S_NONE)
 1986                         pfsync_q_del(st, true, b);
 1987                 PFSYNC_BUCKET_UNLOCK(b);
 1988                 return (full);
 1989         }
 1990 
 1991         switch (st->sync_state) {
 1992         case PFSYNC_S_UPD_C:
 1993         case PFSYNC_S_IACK:
 1994                 pfsync_q_del(st, false, b);
 1995                 ref = false;
 1996                 /* FALLTHROUGH */
 1997 
 1998         case PFSYNC_S_NONE:
 1999                 pfsync_q_ins(st, PFSYNC_S_UPD, ref);
 2000                 pfsync_push(b);
 2001                 break;
 2002 
 2003         case PFSYNC_S_INS:
 2004         case PFSYNC_S_UPD:
 2005         case PFSYNC_S_DEL:
 2006                 /* we're already handling it */
 2007                 break;
 2008 
 2009         default:
 2010                 panic("%s: unexpected sync state %d", __func__, st->sync_state);
 2011         }
 2012 
 2013         if ((sc->sc_ifp->if_mtu - b->b_len) < sizeof(struct pfsync_state))
 2014                 full = true;
 2015 
 2016         PFSYNC_BUCKET_UNLOCK(b);
 2017 
 2018         return (full);
 2019 }
 2020 
 2021 static void
 2022 pfsync_delete_state(struct pf_kstate *st)
 2023 {
 2024         struct pfsync_softc *sc = V_pfsyncif;
 2025         struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
 2026         bool ref = true;
 2027 
 2028         PFSYNC_BUCKET_LOCK(b);
 2029         if (st->state_flags & PFSTATE_ACK)
 2030                 pfsync_undefer_state(st, 1);
 2031         if (st->state_flags & PFSTATE_NOSYNC) {
 2032                 if (st->sync_state != PFSYNC_S_NONE)
 2033                         pfsync_q_del(st, true, b);
 2034                 PFSYNC_BUCKET_UNLOCK(b);
 2035                 return;
 2036         }
 2037 
 2038         if (b->b_len == PFSYNC_MINPKT)
 2039                 callout_reset(&b->b_tmo, 1 * hz, pfsync_timeout, b);
 2040 
 2041         switch (st->sync_state) {
 2042         case PFSYNC_S_INS:
 2043                 /* We never got to tell the world so just forget about it. */
 2044                 pfsync_q_del(st, true, b);
 2045                 break;
 2046 
 2047         case PFSYNC_S_UPD_C:
 2048         case PFSYNC_S_UPD:
 2049         case PFSYNC_S_IACK:
 2050                 pfsync_q_del(st, false, b);
 2051                 ref = false;
 2052                 /* FALLTHROUGH */
 2053 
 2054         case PFSYNC_S_NONE:
 2055                 pfsync_q_ins(st, PFSYNC_S_DEL, ref);
 2056                 break;
 2057 
 2058         default:
 2059                 panic("%s: unexpected sync state %d", __func__, st->sync_state);
 2060         }
 2061 
 2062         PFSYNC_BUCKET_UNLOCK(b);
 2063 }
 2064 
 2065 static void
 2066 pfsync_clear_states(u_int32_t creatorid, const char *ifname)
 2067 {
 2068         struct {
 2069                 struct pfsync_subheader subh;
 2070                 struct pfsync_clr clr;
 2071         } __packed r;
 2072 
 2073         bzero(&r, sizeof(r));
 2074 
 2075         r.subh.action = PFSYNC_ACT_CLR;
 2076         r.subh.count = htons(1);
 2077         V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_CLR]++;
 2078 
 2079         strlcpy(r.clr.ifname, ifname, sizeof(r.clr.ifname));
 2080         r.clr.creatorid = creatorid;
 2081 
 2082         pfsync_send_plus(&r, sizeof(r));
 2083 }
 2084 
 2085 static void
 2086 pfsync_q_ins(struct pf_kstate *st, int q, bool ref)
 2087 {
 2088         struct pfsync_softc *sc = V_pfsyncif;
 2089         size_t nlen = pfsync_qs[q].len;
 2090         struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
 2091 
 2092         PFSYNC_BUCKET_LOCK_ASSERT(b);
 2093 
 2094         KASSERT(st->sync_state == PFSYNC_S_NONE,
 2095                 ("%s: st->sync_state %u", __func__, st->sync_state));
 2096         KASSERT(b->b_len >= PFSYNC_MINPKT, ("pfsync pkt len is too low %zu",
 2097             b->b_len));
 2098 
 2099         if (TAILQ_EMPTY(&b->b_qs[q]))
 2100                 nlen += sizeof(struct pfsync_subheader);
 2101 
 2102         if (b->b_len + nlen > sc->sc_ifp->if_mtu) {
 2103                 pfsync_sendout(1, b->b_id);
 2104 
 2105                 nlen = sizeof(struct pfsync_subheader) + pfsync_qs[q].len;
 2106         }
 2107 
 2108         b->b_len += nlen;
 2109         TAILQ_INSERT_TAIL(&b->b_qs[q], st, sync_list);
 2110         st->sync_state = q;
 2111         if (ref)
 2112                 pf_ref_state(st);
 2113 }
 2114 
 2115 static void
 2116 pfsync_q_del(struct pf_kstate *st, bool unref, struct pfsync_bucket *b)
 2117 {
 2118         int q = st->sync_state;
 2119 
 2120         PFSYNC_BUCKET_LOCK_ASSERT(b);
 2121         KASSERT(st->sync_state != PFSYNC_S_NONE,
 2122                 ("%s: st->sync_state != PFSYNC_S_NONE", __func__));
 2123 
 2124         b->b_len -= pfsync_qs[q].len;
 2125         TAILQ_REMOVE(&b->b_qs[q], st, sync_list);
 2126         st->sync_state = PFSYNC_S_NONE;
 2127         if (unref)
 2128                 pf_release_state(st);
 2129 
 2130         if (TAILQ_EMPTY(&b->b_qs[q]))
 2131                 b->b_len -= sizeof(struct pfsync_subheader);
 2132 }
 2133 
 2134 static void
 2135 pfsync_bulk_start(void)
 2136 {
 2137         struct pfsync_softc *sc = V_pfsyncif;
 2138 
 2139         if (V_pf_status.debug >= PF_DEBUG_MISC)
 2140                 printf("pfsync: received bulk update request\n");
 2141 
 2142         PFSYNC_BLOCK(sc);
 2143 
 2144         sc->sc_ureq_received = time_uptime;
 2145         sc->sc_bulk_hashid = 0;
 2146         sc->sc_bulk_stateid = 0;
 2147         pfsync_bulk_status(PFSYNC_BUS_START);
 2148         callout_reset(&sc->sc_bulk_tmo, 1, pfsync_bulk_update, sc);
 2149         PFSYNC_BUNLOCK(sc);
 2150 }
 2151 
 2152 static void
 2153 pfsync_bulk_update(void *arg)
 2154 {
 2155         struct pfsync_softc *sc = arg;
 2156         struct pf_kstate *s;
 2157         int i;
 2158 
 2159         PFSYNC_BLOCK_ASSERT(sc);
 2160         CURVNET_SET(sc->sc_ifp->if_vnet);
 2161 
 2162         /*
 2163          * Start with last state from previous invocation.
 2164          * It may had gone, in this case start from the
 2165          * hash slot.
 2166          */
 2167         s = pf_find_state_byid(sc->sc_bulk_stateid, sc->sc_bulk_creatorid);
 2168 
 2169         if (s != NULL)
 2170                 i = PF_IDHASH(s);
 2171         else
 2172                 i = sc->sc_bulk_hashid;
 2173 
 2174         for (; i <= pf_hashmask; i++) {
 2175                 struct pf_idhash *ih = &V_pf_idhash[i];
 2176 
 2177                 if (s != NULL)
 2178                         PF_HASHROW_ASSERT(ih);
 2179                 else {
 2180                         PF_HASHROW_LOCK(ih);
 2181                         s = LIST_FIRST(&ih->states);
 2182                 }
 2183 
 2184                 for (; s; s = LIST_NEXT(s, entry)) {
 2185                         if (s->sync_state == PFSYNC_S_NONE &&
 2186                             s->timeout < PFTM_MAX &&
 2187                             s->pfsync_time <= sc->sc_ureq_received) {
 2188                                 if (pfsync_update_state_req(s)) {
 2189                                         /* We've filled a packet. */
 2190                                         sc->sc_bulk_hashid = i;
 2191                                         sc->sc_bulk_stateid = s->id;
 2192                                         sc->sc_bulk_creatorid = s->creatorid;
 2193                                         PF_HASHROW_UNLOCK(ih);
 2194                                         callout_reset(&sc->sc_bulk_tmo, 1,
 2195                                             pfsync_bulk_update, sc);
 2196                                         goto full;
 2197                                 }
 2198                         }
 2199                 }
 2200                 PF_HASHROW_UNLOCK(ih);
 2201         }
 2202 
 2203         /* We're done. */
 2204         pfsync_bulk_status(PFSYNC_BUS_END);
 2205 full:
 2206         CURVNET_RESTORE();
 2207 }
 2208 
 2209 static void
 2210 pfsync_bulk_status(u_int8_t status)
 2211 {
 2212         struct {
 2213                 struct pfsync_subheader subh;
 2214                 struct pfsync_bus bus;
 2215         } __packed r;
 2216 
 2217         struct pfsync_softc *sc = V_pfsyncif;
 2218 
 2219         bzero(&r, sizeof(r));
 2220 
 2221         r.subh.action = PFSYNC_ACT_BUS;
 2222         r.subh.count = htons(1);
 2223         V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_BUS]++;
 2224 
 2225         r.bus.creatorid = V_pf_status.hostid;
 2226         r.bus.endtime = htonl(time_uptime - sc->sc_ureq_received);
 2227         r.bus.status = status;
 2228 
 2229         pfsync_send_plus(&r, sizeof(r));
 2230 }
 2231 
 2232 static void
 2233 pfsync_bulk_fail(void *arg)
 2234 {
 2235         struct pfsync_softc *sc = arg;
 2236         struct pfsync_bucket *b = &sc->sc_buckets[0];
 2237 
 2238         CURVNET_SET(sc->sc_ifp->if_vnet);
 2239 
 2240         PFSYNC_BLOCK_ASSERT(sc);
 2241 
 2242         if (sc->sc_bulk_tries++ < PFSYNC_MAX_BULKTRIES) {
 2243                 /* Try again */
 2244                 callout_reset(&sc->sc_bulkfail_tmo, 5 * hz,
 2245                     pfsync_bulk_fail, V_pfsyncif);
 2246                 PFSYNC_BUCKET_LOCK(b);
 2247                 pfsync_request_update(0, 0);
 2248                 PFSYNC_BUCKET_UNLOCK(b);
 2249         } else {
 2250                 /* Pretend like the transfer was ok. */
 2251                 sc->sc_ureq_sent = 0;
 2252                 sc->sc_bulk_tries = 0;
 2253                 PFSYNC_LOCK(sc);
 2254                 if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
 2255                         (*carp_demote_adj_p)(-V_pfsync_carp_adj,
 2256                             "pfsync bulk fail");
 2257                 sc->sc_flags |= PFSYNCF_OK;
 2258                 PFSYNC_UNLOCK(sc);
 2259                 if (V_pf_status.debug >= PF_DEBUG_MISC)
 2260                         printf("pfsync: failed to receive bulk update\n");
 2261         }
 2262 
 2263         CURVNET_RESTORE();
 2264 }
 2265 
 2266 static void
 2267 pfsync_send_plus(void *plus, size_t pluslen)
 2268 {
 2269         struct pfsync_softc *sc = V_pfsyncif;
 2270         struct pfsync_bucket *b = &sc->sc_buckets[0];
 2271 
 2272         PFSYNC_BUCKET_LOCK(b);
 2273 
 2274         if (b->b_len + pluslen > sc->sc_ifp->if_mtu)
 2275                 pfsync_sendout(1, b->b_id);
 2276 
 2277         b->b_plus = plus;
 2278         b->b_len += (b->b_pluslen = pluslen);
 2279 
 2280         pfsync_sendout(1, b->b_id);
 2281         PFSYNC_BUCKET_UNLOCK(b);
 2282 }
 2283 
 2284 static void
 2285 pfsync_timeout(void *arg)
 2286 {
 2287         struct pfsync_bucket *b = arg;
 2288 
 2289         CURVNET_SET(b->b_sc->sc_ifp->if_vnet);
 2290         PFSYNC_BUCKET_LOCK(b);
 2291         pfsync_push(b);
 2292         PFSYNC_BUCKET_UNLOCK(b);
 2293         CURVNET_RESTORE();
 2294 }
 2295 
 2296 static void
 2297 pfsync_push(struct pfsync_bucket *b)
 2298 {
 2299 
 2300         PFSYNC_BUCKET_LOCK_ASSERT(b);
 2301 
 2302         b->b_flags |= PFSYNCF_BUCKET_PUSH;
 2303         swi_sched(V_pfsync_swi_cookie, 0);
 2304 }
 2305 
 2306 static void
 2307 pfsync_push_all(struct pfsync_softc *sc)
 2308 {
 2309         int c;
 2310         struct pfsync_bucket *b;
 2311 
 2312         for (c = 0; c < pfsync_buckets; c++) {
 2313                 b = &sc->sc_buckets[c];
 2314 
 2315                 PFSYNC_BUCKET_LOCK(b);
 2316                 pfsync_push(b);
 2317                 PFSYNC_BUCKET_UNLOCK(b);
 2318         }
 2319 }
 2320 
 2321 static void
 2322 pfsyncintr(void *arg)
 2323 {
 2324         struct epoch_tracker et;
 2325         struct pfsync_softc *sc = arg;
 2326         struct pfsync_bucket *b;
 2327         struct mbuf *m, *n;
 2328         int c;
 2329 
 2330         NET_EPOCH_ENTER(et);
 2331         CURVNET_SET(sc->sc_ifp->if_vnet);
 2332 
 2333         for (c = 0; c < pfsync_buckets; c++) {
 2334                 b = &sc->sc_buckets[c];
 2335 
 2336                 PFSYNC_BUCKET_LOCK(b);
 2337                 if ((b->b_flags & PFSYNCF_BUCKET_PUSH) && b->b_len > PFSYNC_MINPKT) {
 2338                         pfsync_sendout(0, b->b_id);
 2339                         b->b_flags &= ~PFSYNCF_BUCKET_PUSH;
 2340                 }
 2341                 _IF_DEQUEUE_ALL(&b->b_snd, m);
 2342                 PFSYNC_BUCKET_UNLOCK(b);
 2343 
 2344                 for (; m != NULL; m = n) {
 2345                         n = m->m_nextpkt;
 2346                         m->m_nextpkt = NULL;
 2347 
 2348                         /*
 2349                          * We distinguish between a deferral packet and our
 2350                          * own pfsync packet based on M_SKIP_FIREWALL
 2351                          * flag. This is XXX.
 2352                          */
 2353                         if (m->m_flags & M_SKIP_FIREWALL)
 2354                                 ip_output(m, NULL, NULL, 0, NULL, NULL);
 2355                         else if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo,
 2356                             NULL) == 0)
 2357                                 V_pfsyncstats.pfsyncs_opackets++;
 2358                         else
 2359                                 V_pfsyncstats.pfsyncs_oerrors++;
 2360                 }
 2361         }
 2362         CURVNET_RESTORE();
 2363         NET_EPOCH_EXIT(et);
 2364 }
 2365 
 2366 static int
 2367 pfsync_multicast_setup(struct pfsync_softc *sc, struct ifnet *ifp,
 2368     struct in_mfilter *imf)
 2369 {
 2370         struct ip_moptions *imo = &sc->sc_imo;
 2371         int error;
 2372 
 2373         if (!(ifp->if_flags & IFF_MULTICAST))
 2374                 return (EADDRNOTAVAIL);
 2375 
 2376         imo->imo_multicast_vif = -1;
 2377 
 2378         if ((error = in_joingroup(ifp, &sc->sc_sync_peer, NULL,
 2379             &imf->imf_inm)) != 0)
 2380                 return (error);
 2381 
 2382         ip_mfilter_init(&imo->imo_head);
 2383         ip_mfilter_insert(&imo->imo_head, imf);
 2384         imo->imo_multicast_ifp = ifp;
 2385         imo->imo_multicast_ttl = PFSYNC_DFLTTL;
 2386         imo->imo_multicast_loop = 0;
 2387 
 2388         return (0);
 2389 }
 2390 
 2391 static void
 2392 pfsync_multicast_cleanup(struct pfsync_softc *sc)
 2393 {
 2394         struct ip_moptions *imo = &sc->sc_imo;
 2395         struct in_mfilter *imf;
 2396 
 2397         while ((imf = ip_mfilter_first(&imo->imo_head)) != NULL) {
 2398                 ip_mfilter_remove(&imo->imo_head, imf);
 2399                 in_leavegroup(imf->imf_inm, NULL);
 2400                 ip_mfilter_free(imf);
 2401         }
 2402         imo->imo_multicast_ifp = NULL;
 2403 }
 2404 
 2405 void
 2406 pfsync_detach_ifnet(struct ifnet *ifp)
 2407 {
 2408         struct pfsync_softc *sc = V_pfsyncif;
 2409 
 2410         if (sc == NULL)
 2411                 return;
 2412 
 2413         PFSYNC_LOCK(sc);
 2414 
 2415         if (sc->sc_sync_if == ifp) {
 2416                 /* We don't need mutlicast cleanup here, because the interface
 2417                  * is going away. We do need to ensure we don't try to do
 2418                  * cleanup later.
 2419                  */
 2420                 ip_mfilter_init(&sc->sc_imo.imo_head);
 2421                 sc->sc_imo.imo_multicast_ifp = NULL;
 2422                 sc->sc_sync_if = NULL;
 2423         }
 2424 
 2425         PFSYNC_UNLOCK(sc);
 2426 }
 2427 
 2428 #ifdef INET
 2429 extern  struct domain inetdomain;
 2430 static struct protosw in_pfsync_protosw = {
 2431         .pr_type =              SOCK_RAW,
 2432         .pr_domain =            &inetdomain,
 2433         .pr_protocol =          IPPROTO_PFSYNC,
 2434         .pr_flags =             PR_ATOMIC|PR_ADDR,
 2435         .pr_input =             pfsync_input,
 2436         .pr_output =            rip_output,
 2437         .pr_ctloutput =         rip_ctloutput,
 2438         .pr_usrreqs =           &rip_usrreqs
 2439 };
 2440 #endif
 2441 
 2442 static void
 2443 pfsync_pointers_init(void)
 2444 {
 2445 
 2446         PF_RULES_WLOCK();
 2447         V_pfsync_state_import_ptr = pfsync_state_import;
 2448         V_pfsync_insert_state_ptr = pfsync_insert_state;
 2449         V_pfsync_update_state_ptr = pfsync_update_state;
 2450         V_pfsync_delete_state_ptr = pfsync_delete_state;
 2451         V_pfsync_clear_states_ptr = pfsync_clear_states;
 2452         V_pfsync_defer_ptr = pfsync_defer;
 2453         PF_RULES_WUNLOCK();
 2454 }
 2455 
 2456 static void
 2457 pfsync_pointers_uninit(void)
 2458 {
 2459 
 2460         PF_RULES_WLOCK();
 2461         V_pfsync_state_import_ptr = NULL;
 2462         V_pfsync_insert_state_ptr = NULL;
 2463         V_pfsync_update_state_ptr = NULL;
 2464         V_pfsync_delete_state_ptr = NULL;
 2465         V_pfsync_clear_states_ptr = NULL;
 2466         V_pfsync_defer_ptr = NULL;
 2467         PF_RULES_WUNLOCK();
 2468 }
 2469 
 2470 static void
 2471 vnet_pfsync_init(const void *unused __unused)
 2472 {
 2473         int error;
 2474 
 2475         V_pfsync_cloner = if_clone_simple(pfsyncname,
 2476             pfsync_clone_create, pfsync_clone_destroy, 1);
 2477         error = swi_add(&V_pfsync_swi_ie, pfsyncname, pfsyncintr, V_pfsyncif,
 2478             SWI_NET, INTR_MPSAFE, &V_pfsync_swi_cookie);
 2479         if (error) {
 2480                 if_clone_detach(V_pfsync_cloner);
 2481                 log(LOG_INFO, "swi_add() failed in %s\n", __func__);
 2482         }
 2483 
 2484         pfsync_pointers_init();
 2485 }
 2486 VNET_SYSINIT(vnet_pfsync_init, SI_SUB_PROTO_FIREWALL, SI_ORDER_ANY,
 2487     vnet_pfsync_init, NULL);
 2488 
 2489 static void
 2490 vnet_pfsync_uninit(const void *unused __unused)
 2491 {
 2492         int ret;
 2493 
 2494         pfsync_pointers_uninit();
 2495 
 2496         if_clone_detach(V_pfsync_cloner);
 2497         ret = swi_remove(V_pfsync_swi_cookie);
 2498         MPASS(ret == 0);
 2499         ret = intr_event_destroy(V_pfsync_swi_ie);
 2500         MPASS(ret == 0);
 2501 }
 2502 
 2503 VNET_SYSUNINIT(vnet_pfsync_uninit, SI_SUB_PROTO_FIREWALL, SI_ORDER_FOURTH,
 2504     vnet_pfsync_uninit, NULL);
 2505 
 2506 static int
 2507 pfsync_init(void)
 2508 {
 2509 #ifdef INET
 2510         int error;
 2511 
 2512         pfsync_detach_ifnet_ptr = pfsync_detach_ifnet;
 2513 
 2514         error = pf_proto_register(PF_INET, &in_pfsync_protosw);
 2515         if (error)
 2516                 return (error);
 2517         error = ipproto_register(IPPROTO_PFSYNC);
 2518         if (error) {
 2519                 pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
 2520                 return (error);
 2521         }
 2522 #endif
 2523 
 2524         return (0);
 2525 }
 2526 
 2527 static void
 2528 pfsync_uninit(void)
 2529 {
 2530         pfsync_detach_ifnet_ptr = NULL;
 2531 
 2532 #ifdef INET
 2533         ipproto_unregister(IPPROTO_PFSYNC);
 2534         pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
 2535 #endif
 2536 }
 2537 
 2538 static int
 2539 pfsync_modevent(module_t mod, int type, void *data)
 2540 {
 2541         int error = 0;
 2542 
 2543         switch (type) {
 2544         case MOD_LOAD:
 2545                 error = pfsync_init();
 2546                 break;
 2547         case MOD_UNLOAD:
 2548                 pfsync_uninit();
 2549                 break;
 2550         default:
 2551                 error = EINVAL;
 2552                 break;
 2553         }
 2554 
 2555         return (error);
 2556 }
 2557 
 2558 static moduledata_t pfsync_mod = {
 2559         pfsyncname,
 2560         pfsync_modevent,
 2561         0
 2562 };
 2563 
 2564 #define PFSYNC_MODVER 1
 2565 
 2566 /* Stay on FIREWALL as we depend on pf being initialized and on inetdomain. */
 2567 DECLARE_MODULE(pfsync, pfsync_mod, SI_SUB_PROTO_FIREWALL, SI_ORDER_ANY);
 2568 MODULE_VERSION(pfsync, PFSYNC_MODVER);
 2569 MODULE_DEPEND(pfsync, pf, PF_MODVER, PF_MODVER, PF_MODVER);

Cache object: ef01d1022bac4f44b9c7f02e93835bad


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.