Rename nbs/nbr port names to nbsp/nbrp.
[cascardo/ovs.git] / ovn / northd / ovn-northd.c
1 /*
2  * Licensed under the Apache License, Version 2.0 (the "License");
3  * you may not use this file except in compliance with the License.
4  * You may obtain a copy of the License at:
5  *
6  *     http://www.apache.org/licenses/LICENSE-2.0
7  *
8  * Unless required by applicable law or agreed to in writing, software
9  * distributed under the License is distributed on an "AS IS" BASIS,
10  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  * See the License for the specific language governing permissions and
12  * limitations under the License.
13  */
14
15 #include <config.h>
16
17 #include <getopt.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20
21 #include "command-line.h"
22 #include "daemon.h"
23 #include "dirs.h"
24 #include "openvswitch/dynamic-string.h"
25 #include "fatal-signal.h"
26 #include "hash.h"
27 #include "hmap.h"
28 #include "json.h"
29 #include "ovn/lib/lex.h"
30 #include "ovn/lib/ovn-nb-idl.h"
31 #include "ovn/lib/ovn-sb-idl.h"
32 #include "ovn/lib/ovn-util.h"
33 #include "packets.h"
34 #include "poll-loop.h"
35 #include "smap.h"
36 #include "sset.h"
37 #include "stream.h"
38 #include "stream-ssl.h"
39 #include "unixctl.h"
40 #include "util.h"
41 #include "uuid.h"
42 #include "openvswitch/vlog.h"
43
44 VLOG_DEFINE_THIS_MODULE(ovn_northd);
45
46 static unixctl_cb_func ovn_northd_exit;
47
48 struct northd_context {
49     struct ovsdb_idl *ovnnb_idl;
50     struct ovsdb_idl *ovnsb_idl;
51     struct ovsdb_idl_txn *ovnnb_txn;
52     struct ovsdb_idl_txn *ovnsb_txn;
53 };
54
55 static const char *ovnnb_db;
56 static const char *ovnsb_db;
57
58 static const char *default_nb_db(void);
59 static const char *default_sb_db(void);
60 \f
61 /* Pipeline stages. */
62
63 /* The two pipelines in an OVN logical flow table. */
64 enum ovn_pipeline {
65     P_IN,                       /* Ingress pipeline. */
66     P_OUT                       /* Egress pipeline. */
67 };
68
69 /* The two purposes for which ovn-northd uses OVN logical datapaths. */
70 enum ovn_datapath_type {
71     DP_SWITCH,                  /* OVN logical switch. */
72     DP_ROUTER                   /* OVN logical router. */
73 };
74
75 /* Returns an "enum ovn_stage" built from the arguments.
76  *
77  * (It's better to use ovn_stage_build() for type-safety reasons, but inline
78  * functions can't be used in enums or switch cases.) */
79 #define OVN_STAGE_BUILD(DP_TYPE, PIPELINE, TABLE) \
80     (((DP_TYPE) << 9) | ((PIPELINE) << 8) | (TABLE))
81
82 /* A stage within an OVN logical switch or router.
83  *
84  * An "enum ovn_stage" indicates whether the stage is part of a logical switch
85  * or router, whether the stage is part of the ingress or egress pipeline, and
86  * the table within that pipeline.  The first three components are combined to
87  * form the stage's full name, e.g. S_SWITCH_IN_PORT_SEC_L2,
88  * S_ROUTER_OUT_DELIVERY. */
89 enum ovn_stage {
90 #define PIPELINE_STAGES                                               \
91     /* Logical switch ingress stages. */                              \
92     PIPELINE_STAGE(SWITCH, IN,  PORT_SEC_L2,    0, "ls_in_port_sec_l2")     \
93     PIPELINE_STAGE(SWITCH, IN,  PORT_SEC_IP,    1, "ls_in_port_sec_ip")     \
94     PIPELINE_STAGE(SWITCH, IN,  PORT_SEC_ND,    2, "ls_in_port_sec_nd")     \
95     PIPELINE_STAGE(SWITCH, IN,  PRE_ACL,        3, "ls_in_pre_acl")      \
96     PIPELINE_STAGE(SWITCH, IN,  PRE_LB,         4, "ls_in_pre_lb")         \
97     PIPELINE_STAGE(SWITCH, IN,  PRE_STATEFUL,   5, "ls_in_pre_stateful")    \
98     PIPELINE_STAGE(SWITCH, IN,  ACL,            6, "ls_in_acl")          \
99     PIPELINE_STAGE(SWITCH, IN,  LB,             7, "ls_in_lb")           \
100     PIPELINE_STAGE(SWITCH, IN,  STATEFUL,       8, "ls_in_stateful")     \
101     PIPELINE_STAGE(SWITCH, IN,  ARP_ND_RSP,     9, "ls_in_arp_rsp")      \
102     PIPELINE_STAGE(SWITCH, IN,  L2_LKUP,       10, "ls_in_l2_lkup")      \
103                                                                       \
104     /* Logical switch egress stages. */                               \
105     PIPELINE_STAGE(SWITCH, OUT, PRE_LB,       0, "ls_out_pre_lb")     \
106     PIPELINE_STAGE(SWITCH, OUT, PRE_ACL,      1, "ls_out_pre_acl")     \
107     PIPELINE_STAGE(SWITCH, OUT, PRE_STATEFUL, 2, "ls_out_pre_stateful")  \
108     PIPELINE_STAGE(SWITCH, OUT, LB,           3, "ls_out_lb")            \
109     PIPELINE_STAGE(SWITCH, OUT, ACL,          4, "ls_out_acl")            \
110     PIPELINE_STAGE(SWITCH, OUT, STATEFUL,     5, "ls_out_stateful")       \
111     PIPELINE_STAGE(SWITCH, OUT, PORT_SEC_IP,  6, "ls_out_port_sec_ip")    \
112     PIPELINE_STAGE(SWITCH, OUT, PORT_SEC_L2,  7, "ls_out_port_sec_l2")    \
113                                                                       \
114     /* Logical router ingress stages. */                              \
115     PIPELINE_STAGE(ROUTER, IN,  ADMISSION,   0, "lr_in_admission")    \
116     PIPELINE_STAGE(ROUTER, IN,  IP_INPUT,    1, "lr_in_ip_input")     \
117     PIPELINE_STAGE(ROUTER, IN,  UNSNAT,      2, "lr_in_unsnat")       \
118     PIPELINE_STAGE(ROUTER, IN,  DNAT,        3, "lr_in_dnat")         \
119     PIPELINE_STAGE(ROUTER, IN,  IP_ROUTING,  4, "lr_in_ip_routing")   \
120     PIPELINE_STAGE(ROUTER, IN,  ARP_RESOLVE, 5, "lr_in_arp_resolve")  \
121     PIPELINE_STAGE(ROUTER, IN,  ARP_REQUEST, 6, "lr_in_arp_request")  \
122                                                                       \
123     /* Logical router egress stages. */                               \
124     PIPELINE_STAGE(ROUTER, OUT, SNAT,      0, "lr_out_snat")          \
125     PIPELINE_STAGE(ROUTER, OUT, DELIVERY,  1, "lr_out_delivery")
126
127 #define PIPELINE_STAGE(DP_TYPE, PIPELINE, STAGE, TABLE, NAME)   \
128     S_##DP_TYPE##_##PIPELINE##_##STAGE                          \
129         = OVN_STAGE_BUILD(DP_##DP_TYPE, P_##PIPELINE, TABLE),
130     PIPELINE_STAGES
131 #undef PIPELINE_STAGE
132 };
133
134 /* Due to various hard-coded priorities need to implement ACLs, the
135  * northbound database supports a smaller range of ACL priorities than
136  * are available to logical flows.  This value is added to an ACL
137  * priority to determine the ACL's logical flow priority. */
138 #define OVN_ACL_PRI_OFFSET 1000
139
140 #define REGBIT_CONNTRACK_DEFRAG "reg0[0]"
141 #define REGBIT_CONNTRACK_COMMIT "reg0[1]"
142 #define REGBIT_CONNTRACK_NAT    "reg0[2]"
143
144 /* Returns an "enum ovn_stage" built from the arguments. */
145 static enum ovn_stage
146 ovn_stage_build(enum ovn_datapath_type dp_type, enum ovn_pipeline pipeline,
147                 uint8_t table)
148 {
149     return OVN_STAGE_BUILD(dp_type, pipeline, table);
150 }
151
152 /* Returns the pipeline to which 'stage' belongs. */
153 static enum ovn_pipeline
154 ovn_stage_get_pipeline(enum ovn_stage stage)
155 {
156     return (stage >> 8) & 1;
157 }
158
159 /* Returns the table to which 'stage' belongs. */
160 static uint8_t
161 ovn_stage_get_table(enum ovn_stage stage)
162 {
163     return stage & 0xff;
164 }
165
166 /* Returns a string name for 'stage'. */
167 static const char *
168 ovn_stage_to_str(enum ovn_stage stage)
169 {
170     switch (stage) {
171 #define PIPELINE_STAGE(DP_TYPE, PIPELINE, STAGE, TABLE, NAME)       \
172         case S_##DP_TYPE##_##PIPELINE##_##STAGE: return NAME;
173     PIPELINE_STAGES
174 #undef PIPELINE_STAGE
175         default: return "<unknown>";
176     }
177 }
178
179 /* Returns the type of the datapath to which a flow with the given 'stage' may
180  * be added. */
181 static enum ovn_datapath_type
182 ovn_stage_to_datapath_type(enum ovn_stage stage)
183 {
184     switch (stage) {
185 #define PIPELINE_STAGE(DP_TYPE, PIPELINE, STAGE, TABLE, NAME)       \
186         case S_##DP_TYPE##_##PIPELINE##_##STAGE: return DP_##DP_TYPE;
187     PIPELINE_STAGES
188 #undef PIPELINE_STAGE
189     default: OVS_NOT_REACHED();
190     }
191 }
192 \f
193 static void
194 usage(void)
195 {
196     printf("\
197 %s: OVN northbound management daemon\n\
198 usage: %s [OPTIONS]\n\
199 \n\
200 Options:\n\
201   --ovnnb-db=DATABASE       connect to ovn-nb database at DATABASE\n\
202                             (default: %s)\n\
203   --ovnsb-db=DATABASE       connect to ovn-sb database at DATABASE\n\
204                             (default: %s)\n\
205   -h, --help                display this help message\n\
206   -o, --options             list available options\n\
207   -V, --version             display version information\n\
208 ", program_name, program_name, default_nb_db(), default_sb_db());
209     daemon_usage();
210     vlog_usage();
211     stream_usage("database", true, true, false);
212 }
213 \f
214 struct tnlid_node {
215     struct hmap_node hmap_node;
216     uint32_t tnlid;
217 };
218
219 static void
220 destroy_tnlids(struct hmap *tnlids)
221 {
222     struct tnlid_node *node;
223     HMAP_FOR_EACH_POP (node, hmap_node, tnlids) {
224         free(node);
225     }
226     hmap_destroy(tnlids);
227 }
228
229 static void
230 add_tnlid(struct hmap *set, uint32_t tnlid)
231 {
232     struct tnlid_node *node = xmalloc(sizeof *node);
233     hmap_insert(set, &node->hmap_node, hash_int(tnlid, 0));
234     node->tnlid = tnlid;
235 }
236
237 static bool
238 tnlid_in_use(const struct hmap *set, uint32_t tnlid)
239 {
240     const struct tnlid_node *node;
241     HMAP_FOR_EACH_IN_BUCKET (node, hmap_node, hash_int(tnlid, 0), set) {
242         if (node->tnlid == tnlid) {
243             return true;
244         }
245     }
246     return false;
247 }
248
249 static uint32_t
250 allocate_tnlid(struct hmap *set, const char *name, uint32_t max,
251                uint32_t *hint)
252 {
253     for (uint32_t tnlid = *hint + 1; tnlid != *hint;
254          tnlid = tnlid + 1 <= max ? tnlid + 1 : 1) {
255         if (!tnlid_in_use(set, tnlid)) {
256             add_tnlid(set, tnlid);
257             *hint = tnlid;
258             return tnlid;
259         }
260     }
261
262     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
263     VLOG_WARN_RL(&rl, "all %s tunnel ids exhausted", name);
264     return 0;
265 }
266 \f
267 /* The 'key' comes from nbs->header_.uuid or nbr->header_.uuid or
268  * sb->external_ids:logical-switch. */
269 struct ovn_datapath {
270     struct hmap_node key_node;  /* Index on 'key'. */
271     struct uuid key;            /* (nbs/nbr)->header_.uuid. */
272
273     const struct nbrec_logical_switch *nbs;  /* May be NULL. */
274     const struct nbrec_logical_router *nbr;  /* May be NULL. */
275     const struct sbrec_datapath_binding *sb; /* May be NULL. */
276
277     struct ovs_list list;       /* In list of similar records. */
278
279     /* Logical switch data. */
280     struct ovn_port **router_ports;
281     size_t n_router_ports;
282
283     struct hmap port_tnlids;
284     uint32_t port_key_hint;
285
286     bool has_unknown;
287 };
288
289 static struct ovn_datapath *
290 ovn_datapath_create(struct hmap *datapaths, const struct uuid *key,
291                     const struct nbrec_logical_switch *nbs,
292                     const struct nbrec_logical_router *nbr,
293                     const struct sbrec_datapath_binding *sb)
294 {
295     struct ovn_datapath *od = xzalloc(sizeof *od);
296     od->key = *key;
297     od->sb = sb;
298     od->nbs = nbs;
299     od->nbr = nbr;
300     hmap_init(&od->port_tnlids);
301     od->port_key_hint = 0;
302     hmap_insert(datapaths, &od->key_node, uuid_hash(&od->key));
303     return od;
304 }
305
306 static void
307 ovn_datapath_destroy(struct hmap *datapaths, struct ovn_datapath *od)
308 {
309     if (od) {
310         /* Don't remove od->list.  It is used within build_datapaths() as a
311          * private list and once we've exited that function it is not safe to
312          * use it. */
313         hmap_remove(datapaths, &od->key_node);
314         destroy_tnlids(&od->port_tnlids);
315         free(od->router_ports);
316         free(od);
317     }
318 }
319
320 /* Returns 'od''s datapath type. */
321 static enum ovn_datapath_type
322 ovn_datapath_get_type(const struct ovn_datapath *od)
323 {
324     return od->nbs ? DP_SWITCH : DP_ROUTER;
325 }
326
327 static struct ovn_datapath *
328 ovn_datapath_find(struct hmap *datapaths, const struct uuid *uuid)
329 {
330     struct ovn_datapath *od;
331
332     HMAP_FOR_EACH_WITH_HASH (od, key_node, uuid_hash(uuid), datapaths) {
333         if (uuid_equals(uuid, &od->key)) {
334             return od;
335         }
336     }
337     return NULL;
338 }
339
340 static struct ovn_datapath *
341 ovn_datapath_from_sbrec(struct hmap *datapaths,
342                         const struct sbrec_datapath_binding *sb)
343 {
344     struct uuid key;
345
346     if (!smap_get_uuid(&sb->external_ids, "logical-switch", &key) &&
347         !smap_get_uuid(&sb->external_ids, "logical-router", &key)) {
348         return NULL;
349     }
350     return ovn_datapath_find(datapaths, &key);
351 }
352
353 static bool
354 lrouter_is_enabled(const struct nbrec_logical_router *lrouter)
355 {
356     return !lrouter->enabled || *lrouter->enabled;
357 }
358
359 static void
360 join_datapaths(struct northd_context *ctx, struct hmap *datapaths,
361                struct ovs_list *sb_only, struct ovs_list *nb_only,
362                struct ovs_list *both)
363 {
364     hmap_init(datapaths);
365     ovs_list_init(sb_only);
366     ovs_list_init(nb_only);
367     ovs_list_init(both);
368
369     const struct sbrec_datapath_binding *sb, *sb_next;
370     SBREC_DATAPATH_BINDING_FOR_EACH_SAFE (sb, sb_next, ctx->ovnsb_idl) {
371         struct uuid key;
372         if (!smap_get_uuid(&sb->external_ids, "logical-switch", &key) &&
373             !smap_get_uuid(&sb->external_ids, "logical-router", &key)) {
374             ovsdb_idl_txn_add_comment(
375                 ctx->ovnsb_txn,
376                 "deleting Datapath_Binding "UUID_FMT" that lacks "
377                 "external-ids:logical-switch and "
378                 "external-ids:logical-router",
379                 UUID_ARGS(&sb->header_.uuid));
380             sbrec_datapath_binding_delete(sb);
381             continue;
382         }
383
384         if (ovn_datapath_find(datapaths, &key)) {
385             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
386             VLOG_INFO_RL(
387                 &rl, "deleting Datapath_Binding "UUID_FMT" with "
388                 "duplicate external-ids:logical-switch/router "UUID_FMT,
389                 UUID_ARGS(&sb->header_.uuid), UUID_ARGS(&key));
390             sbrec_datapath_binding_delete(sb);
391             continue;
392         }
393
394         struct ovn_datapath *od = ovn_datapath_create(datapaths, &key,
395                                                       NULL, NULL, sb);
396         ovs_list_push_back(sb_only, &od->list);
397     }
398
399     const struct nbrec_logical_switch *nbs;
400     NBREC_LOGICAL_SWITCH_FOR_EACH (nbs, ctx->ovnnb_idl) {
401         struct ovn_datapath *od = ovn_datapath_find(datapaths,
402                                                     &nbs->header_.uuid);
403         if (od) {
404             od->nbs = nbs;
405             ovs_list_remove(&od->list);
406             ovs_list_push_back(both, &od->list);
407         } else {
408             od = ovn_datapath_create(datapaths, &nbs->header_.uuid,
409                                      nbs, NULL, NULL);
410             ovs_list_push_back(nb_only, &od->list);
411         }
412     }
413
414     const struct nbrec_logical_router *nbr;
415     NBREC_LOGICAL_ROUTER_FOR_EACH (nbr, ctx->ovnnb_idl) {
416         if (!lrouter_is_enabled(nbr)) {
417             continue;
418         }
419
420         struct ovn_datapath *od = ovn_datapath_find(datapaths,
421                                                     &nbr->header_.uuid);
422         if (od) {
423             if (!od->nbs) {
424                 od->nbr = nbr;
425                 ovs_list_remove(&od->list);
426                 ovs_list_push_back(both, &od->list);
427             } else {
428                 /* Can't happen! */
429                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
430                 VLOG_WARN_RL(&rl,
431                              "duplicate UUID "UUID_FMT" in OVN_Northbound",
432                              UUID_ARGS(&nbr->header_.uuid));
433                 continue;
434             }
435         } else {
436             od = ovn_datapath_create(datapaths, &nbr->header_.uuid,
437                                      NULL, nbr, NULL);
438             ovs_list_push_back(nb_only, &od->list);
439         }
440     }
441 }
442
443 static uint32_t
444 ovn_datapath_allocate_key(struct hmap *dp_tnlids)
445 {
446     static uint32_t hint;
447     return allocate_tnlid(dp_tnlids, "datapath", (1u << 24) - 1, &hint);
448 }
449
450 /* Updates the southbound Datapath_Binding table so that it contains the
451  * logical switches and routers specified by the northbound database.
452  *
453  * Initializes 'datapaths' to contain a "struct ovn_datapath" for every logical
454  * switch and router. */
455 static void
456 build_datapaths(struct northd_context *ctx, struct hmap *datapaths)
457 {
458     struct ovs_list sb_only, nb_only, both;
459
460     join_datapaths(ctx, datapaths, &sb_only, &nb_only, &both);
461
462     if (!ovs_list_is_empty(&nb_only)) {
463         /* First index the in-use datapath tunnel IDs. */
464         struct hmap dp_tnlids = HMAP_INITIALIZER(&dp_tnlids);
465         struct ovn_datapath *od;
466         LIST_FOR_EACH (od, list, &both) {
467             add_tnlid(&dp_tnlids, od->sb->tunnel_key);
468         }
469
470         /* Add southbound record for each unmatched northbound record. */
471         LIST_FOR_EACH (od, list, &nb_only) {
472             uint16_t tunnel_key = ovn_datapath_allocate_key(&dp_tnlids);
473             if (!tunnel_key) {
474                 break;
475             }
476
477             od->sb = sbrec_datapath_binding_insert(ctx->ovnsb_txn);
478
479             char uuid_s[UUID_LEN + 1];
480             sprintf(uuid_s, UUID_FMT, UUID_ARGS(&od->key));
481             const char *key = od->nbs ? "logical-switch" : "logical-router";
482             const struct smap id = SMAP_CONST1(&id, key, uuid_s);
483             sbrec_datapath_binding_set_external_ids(od->sb, &id);
484
485             sbrec_datapath_binding_set_tunnel_key(od->sb, tunnel_key);
486         }
487         destroy_tnlids(&dp_tnlids);
488     }
489
490     /* Delete southbound records without northbound matches. */
491     struct ovn_datapath *od, *next;
492     LIST_FOR_EACH_SAFE (od, next, list, &sb_only) {
493         ovs_list_remove(&od->list);
494         sbrec_datapath_binding_delete(od->sb);
495         ovn_datapath_destroy(datapaths, od);
496     }
497 }
498 \f
499 struct ovn_port {
500     struct hmap_node key_node;  /* Index on 'key'. */
501     char *key;                  /* nbs->name, nbr->name, sb->logical_port. */
502     char *json_key;             /* 'key', quoted for use in JSON. */
503
504     const struct sbrec_port_binding *sb;         /* May be NULL. */
505
506     /* Logical switch port data. */
507     const struct nbrec_logical_switch_port *nbsp; /* May be NULL. */
508
509     struct lport_addresses *lsp_addrs;  /* Logical switch port addresses. */
510     unsigned int n_lsp_addrs;
511
512     struct lport_addresses *ps_addrs;   /* Port security addresses. */
513     unsigned int n_ps_addrs;
514
515     /* Logical router port data. */
516     const struct nbrec_logical_router_port *nbrp; /* May be NULL. */
517
518     struct lport_addresses lrp_networks;
519
520     struct ovn_port *peer;
521
522     struct ovn_datapath *od;
523
524     struct ovs_list list;       /* In list of similar records. */
525 };
526
527 static struct ovn_port *
528 ovn_port_create(struct hmap *ports, const char *key,
529                 const struct nbrec_logical_switch_port *nbsp,
530                 const struct nbrec_logical_router_port *nbrp,
531                 const struct sbrec_port_binding *sb)
532 {
533     struct ovn_port *op = xzalloc(sizeof *op);
534
535     struct ds json_key = DS_EMPTY_INITIALIZER;
536     json_string_escape(key, &json_key);
537     op->json_key = ds_steal_cstr(&json_key);
538
539     op->key = xstrdup(key);
540     op->sb = sb;
541     op->nbsp = nbsp;
542     op->nbrp = nbrp;
543     hmap_insert(ports, &op->key_node, hash_string(op->key, 0));
544     return op;
545 }
546
547 static void
548 ovn_port_destroy(struct hmap *ports, struct ovn_port *port)
549 {
550     if (port) {
551         /* Don't remove port->list.  It is used within build_ports() as a
552          * private list and once we've exited that function it is not safe to
553          * use it. */
554         hmap_remove(ports, &port->key_node);
555
556         for (int i = 0; i < port->n_lsp_addrs; i++) {
557             destroy_lport_addresses(&port->lsp_addrs[i]);
558         }
559         free(port->lsp_addrs);
560
561         for (int i = 0; i < port->n_ps_addrs; i++) {
562             destroy_lport_addresses(&port->ps_addrs[i]);
563         }
564         free(port->ps_addrs);
565
566         destroy_lport_addresses(&port->lrp_networks);
567         free(port->json_key);
568         free(port->key);
569         free(port);
570     }
571 }
572
573 static struct ovn_port *
574 ovn_port_find(struct hmap *ports, const char *name)
575 {
576     struct ovn_port *op;
577
578     HMAP_FOR_EACH_WITH_HASH (op, key_node, hash_string(name, 0), ports) {
579         if (!strcmp(op->key, name)) {
580             return op;
581         }
582     }
583     return NULL;
584 }
585
586 static uint32_t
587 ovn_port_allocate_key(struct ovn_datapath *od)
588 {
589     return allocate_tnlid(&od->port_tnlids, "port",
590                           (1u << 15) - 1, &od->port_key_hint);
591 }
592
593 static void
594 join_logical_ports(struct northd_context *ctx,
595                    struct hmap *datapaths, struct hmap *ports,
596                    struct ovs_list *sb_only, struct ovs_list *nb_only,
597                    struct ovs_list *both)
598 {
599     hmap_init(ports);
600     ovs_list_init(sb_only);
601     ovs_list_init(nb_only);
602     ovs_list_init(both);
603
604     const struct sbrec_port_binding *sb;
605     SBREC_PORT_BINDING_FOR_EACH (sb, ctx->ovnsb_idl) {
606         struct ovn_port *op = ovn_port_create(ports, sb->logical_port,
607                                               NULL, NULL, sb);
608         ovs_list_push_back(sb_only, &op->list);
609     }
610
611     struct ovn_datapath *od;
612     HMAP_FOR_EACH (od, key_node, datapaths) {
613         if (od->nbs) {
614             for (size_t i = 0; i < od->nbs->n_ports; i++) {
615                 const struct nbrec_logical_switch_port *nbsp
616                     = od->nbs->ports[i];
617                 struct ovn_port *op = ovn_port_find(ports, nbsp->name);
618                 if (op) {
619                     if (op->nbsp || op->nbrp) {
620                         static struct vlog_rate_limit rl
621                             = VLOG_RATE_LIMIT_INIT(5, 1);
622                         VLOG_WARN_RL(&rl, "duplicate logical port %s",
623                                      nbsp->name);
624                         continue;
625                     }
626                     op->nbsp = nbsp;
627                     ovs_list_remove(&op->list);
628                     ovs_list_push_back(both, &op->list);
629
630                     /* This port exists due to a SB binding, but should
631                      * not have been initialized fully. */
632                     ovs_assert(!op->n_lsp_addrs && !op->n_ps_addrs);
633                 } else {
634                     op = ovn_port_create(ports, nbsp->name, nbsp, NULL, NULL);
635                     ovs_list_push_back(nb_only, &op->list);
636                 }
637
638                 op->lsp_addrs
639                     = xmalloc(sizeof *op->lsp_addrs * nbsp->n_addresses);
640                 for (size_t j = 0; j < nbsp->n_addresses; j++) {
641                     if (!strcmp(nbsp->addresses[j], "unknown")) {
642                         continue;
643                     }
644                     if (!extract_lsp_addresses(nbsp->addresses[j],
645                                            &op->lsp_addrs[op->n_lsp_addrs])) {
646                         static struct vlog_rate_limit rl
647                             = VLOG_RATE_LIMIT_INIT(1, 1);
648                         VLOG_INFO_RL(&rl, "invalid syntax '%s' in logical "
649                                           "switch port addresses. No MAC "
650                                           "address found",
651                                           op->nbsp->addresses[j]);
652                         continue;
653                     }
654                     op->n_lsp_addrs++;
655                 }
656
657                 op->ps_addrs
658                     = xmalloc(sizeof *op->ps_addrs * nbsp->n_port_security);
659                 for (size_t j = 0; j < nbsp->n_port_security; j++) {
660                     if (!extract_lsp_addresses(nbsp->port_security[j],
661                                                &op->ps_addrs[op->n_ps_addrs])) {
662                         static struct vlog_rate_limit rl
663                             = VLOG_RATE_LIMIT_INIT(1, 1);
664                         VLOG_INFO_RL(&rl, "invalid syntax '%s' in port "
665                                           "security. No MAC address found",
666                                           op->nbsp->port_security[j]);
667                         continue;
668                     }
669                     op->n_ps_addrs++;
670                 }
671
672                 op->od = od;
673             }
674         } else {
675             for (size_t i = 0; i < od->nbr->n_ports; i++) {
676                 const struct nbrec_logical_router_port *nbrp
677                     = od->nbr->ports[i];
678
679                 struct lport_addresses lrp_networks;
680                 if (!extract_lrp_networks(nbrp, &lrp_networks)) {
681                     static struct vlog_rate_limit rl
682                         = VLOG_RATE_LIMIT_INIT(5, 1);
683                     VLOG_WARN_RL(&rl, "bad 'mac' %s", nbrp->mac);
684                     continue;
685                 }
686
687                 if (!lrp_networks.n_ipv4_addrs && !lrp_networks.n_ipv6_addrs) {
688                     continue;
689                 }
690
691                 struct ovn_port *op = ovn_port_find(ports, nbrp->name);
692                 if (op) {
693                     if (op->nbsp || op->nbrp) {
694                         static struct vlog_rate_limit rl
695                             = VLOG_RATE_LIMIT_INIT(5, 1);
696                         VLOG_WARN_RL(&rl, "duplicate logical router port %s",
697                                      nbrp->name);
698                         continue;
699                     }
700                     op->nbrp = nbrp;
701                     ovs_list_remove(&op->list);
702                     ovs_list_push_back(both, &op->list);
703
704                     /* This port exists but should not have been
705                      * initialized fully. */
706                     ovs_assert(!op->lrp_networks.n_ipv4_addrs
707                                && !op->lrp_networks.n_ipv6_addrs);
708                 } else {
709                     op = ovn_port_create(ports, nbrp->name, NULL, nbrp, NULL);
710                     ovs_list_push_back(nb_only, &op->list);
711                 }
712
713                 op->lrp_networks = lrp_networks;
714                 op->od = od;
715             }
716         }
717     }
718
719     /* Connect logical router ports, and logical switch ports of type "router",
720      * to their peers. */
721     struct ovn_port *op;
722     HMAP_FOR_EACH (op, key_node, ports) {
723         if (op->nbsp && !strcmp(op->nbsp->type, "router")) {
724             const char *peer_name = smap_get(&op->nbsp->options, "router-port");
725             if (!peer_name) {
726                 continue;
727             }
728
729             struct ovn_port *peer = ovn_port_find(ports, peer_name);
730             if (!peer || !peer->nbrp) {
731                 continue;
732             }
733
734             peer->peer = op;
735             op->peer = peer;
736             op->od->router_ports = xrealloc(
737                 op->od->router_ports,
738                 sizeof *op->od->router_ports * (op->od->n_router_ports + 1));
739             op->od->router_ports[op->od->n_router_ports++] = op;
740         } else if (op->nbrp && op->nbrp->peer) {
741             op->peer = ovn_port_find(ports, op->nbrp->peer);
742         }
743     }
744 }
745
746 static void
747 ovn_port_update_sbrec(const struct ovn_port *op)
748 {
749     sbrec_port_binding_set_datapath(op->sb, op->od->sb);
750     if (op->nbrp) {
751         /* If the router is for l3 gateway, it resides on a chassis
752          * and its port type is "gateway". */
753         const char *chassis = smap_get(&op->od->nbr->options, "chassis");
754         if (chassis) {
755             sbrec_port_binding_set_type(op->sb, "gateway");
756         } else {
757             sbrec_port_binding_set_type(op->sb, "patch");
758         }
759
760         const char *peer = op->peer ? op->peer->key : "<error>";
761         struct smap new;
762         smap_init(&new);
763         smap_add(&new, "peer", peer);
764         if (chassis) {
765             smap_add(&new, "gateway-chassis", chassis);
766         }
767         sbrec_port_binding_set_options(op->sb, &new);
768         smap_destroy(&new);
769
770         sbrec_port_binding_set_parent_port(op->sb, NULL);
771         sbrec_port_binding_set_tag(op->sb, NULL, 0);
772         sbrec_port_binding_set_mac(op->sb, NULL, 0);
773     } else {
774         if (strcmp(op->nbsp->type, "router")) {
775             sbrec_port_binding_set_type(op->sb, op->nbsp->type);
776             sbrec_port_binding_set_options(op->sb, &op->nbsp->options);
777         } else {
778             const char *chassis = NULL;
779             if (op->peer && op->peer->od && op->peer->od->nbr) {
780                 chassis = smap_get(&op->peer->od->nbr->options, "chassis");
781             }
782
783             /* A switch port connected to a gateway router is also of
784              * type "gateway". */
785             if (chassis) {
786                 sbrec_port_binding_set_type(op->sb, "gateway");
787             } else {
788                 sbrec_port_binding_set_type(op->sb, "patch");
789             }
790
791             const char *router_port = smap_get(&op->nbsp->options,
792                                                "router-port");
793             if (!router_port) {
794                 router_port = "<error>";
795             }
796             struct smap new;
797             smap_init(&new);
798             smap_add(&new, "peer", router_port);
799             if (chassis) {
800                 smap_add(&new, "gateway-chassis", chassis);
801             }
802             sbrec_port_binding_set_options(op->sb, &new);
803             smap_destroy(&new);
804         }
805         sbrec_port_binding_set_parent_port(op->sb, op->nbsp->parent_name);
806         sbrec_port_binding_set_tag(op->sb, op->nbsp->tag, op->nbsp->n_tag);
807         sbrec_port_binding_set_mac(op->sb, (const char **) op->nbsp->addresses,
808                                    op->nbsp->n_addresses);
809     }
810 }
811
812 /* Updates the southbound Port_Binding table so that it contains the logical
813  * switch ports specified by the northbound database.
814  *
815  * Initializes 'ports' to contain a "struct ovn_port" for every logical port,
816  * using the "struct ovn_datapath"s in 'datapaths' to look up logical
817  * datapaths. */
818 static void
819 build_ports(struct northd_context *ctx, struct hmap *datapaths,
820             struct hmap *ports)
821 {
822     struct ovs_list sb_only, nb_only, both;
823
824     join_logical_ports(ctx, datapaths, ports, &sb_only, &nb_only, &both);
825
826     /* For logical ports that are in both databases, update the southbound
827      * record based on northbound data.  Also index the in-use tunnel_keys. */
828     struct ovn_port *op, *next;
829     LIST_FOR_EACH_SAFE (op, next, list, &both) {
830         ovn_port_update_sbrec(op);
831
832         add_tnlid(&op->od->port_tnlids, op->sb->tunnel_key);
833         if (op->sb->tunnel_key > op->od->port_key_hint) {
834             op->od->port_key_hint = op->sb->tunnel_key;
835         }
836     }
837
838     /* Add southbound record for each unmatched northbound record. */
839     LIST_FOR_EACH_SAFE (op, next, list, &nb_only) {
840         uint16_t tunnel_key = ovn_port_allocate_key(op->od);
841         if (!tunnel_key) {
842             continue;
843         }
844
845         op->sb = sbrec_port_binding_insert(ctx->ovnsb_txn);
846         ovn_port_update_sbrec(op);
847
848         sbrec_port_binding_set_logical_port(op->sb, op->key);
849         sbrec_port_binding_set_tunnel_key(op->sb, tunnel_key);
850     }
851
852     /* Delete southbound records without northbound matches. */
853     LIST_FOR_EACH_SAFE(op, next, list, &sb_only) {
854         ovs_list_remove(&op->list);
855         sbrec_port_binding_delete(op->sb);
856         ovn_port_destroy(ports, op);
857     }
858 }
859 \f
860 #define OVN_MIN_MULTICAST 32768
861 #define OVN_MAX_MULTICAST 65535
862
863 struct multicast_group {
864     const char *name;
865     uint16_t key;               /* OVN_MIN_MULTICAST...OVN_MAX_MULTICAST. */
866 };
867
868 #define MC_FLOOD "_MC_flood"
869 static const struct multicast_group mc_flood = { MC_FLOOD, 65535 };
870
871 #define MC_UNKNOWN "_MC_unknown"
872 static const struct multicast_group mc_unknown = { MC_UNKNOWN, 65534 };
873
874 static bool
875 multicast_group_equal(const struct multicast_group *a,
876                       const struct multicast_group *b)
877 {
878     return !strcmp(a->name, b->name) && a->key == b->key;
879 }
880
881 /* Multicast group entry. */
882 struct ovn_multicast {
883     struct hmap_node hmap_node; /* Index on 'datapath' and 'key'. */
884     struct ovn_datapath *datapath;
885     const struct multicast_group *group;
886
887     struct ovn_port **ports;
888     size_t n_ports, allocated_ports;
889 };
890
891 static uint32_t
892 ovn_multicast_hash(const struct ovn_datapath *datapath,
893                    const struct multicast_group *group)
894 {
895     return hash_pointer(datapath, group->key);
896 }
897
898 static struct ovn_multicast *
899 ovn_multicast_find(struct hmap *mcgroups, struct ovn_datapath *datapath,
900                    const struct multicast_group *group)
901 {
902     struct ovn_multicast *mc;
903
904     HMAP_FOR_EACH_WITH_HASH (mc, hmap_node,
905                              ovn_multicast_hash(datapath, group), mcgroups) {
906         if (mc->datapath == datapath
907             && multicast_group_equal(mc->group, group)) {
908             return mc;
909         }
910     }
911     return NULL;
912 }
913
914 static void
915 ovn_multicast_add(struct hmap *mcgroups, const struct multicast_group *group,
916                   struct ovn_port *port)
917 {
918     struct ovn_datapath *od = port->od;
919     struct ovn_multicast *mc = ovn_multicast_find(mcgroups, od, group);
920     if (!mc) {
921         mc = xmalloc(sizeof *mc);
922         hmap_insert(mcgroups, &mc->hmap_node, ovn_multicast_hash(od, group));
923         mc->datapath = od;
924         mc->group = group;
925         mc->n_ports = 0;
926         mc->allocated_ports = 4;
927         mc->ports = xmalloc(mc->allocated_ports * sizeof *mc->ports);
928     }
929     if (mc->n_ports >= mc->allocated_ports) {
930         mc->ports = x2nrealloc(mc->ports, &mc->allocated_ports,
931                                sizeof *mc->ports);
932     }
933     mc->ports[mc->n_ports++] = port;
934 }
935
936 static void
937 ovn_multicast_destroy(struct hmap *mcgroups, struct ovn_multicast *mc)
938 {
939     if (mc) {
940         hmap_remove(mcgroups, &mc->hmap_node);
941         free(mc->ports);
942         free(mc);
943     }
944 }
945
946 static void
947 ovn_multicast_update_sbrec(const struct ovn_multicast *mc,
948                            const struct sbrec_multicast_group *sb)
949 {
950     struct sbrec_port_binding **ports = xmalloc(mc->n_ports * sizeof *ports);
951     for (size_t i = 0; i < mc->n_ports; i++) {
952         ports[i] = CONST_CAST(struct sbrec_port_binding *, mc->ports[i]->sb);
953     }
954     sbrec_multicast_group_set_ports(sb, ports, mc->n_ports);
955     free(ports);
956 }
957 \f
958 /* Logical flow generation.
959  *
960  * This code generates the Logical_Flow table in the southbound database, as a
961  * function of most of the northbound database.
962  */
963
964 struct ovn_lflow {
965     struct hmap_node hmap_node;
966
967     struct ovn_datapath *od;
968     enum ovn_stage stage;
969     uint16_t priority;
970     char *match;
971     char *actions;
972 };
973
974 static size_t
975 ovn_lflow_hash(const struct ovn_lflow *lflow)
976 {
977     size_t hash = uuid_hash(&lflow->od->key);
978     hash = hash_2words((lflow->stage << 16) | lflow->priority, hash);
979     hash = hash_string(lflow->match, hash);
980     return hash_string(lflow->actions, hash);
981 }
982
983 static bool
984 ovn_lflow_equal(const struct ovn_lflow *a, const struct ovn_lflow *b)
985 {
986     return (a->od == b->od
987             && a->stage == b->stage
988             && a->priority == b->priority
989             && !strcmp(a->match, b->match)
990             && !strcmp(a->actions, b->actions));
991 }
992
993 static void
994 ovn_lflow_init(struct ovn_lflow *lflow, struct ovn_datapath *od,
995               enum ovn_stage stage, uint16_t priority,
996               char *match, char *actions)
997 {
998     lflow->od = od;
999     lflow->stage = stage;
1000     lflow->priority = priority;
1001     lflow->match = match;
1002     lflow->actions = actions;
1003 }
1004
1005 /* Adds a row with the specified contents to the Logical_Flow table. */
1006 static void
1007 ovn_lflow_add(struct hmap *lflow_map, struct ovn_datapath *od,
1008               enum ovn_stage stage, uint16_t priority,
1009               const char *match, const char *actions)
1010 {
1011     ovs_assert(ovn_stage_to_datapath_type(stage) == ovn_datapath_get_type(od));
1012
1013     struct ovn_lflow *lflow = xmalloc(sizeof *lflow);
1014     ovn_lflow_init(lflow, od, stage, priority,
1015                    xstrdup(match), xstrdup(actions));
1016     hmap_insert(lflow_map, &lflow->hmap_node, ovn_lflow_hash(lflow));
1017 }
1018
1019 static struct ovn_lflow *
1020 ovn_lflow_find(struct hmap *lflows, struct ovn_datapath *od,
1021                enum ovn_stage stage, uint16_t priority,
1022                const char *match, const char *actions)
1023 {
1024     struct ovn_lflow target;
1025     ovn_lflow_init(&target, od, stage, priority,
1026                    CONST_CAST(char *, match), CONST_CAST(char *, actions));
1027
1028     struct ovn_lflow *lflow;
1029     HMAP_FOR_EACH_WITH_HASH (lflow, hmap_node, ovn_lflow_hash(&target),
1030                              lflows) {
1031         if (ovn_lflow_equal(lflow, &target)) {
1032             return lflow;
1033         }
1034     }
1035     return NULL;
1036 }
1037
1038 static void
1039 ovn_lflow_destroy(struct hmap *lflows, struct ovn_lflow *lflow)
1040 {
1041     if (lflow) {
1042         hmap_remove(lflows, &lflow->hmap_node);
1043         free(lflow->match);
1044         free(lflow->actions);
1045         free(lflow);
1046     }
1047 }
1048
1049 /* Appends port security constraints on L2 address field 'eth_addr_field'
1050  * (e.g. "eth.src" or "eth.dst") to 'match'.  'ps_addrs', with 'n_ps_addrs'
1051  * elements, is the collection of port_security constraints from an
1052  * OVN_NB Logical_Switch_Port row generated by extract_lsp_addresses(). */
1053 static void
1054 build_port_security_l2(const char *eth_addr_field,
1055                        struct lport_addresses *ps_addrs,
1056                        unsigned int n_ps_addrs,
1057                        struct ds *match)
1058 {
1059     if (!n_ps_addrs) {
1060         return;
1061     }
1062
1063     ds_put_format(match, " && %s == {", eth_addr_field);
1064
1065     for (size_t i = 0; i < n_ps_addrs; i++) {
1066         ds_put_format(match, "%s ", ps_addrs[i].ea_s);
1067     }
1068     ds_chomp(match, ' ');
1069     ds_put_cstr(match, "}");
1070 }
1071
1072 static void
1073 build_port_security_ipv6_nd_flow(
1074     struct ds *match, struct eth_addr ea, struct ipv6_netaddr *ipv6_addrs,
1075     int n_ipv6_addrs)
1076 {
1077     ds_put_format(match, " && ip6 && nd && ((nd.sll == "ETH_ADDR_FMT" || "
1078                   "nd.sll == "ETH_ADDR_FMT") || ((nd.tll == "ETH_ADDR_FMT" || "
1079                   "nd.tll == "ETH_ADDR_FMT")", ETH_ADDR_ARGS(eth_addr_zero),
1080                   ETH_ADDR_ARGS(ea), ETH_ADDR_ARGS(eth_addr_zero),
1081                   ETH_ADDR_ARGS(ea));
1082     if (!n_ipv6_addrs) {
1083         ds_put_cstr(match, "))");
1084         return;
1085     }
1086
1087     char ip6_str[INET6_ADDRSTRLEN + 1];
1088     struct in6_addr lla;
1089     in6_generate_lla(ea, &lla);
1090     memset(ip6_str, 0, sizeof(ip6_str));
1091     ipv6_string_mapped(ip6_str, &lla);
1092     ds_put_format(match, " && (nd.target == %s", ip6_str);
1093
1094     for(int i = 0; i < n_ipv6_addrs; i++) {
1095         memset(ip6_str, 0, sizeof(ip6_str));
1096         ipv6_string_mapped(ip6_str, &ipv6_addrs[i].addr);
1097         ds_put_format(match, " || nd.target == %s", ip6_str);
1098     }
1099
1100     ds_put_format(match, ")))");
1101 }
1102
1103 static void
1104 build_port_security_ipv6_flow(
1105     enum ovn_pipeline pipeline, struct ds *match, struct eth_addr ea,
1106     struct ipv6_netaddr *ipv6_addrs, int n_ipv6_addrs)
1107 {
1108     char ip6_str[INET6_ADDRSTRLEN + 1];
1109
1110     ds_put_format(match, " && %s == {",
1111                   pipeline == P_IN ? "ip6.src" : "ip6.dst");
1112
1113     /* Allow link-local address. */
1114     struct in6_addr lla;
1115     in6_generate_lla(ea, &lla);
1116     ipv6_string_mapped(ip6_str, &lla);
1117     ds_put_format(match, "%s, ", ip6_str);
1118
1119     /* Allow ip6.dst=ff00::/8 for multicast packets */
1120     if (pipeline == P_OUT) {
1121         ds_put_cstr(match, "ff00::/8, ");
1122     }
1123     for(int i = 0; i < n_ipv6_addrs; i++) {
1124         ipv6_string_mapped(ip6_str, &ipv6_addrs[i].addr);
1125         ds_put_format(match, "%s, ", ip6_str);
1126     }
1127     /* Replace ", " by "}". */
1128     ds_chomp(match, ' ');
1129     ds_chomp(match, ',');
1130     ds_put_cstr(match, "}");
1131 }
1132
1133 /**
1134  * Build port security constraints on ARP and IPv6 ND fields
1135  * and add logical flows to S_SWITCH_IN_PORT_SEC_ND stage.
1136  *
1137  * For each port security of the logical port, following
1138  * logical flows are added
1139  *   - If the port security has no IP (both IPv4 and IPv6) or
1140  *     if it has IPv4 address(es)
1141  *      - Priority 90 flow to allow ARP packets for known MAC addresses
1142  *        in the eth.src and arp.spa fields. If the port security
1143  *        has IPv4 addresses, allow known IPv4 addresses in the arp.tpa field.
1144  *
1145  *   - If the port security has no IP (both IPv4 and IPv6) or
1146  *     if it has IPv6 address(es)
1147  *     - Priority 90 flow to allow IPv6 ND packets for known MAC addresses
1148  *       in the eth.src and nd.sll/nd.tll fields. If the port security
1149  *       has IPv6 addresses, allow known IPv6 addresses in the nd.target field
1150  *       for IPv6 Neighbor Advertisement packet.
1151  *
1152  *   - Priority 80 flow to drop ARP and IPv6 ND packets.
1153  */
1154 static void
1155 build_port_security_nd(struct ovn_port *op, struct hmap *lflows)
1156 {
1157     struct ds match = DS_EMPTY_INITIALIZER;
1158
1159     for (size_t i = 0; i < op->n_ps_addrs; i++) {
1160         struct lport_addresses *ps = &op->ps_addrs[i];
1161
1162         bool no_ip = !(ps->n_ipv4_addrs || ps->n_ipv6_addrs);
1163
1164         ds_clear(&match);
1165         if (ps->n_ipv4_addrs || no_ip) {
1166             ds_put_format(&match,
1167                           "inport == %s && eth.src == %s && arp.sha == %s",
1168                           op->json_key, ps->ea_s, ps->ea_s);
1169
1170             if (ps->n_ipv4_addrs) {
1171                 ds_put_cstr(&match, " && arp.spa == {");
1172                 for (size_t j = 0; j < ps->n_ipv4_addrs; j++) {
1173                     /* When the netmask is applied, if the host portion is
1174                      * non-zero, the host can only use the specified
1175                      * address in the arp.spa.  If zero, the host is allowed
1176                      * to use any address in the subnet. */
1177                     if (ps->ipv4_addrs[j].plen == 32
1178                         || ps->ipv4_addrs[j].addr & ~ps->ipv4_addrs[j].mask) {
1179                         ds_put_cstr(&match, ps->ipv4_addrs[j].addr_s);
1180                     } else {
1181                         ds_put_format(&match, "%s/%d",
1182                                       ps->ipv4_addrs[j].network_s,
1183                                       ps->ipv4_addrs[j].plen);
1184                     }
1185                     ds_put_cstr(&match, ", ");
1186                 }
1187                 ds_chomp(&match, ' ');
1188                 ds_chomp(&match, ',');
1189                 ds_put_cstr(&match, "}");
1190             }
1191             ovn_lflow_add(lflows, op->od, S_SWITCH_IN_PORT_SEC_ND, 90,
1192                           ds_cstr(&match), "next;");
1193         }
1194
1195         if (ps->n_ipv6_addrs || no_ip) {
1196             ds_clear(&match);
1197             ds_put_format(&match, "inport == %s && eth.src == %s",
1198                           op->json_key, ps->ea_s);
1199             build_port_security_ipv6_nd_flow(&match, ps->ea, ps->ipv6_addrs,
1200                                              ps->n_ipv6_addrs);
1201             ovn_lflow_add(lflows, op->od, S_SWITCH_IN_PORT_SEC_ND, 90,
1202                           ds_cstr(&match), "next;");
1203         }
1204     }
1205
1206     ds_clear(&match);
1207     ds_put_format(&match, "inport == %s && (arp || nd)", op->json_key);
1208     ovn_lflow_add(lflows, op->od, S_SWITCH_IN_PORT_SEC_ND, 80,
1209                   ds_cstr(&match), "drop;");
1210     ds_destroy(&match);
1211 }
1212
1213 /**
1214  * Build port security constraints on IPv4 and IPv6 src and dst fields
1215  * and add logical flows to S_SWITCH_(IN/OUT)_PORT_SEC_IP stage.
1216  *
1217  * For each port security of the logical port, following
1218  * logical flows are added
1219  *   - If the port security has IPv4 addresses,
1220  *     - Priority 90 flow to allow IPv4 packets for known IPv4 addresses
1221  *
1222  *   - If the port security has IPv6 addresses,
1223  *     - Priority 90 flow to allow IPv6 packets for known IPv6 addresses
1224  *
1225  *   - If the port security has IPv4 addresses or IPv6 addresses or both
1226  *     - Priority 80 flow to drop all IPv4 and IPv6 traffic
1227  */
1228 static void
1229 build_port_security_ip(enum ovn_pipeline pipeline, struct ovn_port *op,
1230                        struct hmap *lflows)
1231 {
1232     char *port_direction;
1233     enum ovn_stage stage;
1234     if (pipeline == P_IN) {
1235         port_direction = "inport";
1236         stage = S_SWITCH_IN_PORT_SEC_IP;
1237     } else {
1238         port_direction = "outport";
1239         stage = S_SWITCH_OUT_PORT_SEC_IP;
1240     }
1241
1242     for (size_t i = 0; i < op->n_ps_addrs; i++) {
1243         struct lport_addresses *ps = &op->ps_addrs[i];
1244
1245         if (!(ps->n_ipv4_addrs || ps->n_ipv6_addrs)) {
1246             continue;
1247         }
1248
1249         if (ps->n_ipv4_addrs) {
1250             struct ds match = DS_EMPTY_INITIALIZER;
1251             if (pipeline == P_IN) {
1252                 /* Permit use of the unspecified address for DHCP discovery */
1253                 struct ds dhcp_match = DS_EMPTY_INITIALIZER;
1254                 ds_put_format(&dhcp_match, "inport == %s"
1255                               " && eth.src == %s"
1256                               " && ip4.src == 0.0.0.0"
1257                               " && ip4.dst == 255.255.255.255"
1258                               " && udp.src == 68 && udp.dst == 67",
1259                               op->json_key, ps->ea_s);
1260                 ovn_lflow_add(lflows, op->od, stage, 90,
1261                               ds_cstr(&dhcp_match), "next;");
1262                 ds_destroy(&dhcp_match);
1263                 ds_put_format(&match, "inport == %s && eth.src == %s"
1264                               " && ip4.src == {", op->json_key,
1265                               ps->ea_s);
1266             } else {
1267                 ds_put_format(&match, "outport == %s && eth.dst == %s"
1268                               " && ip4.dst == {255.255.255.255, 224.0.0.0/4, ",
1269                               op->json_key, ps->ea_s);
1270             }
1271
1272             for (int j = 0; j < ps->n_ipv4_addrs; j++) {
1273                 ovs_be32 mask = ps->ipv4_addrs[j].mask;
1274                 /* When the netmask is applied, if the host portion is
1275                  * non-zero, the host can only use the specified
1276                  * address.  If zero, the host is allowed to use any
1277                  * address in the subnet.
1278                  */
1279                 if (ps->ipv4_addrs[j].plen == 32
1280                     || ps->ipv4_addrs[j].addr & ~mask) {
1281                     ds_put_format(&match, "%s", ps->ipv4_addrs[j].addr_s);
1282                     if (pipeline == P_OUT && ps->ipv4_addrs[j].plen != 32) {
1283                         /* Host is also allowed to receive packets to the
1284                          * broadcast address in the specified subnet. */
1285                         ds_put_format(&match, ", %s",
1286                                       ps->ipv4_addrs[j].bcast_s);
1287                     }
1288                 } else {
1289                     /* host portion is zero */
1290                     ds_put_format(&match, "%s/%d", ps->ipv4_addrs[j].network_s,
1291                                   ps->ipv4_addrs[j].plen);
1292                 }
1293                 ds_put_cstr(&match, ", ");
1294             }
1295
1296             /* Replace ", " by "}". */
1297             ds_chomp(&match, ' ');
1298             ds_chomp(&match, ',');
1299             ds_put_cstr(&match, "}");
1300             ovn_lflow_add(lflows, op->od, stage, 90, ds_cstr(&match), "next;");
1301             ds_destroy(&match);
1302         }
1303
1304         if (ps->n_ipv6_addrs) {
1305             struct ds match = DS_EMPTY_INITIALIZER;
1306             if (pipeline == P_IN) {
1307                 /* Permit use of unspecified address for duplicate address
1308                  * detection */
1309                 struct ds dad_match = DS_EMPTY_INITIALIZER;
1310                 ds_put_format(&dad_match, "inport == %s"
1311                               " && eth.src == %s"
1312                               " && ip6.src == ::"
1313                               " && ip6.dst == ff02::/16"
1314                               " && icmp6.type == {131, 135, 143}", op->json_key,
1315                               ps->ea_s);
1316                 ovn_lflow_add(lflows, op->od, stage, 90,
1317                               ds_cstr(&dad_match), "next;");
1318                 ds_destroy(&dad_match);
1319             }
1320             ds_put_format(&match, "%s == %s && %s == %s",
1321                           port_direction, op->json_key,
1322                           pipeline == P_IN ? "eth.src" : "eth.dst", ps->ea_s);
1323             build_port_security_ipv6_flow(pipeline, &match, ps->ea,
1324                                           ps->ipv6_addrs, ps->n_ipv6_addrs);
1325             ovn_lflow_add(lflows, op->od, stage, 90,
1326                           ds_cstr(&match), "next;");
1327             ds_destroy(&match);
1328         }
1329
1330         char *match = xasprintf("%s == %s && %s == %s && ip",
1331                                 port_direction, op->json_key,
1332                                 pipeline == P_IN ? "eth.src" : "eth.dst",
1333                                 ps->ea_s);
1334         ovn_lflow_add(lflows, op->od, stage, 80, match, "drop;");
1335         free(match);
1336     }
1337
1338 }
1339
1340 static bool
1341 lsp_is_enabled(const struct nbrec_logical_switch_port *lsp)
1342 {
1343     return !lsp->enabled || *lsp->enabled;
1344 }
1345
1346 static bool
1347 lsp_is_up(const struct nbrec_logical_switch_port *lsp)
1348 {
1349     return !lsp->up || *lsp->up;
1350 }
1351
1352 static bool
1353 has_stateful_acl(struct ovn_datapath *od)
1354 {
1355     for (size_t i = 0; i < od->nbs->n_acls; i++) {
1356         struct nbrec_acl *acl = od->nbs->acls[i];
1357         if (!strcmp(acl->action, "allow-related")) {
1358             return true;
1359         }
1360     }
1361
1362     return false;
1363 }
1364
1365 static void
1366 build_pre_acls(struct ovn_datapath *od, struct hmap *lflows,
1367                struct hmap *ports)
1368 {
1369     bool has_stateful = has_stateful_acl(od);
1370     struct ovn_port *op;
1371
1372     /* Ingress and Egress Pre-ACL Table (Priority 0): Packets are
1373      * allowed by default. */
1374     ovn_lflow_add(lflows, od, S_SWITCH_IN_PRE_ACL, 0, "1", "next;");
1375     ovn_lflow_add(lflows, od, S_SWITCH_OUT_PRE_ACL, 0, "1", "next;");
1376
1377     /* If there are any stateful ACL rules in this dapapath, we must
1378      * send all IP packets through the conntrack action, which handles
1379      * defragmentation, in order to match L4 headers. */
1380     if (has_stateful) {
1381         HMAP_FOR_EACH (op, key_node, ports) {
1382             if (op->od == od && !strcmp(op->nbsp->type, "router")) {
1383                 /* Can't use ct() for router ports. Consider the
1384                  * following configuration: lp1(10.0.0.2) on
1385                  * hostA--ls1--lr0--ls2--lp2(10.0.1.2) on hostB, For a
1386                  * ping from lp1 to lp2, First, the response will go
1387                  * through ct() with a zone for lp2 in the ls2 ingress
1388                  * pipeline on hostB.  That ct zone knows about this
1389                  * connection. Next, it goes through ct() with the zone
1390                  * for the router port in the egress pipeline of ls2 on
1391                  * hostB.  This zone does not know about the connection,
1392                  * as the icmp request went through the logical router
1393                  * on hostA, not hostB. This would only work with
1394                  * distributed conntrack state across all chassis. */
1395                 struct ds match_in = DS_EMPTY_INITIALIZER;
1396                 struct ds match_out = DS_EMPTY_INITIALIZER;
1397
1398                 ds_put_format(&match_in, "ip && inport == %s", op->json_key);
1399                 ds_put_format(&match_out, "ip && outport == %s", op->json_key);
1400                 ovn_lflow_add(lflows, od, S_SWITCH_IN_PRE_ACL, 110,
1401                               ds_cstr(&match_in), "next;");
1402                 ovn_lflow_add(lflows, od, S_SWITCH_OUT_PRE_ACL, 110,
1403                               ds_cstr(&match_out), "next;");
1404
1405                 ds_destroy(&match_in);
1406                 ds_destroy(&match_out);
1407             }
1408         }
1409         /* Ingress and Egress Pre-ACL Table (Priority 110).
1410          *
1411          * Not to do conntrack on ND packets. */
1412         ovn_lflow_add(lflows, od, S_SWITCH_IN_PRE_ACL, 110, "nd", "next;");
1413         ovn_lflow_add(lflows, od, S_SWITCH_OUT_PRE_ACL, 110, "nd", "next;");
1414
1415         /* Ingress and Egress Pre-ACL Table (Priority 100).
1416          *
1417          * Regardless of whether the ACL is "from-lport" or "to-lport",
1418          * we need rules in both the ingress and egress table, because
1419          * the return traffic needs to be followed.
1420          *
1421          * 'REGBIT_CONNTRACK_DEFRAG' is set to let the pre-stateful table send
1422          * it to conntrack for tracking and defragmentation. */
1423         ovn_lflow_add(lflows, od, S_SWITCH_IN_PRE_ACL, 100, "ip",
1424                       REGBIT_CONNTRACK_DEFRAG" = 1; next;");
1425         ovn_lflow_add(lflows, od, S_SWITCH_OUT_PRE_ACL, 100, "ip",
1426                       REGBIT_CONNTRACK_DEFRAG" = 1; next;");
1427     }
1428 }
1429
1430 /* For a 'key' of the form "IP:port" or just "IP", sets 'port' and
1431  * 'ip_address'.  The caller must free() the memory allocated for
1432  * 'ip_address'. */
1433 static void
1434 ip_address_and_port_from_lb_key(const char *key, char **ip_address,
1435                                 uint16_t *port)
1436 {
1437     char *ip_str, *start, *next;
1438     *ip_address = NULL;
1439     *port = 0;
1440
1441     next = start = xstrdup(key);
1442     ip_str = strsep(&next, ":");
1443     if (!ip_str || !ip_str[0]) {
1444         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
1445         VLOG_WARN_RL(&rl, "bad ip address for load balancer key %s", key);
1446         free(start);
1447         return;
1448     }
1449
1450     ovs_be32 ip, mask;
1451     char *error = ip_parse_masked(ip_str, &ip, &mask);
1452     if (error || mask != OVS_BE32_MAX) {
1453         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
1454         VLOG_WARN_RL(&rl, "bad ip address for load balancer key %s", key);
1455         free(start);
1456         free(error);
1457         return;
1458     }
1459
1460     int l4_port = 0;
1461     if (next && next[0]) {
1462         if (!str_to_int(next, 0, &l4_port) || l4_port < 0 || l4_port > 65535) {
1463             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
1464             VLOG_WARN_RL(&rl, "bad ip port for load balancer key %s", key);
1465             free(start);
1466             return;
1467         }
1468     }
1469
1470     *port = l4_port;
1471     *ip_address = strdup(ip_str);
1472     free(start);
1473 }
1474
1475 static void
1476 build_pre_lb(struct ovn_datapath *od, struct hmap *lflows)
1477 {
1478     /* Allow all packets to go to next tables by default. */
1479     ovn_lflow_add(lflows, od, S_SWITCH_IN_PRE_LB, 0, "1", "next;");
1480     ovn_lflow_add(lflows, od, S_SWITCH_OUT_PRE_LB, 0, "1", "next;");
1481
1482     struct sset all_ips = SSET_INITIALIZER(&all_ips);
1483     if (od->nbs->load_balancer) {
1484         struct nbrec_load_balancer *lb = od->nbs->load_balancer;
1485         struct smap *vips = &lb->vips;
1486         struct smap_node *node;
1487         bool vip_configured = false;
1488
1489         SMAP_FOR_EACH (node, vips) {
1490             vip_configured = true;
1491
1492             /* node->key contains IP:port or just IP. */
1493             char *ip_address = NULL;
1494             uint16_t port;
1495             ip_address_and_port_from_lb_key(node->key, &ip_address, &port);
1496             if (!ip_address) {
1497                 continue;
1498             }
1499
1500             if (!sset_contains(&all_ips, ip_address)) {
1501                 sset_add(&all_ips, ip_address);
1502             }
1503
1504             free(ip_address);
1505
1506             /* Ignore L4 port information in the key because fragmented packets
1507              * may not have L4 information.  The pre-stateful table will send
1508              * the packet through ct() action to de-fragment. In stateful
1509              * table, we will eventually look at L4 information. */
1510         }
1511
1512         /* 'REGBIT_CONNTRACK_DEFRAG' is set to let the pre-stateful table send
1513          * packet to conntrack for defragmentation. */
1514         const char *ip_address;
1515         SSET_FOR_EACH(ip_address, &all_ips) {
1516             char *match = xasprintf("ip && ip4.dst == %s", ip_address);
1517             ovn_lflow_add(lflows, od, S_SWITCH_IN_PRE_LB,
1518                           100, match, REGBIT_CONNTRACK_DEFRAG" = 1; next;");
1519             free(match);
1520         }
1521
1522         sset_destroy(&all_ips);
1523
1524         if (vip_configured) {
1525             ovn_lflow_add(lflows, od, S_SWITCH_OUT_PRE_LB,
1526                           100, "ip", REGBIT_CONNTRACK_DEFRAG" = 1; next;");
1527         }
1528     }
1529 }
1530
1531 static void
1532 build_pre_stateful(struct ovn_datapath *od, struct hmap *lflows)
1533 {
1534     /* Ingress and Egress pre-stateful Table (Priority 0): Packets are
1535      * allowed by default. */
1536     ovn_lflow_add(lflows, od, S_SWITCH_IN_PRE_STATEFUL, 0, "1", "next;");
1537     ovn_lflow_add(lflows, od, S_SWITCH_OUT_PRE_STATEFUL, 0, "1", "next;");
1538
1539     /* If REGBIT_CONNTRACK_DEFRAG is set as 1, then the packets should be
1540      * sent to conntrack for tracking and defragmentation. */
1541     ovn_lflow_add(lflows, od, S_SWITCH_IN_PRE_STATEFUL, 100,
1542                   REGBIT_CONNTRACK_DEFRAG" == 1", "ct_next;");
1543     ovn_lflow_add(lflows, od, S_SWITCH_OUT_PRE_STATEFUL, 100,
1544                   REGBIT_CONNTRACK_DEFRAG" == 1", "ct_next;");
1545 }
1546
1547 static void
1548 build_acls(struct ovn_datapath *od, struct hmap *lflows)
1549 {
1550     bool has_stateful = has_stateful_acl(od);
1551
1552     /* Ingress and Egress ACL Table (Priority 0): Packets are allowed by
1553      * default.  A related rule at priority 1 is added below if there
1554      * are any stateful ACLs in this datapath. */
1555     ovn_lflow_add(lflows, od, S_SWITCH_IN_ACL, 0, "1", "next;");
1556     ovn_lflow_add(lflows, od, S_SWITCH_OUT_ACL, 0, "1", "next;");
1557
1558     if (has_stateful) {
1559         /* Ingress and Egress ACL Table (Priority 1).
1560          *
1561          * By default, traffic is allowed.  This is partially handled by
1562          * the Priority 0 ACL flows added earlier, but we also need to
1563          * commit IP flows.  This is because, while the initiater's
1564          * direction may not have any stateful rules, the server's may
1565          * and then its return traffic would not have an associated
1566          * conntrack entry and would return "+invalid".
1567          *
1568          * We use "ct_commit" for a connection that is not already known
1569          * by the connection tracker.  Once a connection is committed,
1570          * subsequent packets will hit the flow at priority 0 that just
1571          * uses "next;"
1572          *
1573          * We also check for established connections that have ct_label[0]
1574          * set on them.  That's a connection that was disallowed, but is
1575          * now allowed by policy again since it hit this default-allow flow.
1576          * We need to set ct_label[0]=0 to let the connection continue,
1577          * which will be done by ct_commit() in the "stateful" stage.
1578          * Subsequent packets will hit the flow at priority 0 that just
1579          * uses "next;". */
1580         ovn_lflow_add(lflows, od, S_SWITCH_IN_ACL, 1,
1581                       "ip && (!ct.est || (ct.est && ct_label[0] == 1))",
1582                        REGBIT_CONNTRACK_COMMIT" = 1; next;");
1583         ovn_lflow_add(lflows, od, S_SWITCH_OUT_ACL, 1,
1584                       "ip && (!ct.est || (ct.est && ct_label[0] == 1))",
1585                        REGBIT_CONNTRACK_COMMIT" = 1; next;");
1586
1587         /* Ingress and Egress ACL Table (Priority 65535).
1588          *
1589          * Always drop traffic that's in an invalid state.  Also drop
1590          * reply direction packets for connections that have been marked
1591          * for deletion (bit 0 of ct_label is set).
1592          *
1593          * This is enforced at a higher priority than ACLs can be defined. */
1594         ovn_lflow_add(lflows, od, S_SWITCH_IN_ACL, UINT16_MAX,
1595                       "ct.inv || (ct.est && ct.rpl && ct_label[0] == 1)",
1596                       "drop;");
1597         ovn_lflow_add(lflows, od, S_SWITCH_OUT_ACL, UINT16_MAX,
1598                       "ct.inv || (ct.est && ct.rpl && ct_label[0] == 1)",
1599                       "drop;");
1600
1601         /* Ingress and Egress ACL Table (Priority 65535).
1602          *
1603          * Allow reply traffic that is part of an established
1604          * conntrack entry that has not been marked for deletion
1605          * (bit 0 of ct_label).  We only match traffic in the
1606          * reply direction because we want traffic in the request
1607          * direction to hit the currently defined policy from ACLs.
1608          *
1609          * This is enforced at a higher priority than ACLs can be defined. */
1610         ovn_lflow_add(lflows, od, S_SWITCH_IN_ACL, UINT16_MAX,
1611                       "ct.est && !ct.rel && !ct.new && !ct.inv "
1612                       "&& ct.rpl && ct_label[0] == 0",
1613                       "next;");
1614         ovn_lflow_add(lflows, od, S_SWITCH_OUT_ACL, UINT16_MAX,
1615                       "ct.est && !ct.rel && !ct.new && !ct.inv "
1616                       "&& ct.rpl && ct_label[0] == 0",
1617                       "next;");
1618
1619         /* Ingress and Egress ACL Table (Priority 65535).
1620          *
1621          * Allow traffic that is related to an existing conntrack entry that
1622          * has not been marked for deletion (bit 0 of ct_label).
1623          *
1624          * This is enforced at a higher priority than ACLs can be defined.
1625          *
1626          * NOTE: This does not support related data sessions (eg,
1627          * a dynamically negotiated FTP data channel), but will allow
1628          * related traffic such as an ICMP Port Unreachable through
1629          * that's generated from a non-listening UDP port.  */
1630         ovn_lflow_add(lflows, od, S_SWITCH_IN_ACL, UINT16_MAX,
1631                       "!ct.est && ct.rel && !ct.new && !ct.inv "
1632                       "&& ct_label[0] == 0",
1633                       "next;");
1634         ovn_lflow_add(lflows, od, S_SWITCH_OUT_ACL, UINT16_MAX,
1635                       "!ct.est && ct.rel && !ct.new && !ct.inv "
1636                       "&& ct_label[0] == 0",
1637                       "next;");
1638
1639         /* Ingress and Egress ACL Table (Priority 65535).
1640          *
1641          * Not to do conntrack on ND packets. */
1642         ovn_lflow_add(lflows, od, S_SWITCH_IN_ACL, UINT16_MAX, "nd", "next;");
1643         ovn_lflow_add(lflows, od, S_SWITCH_OUT_ACL, UINT16_MAX, "nd", "next;");
1644     }
1645
1646     /* Ingress or Egress ACL Table (Various priorities). */
1647     for (size_t i = 0; i < od->nbs->n_acls; i++) {
1648         struct nbrec_acl *acl = od->nbs->acls[i];
1649         bool ingress = !strcmp(acl->direction, "from-lport") ? true :false;
1650         enum ovn_stage stage = ingress ? S_SWITCH_IN_ACL : S_SWITCH_OUT_ACL;
1651
1652         if (!strcmp(acl->action, "allow")
1653             || !strcmp(acl->action, "allow-related")) {
1654             /* If there are any stateful flows, we must even commit "allow"
1655              * actions.  This is because, while the initiater's
1656              * direction may not have any stateful rules, the server's
1657              * may and then its return traffic would not have an
1658              * associated conntrack entry and would return "+invalid". */
1659             if (!has_stateful) {
1660                 ovn_lflow_add(lflows, od, stage,
1661                               acl->priority + OVN_ACL_PRI_OFFSET,
1662                               acl->match, "next;");
1663             } else {
1664                 struct ds match = DS_EMPTY_INITIALIZER;
1665
1666                 /* Commit the connection tracking entry if it's a new
1667                  * connection that matches this ACL.  After this commit,
1668                  * the reply traffic is allowed by a flow we create at
1669                  * priority 65535, defined earlier.
1670                  *
1671                  * It's also possible that a known connection was marked for
1672                  * deletion after a policy was deleted, but the policy was
1673                  * re-added while that connection is still known.  We catch
1674                  * that case here and un-set ct_label[0] (which will be done
1675                  * by ct_commit in the "stateful" stage) to indicate that the
1676                  * connection should be allowed to resume.
1677                  */
1678                 ds_put_format(&match, "((ct.new && !ct.est)"
1679                                       " || (!ct.new && ct.est && !ct.rpl "
1680                                            "&& ct_label[0] == 1)) "
1681                                       "&& (%s)", acl->match);
1682                 ovn_lflow_add(lflows, od, stage,
1683                               acl->priority + OVN_ACL_PRI_OFFSET,
1684                               ds_cstr(&match),
1685                                REGBIT_CONNTRACK_COMMIT" = 1; next;");
1686
1687                 /* Match on traffic in the request direction for an established
1688                  * connection tracking entry that has not been marked for
1689                  * deletion.  There is no need to commit here, so we can just
1690                  * proceed to the next table. We use this to ensure that this
1691                  * connection is still allowed by the currently defined
1692                  * policy. */
1693                 ds_clear(&match);
1694                 ds_put_format(&match,
1695                               "!ct.new && ct.est && !ct.rpl"
1696                               " && ct_label[0] == 0 && (%s)",
1697                               acl->match);
1698                 ovn_lflow_add(lflows, od, stage,
1699                               acl->priority + OVN_ACL_PRI_OFFSET,
1700                               ds_cstr(&match), "next;");
1701
1702                 ds_destroy(&match);
1703             }
1704         } else if (!strcmp(acl->action, "drop")
1705                    || !strcmp(acl->action, "reject")) {
1706             struct ds match = DS_EMPTY_INITIALIZER;
1707
1708             /* XXX Need to support "reject", treat it as "drop;" for now. */
1709             if (!strcmp(acl->action, "reject")) {
1710                 VLOG_INFO("reject is not a supported action");
1711             }
1712
1713             /* The implementation of "drop" differs if stateful ACLs are in
1714              * use for this datapath.  In that case, the actions differ
1715              * depending on whether the connection was previously committed
1716              * to the connection tracker with ct_commit. */
1717             if (has_stateful) {
1718                 /* If the packet is not part of an established connection, then
1719                  * we can simply drop it. */
1720                 ds_put_format(&match,
1721                               "(!ct.est || (ct.est && ct_label[0] == 1)) "
1722                               "&& (%s)",
1723                               acl->match);
1724                 ovn_lflow_add(lflows, od, stage, acl->priority +
1725                         OVN_ACL_PRI_OFFSET, ds_cstr(&match), "drop;");
1726
1727                 /* For an existing connection without ct_label set, we've
1728                  * encountered a policy change. ACLs previously allowed
1729                  * this connection and we committed the connection tracking
1730                  * entry.  Current policy says that we should drop this
1731                  * connection.  First, we set bit 0 of ct_label to indicate
1732                  * that this connection is set for deletion.  By not
1733                  * specifying "next;", we implicitly drop the packet after
1734                  * updating conntrack state.  We would normally defer
1735                  * ct_commit() to the "stateful" stage, but since we're
1736                  * dropping the packet, we go ahead and do it here. */
1737                 ds_clear(&match);
1738                 ds_put_format(&match,
1739                               "ct.est && ct_label[0] == 0 && (%s)",
1740                               acl->match);
1741                 ovn_lflow_add(lflows, od, stage,
1742                               acl->priority + OVN_ACL_PRI_OFFSET,
1743                               ds_cstr(&match), "ct_commit(ct_label=1/1);");
1744
1745                 ds_destroy(&match);
1746             } else {
1747                 /* There are no stateful ACLs in use on this datapath,
1748                  * so a "drop" ACL is simply the "drop" logical flow action
1749                  * in all cases. */
1750                 ovn_lflow_add(lflows, od, stage,
1751                               acl->priority + OVN_ACL_PRI_OFFSET,
1752                               acl->match, "drop;");
1753             }
1754         }
1755     }
1756 }
1757
1758 static void
1759 build_lb(struct ovn_datapath *od, struct hmap *lflows)
1760 {
1761     /* Ingress and Egress LB Table (Priority 0): Packets are allowed by
1762      * default.  */
1763     ovn_lflow_add(lflows, od, S_SWITCH_IN_LB, 0, "1", "next;");
1764     ovn_lflow_add(lflows, od, S_SWITCH_OUT_LB, 0, "1", "next;");
1765
1766     if (od->nbs->load_balancer) {
1767         /* Ingress and Egress LB Table (Priority 65535).
1768          *
1769          * Send established traffic through conntrack for just NAT. */
1770         ovn_lflow_add(lflows, od, S_SWITCH_IN_LB, UINT16_MAX,
1771                       "ct.est && !ct.rel && !ct.new && !ct.inv",
1772                       REGBIT_CONNTRACK_NAT" = 1; next;");
1773         ovn_lflow_add(lflows, od, S_SWITCH_OUT_LB, UINT16_MAX,
1774                       "ct.est && !ct.rel && !ct.new && !ct.inv",
1775                       REGBIT_CONNTRACK_NAT" = 1; next;");
1776     }
1777 }
1778
1779 static void
1780 build_stateful(struct ovn_datapath *od, struct hmap *lflows)
1781 {
1782     /* Ingress and Egress stateful Table (Priority 0): Packets are
1783      * allowed by default. */
1784     ovn_lflow_add(lflows, od, S_SWITCH_IN_STATEFUL, 0, "1", "next;");
1785     ovn_lflow_add(lflows, od, S_SWITCH_OUT_STATEFUL, 0, "1", "next;");
1786
1787     /* If REGBIT_CONNTRACK_COMMIT is set as 1, then the packets should be
1788      * committed to conntrack. We always set ct_label[0] to 0 here as
1789      * any packet that makes it this far is part of a connection we
1790      * want to allow to continue. */
1791     ovn_lflow_add(lflows, od, S_SWITCH_IN_STATEFUL, 100,
1792                   REGBIT_CONNTRACK_COMMIT" == 1", "ct_commit(ct_label=0/1); next;");
1793     ovn_lflow_add(lflows, od, S_SWITCH_OUT_STATEFUL, 100,
1794                   REGBIT_CONNTRACK_COMMIT" == 1", "ct_commit(ct_label=0/1); next;");
1795
1796     /* If REGBIT_CONNTRACK_NAT is set as 1, then packets should just be sent
1797      * through nat (without committing).
1798      *
1799      * REGBIT_CONNTRACK_COMMIT is set for new connections and
1800      * REGBIT_CONNTRACK_NAT is set for established connections. So they
1801      * don't overlap.
1802      */
1803     ovn_lflow_add(lflows, od, S_SWITCH_IN_STATEFUL, 100,
1804                   REGBIT_CONNTRACK_NAT" == 1", "ct_lb;");
1805     ovn_lflow_add(lflows, od, S_SWITCH_OUT_STATEFUL, 100,
1806                   REGBIT_CONNTRACK_NAT" == 1", "ct_lb;");
1807
1808     /* Load balancing rules for new connections get committed to conntrack
1809      * table.  So even if REGBIT_CONNTRACK_COMMIT is set in a previous table
1810      * a higher priority rule for load balancing below also commits the
1811      * connection, so it is okay if we do not hit the above match on
1812      * REGBIT_CONNTRACK_COMMIT. */
1813     if (od->nbs->load_balancer) {
1814         struct nbrec_load_balancer *lb = od->nbs->load_balancer;
1815         struct smap *vips = &lb->vips;
1816         struct smap_node *node;
1817
1818         SMAP_FOR_EACH (node, vips) {
1819             uint16_t port = 0;
1820
1821             /* node->key contains IP:port or just IP. */
1822             char *ip_address = NULL;
1823             ip_address_and_port_from_lb_key(node->key, &ip_address, &port);
1824             if (!ip_address) {
1825                 continue;
1826             }
1827
1828             /* New connections in Ingress table. */
1829             char *action = xasprintf("ct_lb(%s);", node->value);
1830             struct ds match = DS_EMPTY_INITIALIZER;
1831             ds_put_format(&match, "ct.new && ip && ip4.dst == %s", ip_address);
1832             if (port) {
1833                 if (lb->protocol && !strcmp(lb->protocol, "udp")) {
1834                     ds_put_format(&match, "&& udp && udp.dst == %d", port);
1835                 } else {
1836                     ds_put_format(&match, "&& tcp && tcp.dst == %d", port);
1837                 }
1838                 ovn_lflow_add(lflows, od, S_SWITCH_IN_STATEFUL,
1839                               120, ds_cstr(&match), action);
1840             } else {
1841                 ovn_lflow_add(lflows, od, S_SWITCH_IN_STATEFUL,
1842                               110, ds_cstr(&match), action);
1843             }
1844
1845             ds_destroy(&match);
1846             free(action);
1847        }
1848     }
1849 }
1850
1851 static void
1852 build_lswitch_flows(struct hmap *datapaths, struct hmap *ports,
1853                     struct hmap *lflows, struct hmap *mcgroups)
1854 {
1855     /* This flow table structure is documented in ovn-northd(8), so please
1856      * update ovn-northd.8.xml if you change anything. */
1857
1858     struct ds match = DS_EMPTY_INITIALIZER;
1859     struct ds actions = DS_EMPTY_INITIALIZER;
1860
1861     /* Build pre-ACL and ACL tables for both ingress and egress.
1862      * Ingress tables 3 and 4.  Egress tables 0 and 1. */
1863     struct ovn_datapath *od;
1864     HMAP_FOR_EACH (od, key_node, datapaths) {
1865         if (!od->nbs) {
1866             continue;
1867         }
1868
1869         build_pre_acls(od, lflows, ports);
1870         build_pre_lb(od, lflows);
1871         build_pre_stateful(od, lflows);
1872         build_acls(od, lflows);
1873         build_lb(od, lflows);
1874         build_stateful(od, lflows);
1875     }
1876
1877     /* Logical switch ingress table 0: Admission control framework (priority
1878      * 100). */
1879     HMAP_FOR_EACH (od, key_node, datapaths) {
1880         if (!od->nbs) {
1881             continue;
1882         }
1883
1884         /* Logical VLANs not supported. */
1885         ovn_lflow_add(lflows, od, S_SWITCH_IN_PORT_SEC_L2, 100, "vlan.present",
1886                       "drop;");
1887
1888         /* Broadcast/multicast source address is invalid. */
1889         ovn_lflow_add(lflows, od, S_SWITCH_IN_PORT_SEC_L2, 100, "eth.src[40]",
1890                       "drop;");
1891
1892         /* Port security flows have priority 50 (see below) and will continue
1893          * to the next table if packet source is acceptable. */
1894     }
1895
1896     /* Logical switch ingress table 0: Ingress port security - L2
1897      *  (priority 50).
1898      *  Ingress table 1: Ingress port security - IP (priority 90 and 80)
1899      *  Ingress table 2: Ingress port security - ND (priority 90 and 80)
1900      */
1901     struct ovn_port *op;
1902     HMAP_FOR_EACH (op, key_node, ports) {
1903         if (!op->nbsp) {
1904             continue;
1905         }
1906
1907         if (!lsp_is_enabled(op->nbsp)) {
1908             /* Drop packets from disabled logical ports (since logical flow
1909              * tables are default-drop). */
1910             continue;
1911         }
1912
1913         ds_clear(&match);
1914         ds_put_format(&match, "inport == %s", op->json_key);
1915         build_port_security_l2("eth.src", op->ps_addrs, op->n_ps_addrs,
1916                                &match);
1917         ovn_lflow_add(lflows, op->od, S_SWITCH_IN_PORT_SEC_L2, 50,
1918                       ds_cstr(&match), "next;");
1919
1920         if (op->nbsp->n_port_security) {
1921             build_port_security_ip(P_IN, op, lflows);
1922             build_port_security_nd(op, lflows);
1923         }
1924     }
1925
1926     /* Ingress table 1 and 2: Port security - IP and ND, by default goto next.
1927      * (priority 0)*/
1928     HMAP_FOR_EACH (od, key_node, datapaths) {
1929         if (!od->nbs) {
1930             continue;
1931         }
1932
1933         ovn_lflow_add(lflows, od, S_SWITCH_IN_PORT_SEC_ND, 0, "1", "next;");
1934         ovn_lflow_add(lflows, od, S_SWITCH_IN_PORT_SEC_IP, 0, "1", "next;");
1935     }
1936
1937     /* Ingress table 9: ARP responder, skip requests coming from localnet ports.
1938      * (priority 100). */
1939     HMAP_FOR_EACH (op, key_node, ports) {
1940         if (!op->nbsp) {
1941             continue;
1942         }
1943
1944         if (!strcmp(op->nbsp->type, "localnet")) {
1945             ds_clear(&match);
1946             ds_put_format(&match, "inport == %s", op->json_key);
1947             ovn_lflow_add(lflows, op->od, S_SWITCH_IN_ARP_ND_RSP, 100,
1948                           ds_cstr(&match), "next;");
1949         }
1950     }
1951
1952     /* Ingress table 9: ARP/ND responder, reply for known IPs.
1953      * (priority 50). */
1954     HMAP_FOR_EACH (op, key_node, ports) {
1955         if (!op->nbsp) {
1956             continue;
1957         }
1958
1959         /*
1960          * Add ARP/ND reply flows if either the
1961          *  - port is up or
1962          *  - port type is router
1963          */
1964         if (!lsp_is_up(op->nbsp) && strcmp(op->nbsp->type, "router")) {
1965             continue;
1966         }
1967
1968         for (size_t i = 0; i < op->n_lsp_addrs; i++) {
1969             for (size_t j = 0; j < op->lsp_addrs[i].n_ipv4_addrs; j++) {
1970                 ds_clear(&match);
1971                 ds_put_format(&match, "arp.tpa == %s && arp.op == 1",
1972                               op->lsp_addrs[i].ipv4_addrs[j].addr_s);
1973                 ds_clear(&actions);
1974                 ds_put_format(&actions,
1975                     "eth.dst = eth.src; "
1976                     "eth.src = %s; "
1977                     "arp.op = 2; /* ARP reply */ "
1978                     "arp.tha = arp.sha; "
1979                     "arp.sha = %s; "
1980                     "arp.tpa = arp.spa; "
1981                     "arp.spa = %s; "
1982                     "outport = inport; "
1983                     "inport = \"\"; /* Allow sending out inport. */ "
1984                     "output;",
1985                     op->lsp_addrs[i].ea_s, op->lsp_addrs[i].ea_s,
1986                     op->lsp_addrs[i].ipv4_addrs[j].addr_s);
1987                 ovn_lflow_add(lflows, op->od, S_SWITCH_IN_ARP_ND_RSP, 50,
1988                               ds_cstr(&match), ds_cstr(&actions));
1989             }
1990
1991             if (op->lsp_addrs[i].n_ipv6_addrs > 0) {
1992                 ds_clear(&match);
1993                 ds_put_cstr(&match, "icmp6 && icmp6.type == 135 && ");
1994                 if (op->lsp_addrs[i].n_ipv6_addrs == 1) {
1995                     ds_put_format(&match, "nd.target == %s",
1996                                   op->lsp_addrs[i].ipv6_addrs[0].addr_s);
1997                 } else {
1998                     ds_put_format(&match, "nd.target == {");
1999                     for (size_t j = 0; j < op->lsp_addrs[i].n_ipv6_addrs; j++) {
2000                         ds_put_cstr(&match,
2001                                       op->lsp_addrs[i].ipv6_addrs[j].addr_s);
2002                     }
2003                     ds_chomp(&match, ' ');
2004                     ds_chomp(&match, ',');
2005                     ds_put_cstr(&match, "}");
2006                 }
2007                 ds_clear(&actions);
2008                 ds_put_format(&actions,
2009                     "na { eth.src = %s; "
2010                     "nd.tll = %s; "
2011                     "outport = inport; "
2012                     "inport = \"\"; /* Allow sending out inport. */ "
2013                     "output; };",
2014                     op->lsp_addrs[i].ea_s,
2015                     op->lsp_addrs[i].ea_s);
2016
2017                 ovn_lflow_add(lflows, op->od, S_SWITCH_IN_ARP_ND_RSP, 50,
2018                               ds_cstr(&match), ds_cstr(&actions));
2019
2020             }
2021         }
2022     }
2023
2024     /* Ingress table 9: ARP/ND responder, by default goto next.
2025      * (priority 0)*/
2026     HMAP_FOR_EACH (od, key_node, datapaths) {
2027         if (!od->nbs) {
2028             continue;
2029         }
2030
2031         ovn_lflow_add(lflows, od, S_SWITCH_IN_ARP_ND_RSP, 0, "1", "next;");
2032     }
2033
2034     /* Ingress table 10: Destination lookup, broadcast and multicast handling
2035      * (priority 100). */
2036     HMAP_FOR_EACH (op, key_node, ports) {
2037         if (!op->nbsp) {
2038             continue;
2039         }
2040
2041         if (lsp_is_enabled(op->nbsp)) {
2042             ovn_multicast_add(mcgroups, &mc_flood, op);
2043         }
2044     }
2045     HMAP_FOR_EACH (od, key_node, datapaths) {
2046         if (!od->nbs) {
2047             continue;
2048         }
2049
2050         ovn_lflow_add(lflows, od, S_SWITCH_IN_L2_LKUP, 100, "eth.mcast",
2051                       "outport = \""MC_FLOOD"\"; output;");
2052     }
2053
2054     /* Ingress table 10: Destination lookup, unicast handling (priority 50), */
2055     HMAP_FOR_EACH (op, key_node, ports) {
2056         if (!op->nbsp) {
2057             continue;
2058         }
2059
2060         for (size_t i = 0; i < op->nbsp->n_addresses; i++) {
2061             struct eth_addr mac;
2062
2063             if (eth_addr_from_string(op->nbsp->addresses[i], &mac)) {
2064                 ds_clear(&match);
2065                 ds_put_format(&match, "eth.dst == "ETH_ADDR_FMT,
2066                               ETH_ADDR_ARGS(mac));
2067
2068                 ds_clear(&actions);
2069                 ds_put_format(&actions, "outport = %s; output;", op->json_key);
2070                 ovn_lflow_add(lflows, op->od, S_SWITCH_IN_L2_LKUP, 50,
2071                               ds_cstr(&match), ds_cstr(&actions));
2072             } else if (!strcmp(op->nbsp->addresses[i], "unknown")) {
2073                 if (lsp_is_enabled(op->nbsp)) {
2074                     ovn_multicast_add(mcgroups, &mc_unknown, op);
2075                     op->od->has_unknown = true;
2076                 }
2077             } else {
2078                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
2079
2080                 VLOG_INFO_RL(&rl,
2081                              "%s: invalid syntax '%s' in addresses column",
2082                              op->nbsp->name, op->nbsp->addresses[i]);
2083             }
2084         }
2085     }
2086
2087     /* Ingress table 10: Destination lookup for unknown MACs (priority 0). */
2088     HMAP_FOR_EACH (od, key_node, datapaths) {
2089         if (!od->nbs) {
2090             continue;
2091         }
2092
2093         if (od->has_unknown) {
2094             ovn_lflow_add(lflows, od, S_SWITCH_IN_L2_LKUP, 0, "1",
2095                           "outport = \""MC_UNKNOWN"\"; output;");
2096         }
2097     }
2098
2099     /* Egress tables 6: Egress port security - IP (priority 0)
2100      * Egress table 7: Egress port security L2 - multicast/broadcast
2101      *                 (priority 100). */
2102     HMAP_FOR_EACH (od, key_node, datapaths) {
2103         if (!od->nbs) {
2104             continue;
2105         }
2106
2107         ovn_lflow_add(lflows, od, S_SWITCH_OUT_PORT_SEC_IP, 0, "1", "next;");
2108         ovn_lflow_add(lflows, od, S_SWITCH_OUT_PORT_SEC_L2, 100, "eth.mcast",
2109                       "output;");
2110     }
2111
2112     /* Egress table 6: Egress port security - IP (priorities 90 and 80)
2113      * if port security enabled.
2114      *
2115      * Egress table 7: Egress port security - L2 (priorities 50 and 150).
2116      *
2117      * Priority 50 rules implement port security for enabled logical port.
2118      *
2119      * Priority 150 rules drop packets to disabled logical ports, so that they
2120      * don't even receive multicast or broadcast packets. */
2121     HMAP_FOR_EACH (op, key_node, ports) {
2122         if (!op->nbsp) {
2123             continue;
2124         }
2125
2126         ds_clear(&match);
2127         ds_put_format(&match, "outport == %s", op->json_key);
2128         if (lsp_is_enabled(op->nbsp)) {
2129             build_port_security_l2("eth.dst", op->ps_addrs, op->n_ps_addrs,
2130                                    &match);
2131             ovn_lflow_add(lflows, op->od, S_SWITCH_OUT_PORT_SEC_L2, 50,
2132                           ds_cstr(&match), "output;");
2133         } else {
2134             ovn_lflow_add(lflows, op->od, S_SWITCH_OUT_PORT_SEC_L2, 150,
2135                           ds_cstr(&match), "drop;");
2136         }
2137
2138         if (op->nbsp->n_port_security) {
2139             build_port_security_ip(P_OUT, op, lflows);
2140         }
2141     }
2142
2143     ds_destroy(&match);
2144     ds_destroy(&actions);
2145 }
2146
2147 static bool
2148 lrport_is_enabled(const struct nbrec_logical_router_port *lrport)
2149 {
2150     return !lrport->enabled || *lrport->enabled;
2151 }
2152
2153 /* Returns a string of the IP address of the router port 'op' that
2154  * overlaps with 'ip_s".  If one is not found, returns NULL.
2155  *
2156  * The caller must not free the returned string. */
2157 static const char *
2158 find_lrp_member_ip(const struct ovn_port *op, const char *ip_s)
2159 {
2160     ovs_be32 ip;
2161
2162     if (!ip_parse(ip_s, &ip)) {
2163         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
2164         VLOG_WARN_RL(&rl, "bad ip address %s", ip_s);
2165         return NULL;
2166     }
2167
2168     for (int i = 0; i < op->lrp_networks.n_ipv4_addrs; i++) {
2169         const struct ipv4_netaddr *na = &op->lrp_networks.ipv4_addrs[i];
2170
2171         if (!((na->network ^ ip) & na->mask)) {
2172             /* There should be only 1 interface that matches the
2173              * next hop.  Otherwise, it's a configuration error,
2174              * because subnets of router's interfaces should NOT
2175              * overlap. */
2176             return na->addr_s;
2177         }
2178     }
2179
2180     return NULL;
2181 }
2182
2183 static void
2184 add_route(struct hmap *lflows, const struct ovn_port *op,
2185           const char *lrp_addr_s, const char *network_s, int plen,
2186           const char *gateway)
2187 {
2188     char *match = xasprintf("ip4.dst == %s/%d", network_s, plen);
2189
2190     struct ds actions = DS_EMPTY_INITIALIZER;
2191     ds_put_cstr(&actions, "ip.ttl--; reg0 = ");
2192     if (gateway) {
2193         ds_put_cstr(&actions, gateway);
2194     } else {
2195         ds_put_cstr(&actions, "ip4.dst");
2196     }
2197     ds_put_format(&actions, "; "
2198                   "reg1 = %s; "
2199                   "eth.src = %s; "
2200                   "outport = %s; "
2201                   "inport = \"\"; /* Allow sending out inport. */ "
2202                   "next;",
2203                   lrp_addr_s,
2204                   op->lrp_networks.ea_s,
2205                   op->json_key);
2206
2207     /* The priority here is calculated to implement longest-prefix-match
2208      * routing. */
2209     ovn_lflow_add(lflows, op->od, S_ROUTER_IN_IP_ROUTING, plen, match,
2210                   ds_cstr(&actions));
2211     ds_destroy(&actions);
2212     free(match);
2213 }
2214
2215 static void
2216 build_static_route_flow(struct hmap *lflows, struct ovn_datapath *od,
2217                         struct hmap *ports,
2218                         const struct nbrec_logical_router_static_route *route)
2219 {
2220     ovs_be32 prefix, nexthop, mask;
2221     const char *lrp_addr_s;
2222
2223     /* Verify that next hop is an IP address with 32 bits mask. */
2224     char *error = ip_parse_masked(route->nexthop, &nexthop, &mask);
2225     if (error || mask != OVS_BE32_MAX) {
2226         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
2227         VLOG_WARN_RL(&rl, "bad next hop ip address %s", route->nexthop);
2228         free(error);
2229         return;
2230     }
2231
2232     /* Verify that ip prefix is a valid CIDR address. */
2233     error = ip_parse_masked(route->ip_prefix, &prefix, &mask);
2234     if (error || !ip_is_cidr(mask)) {
2235         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
2236         VLOG_WARN_RL(&rl, "bad 'ip_prefix' in static routes %s",
2237                      route->ip_prefix);
2238         free(error);
2239         return;
2240     }
2241
2242     /* Find the outgoing port. */
2243     struct ovn_port *out_port = NULL;
2244     if (route->output_port) {
2245         out_port = ovn_port_find(ports, route->output_port);
2246         if (!out_port) {
2247             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
2248             VLOG_WARN_RL(&rl, "Bad out port %s for static route %s",
2249                          route->output_port, route->ip_prefix);
2250             return;
2251         }
2252         lrp_addr_s = find_lrp_member_ip(out_port, route->nexthop);
2253     } else {
2254         /* output_port is not specified, find the
2255          * router port matching the next hop. */
2256         int i;
2257         for (i = 0; i < od->nbr->n_ports; i++) {
2258             struct nbrec_logical_router_port *lrp = od->nbr->ports[i];
2259             out_port = ovn_port_find(ports, lrp->name);
2260             if (!out_port) {
2261                 /* This should not happen. */
2262                 continue;
2263             }
2264
2265             lrp_addr_s = find_lrp_member_ip(out_port, route->nexthop);
2266             if (lrp_addr_s) {
2267                 break;
2268             }
2269         }
2270     }
2271
2272      if (!lrp_addr_s) {
2273         /* There is no matched out port. */
2274         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
2275         VLOG_WARN_RL(&rl, "No path for static route %s; next hop %s",
2276                      route->ip_prefix, route->nexthop);
2277         return;
2278     }
2279
2280     char *prefix_s = xasprintf(IP_FMT, IP_ARGS(prefix & mask));
2281     add_route(lflows, out_port, lrp_addr_s, prefix_s,
2282               ip_count_cidr_bits(mask), route->nexthop);
2283     free(prefix_s);
2284 }
2285
2286 static void
2287 op_put_networks(struct ds *ds, const struct ovn_port *op, bool add_bcast)
2288 {
2289     if (!add_bcast && op->lrp_networks.n_ipv4_addrs == 1) {
2290         ds_put_format(ds, "%s", op->lrp_networks.ipv4_addrs[0].addr_s);
2291         return;
2292     }
2293
2294     ds_put_cstr(ds, "{");
2295     for (int i = 0; i < op->lrp_networks.n_ipv4_addrs; i++) {
2296         ds_put_format(ds, "%s, ", op->lrp_networks.ipv4_addrs[i].addr_s);
2297         if (add_bcast) {
2298             ds_put_format(ds, "%s, ", op->lrp_networks.ipv4_addrs[i].bcast_s);
2299         }
2300     }
2301     ds_chomp(ds, ' ');
2302     ds_chomp(ds, ',');
2303     ds_put_cstr(ds, "}");
2304 }
2305
2306 static void
2307 build_lrouter_flows(struct hmap *datapaths, struct hmap *ports,
2308                     struct hmap *lflows)
2309 {
2310     /* This flow table structure is documented in ovn-northd(8), so please
2311      * update ovn-northd.8.xml if you change anything. */
2312
2313     struct ds match = DS_EMPTY_INITIALIZER;
2314     struct ds actions = DS_EMPTY_INITIALIZER;
2315
2316     /* Logical router ingress table 0: Admission control framework. */
2317     struct ovn_datapath *od;
2318     HMAP_FOR_EACH (od, key_node, datapaths) {
2319         if (!od->nbr) {
2320             continue;
2321         }
2322
2323         /* Logical VLANs not supported.
2324          * Broadcast/multicast source address is invalid. */
2325         ovn_lflow_add(lflows, od, S_ROUTER_IN_ADMISSION, 100,
2326                       "vlan.present || eth.src[40]", "drop;");
2327     }
2328
2329     /* Logical router ingress table 0: match (priority 50). */
2330     struct ovn_port *op;
2331     HMAP_FOR_EACH (op, key_node, ports) {
2332         if (!op->nbrp) {
2333             continue;
2334         }
2335
2336         if (!lrport_is_enabled(op->nbrp)) {
2337             /* Drop packets from disabled logical ports (since logical flow
2338              * tables are default-drop). */
2339             continue;
2340         }
2341
2342         ds_clear(&match);
2343         ds_put_format(&match, "(eth.mcast || eth.dst == %s) && inport == %s",
2344                       op->lrp_networks.ea_s, op->json_key);
2345         ovn_lflow_add(lflows, op->od, S_ROUTER_IN_ADMISSION, 50,
2346                       ds_cstr(&match), "next;");
2347     }
2348
2349     /* Logical router ingress table 1: IP Input. */
2350     HMAP_FOR_EACH (od, key_node, datapaths) {
2351         if (!od->nbr) {
2352             continue;
2353         }
2354
2355         /* L3 admission control: drop multicast and broadcast source, localhost
2356          * source or destination, and zero network source or destination
2357          * (priority 100). */
2358         ovn_lflow_add(lflows, od, S_ROUTER_IN_IP_INPUT, 100,
2359                       "ip4.mcast || "
2360                       "ip4.src == 255.255.255.255 || "
2361                       "ip4.src == 127.0.0.0/8 || "
2362                       "ip4.dst == 127.0.0.0/8 || "
2363                       "ip4.src == 0.0.0.0/8 || "
2364                       "ip4.dst == 0.0.0.0/8",
2365                       "drop;");
2366
2367         /* ARP reply handling.  Use ARP replies to populate the logical
2368          * router's ARP table. */
2369         ovn_lflow_add(lflows, od, S_ROUTER_IN_IP_INPUT, 90, "arp.op == 2",
2370                       "put_arp(inport, arp.spa, arp.sha);");
2371
2372         /* Drop Ethernet local broadcast.  By definition this traffic should
2373          * not be forwarded.*/
2374         ovn_lflow_add(lflows, od, S_ROUTER_IN_IP_INPUT, 50,
2375                       "eth.bcast", "drop;");
2376
2377         /* TTL discard.
2378          *
2379          * XXX Need to send ICMP time exceeded if !ip.later_frag. */
2380         ds_clear(&match);
2381         ds_put_cstr(&match, "ip4 && ip.ttl == {0, 1}");
2382         ovn_lflow_add(lflows, od, S_ROUTER_IN_IP_INPUT, 30,
2383                       ds_cstr(&match), "drop;");
2384
2385         /* Pass other traffic not already handled to the next table for
2386          * routing. */
2387         ovn_lflow_add(lflows, od, S_ROUTER_IN_IP_INPUT, 0, "1", "next;");
2388     }
2389
2390     HMAP_FOR_EACH (op, key_node, ports) {
2391         if (!op->nbrp) {
2392             continue;
2393         }
2394
2395         /* L3 admission control: drop packets that originate from an IP address
2396          * owned by the router or a broadcast address known to the router
2397          * (priority 100). */
2398         ds_clear(&match);
2399         ds_put_cstr(&match, "ip4.src == ");
2400         op_put_networks(&match, op, true);
2401         ovn_lflow_add(lflows, op->od, S_ROUTER_IN_IP_INPUT, 100,
2402                       ds_cstr(&match), "drop;");
2403
2404         /* ICMP echo reply.  These flows reply to ICMP echo requests
2405          * received for the router's IP address. Since packets only
2406          * get here as part of the logical router datapath, the inport
2407          * (i.e. the incoming locally attached net) does not matter.
2408          * The ip.ttl also does not matter (RFC1812 section 4.2.2.9) */
2409         ds_clear(&match);
2410         ds_put_cstr(&match, "ip4.dst == ");
2411         op_put_networks(&match, op, false);
2412         ds_put_cstr(&match, " && icmp4.type == 8 && icmp4.code == 0");
2413
2414         ds_clear(&actions);
2415         ds_put_format(&actions,
2416             "ip4.dst <-> ip4.src; "
2417             "ip.ttl = 255; "
2418             "icmp4.type = 0; "
2419             "inport = \"\"; /* Allow sending out inport. */ "
2420             "next; ");
2421         ovn_lflow_add(lflows, op->od, S_ROUTER_IN_IP_INPUT, 90,
2422                       ds_cstr(&match), ds_cstr(&actions));
2423
2424         /* ARP reply.  These flows reply to ARP requests for the router's own
2425          * IP address. */
2426         for (int i = 0; i < op->lrp_networks.n_ipv4_addrs; i++) {
2427             ds_clear(&match);
2428             ds_put_format(&match,
2429                           "inport == %s && arp.tpa == %s && arp.op == 1",
2430                           op->json_key, op->lrp_networks.ipv4_addrs[i].addr_s);
2431
2432             ds_clear(&actions);
2433             ds_put_format(&actions,
2434                 "eth.dst = eth.src; "
2435                 "eth.src = %s; "
2436                 "arp.op = 2; /* ARP reply */ "
2437                 "arp.tha = arp.sha; "
2438                 "arp.sha = %s; "
2439                 "arp.tpa = arp.spa; "
2440                 "arp.spa = %s; "
2441                 "outport = %s; "
2442                 "inport = \"\"; /* Allow sending out inport. */ "
2443                 "output;",
2444                 op->lrp_networks.ea_s,
2445                 op->lrp_networks.ea_s,
2446                 op->lrp_networks.ipv4_addrs[i].addr_s,
2447                 op->json_key);
2448             ovn_lflow_add(lflows, op->od, S_ROUTER_IN_IP_INPUT, 90,
2449                           ds_cstr(&match), ds_cstr(&actions));
2450         }
2451
2452         /* ARP handling for external IP addresses.
2453          *
2454          * DNAT IP addresses are external IP addresses that need ARP
2455          * handling. */
2456         for (int i = 0; i < op->od->nbr->n_nat; i++) {
2457             const struct nbrec_nat *nat;
2458
2459             nat = op->od->nbr->nat[i];
2460
2461             if(!strcmp(nat->type, "snat")) {
2462                 continue;
2463             }
2464
2465             ovs_be32 ip;
2466             if (!ip_parse(nat->external_ip, &ip) || !ip) {
2467                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
2468                 VLOG_WARN_RL(&rl, "bad ip address %s in dnat configuration "
2469                              "for router %s", nat->external_ip, op->key);
2470                 continue;
2471             }
2472
2473             ds_clear(&match);
2474             ds_put_format(&match,
2475                           "inport == %s && arp.tpa == "IP_FMT" && arp.op == 1",
2476                           op->json_key, IP_ARGS(ip));
2477
2478             ds_clear(&actions);
2479             ds_put_format(&actions,
2480                 "eth.dst = eth.src; "
2481                 "eth.src = %s; "
2482                 "arp.op = 2; /* ARP reply */ "
2483                 "arp.tha = arp.sha; "
2484                 "arp.sha = %s; "
2485                 "arp.tpa = arp.spa; "
2486                 "arp.spa = "IP_FMT"; "
2487                 "outport = %s; "
2488                 "inport = \"\"; /* Allow sending out inport. */ "
2489                 "output;",
2490                 op->lrp_networks.ea_s,
2491                 op->lrp_networks.ea_s,
2492                 IP_ARGS(ip),
2493                 op->json_key);
2494             ovn_lflow_add(lflows, op->od, S_ROUTER_IN_IP_INPUT, 90,
2495                           ds_cstr(&match), ds_cstr(&actions));
2496         }
2497
2498         /* Drop IP traffic to this router, unless the router ip is used as
2499          * SNAT ip. */
2500         ovs_be32 *nat_ips = xmalloc(sizeof *nat_ips * op->od->nbr->n_nat);
2501         size_t n_nat_ips = 0;
2502         for (int i = 0; i < op->od->nbr->n_nat; i++) {
2503             const struct nbrec_nat *nat;
2504             ovs_be32 ip;
2505
2506             nat = op->od->nbr->nat[i];
2507             if (strcmp(nat->type, "snat")) {
2508                 continue;
2509             }
2510
2511             if (!ip_parse(nat->external_ip, &ip) || !ip) {
2512                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
2513                 VLOG_WARN_RL(&rl, "bad ip address %s in snat configuration "
2514                          "for router %s", nat->external_ip, op->key);
2515                 continue;
2516             }
2517
2518             nat_ips[n_nat_ips++] = ip;
2519         }
2520
2521         ds_clear(&match);
2522         ds_put_cstr(&match, "ip4.dst == {");
2523         bool has_drop_ips = false;
2524         for (int i = 0; i < op->lrp_networks.n_ipv4_addrs; i++) {
2525             for (int j = 0; j < n_nat_ips; j++) {
2526                 if (op->lrp_networks.ipv4_addrs[i].addr == nat_ips[j]) {
2527                     continue;
2528                 }
2529             }
2530             ds_put_format(&match, "%s, ",
2531                           op->lrp_networks.ipv4_addrs[i].addr_s);
2532             has_drop_ips = true;
2533         }
2534         ds_chomp(&match, ' ');
2535         ds_chomp(&match, ',');
2536         ds_put_cstr(&match, "}");
2537
2538         if (has_drop_ips) {
2539             /* Drop IP traffic to this router. */
2540             ovn_lflow_add(lflows, op->od, S_ROUTER_IN_IP_INPUT, 60,
2541                           ds_cstr(&match), "drop;");
2542         }
2543
2544         free(nat_ips);
2545     }
2546
2547     /* NAT in Gateway routers. */
2548     HMAP_FOR_EACH (od, key_node, datapaths) {
2549         if (!od->nbr) {
2550             continue;
2551         }
2552
2553         /* Packets are allowed by default. */
2554         ovn_lflow_add(lflows, od, S_ROUTER_IN_UNSNAT, 0, "1", "next;");
2555         ovn_lflow_add(lflows, od, S_ROUTER_OUT_SNAT, 0, "1", "next;");
2556         ovn_lflow_add(lflows, od, S_ROUTER_IN_DNAT, 0, "1", "next;");
2557
2558         /* NAT rules are only valid on Gateway routers. */
2559         if (!smap_get(&od->nbr->options, "chassis")) {
2560             continue;
2561         }
2562
2563         for (int i = 0; i < od->nbr->n_nat; i++) {
2564             const struct nbrec_nat *nat;
2565
2566             nat = od->nbr->nat[i];
2567
2568             ovs_be32 ip, mask;
2569
2570             char *error = ip_parse_masked(nat->external_ip, &ip, &mask);
2571             if (error || mask != OVS_BE32_MAX) {
2572                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
2573                 VLOG_WARN_RL(&rl, "bad external ip %s for nat",
2574                              nat->external_ip);
2575                 free(error);
2576                 continue;
2577             }
2578
2579             /* Check the validity of nat->logical_ip. 'logical_ip' can
2580              * be a subnet when the type is "snat". */
2581             error = ip_parse_masked(nat->logical_ip, &ip, &mask);
2582             if (!strcmp(nat->type, "snat")) {
2583                 if (error) {
2584                     static struct vlog_rate_limit rl =
2585                         VLOG_RATE_LIMIT_INIT(5, 1);
2586                     VLOG_WARN_RL(&rl, "bad ip network or ip %s for snat "
2587                                  "in router "UUID_FMT"",
2588                                  nat->logical_ip, UUID_ARGS(&od->key));
2589                     free(error);
2590                     continue;
2591                 }
2592             } else {
2593                 if (error || mask != OVS_BE32_MAX) {
2594                     static struct vlog_rate_limit rl =
2595                         VLOG_RATE_LIMIT_INIT(5, 1);
2596                     VLOG_WARN_RL(&rl, "bad ip %s for dnat in router "
2597                         ""UUID_FMT"", nat->logical_ip, UUID_ARGS(&od->key));
2598                     free(error);
2599                     continue;
2600                 }
2601             }
2602
2603             /* Ingress UNSNAT table: It is for already established connections'
2604              * reverse traffic. i.e., SNAT has already been done in egress
2605              * pipeline and now the packet has entered the ingress pipeline as
2606              * part of a reply. We undo the SNAT here.
2607              *
2608              * Undoing SNAT has to happen before DNAT processing.  This is
2609              * because when the packet was DNATed in ingress pipeline, it did
2610              * not know about the possibility of eventual additional SNAT in
2611              * egress pipeline. */
2612             if (!strcmp(nat->type, "snat")
2613                 || !strcmp(nat->type, "dnat_and_snat")) {
2614                 ds_clear(&match);
2615                 ds_put_format(&match, "ip && ip4.dst == %s", nat->external_ip);
2616                 ovn_lflow_add(lflows, od, S_ROUTER_IN_UNSNAT, 100,
2617                               ds_cstr(&match), "ct_snat; next;");
2618             }
2619
2620             /* Ingress DNAT table: Packets enter the pipeline with destination
2621              * IP address that needs to be DNATted from a external IP address
2622              * to a logical IP address. */
2623             if (!strcmp(nat->type, "dnat")
2624                 || !strcmp(nat->type, "dnat_and_snat")) {
2625                 /* Packet when it goes from the initiator to destination.
2626                  * We need to zero the inport because the router can
2627                  * send the packet back through the same interface. */
2628                 ds_clear(&match);
2629                 ds_put_format(&match, "ip && ip4.dst == %s", nat->external_ip);
2630                 ds_clear(&actions);
2631                 ds_put_format(&actions,"inport = \"\"; ct_dnat(%s);",
2632                               nat->logical_ip);
2633                 ovn_lflow_add(lflows, od, S_ROUTER_IN_DNAT, 100,
2634                               ds_cstr(&match), ds_cstr(&actions));
2635             }
2636
2637             /* Egress SNAT table: Packets enter the egress pipeline with
2638              * source ip address that needs to be SNATted to a external ip
2639              * address. */
2640             if (!strcmp(nat->type, "snat")
2641                 || !strcmp(nat->type, "dnat_and_snat")) {
2642                 ds_clear(&match);
2643                 ds_put_format(&match, "ip && ip4.src == %s", nat->logical_ip);
2644                 ds_clear(&actions);
2645                 ds_put_format(&actions, "ct_snat(%s);", nat->external_ip);
2646
2647                 /* The priority here is calculated such that the
2648                  * nat->logical_ip with the longest mask gets a higher
2649                  * priority. */
2650                 ovn_lflow_add(lflows, od, S_ROUTER_OUT_SNAT,
2651                               count_1bits(ntohl(mask)) + 1,
2652                               ds_cstr(&match), ds_cstr(&actions));
2653             }
2654         }
2655
2656         /* Re-circulate every packet through the DNAT zone.
2657         * This helps with two things.
2658         *
2659         * 1. Any packet that needs to be unDNATed in the reverse
2660         * direction gets unDNATed. Ideally this could be done in
2661         * the egress pipeline. But since the gateway router
2662         * does not have any feature that depends on the source
2663         * ip address being external IP address for IP routing,
2664         * we can do it here, saving a future re-circulation.
2665         *
2666         * 2. Any packet that was sent through SNAT zone in the
2667         * previous table automatically gets re-circulated to get
2668         * back the new destination IP address that is needed for
2669         * routing in the openflow pipeline. */
2670         ovn_lflow_add(lflows, od, S_ROUTER_IN_DNAT, 50,
2671                       "ip", "inport = \"\"; ct_dnat;");
2672     }
2673
2674     /* Logical router ingress table 4: IP Routing.
2675      *
2676      * A packet that arrives at this table is an IP packet that should be
2677      * routed to the address in ip4.dst. This table sets outport to the correct
2678      * output port, eth.src to the output port's MAC address, and reg0 to the
2679      * next-hop IP address (leaving ip4.dst, the packet’s final destination,
2680      * unchanged), and advances to the next table for ARP resolution. */
2681     HMAP_FOR_EACH (op, key_node, ports) {
2682         if (!op->nbrp) {
2683             continue;
2684         }
2685
2686         for (int i = 0; i < op->lrp_networks.n_ipv4_addrs; i++) {
2687             add_route(lflows, op, op->lrp_networks.ipv4_addrs[i].addr_s,
2688                       op->lrp_networks.ipv4_addrs[i].network_s,
2689                       op->lrp_networks.ipv4_addrs[i].plen, NULL);
2690         }
2691     }
2692
2693     HMAP_FOR_EACH (od, key_node, datapaths) {
2694         if (!od->nbr) {
2695             continue;
2696         }
2697
2698         /* Convert the static routes to flows. */
2699         for (int i = 0; i < od->nbr->n_static_routes; i++) {
2700             const struct nbrec_logical_router_static_route *route;
2701
2702             route = od->nbr->static_routes[i];
2703             build_static_route_flow(lflows, od, ports, route);
2704         }
2705     }
2706     /* XXX destination unreachable */
2707
2708     /* Local router ingress table 5: ARP Resolution.
2709      *
2710      * Any packet that reaches this table is an IP packet whose next-hop IP
2711      * address is in reg0. (ip4.dst is the final destination.) This table
2712      * resolves the IP address in reg0 into an output port in outport and an
2713      * Ethernet address in eth.dst. */
2714     HMAP_FOR_EACH (op, key_node, ports) {
2715         if (op->nbrp) {
2716             /* This is a logical router port. If next-hop IP address in 'reg0'
2717              * matches ip address of this router port, then the packet is
2718              * intended to eventually be sent to this logical port. Set the
2719              * destination mac address using this port's mac address.
2720              *
2721              * The packet is still in peer's logical pipeline. So the match
2722              * should be on peer's outport. */
2723             if (op->nbrp->peer) {
2724                 struct ovn_port *peer = ovn_port_find(ports, op->nbrp->peer);
2725                 if (!peer) {
2726                     continue;
2727                 }
2728
2729                 ds_clear(&match);
2730                 ds_put_format(&match, "outport == %s && reg0 == ",
2731                               peer->json_key);
2732                 op_put_networks(&match, op, false);
2733
2734                 ds_clear(&actions);
2735                 ds_put_format(&actions, "eth.dst = %s; next;",
2736                               op->lrp_networks.ea_s);
2737                 ovn_lflow_add(lflows, peer->od, S_ROUTER_IN_ARP_RESOLVE,
2738                               100, ds_cstr(&match), ds_cstr(&actions));
2739             }
2740         } else if (op->od->n_router_ports && strcmp(op->nbsp->type, "router")) {
2741             /* This is a logical switch port that backs a VM or a container.
2742              * Extract its addresses. For each of the address, go through all
2743              * the router ports attached to the switch (to which this port
2744              * connects) and if the address in question is reachable from the
2745              * router port, add an ARP entry in that router's pipeline. */
2746
2747             for (size_t i = 0; i < op->n_lsp_addrs; i++) {
2748                 const char *ea_s = op->lsp_addrs[i].ea_s;
2749                 for (size_t j = 0; j < op->lsp_addrs[i].n_ipv4_addrs; j++) {
2750                     const char *ip_s = op->lsp_addrs[i].ipv4_addrs[j].addr_s;
2751                     for (size_t k = 0; k < op->od->n_router_ports; k++) {
2752                         /* Get the Logical_Router_Port that the
2753                          * Logical_Switch_Port is connected to, as
2754                          * 'peer'. */
2755                         const char *peer_name = smap_get(
2756                             &op->od->router_ports[k]->nbsp->options,
2757                             "router-port");
2758                         if (!peer_name) {
2759                             continue;
2760                         }
2761
2762                         struct ovn_port *peer = ovn_port_find(ports, peer_name);
2763                         if (!peer || !peer->nbrp) {
2764                             continue;
2765                         }
2766
2767                         if (!find_lrp_member_ip(peer, ip_s)) {
2768                             continue;
2769                         }
2770
2771                         ds_clear(&match);
2772                         ds_put_format(&match, "outport == %s && reg0 == %s",
2773                                       peer->json_key, ip_s);
2774
2775                         ds_clear(&actions);
2776                         ds_put_format(&actions, "eth.dst = %s; next;", ea_s);
2777                         ovn_lflow_add(lflows, peer->od,
2778                                       S_ROUTER_IN_ARP_RESOLVE, 100,
2779                                       ds_cstr(&match), ds_cstr(&actions));
2780                     }
2781                 }
2782             }
2783         } else if (!strcmp(op->nbsp->type, "router")) {
2784             /* This is a logical switch port that connects to a router. */
2785
2786             /* The peer of this switch port is the router port for which
2787              * we need to add logical flows such that it can resolve
2788              * ARP entries for all the other router ports connected to
2789              * the switch in question. */
2790
2791             const char *peer_name = smap_get(&op->nbsp->options,
2792                                              "router-port");
2793             if (!peer_name) {
2794                 continue;
2795             }
2796
2797             struct ovn_port *peer = ovn_port_find(ports, peer_name);
2798             if (!peer || !peer->nbrp) {
2799                 continue;
2800             }
2801
2802             for (size_t i = 0; i < op->od->n_router_ports; i++) {
2803                 const char *router_port_name = smap_get(
2804                                     &op->od->router_ports[i]->nbsp->options,
2805                                     "router-port");
2806                 struct ovn_port *router_port = ovn_port_find(ports,
2807                                                              router_port_name);
2808                 if (!router_port || !router_port->nbrp) {
2809                     continue;
2810                 }
2811
2812                 /* Skip the router port under consideration. */
2813                 if (router_port == peer) {
2814                    continue;
2815                 }
2816
2817                 ds_clear(&match);
2818                 ds_put_format(&match, "outport == %s && reg0 == ",
2819                               peer->json_key);
2820                 op_put_networks(&match, router_port, false);
2821
2822                 ds_clear(&actions);
2823                 ds_put_format(&actions, "eth.dst = %s; next;",
2824                               router_port->lrp_networks.ea_s);
2825                 ovn_lflow_add(lflows, peer->od, S_ROUTER_IN_ARP_RESOLVE,
2826                               100, ds_cstr(&match), ds_cstr(&actions));
2827             }
2828         }
2829     }
2830
2831     HMAP_FOR_EACH (od, key_node, datapaths) {
2832         if (!od->nbr) {
2833             continue;
2834         }
2835
2836         ovn_lflow_add(lflows, od, S_ROUTER_IN_ARP_RESOLVE, 0, "1",
2837                       "get_arp(outport, reg0); next;");
2838     }
2839
2840     /* Local router ingress table 6: ARP request.
2841      *
2842      * In the common case where the Ethernet destination has been resolved,
2843      * this table outputs the packet (priority 0).  Otherwise, it composes
2844      * and sends an ARP request (priority 100). */
2845     HMAP_FOR_EACH (od, key_node, datapaths) {
2846         if (!od->nbr) {
2847             continue;
2848         }
2849
2850         ovn_lflow_add(lflows, od, S_ROUTER_IN_ARP_REQUEST, 100,
2851                       "eth.dst == 00:00:00:00:00:00",
2852                       "arp { "
2853                       "eth.dst = ff:ff:ff:ff:ff:ff; "
2854                       "arp.spa = reg1; "
2855                       "arp.op = 1; " /* ARP request */
2856                       "output; "
2857                       "};");
2858         ovn_lflow_add(lflows, od, S_ROUTER_IN_ARP_REQUEST, 0, "1", "output;");
2859     }
2860
2861     /* Logical router egress table 1: Delivery (priority 100).
2862      *
2863      * Priority 100 rules deliver packets to enabled logical ports. */
2864     HMAP_FOR_EACH (op, key_node, ports) {
2865         if (!op->nbrp) {
2866             continue;
2867         }
2868
2869         if (!lrport_is_enabled(op->nbrp)) {
2870             /* Drop packets to disabled logical ports (since logical flow
2871              * tables are default-drop). */
2872             continue;
2873         }
2874
2875         ds_clear(&match);
2876         ds_put_format(&match, "outport == %s", op->json_key);
2877         ovn_lflow_add(lflows, op->od, S_ROUTER_OUT_DELIVERY, 100,
2878                       ds_cstr(&match), "output;");
2879     }
2880
2881     ds_destroy(&match);
2882     ds_destroy(&actions);
2883 }
2884
2885 /* Updates the Logical_Flow and Multicast_Group tables in the OVN_SB database,
2886  * constructing their contents based on the OVN_NB database. */
2887 static void
2888 build_lflows(struct northd_context *ctx, struct hmap *datapaths,
2889              struct hmap *ports)
2890 {
2891     struct hmap lflows = HMAP_INITIALIZER(&lflows);
2892     struct hmap mcgroups = HMAP_INITIALIZER(&mcgroups);
2893
2894     build_lswitch_flows(datapaths, ports, &lflows, &mcgroups);
2895     build_lrouter_flows(datapaths, ports, &lflows);
2896
2897     /* Push changes to the Logical_Flow table to database. */
2898     const struct sbrec_logical_flow *sbflow, *next_sbflow;
2899     SBREC_LOGICAL_FLOW_FOR_EACH_SAFE (sbflow, next_sbflow, ctx->ovnsb_idl) {
2900         struct ovn_datapath *od
2901             = ovn_datapath_from_sbrec(datapaths, sbflow->logical_datapath);
2902         if (!od) {
2903             sbrec_logical_flow_delete(sbflow);
2904             continue;
2905         }
2906
2907         enum ovn_datapath_type dp_type = od->nbs ? DP_SWITCH : DP_ROUTER;
2908         enum ovn_pipeline pipeline
2909             = !strcmp(sbflow->pipeline, "ingress") ? P_IN : P_OUT;
2910         struct ovn_lflow *lflow = ovn_lflow_find(
2911             &lflows, od, ovn_stage_build(dp_type, pipeline, sbflow->table_id),
2912             sbflow->priority, sbflow->match, sbflow->actions);
2913         if (lflow) {
2914             ovn_lflow_destroy(&lflows, lflow);
2915         } else {
2916             sbrec_logical_flow_delete(sbflow);
2917         }
2918     }
2919     struct ovn_lflow *lflow, *next_lflow;
2920     HMAP_FOR_EACH_SAFE (lflow, next_lflow, hmap_node, &lflows) {
2921         enum ovn_pipeline pipeline = ovn_stage_get_pipeline(lflow->stage);
2922         uint8_t table = ovn_stage_get_table(lflow->stage);
2923
2924         sbflow = sbrec_logical_flow_insert(ctx->ovnsb_txn);
2925         sbrec_logical_flow_set_logical_datapath(sbflow, lflow->od->sb);
2926         sbrec_logical_flow_set_pipeline(
2927             sbflow, pipeline == P_IN ? "ingress" : "egress");
2928         sbrec_logical_flow_set_table_id(sbflow, table);
2929         sbrec_logical_flow_set_priority(sbflow, lflow->priority);
2930         sbrec_logical_flow_set_match(sbflow, lflow->match);
2931         sbrec_logical_flow_set_actions(sbflow, lflow->actions);
2932
2933         const struct smap ids = SMAP_CONST1(&ids, "stage-name",
2934                                             ovn_stage_to_str(lflow->stage));
2935         sbrec_logical_flow_set_external_ids(sbflow, &ids);
2936
2937         ovn_lflow_destroy(&lflows, lflow);
2938     }
2939     hmap_destroy(&lflows);
2940
2941     /* Push changes to the Multicast_Group table to database. */
2942     const struct sbrec_multicast_group *sbmc, *next_sbmc;
2943     SBREC_MULTICAST_GROUP_FOR_EACH_SAFE (sbmc, next_sbmc, ctx->ovnsb_idl) {
2944         struct ovn_datapath *od = ovn_datapath_from_sbrec(datapaths,
2945                                                           sbmc->datapath);
2946         if (!od) {
2947             sbrec_multicast_group_delete(sbmc);
2948             continue;
2949         }
2950
2951         struct multicast_group group = { .name = sbmc->name,
2952                                          .key = sbmc->tunnel_key };
2953         struct ovn_multicast *mc = ovn_multicast_find(&mcgroups, od, &group);
2954         if (mc) {
2955             ovn_multicast_update_sbrec(mc, sbmc);
2956             ovn_multicast_destroy(&mcgroups, mc);
2957         } else {
2958             sbrec_multicast_group_delete(sbmc);
2959         }
2960     }
2961     struct ovn_multicast *mc, *next_mc;
2962     HMAP_FOR_EACH_SAFE (mc, next_mc, hmap_node, &mcgroups) {
2963         sbmc = sbrec_multicast_group_insert(ctx->ovnsb_txn);
2964         sbrec_multicast_group_set_datapath(sbmc, mc->datapath->sb);
2965         sbrec_multicast_group_set_name(sbmc, mc->group->name);
2966         sbrec_multicast_group_set_tunnel_key(sbmc, mc->group->key);
2967         ovn_multicast_update_sbrec(mc, sbmc);
2968         ovn_multicast_destroy(&mcgroups, mc);
2969     }
2970     hmap_destroy(&mcgroups);
2971 }
2972
2973 /* OVN_Northbound and OVN_Southbound have an identical Address_Set table.
2974  * We always update OVN_Southbound to match the current data in
2975  * OVN_Northbound, so that the address sets used in Logical_Flows in
2976  * OVN_Southbound is checked against the proper set.*/
2977 static void
2978 sync_address_sets(struct northd_context *ctx)
2979 {
2980     struct shash sb_address_sets = SHASH_INITIALIZER(&sb_address_sets);
2981
2982     const struct sbrec_address_set *sb_address_set;
2983     SBREC_ADDRESS_SET_FOR_EACH (sb_address_set, ctx->ovnsb_idl) {
2984         shash_add(&sb_address_sets, sb_address_set->name, sb_address_set);
2985     }
2986
2987     const struct nbrec_address_set *nb_address_set;
2988     NBREC_ADDRESS_SET_FOR_EACH (nb_address_set, ctx->ovnnb_idl) {
2989         sb_address_set = shash_find_and_delete(&sb_address_sets,
2990                                                nb_address_set->name);
2991         if (!sb_address_set) {
2992             sb_address_set = sbrec_address_set_insert(ctx->ovnsb_txn);
2993             sbrec_address_set_set_name(sb_address_set, nb_address_set->name);
2994         }
2995
2996         sbrec_address_set_set_addresses(sb_address_set,
2997                 /* "char **" is not compatible with "const char **" */
2998                 (const char **) nb_address_set->addresses,
2999                 nb_address_set->n_addresses);
3000     }
3001
3002     struct shash_node *node, *next;
3003     SHASH_FOR_EACH_SAFE (node, next, &sb_address_sets) {
3004         sbrec_address_set_delete(node->data);
3005         shash_delete(&sb_address_sets, node);
3006     }
3007     shash_destroy(&sb_address_sets);
3008 }
3009 \f
3010 static void
3011 ovnnb_db_run(struct northd_context *ctx)
3012 {
3013     if (!ctx->ovnsb_txn) {
3014         return;
3015     }
3016     struct hmap datapaths, ports;
3017     build_datapaths(ctx, &datapaths);
3018     build_ports(ctx, &datapaths, &ports);
3019     build_lflows(ctx, &datapaths, &ports);
3020
3021     sync_address_sets(ctx);
3022
3023     struct ovn_datapath *dp, *next_dp;
3024     HMAP_FOR_EACH_SAFE (dp, next_dp, key_node, &datapaths) {
3025         ovn_datapath_destroy(&datapaths, dp);
3026     }
3027     hmap_destroy(&datapaths);
3028
3029     struct ovn_port *port, *next_port;
3030     HMAP_FOR_EACH_SAFE (port, next_port, key_node, &ports) {
3031         ovn_port_destroy(&ports, port);
3032     }
3033     hmap_destroy(&ports);
3034 }
3035
3036 /*
3037  * The only change we get notified about is if the 'chassis' column of the
3038  * 'Port_Binding' table changes.  When this column is not empty, it means we
3039  * need to set the corresponding logical port as 'up' in the northbound DB.
3040  */
3041 static void
3042 ovnsb_db_run(struct northd_context *ctx)
3043 {
3044     if (!ctx->ovnnb_txn) {
3045         return;
3046     }
3047     struct hmap lports_hmap;
3048     const struct sbrec_port_binding *sb;
3049     const struct nbrec_logical_switch_port *nbsp;
3050
3051     struct lport_hash_node {
3052         struct hmap_node node;
3053         const struct nbrec_logical_switch_port *nbsp;
3054     } *hash_node;
3055
3056     hmap_init(&lports_hmap);
3057
3058     NBREC_LOGICAL_SWITCH_PORT_FOR_EACH(nbsp, ctx->ovnnb_idl) {
3059         hash_node = xzalloc(sizeof *hash_node);
3060         hash_node->nbsp = nbsp;
3061         hmap_insert(&lports_hmap, &hash_node->node, hash_string(nbsp->name, 0));
3062     }
3063
3064     SBREC_PORT_BINDING_FOR_EACH(sb, ctx->ovnsb_idl) {
3065         nbsp = NULL;
3066         HMAP_FOR_EACH_WITH_HASH(hash_node, node,
3067                                 hash_string(sb->logical_port, 0),
3068                                 &lports_hmap) {
3069             if (!strcmp(sb->logical_port, hash_node->nbsp->name)) {
3070                 nbsp = hash_node->nbsp;
3071                 break;
3072             }
3073         }
3074
3075         if (!nbsp) {
3076             /* The logical port doesn't exist for this port binding.  This can
3077              * happen under normal circumstances when ovn-northd hasn't gotten
3078              * around to pruning the Port_Binding yet. */
3079             continue;
3080         }
3081
3082         if (sb->chassis && (!nbsp->up || !*nbsp->up)) {
3083             bool up = true;
3084             nbrec_logical_switch_port_set_up(nbsp, &up, 1);
3085         } else if (!sb->chassis && (!nbsp->up || *nbsp->up)) {
3086             bool up = false;
3087             nbrec_logical_switch_port_set_up(nbsp, &up, 1);
3088         }
3089     }
3090
3091     HMAP_FOR_EACH_POP(hash_node, node, &lports_hmap) {
3092         free(hash_node);
3093     }
3094     hmap_destroy(&lports_hmap);
3095 }
3096 \f
3097
3098 static char *default_nb_db_;
3099
3100 static const char *
3101 default_nb_db(void)
3102 {
3103     if (!default_nb_db_) {
3104         default_nb_db_ = xasprintf("unix:%s/ovnnb_db.sock", ovs_rundir());
3105     }
3106     return default_nb_db_;
3107 }
3108
3109 static char *default_sb_db_;
3110
3111 static const char *
3112 default_sb_db(void)
3113 {
3114     if (!default_sb_db_) {
3115         default_sb_db_ = xasprintf("unix:%s/ovnsb_db.sock", ovs_rundir());
3116     }
3117     return default_sb_db_;
3118 }
3119
3120 static void
3121 parse_options(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
3122 {
3123     enum {
3124         DAEMON_OPTION_ENUMS,
3125         VLOG_OPTION_ENUMS,
3126     };
3127     static const struct option long_options[] = {
3128         {"ovnsb-db", required_argument, NULL, 'd'},
3129         {"ovnnb-db", required_argument, NULL, 'D'},
3130         {"help", no_argument, NULL, 'h'},
3131         {"options", no_argument, NULL, 'o'},
3132         {"version", no_argument, NULL, 'V'},
3133         DAEMON_LONG_OPTIONS,
3134         VLOG_LONG_OPTIONS,
3135         STREAM_SSL_LONG_OPTIONS,
3136         {NULL, 0, NULL, 0},
3137     };
3138     char *short_options = ovs_cmdl_long_options_to_short_options(long_options);
3139
3140     for (;;) {
3141         int c;
3142
3143         c = getopt_long(argc, argv, short_options, long_options, NULL);
3144         if (c == -1) {
3145             break;
3146         }
3147
3148         switch (c) {
3149         DAEMON_OPTION_HANDLERS;
3150         VLOG_OPTION_HANDLERS;
3151         STREAM_SSL_OPTION_HANDLERS;
3152
3153         case 'd':
3154             ovnsb_db = optarg;
3155             break;
3156
3157         case 'D':
3158             ovnnb_db = optarg;
3159             break;
3160
3161         case 'h':
3162             usage();
3163             exit(EXIT_SUCCESS);
3164
3165         case 'o':
3166             ovs_cmdl_print_options(long_options);
3167             exit(EXIT_SUCCESS);
3168
3169         case 'V':
3170             ovs_print_version(0, 0);
3171             exit(EXIT_SUCCESS);
3172
3173         default:
3174             break;
3175         }
3176     }
3177
3178     if (!ovnsb_db) {
3179         ovnsb_db = default_sb_db();
3180     }
3181
3182     if (!ovnnb_db) {
3183         ovnnb_db = default_nb_db();
3184     }
3185
3186     free(short_options);
3187 }
3188
3189 static void
3190 add_column_noalert(struct ovsdb_idl *idl,
3191                    const struct ovsdb_idl_column *column)
3192 {
3193     ovsdb_idl_add_column(idl, column);
3194     ovsdb_idl_omit_alert(idl, column);
3195 }
3196
3197 int
3198 main(int argc, char *argv[])
3199 {
3200     int res = EXIT_SUCCESS;
3201     struct unixctl_server *unixctl;
3202     int retval;
3203     bool exiting;
3204
3205     fatal_ignore_sigpipe();
3206     set_program_name(argv[0]);
3207     service_start(&argc, &argv);
3208     parse_options(argc, argv);
3209
3210     daemonize_start(false);
3211
3212     retval = unixctl_server_create(NULL, &unixctl);
3213     if (retval) {
3214         exit(EXIT_FAILURE);
3215     }
3216     unixctl_command_register("exit", "", 0, 0, ovn_northd_exit, &exiting);
3217
3218     daemonize_complete();
3219
3220     nbrec_init();
3221     sbrec_init();
3222
3223     /* We want to detect all changes to the ovn-nb db. */
3224     struct ovsdb_idl_loop ovnnb_idl_loop = OVSDB_IDL_LOOP_INITIALIZER(
3225         ovsdb_idl_create(ovnnb_db, &nbrec_idl_class, true, true));
3226
3227     struct ovsdb_idl_loop ovnsb_idl_loop = OVSDB_IDL_LOOP_INITIALIZER(
3228         ovsdb_idl_create(ovnsb_db, &sbrec_idl_class, false, true));
3229
3230     ovsdb_idl_add_table(ovnsb_idl_loop.idl, &sbrec_table_logical_flow);
3231     add_column_noalert(ovnsb_idl_loop.idl,
3232                        &sbrec_logical_flow_col_logical_datapath);
3233     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_logical_flow_col_pipeline);
3234     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_logical_flow_col_table_id);
3235     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_logical_flow_col_priority);
3236     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_logical_flow_col_match);
3237     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_logical_flow_col_actions);
3238
3239     ovsdb_idl_add_table(ovnsb_idl_loop.idl, &sbrec_table_multicast_group);
3240     add_column_noalert(ovnsb_idl_loop.idl,
3241                        &sbrec_multicast_group_col_datapath);
3242     add_column_noalert(ovnsb_idl_loop.idl,
3243                        &sbrec_multicast_group_col_tunnel_key);
3244     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_multicast_group_col_name);
3245     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_multicast_group_col_ports);
3246
3247     ovsdb_idl_add_table(ovnsb_idl_loop.idl, &sbrec_table_datapath_binding);
3248     add_column_noalert(ovnsb_idl_loop.idl,
3249                        &sbrec_datapath_binding_col_tunnel_key);
3250     add_column_noalert(ovnsb_idl_loop.idl,
3251                        &sbrec_datapath_binding_col_external_ids);
3252
3253     ovsdb_idl_add_table(ovnsb_idl_loop.idl, &sbrec_table_port_binding);
3254     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_port_binding_col_datapath);
3255     add_column_noalert(ovnsb_idl_loop.idl,
3256                        &sbrec_port_binding_col_logical_port);
3257     add_column_noalert(ovnsb_idl_loop.idl,
3258                        &sbrec_port_binding_col_tunnel_key);
3259     add_column_noalert(ovnsb_idl_loop.idl,
3260                        &sbrec_port_binding_col_parent_port);
3261     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_port_binding_col_tag);
3262     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_port_binding_col_type);
3263     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_port_binding_col_options);
3264     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_port_binding_col_mac);
3265     ovsdb_idl_add_column(ovnsb_idl_loop.idl, &sbrec_port_binding_col_chassis);
3266
3267     ovsdb_idl_add_table(ovnsb_idl_loop.idl, &sbrec_table_address_set);
3268     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_address_set_col_name);
3269     add_column_noalert(ovnsb_idl_loop.idl, &sbrec_address_set_col_addresses);
3270
3271     /* Main loop. */
3272     exiting = false;
3273     while (!exiting) {
3274         struct northd_context ctx = {
3275             .ovnnb_idl = ovnnb_idl_loop.idl,
3276             .ovnnb_txn = ovsdb_idl_loop_run(&ovnnb_idl_loop),
3277             .ovnsb_idl = ovnsb_idl_loop.idl,
3278             .ovnsb_txn = ovsdb_idl_loop_run(&ovnsb_idl_loop),
3279         };
3280
3281         ovnnb_db_run(&ctx);
3282         ovnsb_db_run(&ctx);
3283
3284         unixctl_server_run(unixctl);
3285         unixctl_server_wait(unixctl);
3286         if (exiting) {
3287             poll_immediate_wake();
3288         }
3289         ovsdb_idl_loop_commit_and_wait(&ovnnb_idl_loop);
3290         ovsdb_idl_loop_commit_and_wait(&ovnsb_idl_loop);
3291
3292         poll_block();
3293         if (should_service_stop()) {
3294             exiting = true;
3295         }
3296     }
3297
3298     unixctl_server_destroy(unixctl);
3299     ovsdb_idl_loop_destroy(&ovnnb_idl_loop);
3300     ovsdb_idl_loop_destroy(&ovnsb_idl_loop);
3301     service_stop();
3302
3303     free(default_nb_db_);
3304     free(default_sb_db_);
3305     exit(res);
3306 }
3307
3308 static void
3309 ovn_northd_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
3310                 const char *argv[] OVS_UNUSED, void *exiting_)
3311 {
3312     bool *exiting = exiting_;
3313     *exiting = true;
3314
3315     unixctl_command_reply(conn, NULL);
3316 }