afb7dcdf58fbb0a89cb173a7b2283f098e652430
[openvswitch] / lib / ofp-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ofp-print.h"
19 #include <ctype.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <sys/types.h>
23 #include <netinet/in.h>
24 #include <netinet/icmp6.h>
25 #include <stdlib.h>
26 #include "autopath.h"
27 #include "bundle.h"
28 #include "byte-order.h"
29 #include "classifier.h"
30 #include "dynamic-string.h"
31 #include "learn.h"
32 #include "meta-flow.h"
33 #include "multipath.h"
34 #include "netdev.h"
35 #include "nx-match.h"
36 #include "ofp-actions.h"
37 #include "ofp-errors.h"
38 #include "ofp-msgs.h"
39 #include "ofp-util.h"
40 #include "ofpbuf.h"
41 #include "packets.h"
42 #include "random.h"
43 #include "unaligned.h"
44 #include "type-props.h"
45 #include "vlog.h"
46
47 VLOG_DEFINE_THIS_MODULE(ofp_util);
48
49 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
50  * in the peer and so there's not much point in showing a lot of them. */
51 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
52
53 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
54  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
55  * is wildcarded.
56  *
57  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
58  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
59  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
60  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
61  * wildcarded. */
62 ovs_be32
63 ofputil_wcbits_to_netmask(int wcbits)
64 {
65     wcbits &= 0x3f;
66     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
67 }
68
69 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
70  * that it wildcards, that is, the number of 0-bits in 'netmask', a number
71  * between 0 and 32 inclusive.
72  *
73  * If 'netmask' is not a CIDR netmask (see ip_is_cidr()), the return value will
74  * still be in the valid range but isn't otherwise meaningful. */
75 int
76 ofputil_netmask_to_wcbits(ovs_be32 netmask)
77 {
78     return 32 - ip_count_cidr_bits(netmask);
79 }
80
81 /* Converts the OpenFlow 1.0 wildcards in 'ofpfw' (OFPFW10_*) into a
82  * flow_wildcards in 'wc' for use in struct match.  It is the caller's
83  * responsibility to handle the special case where the flow match's dl_vlan is
84  * set to OFP_VLAN_NONE. */
85 void
86 ofputil_wildcard_from_ofpfw10(uint32_t ofpfw, struct flow_wildcards *wc)
87 {
88     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 17);
89
90     /* Initialize most of wc. */
91     flow_wildcards_init_catchall(wc);
92
93     if (!(ofpfw & OFPFW10_IN_PORT)) {
94         wc->masks.in_port = UINT16_MAX;
95     }
96
97     if (!(ofpfw & OFPFW10_NW_TOS)) {
98         wc->masks.nw_tos |= IP_DSCP_MASK;
99     }
100
101     if (!(ofpfw & OFPFW10_NW_PROTO)) {
102         wc->masks.nw_proto = UINT8_MAX;
103     }
104     wc->masks.nw_src = ofputil_wcbits_to_netmask(ofpfw
105                                                  >> OFPFW10_NW_SRC_SHIFT);
106     wc->masks.nw_dst = ofputil_wcbits_to_netmask(ofpfw
107                                                  >> OFPFW10_NW_DST_SHIFT);
108
109     if (!(ofpfw & OFPFW10_TP_SRC)) {
110         wc->masks.tp_src = htons(UINT16_MAX);
111     }
112     if (!(ofpfw & OFPFW10_TP_DST)) {
113         wc->masks.tp_dst = htons(UINT16_MAX);
114     }
115
116     if (!(ofpfw & OFPFW10_DL_SRC)) {
117         memset(wc->masks.dl_src, 0xff, ETH_ADDR_LEN);
118     }
119     if (!(ofpfw & OFPFW10_DL_DST)) {
120         memset(wc->masks.dl_dst, 0xff, ETH_ADDR_LEN);
121     }
122     if (!(ofpfw & OFPFW10_DL_TYPE)) {
123         wc->masks.dl_type = htons(UINT16_MAX);
124     }
125
126     /* VLAN TCI mask. */
127     if (!(ofpfw & OFPFW10_DL_VLAN_PCP)) {
128         wc->masks.vlan_tci |= htons(VLAN_PCP_MASK | VLAN_CFI);
129     }
130     if (!(ofpfw & OFPFW10_DL_VLAN)) {
131         wc->masks.vlan_tci |= htons(VLAN_VID_MASK | VLAN_CFI);
132     }
133 }
134
135 /* Converts the ofp10_match in 'ofmatch' into a struct match in 'match'. */
136 void
137 ofputil_match_from_ofp10_match(const struct ofp10_match *ofmatch,
138                                struct match *match)
139 {
140     uint32_t ofpfw = ntohl(ofmatch->wildcards) & OFPFW10_ALL;
141
142     /* Initialize match->wc. */
143     memset(&match->flow, 0, sizeof match->flow);
144     ofputil_wildcard_from_ofpfw10(ofpfw, &match->wc);
145
146     /* Initialize most of match->flow. */
147     match->flow.nw_src = ofmatch->nw_src;
148     match->flow.nw_dst = ofmatch->nw_dst;
149     match->flow.in_port = ntohs(ofmatch->in_port);
150     match->flow.dl_type = ofputil_dl_type_from_openflow(ofmatch->dl_type);
151     match->flow.tp_src = ofmatch->tp_src;
152     match->flow.tp_dst = ofmatch->tp_dst;
153     memcpy(match->flow.dl_src, ofmatch->dl_src, ETH_ADDR_LEN);
154     memcpy(match->flow.dl_dst, ofmatch->dl_dst, ETH_ADDR_LEN);
155     match->flow.nw_tos = ofmatch->nw_tos & IP_DSCP_MASK;
156     match->flow.nw_proto = ofmatch->nw_proto;
157
158     /* Translate VLANs. */
159     if (!(ofpfw & OFPFW10_DL_VLAN) &&
160         ofmatch->dl_vlan == htons(OFP10_VLAN_NONE)) {
161         /* Match only packets without 802.1Q header.
162          *
163          * When OFPFW10_DL_VLAN_PCP is wildcarded, this is obviously correct.
164          *
165          * If OFPFW10_DL_VLAN_PCP is matched, the flow match is contradictory,
166          * because we can't have a specific PCP without an 802.1Q header.
167          * However, older versions of OVS treated this as matching packets
168          * withut an 802.1Q header, so we do here too. */
169         match->flow.vlan_tci = htons(0);
170         match->wc.masks.vlan_tci = htons(0xffff);
171     } else {
172         ovs_be16 vid, pcp, tci;
173
174         vid = ofmatch->dl_vlan & htons(VLAN_VID_MASK);
175         pcp = htons((ofmatch->dl_vlan_pcp << VLAN_PCP_SHIFT) & VLAN_PCP_MASK);
176         tci = vid | pcp | htons(VLAN_CFI);
177         match->flow.vlan_tci = tci & match->wc.masks.vlan_tci;
178     }
179
180     /* Clean up. */
181     match_zero_wildcarded_fields(match);
182 }
183
184 /* Convert 'match' into the OpenFlow 1.0 match structure 'ofmatch'. */
185 void
186 ofputil_match_to_ofp10_match(const struct match *match,
187                              struct ofp10_match *ofmatch)
188 {
189     const struct flow_wildcards *wc = &match->wc;
190     uint32_t ofpfw;
191
192     /* Figure out most OpenFlow wildcards. */
193     ofpfw = 0;
194     if (!wc->masks.in_port) {
195         ofpfw |= OFPFW10_IN_PORT;
196     }
197     if (!wc->masks.dl_type) {
198         ofpfw |= OFPFW10_DL_TYPE;
199     }
200     if (!wc->masks.nw_proto) {
201         ofpfw |= OFPFW10_NW_PROTO;
202     }
203     ofpfw |= (ofputil_netmask_to_wcbits(wc->masks.nw_src)
204               << OFPFW10_NW_SRC_SHIFT);
205     ofpfw |= (ofputil_netmask_to_wcbits(wc->masks.nw_dst)
206               << OFPFW10_NW_DST_SHIFT);
207     if (!(wc->masks.nw_tos & IP_DSCP_MASK)) {
208         ofpfw |= OFPFW10_NW_TOS;
209     }
210     if (!wc->masks.tp_src) {
211         ofpfw |= OFPFW10_TP_SRC;
212     }
213     if (!wc->masks.tp_dst) {
214         ofpfw |= OFPFW10_TP_DST;
215     }
216     if (eth_addr_is_zero(wc->masks.dl_src)) {
217         ofpfw |= OFPFW10_DL_SRC;
218     }
219     if (eth_addr_is_zero(wc->masks.dl_dst)) {
220         ofpfw |= OFPFW10_DL_DST;
221     }
222
223     /* Translate VLANs. */
224     ofmatch->dl_vlan = htons(0);
225     ofmatch->dl_vlan_pcp = 0;
226     if (match->wc.masks.vlan_tci == htons(0)) {
227         ofpfw |= OFPFW10_DL_VLAN | OFPFW10_DL_VLAN_PCP;
228     } else if (match->wc.masks.vlan_tci & htons(VLAN_CFI)
229                && !(match->flow.vlan_tci & htons(VLAN_CFI))) {
230         ofmatch->dl_vlan = htons(OFP10_VLAN_NONE);
231         ofpfw |= OFPFW10_DL_VLAN_PCP;
232     } else {
233         if (!(match->wc.masks.vlan_tci & htons(VLAN_VID_MASK))) {
234             ofpfw |= OFPFW10_DL_VLAN;
235         } else {
236             ofmatch->dl_vlan = htons(vlan_tci_to_vid(match->flow.vlan_tci));
237         }
238
239         if (!(match->wc.masks.vlan_tci & htons(VLAN_PCP_MASK))) {
240             ofpfw |= OFPFW10_DL_VLAN_PCP;
241         } else {
242             ofmatch->dl_vlan_pcp = vlan_tci_to_pcp(match->flow.vlan_tci);
243         }
244     }
245
246     /* Compose most of the match structure. */
247     ofmatch->wildcards = htonl(ofpfw);
248     ofmatch->in_port = htons(match->flow.in_port);
249     memcpy(ofmatch->dl_src, match->flow.dl_src, ETH_ADDR_LEN);
250     memcpy(ofmatch->dl_dst, match->flow.dl_dst, ETH_ADDR_LEN);
251     ofmatch->dl_type = ofputil_dl_type_to_openflow(match->flow.dl_type);
252     ofmatch->nw_src = match->flow.nw_src;
253     ofmatch->nw_dst = match->flow.nw_dst;
254     ofmatch->nw_tos = match->flow.nw_tos & IP_DSCP_MASK;
255     ofmatch->nw_proto = match->flow.nw_proto;
256     ofmatch->tp_src = match->flow.tp_src;
257     ofmatch->tp_dst = match->flow.tp_dst;
258     memset(ofmatch->pad1, '\0', sizeof ofmatch->pad1);
259     memset(ofmatch->pad2, '\0', sizeof ofmatch->pad2);
260 }
261
262 enum ofperr
263 ofputil_pull_ofp11_match(struct ofpbuf *buf, struct match *match,
264                          uint16_t *padded_match_len)
265 {
266     struct ofp11_match_header *omh = buf->data;
267     uint16_t match_len;
268
269     if (buf->size < sizeof *omh) {
270         return OFPERR_OFPBMC_BAD_LEN;
271     }
272
273     match_len = ntohs(omh->length);
274
275     switch (ntohs(omh->type)) {
276     case OFPMT_STANDARD: {
277         struct ofp11_match *om;
278
279         if (match_len != sizeof *om || buf->size < sizeof *om) {
280             return OFPERR_OFPBMC_BAD_LEN;
281         }
282         om = ofpbuf_pull(buf, sizeof *om);
283         if (padded_match_len) {
284             *padded_match_len = match_len;
285         }
286         return ofputil_match_from_ofp11_match(om, match);
287     }
288
289     case OFPMT_OXM:
290         if (padded_match_len) {
291             *padded_match_len = ROUND_UP(match_len, 8);
292         }
293         return oxm_pull_match(buf, match);
294
295     default:
296         return OFPERR_OFPBMC_BAD_TYPE;
297     }
298 }
299
300 /* Converts the ofp11_match in 'match' into a struct match in 'match.  Returns
301  * 0 if successful, otherwise an OFPERR_* value. */
302 enum ofperr
303 ofputil_match_from_ofp11_match(const struct ofp11_match *ofmatch,
304                                struct match *match)
305 {
306     uint16_t wc = ntohl(ofmatch->wildcards);
307     uint8_t dl_src_mask[ETH_ADDR_LEN];
308     uint8_t dl_dst_mask[ETH_ADDR_LEN];
309     bool ipv4, arp, rarp;
310     int i;
311
312     match_init_catchall(match);
313
314     if (!(wc & OFPFW11_IN_PORT)) {
315         uint16_t ofp_port;
316         enum ofperr error;
317
318         error = ofputil_port_from_ofp11(ofmatch->in_port, &ofp_port);
319         if (error) {
320             return OFPERR_OFPBMC_BAD_VALUE;
321         }
322         match_set_in_port(match, ofp_port);
323     }
324
325     for (i = 0; i < ETH_ADDR_LEN; i++) {
326         dl_src_mask[i] = ~ofmatch->dl_src_mask[i];
327     }
328     match_set_dl_src_masked(match, ofmatch->dl_src, dl_src_mask);
329
330     for (i = 0; i < ETH_ADDR_LEN; i++) {
331         dl_dst_mask[i] = ~ofmatch->dl_dst_mask[i];
332     }
333     match_set_dl_dst_masked(match, ofmatch->dl_dst, dl_dst_mask);
334
335     if (!(wc & OFPFW11_DL_VLAN)) {
336         if (ofmatch->dl_vlan == htons(OFPVID11_NONE)) {
337             /* Match only packets without a VLAN tag. */
338             match->flow.vlan_tci = htons(0);
339             match->wc.masks.vlan_tci = htons(UINT16_MAX);
340         } else {
341             if (ofmatch->dl_vlan == htons(OFPVID11_ANY)) {
342                 /* Match any packet with a VLAN tag regardless of VID. */
343                 match->flow.vlan_tci = htons(VLAN_CFI);
344                 match->wc.masks.vlan_tci = htons(VLAN_CFI);
345             } else if (ntohs(ofmatch->dl_vlan) < 4096) {
346                 /* Match only packets with the specified VLAN VID. */
347                 match->flow.vlan_tci = htons(VLAN_CFI) | ofmatch->dl_vlan;
348                 match->wc.masks.vlan_tci = htons(VLAN_CFI | VLAN_VID_MASK);
349             } else {
350                 /* Invalid VID. */
351                 return OFPERR_OFPBMC_BAD_VALUE;
352             }
353
354             if (!(wc & OFPFW11_DL_VLAN_PCP)) {
355                 if (ofmatch->dl_vlan_pcp <= 7) {
356                     match->flow.vlan_tci |= htons(ofmatch->dl_vlan_pcp
357                                                   << VLAN_PCP_SHIFT);
358                     match->wc.masks.vlan_tci |= htons(VLAN_PCP_MASK);
359                 } else {
360                     /* Invalid PCP. */
361                     return OFPERR_OFPBMC_BAD_VALUE;
362                 }
363             }
364         }
365     }
366
367     if (!(wc & OFPFW11_DL_TYPE)) {
368         match_set_dl_type(match,
369                           ofputil_dl_type_from_openflow(ofmatch->dl_type));
370     }
371
372     ipv4 = match->flow.dl_type == htons(ETH_TYPE_IP);
373     arp = match->flow.dl_type == htons(ETH_TYPE_ARP);
374     rarp = match->flow.dl_type == htons(ETH_TYPE_RARP);
375
376     if (ipv4 && !(wc & OFPFW11_NW_TOS)) {
377         if (ofmatch->nw_tos & ~IP_DSCP_MASK) {
378             /* Invalid TOS. */
379             return OFPERR_OFPBMC_BAD_VALUE;
380         }
381
382         match_set_nw_dscp(match, ofmatch->nw_tos);
383     }
384
385     if (ipv4 || arp || rarp) {
386         if (!(wc & OFPFW11_NW_PROTO)) {
387             match_set_nw_proto(match, ofmatch->nw_proto);
388         }
389         match_set_nw_src_masked(match, ofmatch->nw_src, ~ofmatch->nw_src_mask);
390         match_set_nw_dst_masked(match, ofmatch->nw_dst, ~ofmatch->nw_dst_mask);
391     }
392
393 #define OFPFW11_TP_ALL (OFPFW11_TP_SRC | OFPFW11_TP_DST)
394     if (ipv4 && (wc & OFPFW11_TP_ALL) != OFPFW11_TP_ALL) {
395         switch (match->flow.nw_proto) {
396         case IPPROTO_ICMP:
397             /* "A.2.3 Flow Match Structures" in OF1.1 says:
398              *
399              *    The tp_src and tp_dst fields will be ignored unless the
400              *    network protocol specified is as TCP, UDP or SCTP.
401              *
402              * but I'm pretty sure we should support ICMP too, otherwise
403              * that's a regression from OF1.0. */
404             if (!(wc & OFPFW11_TP_SRC)) {
405                 uint16_t icmp_type = ntohs(ofmatch->tp_src);
406                 if (icmp_type < 0x100) {
407                     match_set_icmp_type(match, icmp_type);
408                 } else {
409                     return OFPERR_OFPBMC_BAD_FIELD;
410                 }
411             }
412             if (!(wc & OFPFW11_TP_DST)) {
413                 uint16_t icmp_code = ntohs(ofmatch->tp_dst);
414                 if (icmp_code < 0x100) {
415                     match_set_icmp_code(match, icmp_code);
416                 } else {
417                     return OFPERR_OFPBMC_BAD_FIELD;
418                 }
419             }
420             break;
421
422         case IPPROTO_TCP:
423         case IPPROTO_UDP:
424             if (!(wc & (OFPFW11_TP_SRC))) {
425                 match_set_tp_src(match, ofmatch->tp_src);
426             }
427             if (!(wc & (OFPFW11_TP_DST))) {
428                 match_set_tp_dst(match, ofmatch->tp_dst);
429             }
430             break;
431
432         case IPPROTO_SCTP:
433             /* We don't support SCTP and it seems that we should tell the
434              * controller, since OF1.1 implementations are supposed to. */
435             return OFPERR_OFPBMC_BAD_FIELD;
436
437         default:
438             /* OF1.1 says explicitly to ignore this. */
439             break;
440         }
441     }
442
443     if (match->flow.dl_type == htons(ETH_TYPE_MPLS) ||
444         match->flow.dl_type == htons(ETH_TYPE_MPLS_MCAST)) {
445         enum { OFPFW11_MPLS_ALL = OFPFW11_MPLS_LABEL | OFPFW11_MPLS_TC };
446
447         if ((wc & OFPFW11_MPLS_ALL) != OFPFW11_MPLS_ALL) {
448             /* MPLS not supported. */
449             return OFPERR_OFPBMC_BAD_TAG;
450         }
451     }
452
453     match_set_metadata_masked(match, ofmatch->metadata,
454                               ~ofmatch->metadata_mask);
455
456     return 0;
457 }
458
459 /* Convert 'match' into the OpenFlow 1.1 match structure 'ofmatch'. */
460 void
461 ofputil_match_to_ofp11_match(const struct match *match,
462                              struct ofp11_match *ofmatch)
463 {
464     uint32_t wc = 0;
465     int i;
466
467     memset(ofmatch, 0, sizeof *ofmatch);
468     ofmatch->omh.type = htons(OFPMT_STANDARD);
469     ofmatch->omh.length = htons(OFPMT11_STANDARD_LENGTH);
470
471     if (!match->wc.masks.in_port) {
472         wc |= OFPFW11_IN_PORT;
473     } else {
474         ofmatch->in_port = ofputil_port_to_ofp11(match->flow.in_port);
475     }
476
477     memcpy(ofmatch->dl_src, match->flow.dl_src, ETH_ADDR_LEN);
478     for (i = 0; i < ETH_ADDR_LEN; i++) {
479         ofmatch->dl_src_mask[i] = ~match->wc.masks.dl_src[i];
480     }
481
482     memcpy(ofmatch->dl_dst, match->flow.dl_dst, ETH_ADDR_LEN);
483     for (i = 0; i < ETH_ADDR_LEN; i++) {
484         ofmatch->dl_dst_mask[i] = ~match->wc.masks.dl_dst[i];
485     }
486
487     if (match->wc.masks.vlan_tci == htons(0)) {
488         wc |= OFPFW11_DL_VLAN | OFPFW11_DL_VLAN_PCP;
489     } else if (match->wc.masks.vlan_tci & htons(VLAN_CFI)
490                && !(match->flow.vlan_tci & htons(VLAN_CFI))) {
491         ofmatch->dl_vlan = htons(OFPVID11_NONE);
492         wc |= OFPFW11_DL_VLAN_PCP;
493     } else {
494         if (!(match->wc.masks.vlan_tci & htons(VLAN_VID_MASK))) {
495             ofmatch->dl_vlan = htons(OFPVID11_ANY);
496         } else {
497             ofmatch->dl_vlan = htons(vlan_tci_to_vid(match->flow.vlan_tci));
498         }
499
500         if (!(match->wc.masks.vlan_tci & htons(VLAN_PCP_MASK))) {
501             wc |= OFPFW11_DL_VLAN_PCP;
502         } else {
503             ofmatch->dl_vlan_pcp = vlan_tci_to_pcp(match->flow.vlan_tci);
504         }
505     }
506
507     if (!match->wc.masks.dl_type) {
508         wc |= OFPFW11_DL_TYPE;
509     } else {
510         ofmatch->dl_type = ofputil_dl_type_to_openflow(match->flow.dl_type);
511     }
512
513     if (!(match->wc.masks.nw_tos & IP_DSCP_MASK)) {
514         wc |= OFPFW11_NW_TOS;
515     } else {
516         ofmatch->nw_tos = match->flow.nw_tos & IP_DSCP_MASK;
517     }
518
519     if (!match->wc.masks.nw_proto) {
520         wc |= OFPFW11_NW_PROTO;
521     } else {
522         ofmatch->nw_proto = match->flow.nw_proto;
523     }
524
525     ofmatch->nw_src = match->flow.nw_src;
526     ofmatch->nw_src_mask = ~match->wc.masks.nw_src;
527     ofmatch->nw_dst = match->flow.nw_dst;
528     ofmatch->nw_dst_mask = ~match->wc.masks.nw_dst;
529
530     if (!match->wc.masks.tp_src) {
531         wc |= OFPFW11_TP_SRC;
532     } else {
533         ofmatch->tp_src = match->flow.tp_src;
534     }
535
536     if (!match->wc.masks.tp_dst) {
537         wc |= OFPFW11_TP_DST;
538     } else {
539         ofmatch->tp_dst = match->flow.tp_dst;
540     }
541
542     /* MPLS not supported. */
543     wc |= OFPFW11_MPLS_LABEL;
544     wc |= OFPFW11_MPLS_TC;
545
546     ofmatch->metadata = match->flow.metadata;
547     ofmatch->metadata_mask = ~match->wc.masks.metadata;
548
549     ofmatch->wildcards = htonl(wc);
550 }
551
552 /* Given a 'dl_type' value in the format used in struct flow, returns the
553  * corresponding 'dl_type' value for use in an ofp10_match or ofp11_match
554  * structure. */
555 ovs_be16
556 ofputil_dl_type_to_openflow(ovs_be16 flow_dl_type)
557 {
558     return (flow_dl_type == htons(FLOW_DL_TYPE_NONE)
559             ? htons(OFP_DL_TYPE_NOT_ETH_TYPE)
560             : flow_dl_type);
561 }
562
563 /* Given a 'dl_type' value in the format used in an ofp10_match or ofp11_match
564  * structure, returns the corresponding 'dl_type' value for use in struct
565  * flow. */
566 ovs_be16
567 ofputil_dl_type_from_openflow(ovs_be16 ofp_dl_type)
568 {
569     return (ofp_dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
570             ? htons(FLOW_DL_TYPE_NONE)
571             : ofp_dl_type);
572 }
573 \f
574 /* Protocols. */
575
576 struct proto_abbrev {
577     enum ofputil_protocol protocol;
578     const char *name;
579 };
580
581 /* Most users really don't care about some of the differences between
582  * protocols.  These abbreviations help with that. */
583 static const struct proto_abbrev proto_abbrevs[] = {
584     { OFPUTIL_P_ANY,      "any" },
585     { OFPUTIL_P_OF10_ANY, "OpenFlow10" },
586     { OFPUTIL_P_NXM_ANY,  "NXM" },
587 };
588 #define N_PROTO_ABBREVS ARRAY_SIZE(proto_abbrevs)
589
590 enum ofputil_protocol ofputil_flow_dump_protocols[] = {
591     OFPUTIL_P_NXM,
592     OFPUTIL_P_OF10,
593 };
594 size_t ofputil_n_flow_dump_protocols = ARRAY_SIZE(ofputil_flow_dump_protocols);
595
596 /* Returns the ofputil_protocol that is initially in effect on an OpenFlow
597  * connection that has negotiated the given 'version'.  'version' should
598  * normally be an 8-bit OpenFlow version identifier (e.g. 0x01 for OpenFlow
599  * 1.0, 0x02 for OpenFlow 1.1).  Returns 0 if 'version' is not supported or
600  * outside the valid range.  */
601 enum ofputil_protocol
602 ofputil_protocol_from_ofp_version(enum ofp_version version)
603 {
604     switch (version) {
605     case OFP10_VERSION:
606         return OFPUTIL_P_OF10;
607     case OFP12_VERSION:
608         return OFPUTIL_P_OF12;
609     case OFP11_VERSION:
610     default:
611         return 0;
612     }
613 }
614
615 /* Returns the OpenFlow protocol version number (e.g. OFP10_VERSION,
616  * OFP11_VERSION or OFP12_VERSION) that corresponds to 'protocol'. */
617 enum ofp_version
618 ofputil_protocol_to_ofp_version(enum ofputil_protocol protocol)
619 {
620     switch (protocol) {
621     case OFPUTIL_P_OF10:
622     case OFPUTIL_P_OF10_TID:
623     case OFPUTIL_P_NXM:
624     case OFPUTIL_P_NXM_TID:
625         return OFP10_VERSION;
626     case OFPUTIL_P_OF12:
627         return OFP12_VERSION;
628     }
629
630     NOT_REACHED();
631 }
632
633 /* Returns true if 'protocol' is a single OFPUTIL_P_* value, false
634  * otherwise. */
635 bool
636 ofputil_protocol_is_valid(enum ofputil_protocol protocol)
637 {
638     return protocol & OFPUTIL_P_ANY && is_pow2(protocol);
639 }
640
641 /* Returns the equivalent of 'protocol' with the Nicira flow_mod_table_id
642  * extension turned on or off if 'enable' is true or false, respectively.
643  *
644  * This extension is only useful for protocols whose "standard" version does
645  * not allow specific tables to be modified.  In particular, this is true of
646  * OpenFlow 1.0.  In later versions of OpenFlow, a flow_mod request always
647  * specifies a table ID and so there is no need for such an extension.  When
648  * 'protocol' is such a protocol that doesn't need a flow_mod_table_id
649  * extension, this function just returns its 'protocol' argument unchanged
650  * regardless of the value of 'enable'.  */
651 enum ofputil_protocol
652 ofputil_protocol_set_tid(enum ofputil_protocol protocol, bool enable)
653 {
654     switch (protocol) {
655     case OFPUTIL_P_OF10:
656     case OFPUTIL_P_OF10_TID:
657         return enable ? OFPUTIL_P_OF10_TID : OFPUTIL_P_OF10;
658
659     case OFPUTIL_P_NXM:
660     case OFPUTIL_P_NXM_TID:
661         return enable ? OFPUTIL_P_NXM_TID : OFPUTIL_P_NXM;
662
663     case OFPUTIL_P_OF12:
664         return OFPUTIL_P_OF12;
665
666     default:
667         NOT_REACHED();
668     }
669 }
670
671 /* Returns the "base" version of 'protocol'.  That is, if 'protocol' includes
672  * some extension to a standard protocol version, the return value is the
673  * standard version of that protocol without any extension.  If 'protocol' is a
674  * standard protocol version, returns 'protocol' unchanged. */
675 enum ofputil_protocol
676 ofputil_protocol_to_base(enum ofputil_protocol protocol)
677 {
678     return ofputil_protocol_set_tid(protocol, false);
679 }
680
681 /* Returns 'new_base' with any extensions taken from 'cur'. */
682 enum ofputil_protocol
683 ofputil_protocol_set_base(enum ofputil_protocol cur,
684                           enum ofputil_protocol new_base)
685 {
686     bool tid = (cur & OFPUTIL_P_TID) != 0;
687
688     switch (new_base) {
689     case OFPUTIL_P_OF10:
690     case OFPUTIL_P_OF10_TID:
691         return ofputil_protocol_set_tid(OFPUTIL_P_OF10, tid);
692
693     case OFPUTIL_P_NXM:
694     case OFPUTIL_P_NXM_TID:
695         return ofputil_protocol_set_tid(OFPUTIL_P_NXM, tid);
696
697     case OFPUTIL_P_OF12:
698         return ofputil_protocol_set_tid(OFPUTIL_P_OF12, tid);
699
700     default:
701         NOT_REACHED();
702     }
703 }
704
705 /* Returns a string form of 'protocol', if a simple form exists (that is, if
706  * 'protocol' is either a single protocol or it is a combination of protocols
707  * that have a single abbreviation).  Otherwise, returns NULL. */
708 const char *
709 ofputil_protocol_to_string(enum ofputil_protocol protocol)
710 {
711     const struct proto_abbrev *p;
712
713     /* Use a "switch" statement for single-bit names so that we get a compiler
714      * warning if we forget any. */
715     switch (protocol) {
716     case OFPUTIL_P_NXM:
717         return "NXM-table_id";
718
719     case OFPUTIL_P_NXM_TID:
720         return "NXM+table_id";
721
722     case OFPUTIL_P_OF10:
723         return "OpenFlow10-table_id";
724
725     case OFPUTIL_P_OF10_TID:
726         return "OpenFlow10+table_id";
727
728     case OFPUTIL_P_OF12:
729         return NULL;
730     }
731
732     /* Check abbreviations. */
733     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
734         if (protocol == p->protocol) {
735             return p->name;
736         }
737     }
738
739     return NULL;
740 }
741
742 /* Returns a string that represents 'protocols'.  The return value might be a
743  * comma-separated list if 'protocols' doesn't have a simple name.  The return
744  * value is "none" if 'protocols' is 0.
745  *
746  * The caller must free the returned string (with free()). */
747 char *
748 ofputil_protocols_to_string(enum ofputil_protocol protocols)
749 {
750     struct ds s;
751
752     assert(!(protocols & ~OFPUTIL_P_ANY));
753     if (protocols == 0) {
754         return xstrdup("none");
755     }
756
757     ds_init(&s);
758     while (protocols) {
759         const struct proto_abbrev *p;
760         int i;
761
762         if (s.length) {
763             ds_put_char(&s, ',');
764         }
765
766         for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
767             if ((protocols & p->protocol) == p->protocol) {
768                 ds_put_cstr(&s, p->name);
769                 protocols &= ~p->protocol;
770                 goto match;
771             }
772         }
773
774         for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
775             enum ofputil_protocol bit = 1u << i;
776
777             if (protocols & bit) {
778                 ds_put_cstr(&s, ofputil_protocol_to_string(bit));
779                 protocols &= ~bit;
780                 goto match;
781             }
782         }
783         NOT_REACHED();
784
785     match: ;
786     }
787     return ds_steal_cstr(&s);
788 }
789
790 static enum ofputil_protocol
791 ofputil_protocol_from_string__(const char *s, size_t n)
792 {
793     const struct proto_abbrev *p;
794     int i;
795
796     for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
797         enum ofputil_protocol bit = 1u << i;
798         const char *name = ofputil_protocol_to_string(bit);
799
800         if (name && n == strlen(name) && !strncasecmp(s, name, n)) {
801             return bit;
802         }
803     }
804
805     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
806         if (n == strlen(p->name) && !strncasecmp(s, p->name, n)) {
807             return p->protocol;
808         }
809     }
810
811     return 0;
812 }
813
814 /* Returns the nonempty set of protocols represented by 's', which can be a
815  * single protocol name or abbreviation or a comma-separated list of them.
816  *
817  * Aborts the program with an error message if 's' is invalid. */
818 enum ofputil_protocol
819 ofputil_protocols_from_string(const char *s)
820 {
821     const char *orig_s = s;
822     enum ofputil_protocol protocols;
823
824     protocols = 0;
825     while (*s) {
826         enum ofputil_protocol p;
827         size_t n;
828
829         n = strcspn(s, ",");
830         if (n == 0) {
831             s++;
832             continue;
833         }
834
835         p = ofputil_protocol_from_string__(s, n);
836         if (!p) {
837             ovs_fatal(0, "%.*s: unknown flow protocol", (int) n, s);
838         }
839         protocols |= p;
840
841         s += n;
842     }
843
844     if (!protocols) {
845         ovs_fatal(0, "%s: no flow protocol specified", orig_s);
846     }
847     return protocols;
848 }
849
850 static enum ofp_version
851 ofputil_version_from_string(const char *s)
852 {
853     if (!strcasecmp(s, "OpenFlow10")) {
854         return OFP10_VERSION;
855     }
856     if (!strcasecmp(s, "OpenFlow11")) {
857         return OFP11_VERSION;
858     }
859     if (!strcasecmp(s, "OpenFlow12")) {
860         return OFP12_VERSION;
861     }
862     VLOG_FATAL("Unknown OpenFlow version: \"%s\"", s);
863 }
864
865 static bool
866 is_delimiter(char c)
867 {
868     return isspace(c) || c == ',';
869 }
870
871 uint32_t
872 ofputil_versions_from_string(const char *s)
873 {
874     size_t i = 0;
875     uint32_t bitmap = 0;
876
877     while (s[i]) {
878         size_t j;
879         enum ofp_version version;
880         char *key;
881
882         if (is_delimiter(s[i])) {
883             i++;
884             continue;
885         }
886         j = 0;
887         while (s[i + j] && !is_delimiter(s[i + j])) {
888             j++;
889         }
890         key = xmemdup0(s + i, j);
891         version = ofputil_version_from_string(key);
892         free(key);
893         bitmap |= 1u << version;
894         i += j;
895     }
896
897     return bitmap;
898 }
899
900 const char *
901 ofputil_version_to_string(enum ofp_version ofp_version)
902 {
903     switch (ofp_version) {
904     case OFP10_VERSION:
905         return "OpenFlow10";
906     case OFP11_VERSION:
907         return "OpenFlow11";
908     case OFP12_VERSION:
909         return "OpenFlow12";
910     default:
911         NOT_REACHED();
912     }
913 }
914
915 bool
916 ofputil_packet_in_format_is_valid(enum nx_packet_in_format packet_in_format)
917 {
918     switch (packet_in_format) {
919     case NXPIF_OPENFLOW10:
920     case NXPIF_NXM:
921         return true;
922     }
923
924     return false;
925 }
926
927 const char *
928 ofputil_packet_in_format_to_string(enum nx_packet_in_format packet_in_format)
929 {
930     switch (packet_in_format) {
931     case NXPIF_OPENFLOW10:
932         return "openflow10";
933     case NXPIF_NXM:
934         return "nxm";
935     default:
936         NOT_REACHED();
937     }
938 }
939
940 int
941 ofputil_packet_in_format_from_string(const char *s)
942 {
943     return (!strcmp(s, "openflow10") ? NXPIF_OPENFLOW10
944             : !strcmp(s, "nxm") ? NXPIF_NXM
945             : -1);
946 }
947
948 static bool
949 regs_fully_wildcarded(const struct flow_wildcards *wc)
950 {
951     int i;
952
953     for (i = 0; i < FLOW_N_REGS; i++) {
954         if (wc->masks.regs[i] != 0) {
955             return false;
956         }
957     }
958     return true;
959 }
960
961 /* Returns a bit-mask of ofputil_protocols that can be used for sending 'match'
962  * to a switch (e.g. to add or remove a flow).  Only NXM can handle tunnel IDs,
963  * registers, or fixing the Ethernet multicast bit.  Otherwise, it's better to
964  * use OpenFlow 1.0 protocol for backward compatibility. */
965 enum ofputil_protocol
966 ofputil_usable_protocols(const struct match *match)
967 {
968     const struct flow_wildcards *wc = &match->wc;
969
970     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 17);
971
972     /* NXM and OF1.1+ supports bitwise matching on ethernet addresses. */
973     if (!eth_mask_is_exact(wc->masks.dl_src)
974         && !eth_addr_is_zero(wc->masks.dl_src)) {
975         return OFPUTIL_P_NXM_ANY;
976     }
977     if (!eth_mask_is_exact(wc->masks.dl_dst)
978         && !eth_addr_is_zero(wc->masks.dl_dst)) {
979         return OFPUTIL_P_NXM_ANY;
980     }
981
982     /* NXM and OF1.1+ support matching metadata. */
983     if (wc->masks.metadata != htonll(0)) {
984         return OFPUTIL_P_NXM_ANY;
985     }
986
987     /* Only NXM supports matching ARP hardware addresses. */
988     if (!eth_addr_is_zero(wc->masks.arp_sha) ||
989         !eth_addr_is_zero(wc->masks.arp_tha)) {
990         return OFPUTIL_P_NXM_ANY;
991     }
992
993     /* Only NXM supports matching IPv6 traffic. */
994     if (match->flow.dl_type == htons(ETH_TYPE_IPV6)) {
995         return OFPUTIL_P_NXM_ANY;
996     }
997
998     /* Only NXM supports matching registers. */
999     if (!regs_fully_wildcarded(wc)) {
1000         return OFPUTIL_P_NXM_ANY;
1001     }
1002
1003     /* Only NXM supports matching tun_id. */
1004     if (wc->masks.tunnel.tun_id != htonll(0)) {
1005         return OFPUTIL_P_NXM_ANY;
1006     }
1007
1008     /* Only NXM supports matching fragments. */
1009     if (wc->masks.nw_frag) {
1010         return OFPUTIL_P_NXM_ANY;
1011     }
1012
1013     /* Only NXM supports matching IPv6 flow label. */
1014     if (wc->masks.ipv6_label) {
1015         return OFPUTIL_P_NXM_ANY;
1016     }
1017
1018     /* Only NXM supports matching IP ECN bits. */
1019     if (wc->masks.nw_tos & IP_ECN_MASK) {
1020         return OFPUTIL_P_NXM_ANY;
1021     }
1022
1023     /* Only NXM supports matching IP TTL/hop limit. */
1024     if (wc->masks.nw_ttl) {
1025         return OFPUTIL_P_NXM_ANY;
1026     }
1027
1028     /* Only NXM supports non-CIDR IPv4 address masks. */
1029     if (!ip_is_cidr(wc->masks.nw_src) || !ip_is_cidr(wc->masks.nw_dst)) {
1030         return OFPUTIL_P_NXM_ANY;
1031     }
1032
1033     /* Only NXM supports bitwise matching on transport port. */
1034     if ((wc->masks.tp_src && wc->masks.tp_src != htons(UINT16_MAX)) ||
1035         (wc->masks.tp_dst && wc->masks.tp_dst != htons(UINT16_MAX))) {
1036         return OFPUTIL_P_NXM_ANY;
1037     }
1038
1039     /* Other formats can express this rule. */
1040     return OFPUTIL_P_ANY;
1041 }
1042
1043 void
1044 ofputil_format_version(struct ds *msg, enum ofp_version version)
1045 {
1046     ds_put_format(msg, "0x%02zx", version);
1047 }
1048
1049 void
1050 ofputil_format_version_name(struct ds *msg, enum ofp_version version)
1051 {
1052     ds_put_cstr(msg, ofputil_version_to_string(version));
1053 }
1054
1055 static void
1056 ofputil_format_version_bitmap__(struct ds *msg, uint32_t bitmap,
1057                                 void (*format_version)(struct ds *msg,
1058                                                        enum ofp_version))
1059 {
1060     while (bitmap) {
1061         format_version(msg, raw_ctz(bitmap));
1062         bitmap = zero_rightmost_1bit(bitmap);
1063         if (bitmap) {
1064             ds_put_cstr(msg, ", ");
1065         }
1066     }
1067 }
1068
1069 void
1070 ofputil_format_version_bitmap(struct ds *msg, uint32_t bitmap)
1071 {
1072     ofputil_format_version_bitmap__(msg, bitmap, ofputil_format_version);
1073 }
1074
1075 void
1076 ofputil_format_version_bitmap_names(struct ds *msg, uint32_t bitmap)
1077 {
1078     ofputil_format_version_bitmap__(msg, bitmap, ofputil_format_version_name);
1079 }
1080
1081 /* Returns an OpenFlow message that, sent on an OpenFlow connection whose
1082  * protocol is 'current', at least partly transitions the protocol to 'want'.
1083  * Stores in '*next' the protocol that will be in effect on the OpenFlow
1084  * connection if the switch processes the returned message correctly.  (If
1085  * '*next != want' then the caller will have to iterate.)
1086  *
1087  * If 'current == want', returns NULL and stores 'current' in '*next'. */
1088 struct ofpbuf *
1089 ofputil_encode_set_protocol(enum ofputil_protocol current,
1090                             enum ofputil_protocol want,
1091                             enum ofputil_protocol *next)
1092 {
1093     enum ofputil_protocol cur_base, want_base;
1094     bool cur_tid, want_tid;
1095
1096     cur_base = ofputil_protocol_to_base(current);
1097     want_base = ofputil_protocol_to_base(want);
1098     if (cur_base != want_base) {
1099         *next = ofputil_protocol_set_base(current, want_base);
1100
1101         switch (want_base) {
1102         case OFPUTIL_P_NXM:
1103             return ofputil_encode_nx_set_flow_format(NXFF_NXM);
1104
1105         case OFPUTIL_P_OF10:
1106             return ofputil_encode_nx_set_flow_format(NXFF_OPENFLOW10);
1107
1108         case OFPUTIL_P_OF12:
1109             return ofputil_encode_nx_set_flow_format(NXFF_OPENFLOW12);
1110
1111         case OFPUTIL_P_OF10_TID:
1112         case OFPUTIL_P_NXM_TID:
1113             NOT_REACHED();
1114         }
1115     }
1116
1117     cur_tid = (current & OFPUTIL_P_TID) != 0;
1118     want_tid = (want & OFPUTIL_P_TID) != 0;
1119     if (cur_tid != want_tid) {
1120         *next = ofputil_protocol_set_tid(current, want_tid);
1121         return ofputil_make_flow_mod_table_id(want_tid);
1122     }
1123
1124     assert(current == want);
1125
1126     *next = current;
1127     return NULL;
1128 }
1129
1130 /* Returns an NXT_SET_FLOW_FORMAT message that can be used to set the flow
1131  * format to 'nxff'.  */
1132 struct ofpbuf *
1133 ofputil_encode_nx_set_flow_format(enum nx_flow_format nxff)
1134 {
1135     struct nx_set_flow_format *sff;
1136     struct ofpbuf *msg;
1137
1138     assert(ofputil_nx_flow_format_is_valid(nxff));
1139
1140     msg = ofpraw_alloc(OFPRAW_NXT_SET_FLOW_FORMAT, OFP10_VERSION, 0);
1141     sff = ofpbuf_put_zeros(msg, sizeof *sff);
1142     sff->format = htonl(nxff);
1143
1144     return msg;
1145 }
1146
1147 /* Returns the base protocol if 'flow_format' is a valid NXFF_* value, false
1148  * otherwise. */
1149 enum ofputil_protocol
1150 ofputil_nx_flow_format_to_protocol(enum nx_flow_format flow_format)
1151 {
1152     switch (flow_format) {
1153     case NXFF_OPENFLOW10:
1154         return OFPUTIL_P_OF10;
1155
1156     case NXFF_NXM:
1157         return OFPUTIL_P_NXM;
1158
1159     case NXFF_OPENFLOW12:
1160         return OFPUTIL_P_OF12;
1161
1162     default:
1163         return 0;
1164     }
1165 }
1166
1167 /* Returns true if 'flow_format' is a valid NXFF_* value, false otherwise. */
1168 bool
1169 ofputil_nx_flow_format_is_valid(enum nx_flow_format flow_format)
1170 {
1171     return ofputil_nx_flow_format_to_protocol(flow_format) != 0;
1172 }
1173
1174 /* Returns a string version of 'flow_format', which must be a valid NXFF_*
1175  * value. */
1176 const char *
1177 ofputil_nx_flow_format_to_string(enum nx_flow_format flow_format)
1178 {
1179     switch (flow_format) {
1180     case NXFF_OPENFLOW10:
1181         return "openflow10";
1182     case NXFF_NXM:
1183         return "nxm";
1184     case NXFF_OPENFLOW12:
1185         return "openflow12";
1186     default:
1187         NOT_REACHED();
1188     }
1189 }
1190
1191 struct ofpbuf *
1192 ofputil_make_set_packet_in_format(enum ofp_version ofp_version,
1193                                   enum nx_packet_in_format packet_in_format)
1194 {
1195     struct nx_set_packet_in_format *spif;
1196     struct ofpbuf *msg;
1197
1198     msg = ofpraw_alloc(OFPRAW_NXT_SET_PACKET_IN_FORMAT, ofp_version, 0);
1199     spif = ofpbuf_put_zeros(msg, sizeof *spif);
1200     spif->format = htonl(packet_in_format);
1201
1202     return msg;
1203 }
1204
1205 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
1206  * extension on or off (according to 'flow_mod_table_id'). */
1207 struct ofpbuf *
1208 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
1209 {
1210     struct nx_flow_mod_table_id *nfmti;
1211     struct ofpbuf *msg;
1212
1213     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD_TABLE_ID, OFP10_VERSION, 0);
1214     nfmti = ofpbuf_put_zeros(msg, sizeof *nfmti);
1215     nfmti->set = flow_mod_table_id;
1216     return msg;
1217 }
1218
1219 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
1220  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
1221  * code.
1222  *
1223  * Uses 'ofpacts' to store the abstract OFPACT_* version of 'oh''s actions.
1224  * The caller must initialize 'ofpacts' and retains ownership of it.
1225  * 'fm->ofpacts' will point into the 'ofpacts' buffer.
1226  *
1227  * Does not validate the flow_mod actions.  The caller should do that, with
1228  * ofpacts_check(). */
1229 enum ofperr
1230 ofputil_decode_flow_mod(struct ofputil_flow_mod *fm,
1231                         const struct ofp_header *oh,
1232                         enum ofputil_protocol protocol,
1233                         struct ofpbuf *ofpacts)
1234 {
1235     uint16_t command;
1236     struct ofpbuf b;
1237     enum ofpraw raw;
1238
1239     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1240     raw = ofpraw_pull_assert(&b);
1241     if (raw == OFPRAW_OFPT11_FLOW_MOD) {
1242         /* Standard OpenFlow 1.1 flow_mod. */
1243         const struct ofp11_flow_mod *ofm;
1244         enum ofperr error;
1245
1246         ofm = ofpbuf_pull(&b, sizeof *ofm);
1247
1248         error = ofputil_pull_ofp11_match(&b, &fm->match, NULL);
1249         if (error) {
1250             return error;
1251         }
1252
1253         error = ofpacts_pull_openflow11_instructions(&b, b.size, ofpacts);
1254         if (error) {
1255             return error;
1256         }
1257
1258         /* Translate the message. */
1259         fm->priority = ntohs(ofm->priority);
1260         if (ofm->command == OFPFC_ADD) {
1261             fm->cookie = htonll(0);
1262             fm->cookie_mask = htonll(0);
1263             fm->new_cookie = ofm->cookie;
1264         } else {
1265             fm->cookie = ofm->cookie;
1266             fm->cookie_mask = ofm->cookie_mask;
1267             fm->new_cookie = htonll(UINT64_MAX);
1268         }
1269         fm->command = ofm->command;
1270         fm->table_id = ofm->table_id;
1271         fm->idle_timeout = ntohs(ofm->idle_timeout);
1272         fm->hard_timeout = ntohs(ofm->hard_timeout);
1273         fm->buffer_id = ntohl(ofm->buffer_id);
1274         error = ofputil_port_from_ofp11(ofm->out_port, &fm->out_port);
1275         if (error) {
1276             return error;
1277         }
1278         if (ofm->out_group != htonl(OFPG_ANY)) {
1279             return OFPERR_OFPFMFC_UNKNOWN;
1280         }
1281         fm->flags = ntohs(ofm->flags);
1282     } else {
1283         if (raw == OFPRAW_OFPT10_FLOW_MOD) {
1284             /* Standard OpenFlow 1.0 flow_mod. */
1285             const struct ofp10_flow_mod *ofm;
1286             enum ofperr error;
1287
1288             /* Get the ofp10_flow_mod. */
1289             ofm = ofpbuf_pull(&b, sizeof *ofm);
1290
1291             /* Translate the rule. */
1292             ofputil_match_from_ofp10_match(&ofm->match, &fm->match);
1293             ofputil_normalize_match(&fm->match);
1294
1295             /* Now get the actions. */
1296             error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1297             if (error) {
1298                 return error;
1299             }
1300
1301             /* OpenFlow 1.0 says that exact-match rules have to have the
1302              * highest possible priority. */
1303             fm->priority = (ofm->match.wildcards & htonl(OFPFW10_ALL)
1304                             ? ntohs(ofm->priority)
1305                             : UINT16_MAX);
1306
1307             /* Translate the message. */
1308             command = ntohs(ofm->command);
1309             fm->cookie = htonll(0);
1310             fm->cookie_mask = htonll(0);
1311             fm->new_cookie = ofm->cookie;
1312             fm->idle_timeout = ntohs(ofm->idle_timeout);
1313             fm->hard_timeout = ntohs(ofm->hard_timeout);
1314             fm->buffer_id = ntohl(ofm->buffer_id);
1315             fm->out_port = ntohs(ofm->out_port);
1316             fm->flags = ntohs(ofm->flags);
1317         } else if (raw == OFPRAW_NXT_FLOW_MOD) {
1318             /* Nicira extended flow_mod. */
1319             const struct nx_flow_mod *nfm;
1320             enum ofperr error;
1321
1322             /* Dissect the message. */
1323             nfm = ofpbuf_pull(&b, sizeof *nfm);
1324             error = nx_pull_match(&b, ntohs(nfm->match_len),
1325                                   &fm->match, &fm->cookie, &fm->cookie_mask);
1326             if (error) {
1327                 return error;
1328             }
1329             error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1330             if (error) {
1331                 return error;
1332             }
1333
1334             /* Translate the message. */
1335             command = ntohs(nfm->command);
1336             if ((command & 0xff) == OFPFC_ADD && fm->cookie_mask) {
1337                 /* Flow additions may only set a new cookie, not match an
1338                  * existing cookie. */
1339                 return OFPERR_NXBRC_NXM_INVALID;
1340             }
1341             fm->priority = ntohs(nfm->priority);
1342             fm->new_cookie = nfm->cookie;
1343             fm->idle_timeout = ntohs(nfm->idle_timeout);
1344             fm->hard_timeout = ntohs(nfm->hard_timeout);
1345             fm->buffer_id = ntohl(nfm->buffer_id);
1346             fm->out_port = ntohs(nfm->out_port);
1347             fm->flags = ntohs(nfm->flags);
1348         } else {
1349             NOT_REACHED();
1350         }
1351
1352         if (protocol & OFPUTIL_P_TID) {
1353             fm->command = command & 0xff;
1354             fm->table_id = command >> 8;
1355         } else {
1356             fm->command = command;
1357             fm->table_id = 0xff;
1358         }
1359     }
1360
1361     fm->ofpacts = ofpacts->data;
1362     fm->ofpacts_len = ofpacts->size;
1363
1364     return 0;
1365 }
1366
1367 static ovs_be16
1368 ofputil_tid_command(const struct ofputil_flow_mod *fm,
1369                     enum ofputil_protocol protocol)
1370 {
1371     return htons(protocol & OFPUTIL_P_TID
1372                  ? (fm->command & 0xff) | (fm->table_id << 8)
1373                  : fm->command);
1374 }
1375
1376 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
1377  * 'protocol' and returns the message. */
1378 struct ofpbuf *
1379 ofputil_encode_flow_mod(const struct ofputil_flow_mod *fm,
1380                         enum ofputil_protocol protocol)
1381 {
1382     struct ofpbuf *msg;
1383
1384     switch (protocol) {
1385     case OFPUTIL_P_OF12: {
1386         struct ofp11_flow_mod *ofm;
1387
1388         msg = ofpraw_alloc(OFPRAW_OFPT11_FLOW_MOD, OFP12_VERSION,
1389                            NXM_TYPICAL_LEN + fm->ofpacts_len);
1390         ofm = ofpbuf_put_zeros(msg, sizeof *ofm);
1391         if (fm->command == OFPFC_ADD) {
1392             ofm->cookie = fm->new_cookie;
1393         } else {
1394             ofm->cookie = fm->cookie;
1395         }
1396         ofm->cookie_mask = fm->cookie_mask;
1397         ofm->table_id = fm->table_id;
1398         ofm->command = fm->command;
1399         ofm->idle_timeout = htons(fm->idle_timeout);
1400         ofm->hard_timeout = htons(fm->hard_timeout);
1401         ofm->priority = htons(fm->priority);
1402         ofm->buffer_id = htonl(fm->buffer_id);
1403         ofm->out_port = ofputil_port_to_ofp11(fm->out_port);
1404         ofm->out_group = htonl(OFPG11_ANY);
1405         ofm->flags = htons(fm->flags);
1406         oxm_put_match(msg, &fm->match);
1407         ofpacts_put_openflow11_instructions(fm->ofpacts, fm->ofpacts_len, msg);
1408         break;
1409     }
1410
1411     case OFPUTIL_P_OF10:
1412     case OFPUTIL_P_OF10_TID: {
1413         struct ofp10_flow_mod *ofm;
1414
1415         msg = ofpraw_alloc(OFPRAW_OFPT10_FLOW_MOD, OFP10_VERSION,
1416                            fm->ofpacts_len);
1417         ofm = ofpbuf_put_zeros(msg, sizeof *ofm);
1418         ofputil_match_to_ofp10_match(&fm->match, &ofm->match);
1419         ofm->cookie = fm->new_cookie;
1420         ofm->command = ofputil_tid_command(fm, protocol);
1421         ofm->idle_timeout = htons(fm->idle_timeout);
1422         ofm->hard_timeout = htons(fm->hard_timeout);
1423         ofm->priority = htons(fm->priority);
1424         ofm->buffer_id = htonl(fm->buffer_id);
1425         ofm->out_port = htons(fm->out_port);
1426         ofm->flags = htons(fm->flags);
1427         ofpacts_put_openflow10(fm->ofpacts, fm->ofpacts_len, msg);
1428         break;
1429     }
1430
1431     case OFPUTIL_P_NXM:
1432     case OFPUTIL_P_NXM_TID: {
1433         struct nx_flow_mod *nfm;
1434         int match_len;
1435
1436         msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD, OFP10_VERSION,
1437                            NXM_TYPICAL_LEN + fm->ofpacts_len);
1438         nfm = ofpbuf_put_zeros(msg, sizeof *nfm);
1439         nfm->command = ofputil_tid_command(fm, protocol);
1440         nfm->cookie = fm->new_cookie;
1441         match_len = nx_put_match(msg, &fm->match, fm->cookie, fm->cookie_mask);
1442         nfm = msg->l3;
1443         nfm->idle_timeout = htons(fm->idle_timeout);
1444         nfm->hard_timeout = htons(fm->hard_timeout);
1445         nfm->priority = htons(fm->priority);
1446         nfm->buffer_id = htonl(fm->buffer_id);
1447         nfm->out_port = htons(fm->out_port);
1448         nfm->flags = htons(fm->flags);
1449         nfm->match_len = htons(match_len);
1450         ofpacts_put_openflow10(fm->ofpacts, fm->ofpacts_len, msg);
1451         break;
1452     }
1453
1454     default:
1455         NOT_REACHED();
1456     }
1457
1458     ofpmsg_update_length(msg);
1459     return msg;
1460 }
1461
1462 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1463  * send all of the 'n_fm's flow table modification requests in 'fms', and a
1464  * 0-bit for each protocol that is inadequate.
1465  *
1466  * (The return value will have at least one 1-bit.) */
1467 enum ofputil_protocol
1468 ofputil_flow_mod_usable_protocols(const struct ofputil_flow_mod *fms,
1469                                   size_t n_fms)
1470 {
1471     enum ofputil_protocol usable_protocols;
1472     size_t i;
1473
1474     usable_protocols = OFPUTIL_P_ANY;
1475     for (i = 0; i < n_fms; i++) {
1476         const struct ofputil_flow_mod *fm = &fms[i];
1477
1478         usable_protocols &= ofputil_usable_protocols(&fm->match);
1479         if (fm->table_id != 0xff) {
1480             usable_protocols &= OFPUTIL_P_TID;
1481         }
1482
1483         /* Matching of the cookie is only supported through NXM. */
1484         if (fm->cookie_mask != htonll(0)) {
1485             usable_protocols &= OFPUTIL_P_NXM_ANY;
1486         }
1487     }
1488     assert(usable_protocols);
1489
1490     return usable_protocols;
1491 }
1492
1493 static enum ofperr
1494 ofputil_decode_ofpst10_flow_request(struct ofputil_flow_stats_request *fsr,
1495                                     const struct ofp10_flow_stats_request *ofsr,
1496                                     bool aggregate)
1497 {
1498     fsr->aggregate = aggregate;
1499     ofputil_match_from_ofp10_match(&ofsr->match, &fsr->match);
1500     fsr->out_port = ntohs(ofsr->out_port);
1501     fsr->table_id = ofsr->table_id;
1502     fsr->cookie = fsr->cookie_mask = htonll(0);
1503
1504     return 0;
1505 }
1506
1507 static enum ofperr
1508 ofputil_decode_ofpst11_flow_request(struct ofputil_flow_stats_request *fsr,
1509                                     struct ofpbuf *b, bool aggregate)
1510 {
1511     const struct ofp11_flow_stats_request *ofsr;
1512     enum ofperr error;
1513
1514     ofsr = ofpbuf_pull(b, sizeof *ofsr);
1515     fsr->aggregate = aggregate;
1516     fsr->table_id = ofsr->table_id;
1517     error = ofputil_port_from_ofp11(ofsr->out_port, &fsr->out_port);
1518     if (error) {
1519         return error;
1520     }
1521     if (ofsr->out_group != htonl(OFPG11_ANY)) {
1522         return OFPERR_OFPFMFC_UNKNOWN;
1523     }
1524     fsr->cookie = ofsr->cookie;
1525     fsr->cookie_mask = ofsr->cookie_mask;
1526     error = ofputil_pull_ofp11_match(b, &fsr->match, NULL);
1527     if (error) {
1528         return error;
1529     }
1530
1531     return 0;
1532 }
1533
1534 static enum ofperr
1535 ofputil_decode_nxst_flow_request(struct ofputil_flow_stats_request *fsr,
1536                                  struct ofpbuf *b, bool aggregate)
1537 {
1538     const struct nx_flow_stats_request *nfsr;
1539     enum ofperr error;
1540
1541     nfsr = ofpbuf_pull(b, sizeof *nfsr);
1542     error = nx_pull_match(b, ntohs(nfsr->match_len), &fsr->match,
1543                           &fsr->cookie, &fsr->cookie_mask);
1544     if (error) {
1545         return error;
1546     }
1547     if (b->size) {
1548         return OFPERR_OFPBRC_BAD_LEN;
1549     }
1550
1551     fsr->aggregate = aggregate;
1552     fsr->out_port = ntohs(nfsr->out_port);
1553     fsr->table_id = nfsr->table_id;
1554
1555     return 0;
1556 }
1557
1558 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1559  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1560  * successful, otherwise an OpenFlow error code. */
1561 enum ofperr
1562 ofputil_decode_flow_stats_request(struct ofputil_flow_stats_request *fsr,
1563                                   const struct ofp_header *oh)
1564 {
1565     enum ofpraw raw;
1566     struct ofpbuf b;
1567
1568     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1569     raw = ofpraw_pull_assert(&b);
1570     switch ((int) raw) {
1571     case OFPRAW_OFPST10_FLOW_REQUEST:
1572         return ofputil_decode_ofpst10_flow_request(fsr, b.data, false);
1573
1574     case OFPRAW_OFPST10_AGGREGATE_REQUEST:
1575         return ofputil_decode_ofpst10_flow_request(fsr, b.data, true);
1576
1577     case OFPRAW_OFPST11_FLOW_REQUEST:
1578         return ofputil_decode_ofpst11_flow_request(fsr, &b, false);
1579
1580     case OFPRAW_OFPST11_AGGREGATE_REQUEST:
1581         return ofputil_decode_ofpst11_flow_request(fsr, &b, true);
1582
1583     case OFPRAW_NXST_FLOW_REQUEST:
1584         return ofputil_decode_nxst_flow_request(fsr, &b, false);
1585
1586     case OFPRAW_NXST_AGGREGATE_REQUEST:
1587         return ofputil_decode_nxst_flow_request(fsr, &b, true);
1588
1589     default:
1590         /* Hey, the caller lied. */
1591         NOT_REACHED();
1592     }
1593 }
1594
1595 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1596  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1597  * 'protocol', and returns the message. */
1598 struct ofpbuf *
1599 ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr,
1600                                   enum ofputil_protocol protocol)
1601 {
1602     struct ofpbuf *msg;
1603     enum ofpraw raw;
1604
1605     switch (protocol) {
1606     case OFPUTIL_P_OF12: {
1607         struct ofp11_flow_stats_request *ofsr;
1608
1609         raw = (fsr->aggregate
1610                ? OFPRAW_OFPST11_AGGREGATE_REQUEST
1611                : OFPRAW_OFPST11_FLOW_REQUEST);
1612         msg = ofpraw_alloc(raw, OFP12_VERSION, NXM_TYPICAL_LEN);
1613         ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr);
1614         ofsr->table_id = fsr->table_id;
1615         ofsr->out_port = ofputil_port_to_ofp11(fsr->out_port);
1616         ofsr->out_group = htonl(OFPG11_ANY);
1617         ofsr->cookie = fsr->cookie;
1618         ofsr->cookie_mask = fsr->cookie_mask;
1619         oxm_put_match(msg, &fsr->match);
1620         break;
1621     }
1622
1623     case OFPUTIL_P_OF10:
1624     case OFPUTIL_P_OF10_TID: {
1625         struct ofp10_flow_stats_request *ofsr;
1626
1627         raw = (fsr->aggregate
1628                ? OFPRAW_OFPST10_AGGREGATE_REQUEST
1629                : OFPRAW_OFPST10_FLOW_REQUEST);
1630         msg = ofpraw_alloc(raw, OFP10_VERSION, 0);
1631         ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr);
1632         ofputil_match_to_ofp10_match(&fsr->match, &ofsr->match);
1633         ofsr->table_id = fsr->table_id;
1634         ofsr->out_port = htons(fsr->out_port);
1635         break;
1636     }
1637
1638     case OFPUTIL_P_NXM:
1639     case OFPUTIL_P_NXM_TID: {
1640         struct nx_flow_stats_request *nfsr;
1641         int match_len;
1642
1643         raw = (fsr->aggregate
1644                ? OFPRAW_NXST_AGGREGATE_REQUEST
1645                : OFPRAW_NXST_FLOW_REQUEST);
1646         msg = ofpraw_alloc(raw, OFP10_VERSION, NXM_TYPICAL_LEN);
1647         ofpbuf_put_zeros(msg, sizeof *nfsr);
1648         match_len = nx_put_match(msg, &fsr->match,
1649                                  fsr->cookie, fsr->cookie_mask);
1650
1651         nfsr = msg->l3;
1652         nfsr->out_port = htons(fsr->out_port);
1653         nfsr->match_len = htons(match_len);
1654         nfsr->table_id = fsr->table_id;
1655         break;
1656     }
1657
1658     default:
1659         NOT_REACHED();
1660     }
1661
1662     return msg;
1663 }
1664
1665 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1666  * accurately encode 'fsr', and a 0-bit for each protocol that is inadequate.
1667  *
1668  * (The return value will have at least one 1-bit.) */
1669 enum ofputil_protocol
1670 ofputil_flow_stats_request_usable_protocols(
1671     const struct ofputil_flow_stats_request *fsr)
1672 {
1673     enum ofputil_protocol usable_protocols;
1674
1675     usable_protocols = ofputil_usable_protocols(&fsr->match);
1676     if (fsr->cookie_mask != htonll(0)) {
1677         usable_protocols &= OFPUTIL_P_NXM_ANY;
1678     }
1679     return usable_protocols;
1680 }
1681
1682 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1683  * ofputil_flow_stats in 'fs'.
1684  *
1685  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1686  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1687  * iterates through the replies.  The caller must initially leave 'msg''s layer
1688  * pointers null and not modify them between calls.
1689  *
1690  * Most switches don't send the values needed to populate fs->idle_age and
1691  * fs->hard_age, so those members will usually be set to 0.  If the switch from
1692  * which 'msg' originated is known to implement NXT_FLOW_AGE, then pass
1693  * 'flow_age_extension' as true so that the contents of 'msg' determine the
1694  * 'idle_age' and 'hard_age' members in 'fs'.
1695  *
1696  * Uses 'ofpacts' to store the abstract OFPACT_* version of the flow stats
1697  * reply's actions.  The caller must initialize 'ofpacts' and retains ownership
1698  * of it.  'fs->ofpacts' will point into the 'ofpacts' buffer.
1699  *
1700  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1701  * otherwise a positive errno value. */
1702 int
1703 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
1704                                 struct ofpbuf *msg,
1705                                 bool flow_age_extension,
1706                                 struct ofpbuf *ofpacts)
1707 {
1708     enum ofperr error;
1709     enum ofpraw raw;
1710
1711     error = (msg->l2
1712              ? ofpraw_decode(&raw, msg->l2)
1713              : ofpraw_pull(&raw, msg));
1714     if (error) {
1715         return error;
1716     }
1717
1718     if (!msg->size) {
1719         return EOF;
1720     } else if (raw == OFPRAW_OFPST11_FLOW_REPLY) {
1721         const struct ofp11_flow_stats *ofs;
1722         size_t length;
1723         uint16_t padded_match_len;
1724
1725         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
1726         if (!ofs) {
1727             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
1728                          "bytes at end", msg->size);
1729             return EINVAL;
1730         }
1731
1732         length = ntohs(ofs->length);
1733         if (length < sizeof *ofs) {
1734             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
1735                          "length %zu", length);
1736             return EINVAL;
1737         }
1738
1739         if (ofputil_pull_ofp11_match(msg, &fs->match, &padded_match_len)) {
1740             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad match");
1741             return EINVAL;
1742         }
1743
1744         if (ofpacts_pull_openflow11_instructions(msg, length - sizeof *ofs -
1745                                                  padded_match_len, ofpacts)) {
1746             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad instructions");
1747             return EINVAL;
1748         }
1749
1750         fs->priority = ntohs(ofs->priority);
1751         fs->table_id = ofs->table_id;
1752         fs->duration_sec = ntohl(ofs->duration_sec);
1753         fs->duration_nsec = ntohl(ofs->duration_nsec);
1754         fs->idle_timeout = ntohs(ofs->idle_timeout);
1755         fs->hard_timeout = ntohs(ofs->hard_timeout);
1756         fs->idle_age = -1;
1757         fs->hard_age = -1;
1758         fs->cookie = ofs->cookie;
1759         fs->packet_count = ntohll(ofs->packet_count);
1760         fs->byte_count = ntohll(ofs->byte_count);
1761     } else if (raw == OFPRAW_OFPST10_FLOW_REPLY) {
1762         const struct ofp10_flow_stats *ofs;
1763         size_t length;
1764
1765         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
1766         if (!ofs) {
1767             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
1768                          "bytes at end", msg->size);
1769             return EINVAL;
1770         }
1771
1772         length = ntohs(ofs->length);
1773         if (length < sizeof *ofs) {
1774             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
1775                          "length %zu", length);
1776             return EINVAL;
1777         }
1778
1779         if (ofpacts_pull_openflow10(msg, length - sizeof *ofs, ofpacts)) {
1780             return EINVAL;
1781         }
1782
1783         fs->cookie = get_32aligned_be64(&ofs->cookie);
1784         ofputil_match_from_ofp10_match(&ofs->match, &fs->match);
1785         fs->priority = ntohs(ofs->priority);
1786         fs->table_id = ofs->table_id;
1787         fs->duration_sec = ntohl(ofs->duration_sec);
1788         fs->duration_nsec = ntohl(ofs->duration_nsec);
1789         fs->idle_timeout = ntohs(ofs->idle_timeout);
1790         fs->hard_timeout = ntohs(ofs->hard_timeout);
1791         fs->idle_age = -1;
1792         fs->hard_age = -1;
1793         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
1794         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
1795     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
1796         const struct nx_flow_stats *nfs;
1797         size_t match_len, actions_len, length;
1798
1799         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
1800         if (!nfs) {
1801             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
1802                          "bytes at end", msg->size);
1803             return EINVAL;
1804         }
1805
1806         length = ntohs(nfs->length);
1807         match_len = ntohs(nfs->match_len);
1808         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
1809             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
1810                          "claims invalid length %zu", match_len, length);
1811             return EINVAL;
1812         }
1813         if (nx_pull_match(msg, match_len, &fs->match, NULL, NULL)) {
1814             return EINVAL;
1815         }
1816
1817         actions_len = length - sizeof *nfs - ROUND_UP(match_len, 8);
1818         if (ofpacts_pull_openflow10(msg, actions_len, ofpacts)) {
1819             return EINVAL;
1820         }
1821
1822         fs->cookie = nfs->cookie;
1823         fs->table_id = nfs->table_id;
1824         fs->duration_sec = ntohl(nfs->duration_sec);
1825         fs->duration_nsec = ntohl(nfs->duration_nsec);
1826         fs->priority = ntohs(nfs->priority);
1827         fs->idle_timeout = ntohs(nfs->idle_timeout);
1828         fs->hard_timeout = ntohs(nfs->hard_timeout);
1829         fs->idle_age = -1;
1830         fs->hard_age = -1;
1831         if (flow_age_extension) {
1832             if (nfs->idle_age) {
1833                 fs->idle_age = ntohs(nfs->idle_age) - 1;
1834             }
1835             if (nfs->hard_age) {
1836                 fs->hard_age = ntohs(nfs->hard_age) - 1;
1837             }
1838         }
1839         fs->packet_count = ntohll(nfs->packet_count);
1840         fs->byte_count = ntohll(nfs->byte_count);
1841     } else {
1842         NOT_REACHED();
1843     }
1844
1845     fs->ofpacts = ofpacts->data;
1846     fs->ofpacts_len = ofpacts->size;
1847
1848     return 0;
1849 }
1850
1851 /* Returns 'count' unchanged except that UINT64_MAX becomes 0.
1852  *
1853  * We use this in situations where OVS internally uses UINT64_MAX to mean
1854  * "value unknown" but OpenFlow 1.0 does not define any unknown value. */
1855 static uint64_t
1856 unknown_to_zero(uint64_t count)
1857 {
1858     return count != UINT64_MAX ? count : 0;
1859 }
1860
1861 /* Appends an OFPST_FLOW or NXST_FLOW reply that contains the data in 'fs' to
1862  * those already present in the list of ofpbufs in 'replies'.  'replies' should
1863  * have been initialized with ofputil_start_stats_reply(). */
1864 void
1865 ofputil_append_flow_stats_reply(const struct ofputil_flow_stats *fs,
1866                                 struct list *replies)
1867 {
1868     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
1869     size_t start_ofs = reply->size;
1870     enum ofpraw raw;
1871
1872     ofpraw_decode_partial(&raw, reply->data, reply->size);
1873     if (raw == OFPRAW_OFPST11_FLOW_REPLY) {
1874         struct ofp11_flow_stats *ofs;
1875
1876         ofpbuf_put_uninit(reply, sizeof *ofs);
1877         oxm_put_match(reply, &fs->match);
1878         ofpacts_put_openflow11_instructions(fs->ofpacts, fs->ofpacts_len,
1879                                             reply);
1880
1881         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
1882         ofs->length = htons(reply->size - start_ofs);
1883         ofs->table_id = fs->table_id;
1884         ofs->pad = 0;
1885         ofs->duration_sec = htonl(fs->duration_sec);
1886         ofs->duration_nsec = htonl(fs->duration_nsec);
1887         ofs->priority = htons(fs->priority);
1888         ofs->idle_timeout = htons(fs->idle_timeout);
1889         ofs->hard_timeout = htons(fs->hard_timeout);
1890         memset(ofs->pad2, 0, sizeof ofs->pad2);
1891         ofs->cookie = fs->cookie;
1892         ofs->packet_count = htonll(unknown_to_zero(fs->packet_count));
1893         ofs->byte_count = htonll(unknown_to_zero(fs->byte_count));
1894     } else if (raw == OFPRAW_OFPST10_FLOW_REPLY) {
1895         struct ofp10_flow_stats *ofs;
1896
1897         ofpbuf_put_uninit(reply, sizeof *ofs);
1898         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
1899
1900         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
1901         ofs->length = htons(reply->size - start_ofs);
1902         ofs->table_id = fs->table_id;
1903         ofs->pad = 0;
1904         ofputil_match_to_ofp10_match(&fs->match, &ofs->match);
1905         ofs->duration_sec = htonl(fs->duration_sec);
1906         ofs->duration_nsec = htonl(fs->duration_nsec);
1907         ofs->priority = htons(fs->priority);
1908         ofs->idle_timeout = htons(fs->idle_timeout);
1909         ofs->hard_timeout = htons(fs->hard_timeout);
1910         memset(ofs->pad2, 0, sizeof ofs->pad2);
1911         put_32aligned_be64(&ofs->cookie, fs->cookie);
1912         put_32aligned_be64(&ofs->packet_count,
1913                            htonll(unknown_to_zero(fs->packet_count)));
1914         put_32aligned_be64(&ofs->byte_count,
1915                            htonll(unknown_to_zero(fs->byte_count)));
1916     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
1917         struct nx_flow_stats *nfs;
1918         int match_len;
1919
1920         ofpbuf_put_uninit(reply, sizeof *nfs);
1921         match_len = nx_put_match(reply, &fs->match, 0, 0);
1922         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
1923
1924         nfs = ofpbuf_at_assert(reply, start_ofs, sizeof *nfs);
1925         nfs->length = htons(reply->size - start_ofs);
1926         nfs->table_id = fs->table_id;
1927         nfs->pad = 0;
1928         nfs->duration_sec = htonl(fs->duration_sec);
1929         nfs->duration_nsec = htonl(fs->duration_nsec);
1930         nfs->priority = htons(fs->priority);
1931         nfs->idle_timeout = htons(fs->idle_timeout);
1932         nfs->hard_timeout = htons(fs->hard_timeout);
1933         nfs->idle_age = htons(fs->idle_age < 0 ? 0
1934                               : fs->idle_age < UINT16_MAX ? fs->idle_age + 1
1935                               : UINT16_MAX);
1936         nfs->hard_age = htons(fs->hard_age < 0 ? 0
1937                               : fs->hard_age < UINT16_MAX ? fs->hard_age + 1
1938                               : UINT16_MAX);
1939         nfs->match_len = htons(match_len);
1940         nfs->cookie = fs->cookie;
1941         nfs->packet_count = htonll(fs->packet_count);
1942         nfs->byte_count = htonll(fs->byte_count);
1943     } else {
1944         NOT_REACHED();
1945     }
1946
1947     ofpmp_postappend(replies, start_ofs);
1948 }
1949
1950 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
1951  * NXST_AGGREGATE reply matching 'request', and returns the message. */
1952 struct ofpbuf *
1953 ofputil_encode_aggregate_stats_reply(
1954     const struct ofputil_aggregate_stats *stats,
1955     const struct ofp_header *request)
1956 {
1957     struct ofp_aggregate_stats_reply *asr;
1958     uint64_t packet_count;
1959     uint64_t byte_count;
1960     struct ofpbuf *msg;
1961     enum ofpraw raw;
1962
1963     ofpraw_decode(&raw, request);
1964     if (raw == OFPRAW_OFPST10_AGGREGATE_REQUEST) {
1965         packet_count = unknown_to_zero(stats->packet_count);
1966         byte_count = unknown_to_zero(stats->byte_count);
1967     } else {
1968         packet_count = stats->packet_count;
1969         byte_count = stats->byte_count;
1970     }
1971
1972     msg = ofpraw_alloc_stats_reply(request, 0);
1973     asr = ofpbuf_put_zeros(msg, sizeof *asr);
1974     put_32aligned_be64(&asr->packet_count, htonll(packet_count));
1975     put_32aligned_be64(&asr->byte_count, htonll(byte_count));
1976     asr->flow_count = htonl(stats->flow_count);
1977
1978     return msg;
1979 }
1980
1981 enum ofperr
1982 ofputil_decode_aggregate_stats_reply(struct ofputil_aggregate_stats *stats,
1983                                      const struct ofp_header *reply)
1984 {
1985     struct ofp_aggregate_stats_reply *asr;
1986     struct ofpbuf msg;
1987
1988     ofpbuf_use_const(&msg, reply, ntohs(reply->length));
1989     ofpraw_pull_assert(&msg);
1990
1991     asr = msg.l3;
1992     stats->packet_count = ntohll(get_32aligned_be64(&asr->packet_count));
1993     stats->byte_count = ntohll(get_32aligned_be64(&asr->byte_count));
1994     stats->flow_count = ntohl(asr->flow_count);
1995
1996     return 0;
1997 }
1998
1999 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
2000  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
2001  * an OpenFlow error code. */
2002 enum ofperr
2003 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
2004                             const struct ofp_header *oh)
2005 {
2006     enum ofpraw raw;
2007     struct ofpbuf b;
2008
2009     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2010     raw = ofpraw_pull_assert(&b);
2011     if (raw == OFPRAW_OFPT11_FLOW_REMOVED) {
2012         const struct ofp12_flow_removed *ofr;
2013         enum ofperr error;
2014
2015         ofr = ofpbuf_pull(&b, sizeof *ofr);
2016
2017         error = ofputil_pull_ofp11_match(&b, &fr->match, NULL);
2018         if (error) {
2019             return error;
2020         }
2021
2022         fr->priority = ntohs(ofr->priority);
2023         fr->cookie = ofr->cookie;
2024         fr->reason = ofr->reason;
2025         fr->table_id = ofr->table_id;
2026         fr->duration_sec = ntohl(ofr->duration_sec);
2027         fr->duration_nsec = ntohl(ofr->duration_nsec);
2028         fr->idle_timeout = ntohs(ofr->idle_timeout);
2029         fr->hard_timeout = ntohs(ofr->hard_timeout);
2030         fr->packet_count = ntohll(ofr->packet_count);
2031         fr->byte_count = ntohll(ofr->byte_count);
2032     } else if (raw == OFPRAW_OFPT10_FLOW_REMOVED) {
2033         const struct ofp_flow_removed *ofr;
2034
2035         ofr = ofpbuf_pull(&b, sizeof *ofr);
2036
2037         ofputil_match_from_ofp10_match(&ofr->match, &fr->match);
2038         fr->priority = ntohs(ofr->priority);
2039         fr->cookie = ofr->cookie;
2040         fr->reason = ofr->reason;
2041         fr->table_id = 255;
2042         fr->duration_sec = ntohl(ofr->duration_sec);
2043         fr->duration_nsec = ntohl(ofr->duration_nsec);
2044         fr->idle_timeout = ntohs(ofr->idle_timeout);
2045         fr->hard_timeout = 0;
2046         fr->packet_count = ntohll(ofr->packet_count);
2047         fr->byte_count = ntohll(ofr->byte_count);
2048     } else if (raw == OFPRAW_NXT_FLOW_REMOVED) {
2049         struct nx_flow_removed *nfr;
2050         enum ofperr error;
2051
2052         nfr = ofpbuf_pull(&b, sizeof *nfr);
2053         error = nx_pull_match(&b, ntohs(nfr->match_len), &fr->match,
2054                               NULL, NULL);
2055         if (error) {
2056             return error;
2057         }
2058         if (b.size) {
2059             return OFPERR_OFPBRC_BAD_LEN;
2060         }
2061
2062         fr->priority = ntohs(nfr->priority);
2063         fr->cookie = nfr->cookie;
2064         fr->reason = nfr->reason;
2065         fr->table_id = 255;
2066         fr->duration_sec = ntohl(nfr->duration_sec);
2067         fr->duration_nsec = ntohl(nfr->duration_nsec);
2068         fr->idle_timeout = ntohs(nfr->idle_timeout);
2069         fr->hard_timeout = 0;
2070         fr->packet_count = ntohll(nfr->packet_count);
2071         fr->byte_count = ntohll(nfr->byte_count);
2072     } else {
2073         NOT_REACHED();
2074     }
2075
2076     return 0;
2077 }
2078
2079 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
2080  * NXT_FLOW_REMOVED message 'oh' according to 'protocol', and returns the
2081  * message. */
2082 struct ofpbuf *
2083 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
2084                             enum ofputil_protocol protocol)
2085 {
2086     struct ofpbuf *msg;
2087
2088     switch (protocol) {
2089     case OFPUTIL_P_OF12: {
2090         struct ofp12_flow_removed *ofr;
2091
2092         msg = ofpraw_alloc_xid(OFPRAW_OFPT11_FLOW_REMOVED,
2093                                ofputil_protocol_to_ofp_version(protocol),
2094                                htonl(0), NXM_TYPICAL_LEN);
2095         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
2096         ofr->cookie = fr->cookie;
2097         ofr->priority = htons(fr->priority);
2098         ofr->reason = fr->reason;
2099         ofr->table_id = fr->table_id;
2100         ofr->duration_sec = htonl(fr->duration_sec);
2101         ofr->duration_nsec = htonl(fr->duration_nsec);
2102         ofr->idle_timeout = htons(fr->idle_timeout);
2103         ofr->hard_timeout = htons(fr->hard_timeout);
2104         ofr->packet_count = htonll(fr->packet_count);
2105         ofr->byte_count = htonll(fr->byte_count);
2106         oxm_put_match(msg, &fr->match);
2107         break;
2108     }
2109
2110     case OFPUTIL_P_OF10:
2111     case OFPUTIL_P_OF10_TID: {
2112         struct ofp_flow_removed *ofr;
2113
2114         msg = ofpraw_alloc_xid(OFPRAW_OFPT10_FLOW_REMOVED, OFP10_VERSION,
2115                                htonl(0), 0);
2116         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
2117         ofputil_match_to_ofp10_match(&fr->match, &ofr->match);
2118         ofr->cookie = fr->cookie;
2119         ofr->priority = htons(fr->priority);
2120         ofr->reason = fr->reason;
2121         ofr->duration_sec = htonl(fr->duration_sec);
2122         ofr->duration_nsec = htonl(fr->duration_nsec);
2123         ofr->idle_timeout = htons(fr->idle_timeout);
2124         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
2125         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
2126         break;
2127     }
2128
2129     case OFPUTIL_P_NXM:
2130     case OFPUTIL_P_NXM_TID: {
2131         struct nx_flow_removed *nfr;
2132         int match_len;
2133
2134         msg = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_REMOVED, OFP10_VERSION,
2135                                htonl(0), NXM_TYPICAL_LEN);
2136         nfr = ofpbuf_put_zeros(msg, sizeof *nfr);
2137         match_len = nx_put_match(msg, &fr->match, 0, 0);
2138
2139         nfr = msg->l3;
2140         nfr->cookie = fr->cookie;
2141         nfr->priority = htons(fr->priority);
2142         nfr->reason = fr->reason;
2143         nfr->duration_sec = htonl(fr->duration_sec);
2144         nfr->duration_nsec = htonl(fr->duration_nsec);
2145         nfr->idle_timeout = htons(fr->idle_timeout);
2146         nfr->match_len = htons(match_len);
2147         nfr->packet_count = htonll(fr->packet_count);
2148         nfr->byte_count = htonll(fr->byte_count);
2149         break;
2150     }
2151
2152     default:
2153         NOT_REACHED();
2154     }
2155
2156     return msg;
2157 }
2158
2159 static void
2160 ofputil_decode_packet_in_finish(struct ofputil_packet_in *pin,
2161                                 struct match *match, struct ofpbuf *b)
2162 {
2163     pin->packet = b->data;
2164     pin->packet_len = b->size;
2165
2166     pin->fmd.in_port = match->flow.in_port;
2167     pin->fmd.tun_id = match->flow.tunnel.tun_id;
2168     pin->fmd.metadata = match->flow.metadata;
2169     memcpy(pin->fmd.regs, match->flow.regs, sizeof pin->fmd.regs);
2170 }
2171
2172 enum ofperr
2173 ofputil_decode_packet_in(struct ofputil_packet_in *pin,
2174                          const struct ofp_header *oh)
2175 {
2176     enum ofpraw raw;
2177     struct ofpbuf b;
2178
2179     memset(pin, 0, sizeof *pin);
2180
2181     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2182     raw = ofpraw_pull_assert(&b);
2183     if (raw == OFPRAW_OFPT12_PACKET_IN) {
2184         const struct ofp12_packet_in *opi;
2185         struct match match;
2186         int error;
2187
2188         opi = ofpbuf_pull(&b, sizeof *opi);
2189         error = oxm_pull_match_loose(&b, &match);
2190         if (error) {
2191             return error;
2192         }
2193
2194         if (!ofpbuf_try_pull(&b, 2)) {
2195             return OFPERR_OFPBRC_BAD_LEN;
2196         }
2197
2198         pin->reason = opi->reason;
2199         pin->table_id = opi->table_id;
2200
2201         pin->buffer_id = ntohl(opi->buffer_id);
2202         pin->total_len = ntohs(opi->total_len);
2203
2204         ofputil_decode_packet_in_finish(pin, &match, &b);
2205     } else if (raw == OFPRAW_OFPT10_PACKET_IN) {
2206         const struct ofp_packet_in *opi;
2207
2208         opi = ofpbuf_pull(&b, offsetof(struct ofp_packet_in, data));
2209
2210         pin->packet = opi->data;
2211         pin->packet_len = b.size;
2212
2213         pin->fmd.in_port = ntohs(opi->in_port);
2214         pin->reason = opi->reason;
2215         pin->buffer_id = ntohl(opi->buffer_id);
2216         pin->total_len = ntohs(opi->total_len);
2217     } else if (raw == OFPRAW_NXT_PACKET_IN) {
2218         const struct nx_packet_in *npi;
2219         struct match match;
2220         int error;
2221
2222         npi = ofpbuf_pull(&b, sizeof *npi);
2223         error = nx_pull_match_loose(&b, ntohs(npi->match_len), &match, NULL,
2224                                     NULL);
2225         if (error) {
2226             return error;
2227         }
2228
2229         if (!ofpbuf_try_pull(&b, 2)) {
2230             return OFPERR_OFPBRC_BAD_LEN;
2231         }
2232
2233         pin->reason = npi->reason;
2234         pin->table_id = npi->table_id;
2235         pin->cookie = npi->cookie;
2236
2237         pin->buffer_id = ntohl(npi->buffer_id);
2238         pin->total_len = ntohs(npi->total_len);
2239
2240         ofputil_decode_packet_in_finish(pin, &match, &b);
2241     } else {
2242         NOT_REACHED();
2243     }
2244
2245     return 0;
2246 }
2247
2248 static void
2249 ofputil_packet_in_to_match(const struct ofputil_packet_in *pin,
2250                            struct match *match)
2251 {
2252     int i;
2253
2254     match_init_catchall(match);
2255     if (pin->fmd.tun_id != htonll(0)) {
2256         match_set_tun_id(match, pin->fmd.tun_id);
2257     }
2258     if (pin->fmd.metadata != htonll(0)) {
2259         match_set_metadata(match, pin->fmd.metadata);
2260     }
2261
2262     for (i = 0; i < FLOW_N_REGS; i++) {
2263         if (pin->fmd.regs[i]) {
2264             match_set_reg(match, i, pin->fmd.regs[i]);
2265         }
2266     }
2267
2268     match_set_in_port(match, pin->fmd.in_port);
2269 }
2270
2271 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message
2272  * in the format specified by 'packet_in_format'.  */
2273 struct ofpbuf *
2274 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
2275                          enum ofputil_protocol protocol,
2276                          enum nx_packet_in_format packet_in_format)
2277 {
2278     size_t send_len = MIN(pin->send_len, pin->packet_len);
2279     struct ofpbuf *packet;
2280
2281     /* Add OFPT_PACKET_IN. */
2282     if (protocol == OFPUTIL_P_OF12) {
2283         struct ofp12_packet_in *opi;
2284         struct match match;
2285
2286         ofputil_packet_in_to_match(pin, &match);
2287
2288         /* The final argument is just an estimate of the space required. */
2289         packet = ofpraw_alloc_xid(OFPRAW_OFPT12_PACKET_IN, OFP12_VERSION,
2290                                   htonl(0), (sizeof(struct flow_metadata) * 2
2291                                              + 2 + send_len));
2292         ofpbuf_put_zeros(packet, sizeof *opi);
2293         oxm_put_match(packet, &match);
2294         ofpbuf_put_zeros(packet, 2);
2295         ofpbuf_put(packet, pin->packet, send_len);
2296
2297         opi = packet->l3;
2298         opi->buffer_id = htonl(pin->buffer_id);
2299         opi->total_len = htons(pin->total_len);
2300         opi->reason = pin->reason;
2301         opi->table_id = pin->table_id;
2302    } else if (packet_in_format == NXPIF_OPENFLOW10) {
2303         struct ofp_packet_in *opi;
2304
2305         packet = ofpraw_alloc_xid(OFPRAW_OFPT10_PACKET_IN, OFP10_VERSION,
2306                                   htonl(0), send_len);
2307         opi = ofpbuf_put_zeros(packet, offsetof(struct ofp_packet_in, data));
2308         opi->total_len = htons(pin->total_len);
2309         opi->in_port = htons(pin->fmd.in_port);
2310         opi->reason = pin->reason;
2311         opi->buffer_id = htonl(pin->buffer_id);
2312
2313         ofpbuf_put(packet, pin->packet, send_len);
2314     } else if (packet_in_format == NXPIF_NXM) {
2315         struct nx_packet_in *npi;
2316         struct match match;
2317         size_t match_len;
2318
2319         ofputil_packet_in_to_match(pin, &match);
2320
2321         /* The final argument is just an estimate of the space required. */
2322         packet = ofpraw_alloc_xid(OFPRAW_NXT_PACKET_IN, OFP10_VERSION,
2323                                   htonl(0), (sizeof(struct flow_metadata) * 2
2324                                              + 2 + send_len));
2325         ofpbuf_put_zeros(packet, sizeof *npi);
2326         match_len = nx_put_match(packet, &match, 0, 0);
2327         ofpbuf_put_zeros(packet, 2);
2328         ofpbuf_put(packet, pin->packet, send_len);
2329
2330         npi = packet->l3;
2331         npi->buffer_id = htonl(pin->buffer_id);
2332         npi->total_len = htons(pin->total_len);
2333         npi->reason = pin->reason;
2334         npi->table_id = pin->table_id;
2335         npi->cookie = pin->cookie;
2336         npi->match_len = htons(match_len);
2337     } else {
2338         NOT_REACHED();
2339     }
2340     ofpmsg_update_length(packet);
2341
2342     return packet;
2343 }
2344
2345 const char *
2346 ofputil_packet_in_reason_to_string(enum ofp_packet_in_reason reason)
2347 {
2348     static char s[INT_STRLEN(int) + 1];
2349
2350     switch (reason) {
2351     case OFPR_NO_MATCH:
2352         return "no_match";
2353     case OFPR_ACTION:
2354         return "action";
2355     case OFPR_INVALID_TTL:
2356         return "invalid_ttl";
2357
2358     case OFPR_N_REASONS:
2359     default:
2360         sprintf(s, "%d", (int) reason);
2361         return s;
2362     }
2363 }
2364
2365 bool
2366 ofputil_packet_in_reason_from_string(const char *s,
2367                                      enum ofp_packet_in_reason *reason)
2368 {
2369     int i;
2370
2371     for (i = 0; i < OFPR_N_REASONS; i++) {
2372         if (!strcasecmp(s, ofputil_packet_in_reason_to_string(i))) {
2373             *reason = i;
2374             return true;
2375         }
2376     }
2377     return false;
2378 }
2379
2380 /* Converts an OFPT_PACKET_OUT in 'opo' into an abstract ofputil_packet_out in
2381  * 'po'.
2382  *
2383  * Uses 'ofpacts' to store the abstract OFPACT_* version of the packet out
2384  * message's actions.  The caller must initialize 'ofpacts' and retains
2385  * ownership of it.  'po->ofpacts' will point into the 'ofpacts' buffer.
2386  *
2387  * Returns 0 if successful, otherwise an OFPERR_* value. */
2388 enum ofperr
2389 ofputil_decode_packet_out(struct ofputil_packet_out *po,
2390                           const struct ofp_header *oh,
2391                           struct ofpbuf *ofpacts)
2392 {
2393     enum ofpraw raw;
2394     struct ofpbuf b;
2395
2396     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2397     raw = ofpraw_pull_assert(&b);
2398
2399     if (raw == OFPRAW_OFPT11_PACKET_OUT) {
2400         enum ofperr error;
2401         const struct ofp11_packet_out *opo = ofpbuf_pull(&b, sizeof *opo);
2402
2403         po->buffer_id = ntohl(opo->buffer_id);
2404         error = ofputil_port_from_ofp11(opo->in_port, &po->in_port);
2405         if (error) {
2406             return error;
2407         }
2408
2409         error = ofpacts_pull_openflow11_actions(&b, ntohs(opo->actions_len),
2410                                                 ofpacts);
2411         if (error) {
2412             return error;
2413         }
2414     } else if (raw == OFPRAW_OFPT10_PACKET_OUT) {
2415         enum ofperr error;
2416         const struct ofp_packet_out *opo = ofpbuf_pull(&b, sizeof *opo);
2417
2418         po->buffer_id = ntohl(opo->buffer_id);
2419         po->in_port = ntohs(opo->in_port);
2420
2421         error = ofpacts_pull_openflow10(&b, ntohs(opo->actions_len), ofpacts);
2422         if (error) {
2423             return error;
2424         }
2425     } else {
2426         NOT_REACHED();
2427     }
2428
2429     if (po->in_port >= OFPP_MAX && po->in_port != OFPP_LOCAL
2430         && po->in_port != OFPP_NONE && po->in_port != OFPP_CONTROLLER) {
2431         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
2432                      po->in_port);
2433         return OFPERR_OFPBRC_BAD_PORT;
2434     }
2435
2436     po->ofpacts = ofpacts->data;
2437     po->ofpacts_len = ofpacts->size;
2438
2439     if (po->buffer_id == UINT32_MAX) {
2440         po->packet = b.data;
2441         po->packet_len = b.size;
2442     } else {
2443         po->packet = NULL;
2444         po->packet_len = 0;
2445     }
2446
2447     return 0;
2448 }
2449 \f
2450 /* ofputil_phy_port */
2451
2452 /* NETDEV_F_* to and from OFPPF_* and OFPPF10_*. */
2453 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);  /* bit 0 */
2454 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);  /* bit 1 */
2455 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD); /* bit 2 */
2456 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD); /* bit 3 */
2457 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);   /* bit 4 */
2458 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);   /* bit 5 */
2459 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);  /* bit 6 */
2460
2461 /* NETDEV_F_ bits 11...15 are OFPPF10_ bits 7...11: */
2462 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER == (OFPPF10_COPPER << 4));
2463 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER == (OFPPF10_FIBER << 4));
2464 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG == (OFPPF10_AUTONEG << 4));
2465 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE == (OFPPF10_PAUSE << 4));
2466 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == (OFPPF10_PAUSE_ASYM << 4));
2467
2468 static enum netdev_features
2469 netdev_port_features_from_ofp10(ovs_be32 ofp10_)
2470 {
2471     uint32_t ofp10 = ntohl(ofp10_);
2472     return (ofp10 & 0x7f) | ((ofp10 & 0xf80) << 4);
2473 }
2474
2475 static ovs_be32
2476 netdev_port_features_to_ofp10(enum netdev_features features)
2477 {
2478     return htonl((features & 0x7f) | ((features & 0xf800) >> 4));
2479 }
2480
2481 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);     /* bit 0 */
2482 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);     /* bit 1 */
2483 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD);    /* bit 2 */
2484 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD);    /* bit 3 */
2485 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);      /* bit 4 */
2486 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);      /* bit 5 */
2487 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);     /* bit 6 */
2488 BUILD_ASSERT_DECL((int) NETDEV_F_40GB_FD    == OFPPF11_40GB_FD);   /* bit 7 */
2489 BUILD_ASSERT_DECL((int) NETDEV_F_100GB_FD   == OFPPF11_100GB_FD);  /* bit 8 */
2490 BUILD_ASSERT_DECL((int) NETDEV_F_1TB_FD     == OFPPF11_1TB_FD);    /* bit 9 */
2491 BUILD_ASSERT_DECL((int) NETDEV_F_OTHER      == OFPPF11_OTHER);     /* bit 10 */
2492 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER     == OFPPF11_COPPER);    /* bit 11 */
2493 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER      == OFPPF11_FIBER);     /* bit 12 */
2494 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG    == OFPPF11_AUTONEG);   /* bit 13 */
2495 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE      == OFPPF11_PAUSE);     /* bit 14 */
2496 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == OFPPF11_PAUSE_ASYM);/* bit 15 */
2497
2498 static enum netdev_features
2499 netdev_port_features_from_ofp11(ovs_be32 ofp11)
2500 {
2501     return ntohl(ofp11) & 0xffff;
2502 }
2503
2504 static ovs_be32
2505 netdev_port_features_to_ofp11(enum netdev_features features)
2506 {
2507     return htonl(features & 0xffff);
2508 }
2509
2510 static enum ofperr
2511 ofputil_decode_ofp10_phy_port(struct ofputil_phy_port *pp,
2512                               const struct ofp10_phy_port *opp)
2513 {
2514     memset(pp, 0, sizeof *pp);
2515
2516     pp->port_no = ntohs(opp->port_no);
2517     memcpy(pp->hw_addr, opp->hw_addr, OFP_ETH_ALEN);
2518     ovs_strlcpy(pp->name, opp->name, OFP_MAX_PORT_NAME_LEN);
2519
2520     pp->config = ntohl(opp->config) & OFPPC10_ALL;
2521     pp->state = ntohl(opp->state) & OFPPS10_ALL;
2522
2523     pp->curr = netdev_port_features_from_ofp10(opp->curr);
2524     pp->advertised = netdev_port_features_from_ofp10(opp->advertised);
2525     pp->supported = netdev_port_features_from_ofp10(opp->supported);
2526     pp->peer = netdev_port_features_from_ofp10(opp->peer);
2527
2528     pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
2529     pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
2530
2531     return 0;
2532 }
2533
2534 static enum ofperr
2535 ofputil_decode_ofp11_port(struct ofputil_phy_port *pp,
2536                           const struct ofp11_port *op)
2537 {
2538     enum ofperr error;
2539
2540     memset(pp, 0, sizeof *pp);
2541
2542     error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
2543     if (error) {
2544         return error;
2545     }
2546     memcpy(pp->hw_addr, op->hw_addr, OFP_ETH_ALEN);
2547     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
2548
2549     pp->config = ntohl(op->config) & OFPPC11_ALL;
2550     pp->state = ntohl(op->state) & OFPPC11_ALL;
2551
2552     pp->curr = netdev_port_features_from_ofp11(op->curr);
2553     pp->advertised = netdev_port_features_from_ofp11(op->advertised);
2554     pp->supported = netdev_port_features_from_ofp11(op->supported);
2555     pp->peer = netdev_port_features_from_ofp11(op->peer);
2556
2557     pp->curr_speed = ntohl(op->curr_speed);
2558     pp->max_speed = ntohl(op->max_speed);
2559
2560     return 0;
2561 }
2562
2563 static size_t
2564 ofputil_get_phy_port_size(enum ofp_version ofp_version)
2565 {
2566     switch (ofp_version) {
2567     case OFP10_VERSION:
2568         return sizeof(struct ofp10_phy_port);
2569     case OFP11_VERSION:
2570     case OFP12_VERSION:
2571         return sizeof(struct ofp11_port);
2572     default:
2573         NOT_REACHED();
2574     }
2575 }
2576
2577 static void
2578 ofputil_encode_ofp10_phy_port(const struct ofputil_phy_port *pp,
2579                               struct ofp10_phy_port *opp)
2580 {
2581     memset(opp, 0, sizeof *opp);
2582
2583     opp->port_no = htons(pp->port_no);
2584     memcpy(opp->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2585     ovs_strlcpy(opp->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2586
2587     opp->config = htonl(pp->config & OFPPC10_ALL);
2588     opp->state = htonl(pp->state & OFPPS10_ALL);
2589
2590     opp->curr = netdev_port_features_to_ofp10(pp->curr);
2591     opp->advertised = netdev_port_features_to_ofp10(pp->advertised);
2592     opp->supported = netdev_port_features_to_ofp10(pp->supported);
2593     opp->peer = netdev_port_features_to_ofp10(pp->peer);
2594 }
2595
2596 static void
2597 ofputil_encode_ofp11_port(const struct ofputil_phy_port *pp,
2598                           struct ofp11_port *op)
2599 {
2600     memset(op, 0, sizeof *op);
2601
2602     op->port_no = ofputil_port_to_ofp11(pp->port_no);
2603     memcpy(op->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2604     ovs_strlcpy(op->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2605
2606     op->config = htonl(pp->config & OFPPC11_ALL);
2607     op->state = htonl(pp->state & OFPPS11_ALL);
2608
2609     op->curr = netdev_port_features_to_ofp11(pp->curr);
2610     op->advertised = netdev_port_features_to_ofp11(pp->advertised);
2611     op->supported = netdev_port_features_to_ofp11(pp->supported);
2612     op->peer = netdev_port_features_to_ofp11(pp->peer);
2613
2614     op->curr_speed = htonl(pp->curr_speed);
2615     op->max_speed = htonl(pp->max_speed);
2616 }
2617
2618 static void
2619 ofputil_put_phy_port(enum ofp_version ofp_version,
2620                      const struct ofputil_phy_port *pp, struct ofpbuf *b)
2621 {
2622     switch (ofp_version) {
2623     case OFP10_VERSION: {
2624         struct ofp10_phy_port *opp;
2625         if (b->size + sizeof *opp <= UINT16_MAX) {
2626             opp = ofpbuf_put_uninit(b, sizeof *opp);
2627             ofputil_encode_ofp10_phy_port(pp, opp);
2628         }
2629         break;
2630     }
2631
2632     case OFP11_VERSION:
2633     case OFP12_VERSION: {
2634         struct ofp11_port *op;
2635         if (b->size + sizeof *op <= UINT16_MAX) {
2636             op = ofpbuf_put_uninit(b, sizeof *op);
2637             ofputil_encode_ofp11_port(pp, op);
2638         }
2639         break;
2640     }
2641
2642     default:
2643         NOT_REACHED();
2644     }
2645 }
2646
2647 void
2648 ofputil_append_port_desc_stats_reply(enum ofp_version ofp_version,
2649                                      const struct ofputil_phy_port *pp,
2650                                      struct list *replies)
2651 {
2652     switch (ofp_version) {
2653     case OFP10_VERSION: {
2654         struct ofp10_phy_port *opp;
2655
2656         opp = ofpmp_append(replies, sizeof *opp);
2657         ofputil_encode_ofp10_phy_port(pp, opp);
2658         break;
2659     }
2660
2661     case OFP11_VERSION:
2662     case OFP12_VERSION: {
2663         struct ofp11_port *op;
2664
2665         op = ofpmp_append(replies, sizeof *op);
2666         ofputil_encode_ofp11_port(pp, op);
2667         break;
2668     }
2669
2670     default:
2671       NOT_REACHED();
2672     }
2673 }
2674 \f
2675 /* ofputil_switch_features */
2676
2677 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
2678                      OFPC_IP_REASM | OFPC_QUEUE_STATS)
2679 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
2680 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
2681 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
2682 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
2683 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
2684 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
2685
2686 struct ofputil_action_bit_translation {
2687     enum ofputil_action_bitmap ofputil_bit;
2688     int of_bit;
2689 };
2690
2691 static const struct ofputil_action_bit_translation of10_action_bits[] = {
2692     { OFPUTIL_A_OUTPUT,       OFPAT10_OUTPUT },
2693     { OFPUTIL_A_SET_VLAN_VID, OFPAT10_SET_VLAN_VID },
2694     { OFPUTIL_A_SET_VLAN_PCP, OFPAT10_SET_VLAN_PCP },
2695     { OFPUTIL_A_STRIP_VLAN,   OFPAT10_STRIP_VLAN },
2696     { OFPUTIL_A_SET_DL_SRC,   OFPAT10_SET_DL_SRC },
2697     { OFPUTIL_A_SET_DL_DST,   OFPAT10_SET_DL_DST },
2698     { OFPUTIL_A_SET_NW_SRC,   OFPAT10_SET_NW_SRC },
2699     { OFPUTIL_A_SET_NW_DST,   OFPAT10_SET_NW_DST },
2700     { OFPUTIL_A_SET_NW_TOS,   OFPAT10_SET_NW_TOS },
2701     { OFPUTIL_A_SET_TP_SRC,   OFPAT10_SET_TP_SRC },
2702     { OFPUTIL_A_SET_TP_DST,   OFPAT10_SET_TP_DST },
2703     { OFPUTIL_A_ENQUEUE,      OFPAT10_ENQUEUE },
2704     { 0, 0 },
2705 };
2706
2707 static enum ofputil_action_bitmap
2708 decode_action_bits(ovs_be32 of_actions,
2709                    const struct ofputil_action_bit_translation *x)
2710 {
2711     enum ofputil_action_bitmap ofputil_actions;
2712
2713     ofputil_actions = 0;
2714     for (; x->ofputil_bit; x++) {
2715         if (of_actions & htonl(1u << x->of_bit)) {
2716             ofputil_actions |= x->ofputil_bit;
2717         }
2718     }
2719     return ofputil_actions;
2720 }
2721
2722 static uint32_t
2723 ofputil_capabilities_mask(enum ofp_version ofp_version)
2724 {
2725     /* Handle capabilities whose bit is unique for all Open Flow versions */
2726     switch (ofp_version) {
2727     case OFP10_VERSION:
2728     case OFP11_VERSION:
2729         return OFPC_COMMON | OFPC_ARP_MATCH_IP;
2730     case OFP12_VERSION:
2731         return OFPC_COMMON | OFPC12_PORT_BLOCKED;
2732     default:
2733         /* Caller needs to check osf->header.version itself */
2734         return 0;
2735     }
2736 }
2737
2738 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
2739  * abstract representation in '*features'.  Initializes '*b' to iterate over
2740  * the OpenFlow port structures following 'osf' with later calls to
2741  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
2742  * OFPERR_* value.  */
2743 enum ofperr
2744 ofputil_decode_switch_features(const struct ofp_header *oh,
2745                                struct ofputil_switch_features *features,
2746                                struct ofpbuf *b)
2747 {
2748     const struct ofp_switch_features *osf;
2749     enum ofpraw raw;
2750
2751     ofpbuf_use_const(b, oh, ntohs(oh->length));
2752     raw = ofpraw_pull_assert(b);
2753
2754     osf = ofpbuf_pull(b, sizeof *osf);
2755     features->datapath_id = ntohll(osf->datapath_id);
2756     features->n_buffers = ntohl(osf->n_buffers);
2757     features->n_tables = osf->n_tables;
2758
2759     features->capabilities = ntohl(osf->capabilities) &
2760         ofputil_capabilities_mask(oh->version);
2761
2762     if (b->size % ofputil_get_phy_port_size(oh->version)) {
2763         return OFPERR_OFPBRC_BAD_LEN;
2764     }
2765
2766     if (raw == OFPRAW_OFPT10_FEATURES_REPLY) {
2767         if (osf->capabilities & htonl(OFPC10_STP)) {
2768             features->capabilities |= OFPUTIL_C_STP;
2769         }
2770         features->actions = decode_action_bits(osf->actions, of10_action_bits);
2771     } else if (raw == OFPRAW_OFPT11_FEATURES_REPLY) {
2772         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
2773             features->capabilities |= OFPUTIL_C_GROUP_STATS;
2774         }
2775         features->actions = 0;
2776     } else {
2777         return OFPERR_OFPBRC_BAD_VERSION;
2778     }
2779
2780     return 0;
2781 }
2782
2783 /* Returns true if the maximum number of ports are in 'oh'. */
2784 static bool
2785 max_ports_in_features(const struct ofp_header *oh)
2786 {
2787     size_t pp_size = ofputil_get_phy_port_size(oh->version);
2788     return ntohs(oh->length) + pp_size > UINT16_MAX;
2789 }
2790
2791 /* Given a buffer 'b' that contains a Features Reply message, checks if
2792  * it contains the maximum number of ports that will fit.  If so, it
2793  * returns true and removes the ports from the message.  The caller
2794  * should then send an OFPST_PORT_DESC stats request to get the ports,
2795  * since the switch may have more ports than could be represented in the
2796  * Features Reply.  Otherwise, returns false.
2797  */
2798 bool
2799 ofputil_switch_features_ports_trunc(struct ofpbuf *b)
2800 {
2801     struct ofp_header *oh = b->data;
2802
2803     if (max_ports_in_features(oh)) {
2804         /* Remove all the ports. */
2805         b->size = (sizeof(struct ofp_header)
2806                    + sizeof(struct ofp_switch_features));
2807         ofpmsg_update_length(b);
2808
2809         return true;
2810     }
2811
2812     return false;
2813 }
2814
2815 static ovs_be32
2816 encode_action_bits(enum ofputil_action_bitmap ofputil_actions,
2817                    const struct ofputil_action_bit_translation *x)
2818 {
2819     uint32_t of_actions;
2820
2821     of_actions = 0;
2822     for (; x->ofputil_bit; x++) {
2823         if (ofputil_actions & x->ofputil_bit) {
2824             of_actions |= 1 << x->of_bit;
2825         }
2826     }
2827     return htonl(of_actions);
2828 }
2829
2830 /* Returns a buffer owned by the caller that encodes 'features' in the format
2831  * required by 'protocol' with the given 'xid'.  The caller should append port
2832  * information to the buffer with subsequent calls to
2833  * ofputil_put_switch_features_port(). */
2834 struct ofpbuf *
2835 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
2836                                enum ofputil_protocol protocol, ovs_be32 xid)
2837 {
2838     struct ofp_switch_features *osf;
2839     struct ofpbuf *b;
2840     enum ofp_version version;
2841     enum ofpraw raw;
2842
2843     version = ofputil_protocol_to_ofp_version(protocol);
2844     switch (version) {
2845     case OFP10_VERSION:
2846         raw = OFPRAW_OFPT10_FEATURES_REPLY;
2847         break;
2848     case OFP11_VERSION:
2849     case OFP12_VERSION:
2850         raw = OFPRAW_OFPT11_FEATURES_REPLY;
2851         break;
2852     default:
2853         NOT_REACHED();
2854     }
2855     b = ofpraw_alloc_xid(raw, version, xid, 0);
2856     osf = ofpbuf_put_zeros(b, sizeof *osf);
2857     osf->datapath_id = htonll(features->datapath_id);
2858     osf->n_buffers = htonl(features->n_buffers);
2859     osf->n_tables = features->n_tables;
2860
2861     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
2862     osf->capabilities = htonl(features->capabilities &
2863                               ofputil_capabilities_mask(version));
2864     switch (version) {
2865     case OFP10_VERSION:
2866         if (features->capabilities & OFPUTIL_C_STP) {
2867             osf->capabilities |= htonl(OFPC10_STP);
2868         }
2869         osf->actions = encode_action_bits(features->actions, of10_action_bits);
2870         break;
2871     case OFP11_VERSION:
2872     case OFP12_VERSION:
2873         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
2874             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
2875         }
2876         break;
2877     default:
2878         NOT_REACHED();
2879     }
2880
2881     return b;
2882 }
2883
2884 /* Encodes 'pp' into the format required by the switch_features message already
2885  * in 'b', which should have been returned by ofputil_encode_switch_features(),
2886  * and appends the encoded version to 'b'. */
2887 void
2888 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
2889                                  struct ofpbuf *b)
2890 {
2891     const struct ofp_header *oh = b->data;
2892
2893     ofputil_put_phy_port(oh->version, pp, b);
2894 }
2895 \f
2896 /* ofputil_port_status */
2897
2898 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
2899  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
2900 enum ofperr
2901 ofputil_decode_port_status(const struct ofp_header *oh,
2902                            struct ofputil_port_status *ps)
2903 {
2904     const struct ofp_port_status *ops;
2905     struct ofpbuf b;
2906     int retval;
2907
2908     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2909     ofpraw_pull_assert(&b);
2910     ops = ofpbuf_pull(&b, sizeof *ops);
2911
2912     if (ops->reason != OFPPR_ADD &&
2913         ops->reason != OFPPR_DELETE &&
2914         ops->reason != OFPPR_MODIFY) {
2915         return OFPERR_NXBRC_BAD_REASON;
2916     }
2917     ps->reason = ops->reason;
2918
2919     retval = ofputil_pull_phy_port(oh->version, &b, &ps->desc);
2920     assert(retval != EOF);
2921     return retval;
2922 }
2923
2924 /* Converts the abstract form of a "port status" message in '*ps' into an
2925  * OpenFlow message suitable for 'protocol', and returns that encoded form in
2926  * a buffer owned by the caller. */
2927 struct ofpbuf *
2928 ofputil_encode_port_status(const struct ofputil_port_status *ps,
2929                            enum ofputil_protocol protocol)
2930 {
2931     struct ofp_port_status *ops;
2932     struct ofpbuf *b;
2933     enum ofp_version version;
2934     enum ofpraw raw;
2935
2936     version = ofputil_protocol_to_ofp_version(protocol);
2937     switch (version) {
2938     case OFP10_VERSION:
2939         raw = OFPRAW_OFPT10_PORT_STATUS;
2940         break;
2941
2942     case OFP11_VERSION:
2943     case OFP12_VERSION:
2944         raw = OFPRAW_OFPT11_PORT_STATUS;
2945         break;
2946
2947     default:
2948         NOT_REACHED();
2949     }
2950
2951     b = ofpraw_alloc_xid(raw, version, htonl(0), 0);
2952     ops = ofpbuf_put_zeros(b, sizeof *ops);
2953     ops->reason = ps->reason;
2954     ofputil_put_phy_port(version, &ps->desc, b);
2955     ofpmsg_update_length(b);
2956     return b;
2957 }
2958 \f
2959 /* ofputil_port_mod */
2960
2961 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
2962  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
2963 enum ofperr
2964 ofputil_decode_port_mod(const struct ofp_header *oh,
2965                         struct ofputil_port_mod *pm)
2966 {
2967     enum ofpraw raw;
2968     struct ofpbuf b;
2969
2970     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2971     raw = ofpraw_pull_assert(&b);
2972
2973     if (raw == OFPRAW_OFPT10_PORT_MOD) {
2974         const struct ofp10_port_mod *opm = b.data;
2975
2976         pm->port_no = ntohs(opm->port_no);
2977         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
2978         pm->config = ntohl(opm->config) & OFPPC10_ALL;
2979         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
2980         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
2981     } else if (raw == OFPRAW_OFPT11_PORT_MOD) {
2982         const struct ofp11_port_mod *opm = b.data;
2983         enum ofperr error;
2984
2985         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
2986         if (error) {
2987             return error;
2988         }
2989
2990         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
2991         pm->config = ntohl(opm->config) & OFPPC11_ALL;
2992         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
2993         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
2994     } else {
2995         return OFPERR_OFPBRC_BAD_TYPE;
2996     }
2997
2998     pm->config &= pm->mask;
2999     return 0;
3000 }
3001
3002 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
3003  * message suitable for 'protocol', and returns that encoded form in a buffer
3004  * owned by the caller. */
3005 struct ofpbuf *
3006 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
3007                         enum ofputil_protocol protocol)
3008 {
3009     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
3010     struct ofpbuf *b;
3011
3012     switch (ofp_version) {
3013     case OFP10_VERSION: {
3014         struct ofp10_port_mod *opm;
3015
3016         b = ofpraw_alloc(OFPRAW_OFPT10_PORT_MOD, ofp_version, 0);
3017         opm = ofpbuf_put_zeros(b, sizeof *opm);
3018         opm->port_no = htons(pm->port_no);
3019         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3020         opm->config = htonl(pm->config & OFPPC10_ALL);
3021         opm->mask = htonl(pm->mask & OFPPC10_ALL);
3022         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
3023         break;
3024     }
3025
3026     case OFP11_VERSION:
3027     case OFP12_VERSION: {
3028         struct ofp11_port_mod *opm;
3029
3030         b = ofpraw_alloc(OFPRAW_OFPT11_PORT_MOD, ofp_version, 0);
3031         opm = ofpbuf_put_zeros(b, sizeof *opm);
3032         opm->port_no = ofputil_port_to_ofp11(pm->port_no);
3033         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3034         opm->config = htonl(pm->config & OFPPC11_ALL);
3035         opm->mask = htonl(pm->mask & OFPPC11_ALL);
3036         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
3037         break;
3038     }
3039
3040     default:
3041         NOT_REACHED();
3042     }
3043
3044     return b;
3045 }
3046 \f
3047 /* Table stats. */
3048
3049 static void
3050 ofputil_put_ofp10_table_stats(const struct ofp12_table_stats *in,
3051                               struct ofpbuf *buf)
3052 {
3053     struct wc_map {
3054         enum ofp_flow_wildcards wc10;
3055         enum oxm12_ofb_match_fields mf12;
3056     };
3057
3058     static const struct wc_map wc_map[] = {
3059         { OFPFW10_IN_PORT,     OFPXMT12_OFB_IN_PORT },
3060         { OFPFW10_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
3061         { OFPFW10_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
3062         { OFPFW10_DL_DST,      OFPXMT12_OFB_ETH_DST},
3063         { OFPFW10_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
3064         { OFPFW10_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
3065         { OFPFW10_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
3066         { OFPFW10_TP_DST,      OFPXMT12_OFB_TCP_DST },
3067         { OFPFW10_NW_SRC_MASK, OFPXMT12_OFB_IPV4_SRC },
3068         { OFPFW10_NW_DST_MASK, OFPXMT12_OFB_IPV4_DST },
3069         { OFPFW10_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
3070         { OFPFW10_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
3071     };
3072
3073     struct ofp10_table_stats *out;
3074     const struct wc_map *p;
3075
3076     out = ofpbuf_put_uninit(buf, sizeof *out);
3077     out->table_id = in->table_id;
3078     strcpy(out->name, in->name);
3079     out->wildcards = 0;
3080     for (p = wc_map; p < &wc_map[ARRAY_SIZE(wc_map)]; p++) {
3081         if (in->wildcards & htonll(1ULL << p->mf12)) {
3082             out->wildcards |= htonl(p->wc10);
3083         }
3084     }
3085     out->max_entries = in->max_entries;
3086     out->active_count = in->active_count;
3087     put_32aligned_be64(&out->lookup_count, in->lookup_count);
3088     put_32aligned_be64(&out->matched_count, in->matched_count);
3089 }
3090
3091 static ovs_be32
3092 oxm12_to_ofp11_flow_match_fields(ovs_be64 oxm12)
3093 {
3094     struct map {
3095         enum ofp11_flow_match_fields fmf11;
3096         enum oxm12_ofb_match_fields mf12;
3097     };
3098
3099     static const struct map map[] = {
3100         { OFPFMF11_IN_PORT,     OFPXMT12_OFB_IN_PORT },
3101         { OFPFMF11_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
3102         { OFPFMF11_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
3103         { OFPFMF11_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
3104         { OFPFMF11_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
3105         { OFPFMF11_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
3106         { OFPFMF11_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
3107         { OFPFMF11_TP_DST,      OFPXMT12_OFB_TCP_DST },
3108         { OFPFMF11_MPLS_LABEL,  OFPXMT12_OFB_MPLS_LABEL },
3109         { OFPFMF11_MPLS_TC,     OFPXMT12_OFB_MPLS_TC },
3110         /* I don't know what OFPFMF11_TYPE means. */
3111         { OFPFMF11_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
3112         { OFPFMF11_DL_DST,      OFPXMT12_OFB_ETH_DST },
3113         { OFPFMF11_NW_SRC,      OFPXMT12_OFB_IPV4_SRC },
3114         { OFPFMF11_NW_DST,      OFPXMT12_OFB_IPV4_DST },
3115         { OFPFMF11_METADATA,    OFPXMT12_OFB_METADATA },
3116     };
3117
3118     const struct map *p;
3119     uint32_t fmf11;
3120
3121     fmf11 = 0;
3122     for (p = map; p < &map[ARRAY_SIZE(map)]; p++) {
3123         if (oxm12 & htonll(1ULL << p->mf12)) {
3124             fmf11 |= p->fmf11;
3125         }
3126     }
3127     return htonl(fmf11);
3128 }
3129
3130 static void
3131 ofputil_put_ofp11_table_stats(const struct ofp12_table_stats *in,
3132                               struct ofpbuf *buf)
3133 {
3134     struct ofp11_table_stats *out;
3135
3136     out = ofpbuf_put_uninit(buf, sizeof *out);
3137     out->table_id = in->table_id;
3138     strcpy(out->name, in->name);
3139     out->wildcards = oxm12_to_ofp11_flow_match_fields(in->wildcards);
3140     out->match = oxm12_to_ofp11_flow_match_fields(in->match);
3141     out->instructions = in->instructions;
3142     out->write_actions = in->write_actions;
3143     out->apply_actions = in->apply_actions;
3144     out->config = in->config;
3145     out->max_entries = in->max_entries;
3146     out->active_count = in->active_count;
3147     out->lookup_count = in->lookup_count;
3148     out->matched_count = in->matched_count;
3149 }
3150
3151 struct ofpbuf *
3152 ofputil_encode_table_stats_reply(const struct ofp12_table_stats stats[], int n,
3153                                  const struct ofp_header *request)
3154 {
3155     struct ofpbuf *reply;
3156     int i;
3157
3158     reply = ofpraw_alloc_stats_reply(request, n * sizeof *stats);
3159
3160     switch ((enum ofp_version) request->version) {
3161     case OFP10_VERSION:
3162         for (i = 0; i < n; i++) {
3163             ofputil_put_ofp10_table_stats(&stats[i], reply);
3164         }
3165         break;
3166
3167     case OFP11_VERSION:
3168         for (i = 0; i < n; i++) {
3169             ofputil_put_ofp11_table_stats(&stats[i], reply);
3170         }
3171         break;
3172
3173     case OFP12_VERSION:
3174         ofpbuf_put(reply, stats, n * sizeof *stats);
3175         break;
3176
3177     default:
3178         NOT_REACHED();
3179     }
3180
3181     return reply;
3182 }
3183 \f
3184 /* ofputil_flow_monitor_request */
3185
3186 /* Converts an NXST_FLOW_MONITOR request in 'msg' into an abstract
3187  * ofputil_flow_monitor_request in 'rq'.
3188  *
3189  * Multiple NXST_FLOW_MONITOR requests can be packed into a single OpenFlow
3190  * message.  Calling this function multiple times for a single 'msg' iterates
3191  * through the requests.  The caller must initially leave 'msg''s layer
3192  * pointers null and not modify them between calls.
3193  *
3194  * Returns 0 if successful, EOF if no requests were left in this 'msg',
3195  * otherwise an OFPERR_* value. */
3196 int
3197 ofputil_decode_flow_monitor_request(struct ofputil_flow_monitor_request *rq,
3198                                     struct ofpbuf *msg)
3199 {
3200     struct nx_flow_monitor_request *nfmr;
3201     uint16_t flags;
3202
3203     if (!msg->l2) {
3204         msg->l2 = msg->data;
3205         ofpraw_pull_assert(msg);
3206     }
3207
3208     if (!msg->size) {
3209         return EOF;
3210     }
3211
3212     nfmr = ofpbuf_try_pull(msg, sizeof *nfmr);
3213     if (!nfmr) {
3214         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR request has %zu "
3215                      "leftover bytes at end", msg->size);
3216         return OFPERR_OFPBRC_BAD_LEN;
3217     }
3218
3219     flags = ntohs(nfmr->flags);
3220     if (!(flags & (NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY))
3221         || flags & ~(NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE
3222                      | NXFMF_MODIFY | NXFMF_ACTIONS | NXFMF_OWN)) {
3223         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR has bad flags %#"PRIx16,
3224                      flags);
3225         return OFPERR_NXBRC_FM_BAD_FLAGS;
3226     }
3227
3228     if (!is_all_zeros(nfmr->zeros, sizeof nfmr->zeros)) {
3229         return OFPERR_NXBRC_MUST_BE_ZERO;
3230     }
3231
3232     rq->id = ntohl(nfmr->id);
3233     rq->flags = flags;
3234     rq->out_port = ntohs(nfmr->out_port);
3235     rq->table_id = nfmr->table_id;
3236
3237     return nx_pull_match(msg, ntohs(nfmr->match_len), &rq->match, NULL, NULL);
3238 }
3239
3240 void
3241 ofputil_append_flow_monitor_request(
3242     const struct ofputil_flow_monitor_request *rq, struct ofpbuf *msg)
3243 {
3244     struct nx_flow_monitor_request *nfmr;
3245     size_t start_ofs;
3246     int match_len;
3247
3248     if (!msg->size) {
3249         ofpraw_put(OFPRAW_NXST_FLOW_MONITOR_REQUEST, OFP10_VERSION, msg);
3250     }
3251
3252     start_ofs = msg->size;
3253     ofpbuf_put_zeros(msg, sizeof *nfmr);
3254     match_len = nx_put_match(msg, &rq->match, htonll(0), htonll(0));
3255
3256     nfmr = ofpbuf_at_assert(msg, start_ofs, sizeof *nfmr);
3257     nfmr->id = htonl(rq->id);
3258     nfmr->flags = htons(rq->flags);
3259     nfmr->out_port = htons(rq->out_port);
3260     nfmr->match_len = htons(match_len);
3261     nfmr->table_id = rq->table_id;
3262 }
3263
3264 /* Converts an NXST_FLOW_MONITOR reply (also known as a flow update) in 'msg'
3265  * into an abstract ofputil_flow_update in 'update'.  The caller must have
3266  * initialized update->match to point to space allocated for a match.
3267  *
3268  * Uses 'ofpacts' to store the abstract OFPACT_* version of the update's
3269  * actions (except for NXFME_ABBREV, which never includes actions).  The caller
3270  * must initialize 'ofpacts' and retains ownership of it.  'update->ofpacts'
3271  * will point into the 'ofpacts' buffer.
3272  *
3273  * Multiple flow updates can be packed into a single OpenFlow message.  Calling
3274  * this function multiple times for a single 'msg' iterates through the
3275  * updates.  The caller must initially leave 'msg''s layer pointers null and
3276  * not modify them between calls.
3277  *
3278  * Returns 0 if successful, EOF if no updates were left in this 'msg',
3279  * otherwise an OFPERR_* value. */
3280 int
3281 ofputil_decode_flow_update(struct ofputil_flow_update *update,
3282                            struct ofpbuf *msg, struct ofpbuf *ofpacts)
3283 {
3284     struct nx_flow_update_header *nfuh;
3285     unsigned int length;
3286
3287     if (!msg->l2) {
3288         msg->l2 = msg->data;
3289         ofpraw_pull_assert(msg);
3290     }
3291
3292     if (!msg->size) {
3293         return EOF;
3294     }
3295
3296     if (msg->size < sizeof(struct nx_flow_update_header)) {
3297         goto bad_len;
3298     }
3299
3300     nfuh = msg->data;
3301     update->event = ntohs(nfuh->event);
3302     length = ntohs(nfuh->length);
3303     if (length > msg->size || length % 8) {
3304         goto bad_len;
3305     }
3306
3307     if (update->event == NXFME_ABBREV) {
3308         struct nx_flow_update_abbrev *nfua;
3309
3310         if (length != sizeof *nfua) {
3311             goto bad_len;
3312         }
3313
3314         nfua = ofpbuf_pull(msg, sizeof *nfua);
3315         update->xid = nfua->xid;
3316         return 0;
3317     } else if (update->event == NXFME_ADDED
3318                || update->event == NXFME_DELETED
3319                || update->event == NXFME_MODIFIED) {
3320         struct nx_flow_update_full *nfuf;
3321         unsigned int actions_len;
3322         unsigned int match_len;
3323         enum ofperr error;
3324
3325         if (length < sizeof *nfuf) {
3326             goto bad_len;
3327         }
3328
3329         nfuf = ofpbuf_pull(msg, sizeof *nfuf);
3330         match_len = ntohs(nfuf->match_len);
3331         if (sizeof *nfuf + match_len > length) {
3332             goto bad_len;
3333         }
3334
3335         update->reason = ntohs(nfuf->reason);
3336         update->idle_timeout = ntohs(nfuf->idle_timeout);
3337         update->hard_timeout = ntohs(nfuf->hard_timeout);
3338         update->table_id = nfuf->table_id;
3339         update->cookie = nfuf->cookie;
3340         update->priority = ntohs(nfuf->priority);
3341
3342         error = nx_pull_match(msg, match_len, update->match, NULL, NULL);
3343         if (error) {
3344             return error;
3345         }
3346
3347         actions_len = length - sizeof *nfuf - ROUND_UP(match_len, 8);
3348         error = ofpacts_pull_openflow10(msg, actions_len, ofpacts);
3349         if (error) {
3350             return error;
3351         }
3352
3353         update->ofpacts = ofpacts->data;
3354         update->ofpacts_len = ofpacts->size;
3355         return 0;
3356     } else {
3357         VLOG_WARN_RL(&bad_ofmsg_rl,
3358                      "NXST_FLOW_MONITOR reply has bad event %"PRIu16,
3359                      ntohs(nfuh->event));
3360         return OFPERR_OFPET_BAD_REQUEST;
3361     }
3362
3363 bad_len:
3364     VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR reply has %zu "
3365                  "leftover bytes at end", msg->size);
3366     return OFPERR_OFPBRC_BAD_LEN;
3367 }
3368
3369 uint32_t
3370 ofputil_decode_flow_monitor_cancel(const struct ofp_header *oh)
3371 {
3372     const struct nx_flow_monitor_cancel *cancel = ofpmsg_body(oh);
3373
3374     return ntohl(cancel->id);
3375 }
3376
3377 struct ofpbuf *
3378 ofputil_encode_flow_monitor_cancel(uint32_t id)
3379 {
3380     struct nx_flow_monitor_cancel *nfmc;
3381     struct ofpbuf *msg;
3382
3383     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MONITOR_CANCEL, OFP10_VERSION, 0);
3384     nfmc = ofpbuf_put_uninit(msg, sizeof *nfmc);
3385     nfmc->id = htonl(id);
3386     return msg;
3387 }
3388
3389 void
3390 ofputil_start_flow_update(struct list *replies)
3391 {
3392     struct ofpbuf *msg;
3393
3394     msg = ofpraw_alloc_xid(OFPRAW_NXST_FLOW_MONITOR_REPLY, OFP10_VERSION,
3395                            htonl(0), 1024);
3396
3397     list_init(replies);
3398     list_push_back(replies, &msg->list_node);
3399 }
3400
3401 void
3402 ofputil_append_flow_update(const struct ofputil_flow_update *update,
3403                            struct list *replies)
3404 {
3405     struct nx_flow_update_header *nfuh;
3406     struct ofpbuf *msg;
3407     size_t start_ofs;
3408
3409     msg = ofpbuf_from_list(list_back(replies));
3410     start_ofs = msg->size;
3411
3412     if (update->event == NXFME_ABBREV) {
3413         struct nx_flow_update_abbrev *nfua;
3414
3415         nfua = ofpbuf_put_zeros(msg, sizeof *nfua);
3416         nfua->xid = update->xid;
3417     } else {
3418         struct nx_flow_update_full *nfuf;
3419         int match_len;
3420
3421         ofpbuf_put_zeros(msg, sizeof *nfuf);
3422         match_len = nx_put_match(msg, update->match, htonll(0), htonll(0));
3423         ofpacts_put_openflow10(update->ofpacts, update->ofpacts_len, msg);
3424
3425         nfuf = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuf);
3426         nfuf->reason = htons(update->reason);
3427         nfuf->priority = htons(update->priority);
3428         nfuf->idle_timeout = htons(update->idle_timeout);
3429         nfuf->hard_timeout = htons(update->hard_timeout);
3430         nfuf->match_len = htons(match_len);
3431         nfuf->table_id = update->table_id;
3432         nfuf->cookie = update->cookie;
3433     }
3434
3435     nfuh = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuh);
3436     nfuh->length = htons(msg->size - start_ofs);
3437     nfuh->event = htons(update->event);
3438
3439     ofpmp_postappend(replies, start_ofs);
3440 }
3441 \f
3442 struct ofpbuf *
3443 ofputil_encode_packet_out(const struct ofputil_packet_out *po,
3444                           enum ofputil_protocol protocol)
3445 {
3446     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
3447     struct ofpbuf *msg;
3448     size_t size;
3449
3450     size = po->ofpacts_len;
3451     if (po->buffer_id == UINT32_MAX) {
3452         size += po->packet_len;
3453     }
3454
3455     switch (ofp_version) {
3456     case OFP10_VERSION: {
3457         struct ofp_packet_out *opo;
3458         size_t actions_ofs;
3459
3460         msg = ofpraw_alloc(OFPRAW_OFPT10_PACKET_OUT, OFP10_VERSION, size);
3461         ofpbuf_put_zeros(msg, sizeof *opo);
3462         actions_ofs = msg->size;
3463         ofpacts_put_openflow10(po->ofpacts, po->ofpacts_len, msg);
3464
3465         opo = msg->l3;
3466         opo->buffer_id = htonl(po->buffer_id);
3467         opo->in_port = htons(po->in_port);
3468         opo->actions_len = htons(msg->size - actions_ofs);
3469         break;
3470     }
3471
3472     case OFP11_VERSION:
3473     case OFP12_VERSION: {
3474         struct ofp11_packet_out *opo;
3475         size_t len;
3476
3477         msg = ofpraw_alloc(OFPRAW_OFPT11_PACKET_OUT, ofp_version, size);
3478         ofpbuf_put_zeros(msg, sizeof *opo);
3479         len = ofpacts_put_openflow11_actions(po->ofpacts, po->ofpacts_len, msg);
3480
3481         opo = msg->l3;
3482         opo->buffer_id = htonl(po->buffer_id);
3483         opo->in_port = ofputil_port_to_ofp11(po->in_port);
3484         opo->actions_len = htons(len);
3485         break;
3486     }
3487
3488     default:
3489         NOT_REACHED();
3490     }
3491
3492     if (po->buffer_id == UINT32_MAX) {
3493         ofpbuf_put(msg, po->packet, po->packet_len);
3494     }
3495
3496     ofpmsg_update_length(msg);
3497
3498     return msg;
3499 }
3500 \f
3501 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
3502 struct ofpbuf *
3503 make_echo_request(enum ofp_version ofp_version)
3504 {
3505     return ofpraw_alloc_xid(OFPRAW_OFPT_ECHO_REQUEST, ofp_version,
3506                             htonl(0), 0);
3507 }
3508
3509 /* Creates and returns an OFPT_ECHO_REPLY message matching the
3510  * OFPT_ECHO_REQUEST message in 'rq'. */
3511 struct ofpbuf *
3512 make_echo_reply(const struct ofp_header *rq)
3513 {
3514     struct ofpbuf rq_buf;
3515     struct ofpbuf *reply;
3516
3517     ofpbuf_use_const(&rq_buf, rq, ntohs(rq->length));
3518     ofpraw_pull_assert(&rq_buf);
3519
3520     reply = ofpraw_alloc_reply(OFPRAW_OFPT_ECHO_REPLY, rq, rq_buf.size);
3521     ofpbuf_put(reply, rq_buf.data, rq_buf.size);
3522     return reply;
3523 }
3524
3525 struct ofpbuf *
3526 ofputil_encode_barrier_request(enum ofp_version ofp_version)
3527 {
3528     enum ofpraw type;
3529
3530     switch (ofp_version) {
3531     case OFP12_VERSION:
3532     case OFP11_VERSION:
3533         type = OFPRAW_OFPT11_BARRIER_REQUEST;
3534         break;
3535
3536     case OFP10_VERSION:
3537         type = OFPRAW_OFPT10_BARRIER_REQUEST;
3538         break;
3539
3540     default:
3541         NOT_REACHED();
3542     }
3543
3544     return ofpraw_alloc(type, ofp_version, 0);
3545 }
3546
3547 const char *
3548 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
3549 {
3550     switch (flags & OFPC_FRAG_MASK) {
3551     case OFPC_FRAG_NORMAL:   return "normal";
3552     case OFPC_FRAG_DROP:     return "drop";
3553     case OFPC_FRAG_REASM:    return "reassemble";
3554     case OFPC_FRAG_NX_MATCH: return "nx-match";
3555     }
3556
3557     NOT_REACHED();
3558 }
3559
3560 bool
3561 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
3562 {
3563     if (!strcasecmp(s, "normal")) {
3564         *flags = OFPC_FRAG_NORMAL;
3565     } else if (!strcasecmp(s, "drop")) {
3566         *flags = OFPC_FRAG_DROP;
3567     } else if (!strcasecmp(s, "reassemble")) {
3568         *flags = OFPC_FRAG_REASM;
3569     } else if (!strcasecmp(s, "nx-match")) {
3570         *flags = OFPC_FRAG_NX_MATCH;
3571     } else {
3572         return false;
3573     }
3574     return true;
3575 }
3576
3577 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
3578  * port number and stores the latter in '*ofp10_port', for the purpose of
3579  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
3580  * otherwise an OFPERR_* number.
3581  *
3582  * See the definition of OFP11_MAX for an explanation of the mapping. */
3583 enum ofperr
3584 ofputil_port_from_ofp11(ovs_be32 ofp11_port, uint16_t *ofp10_port)
3585 {
3586     uint32_t ofp11_port_h = ntohl(ofp11_port);
3587
3588     if (ofp11_port_h < OFPP_MAX) {
3589         *ofp10_port = ofp11_port_h;
3590         return 0;
3591     } else if (ofp11_port_h >= OFPP11_MAX) {
3592         *ofp10_port = ofp11_port_h - OFPP11_OFFSET;
3593         return 0;
3594     } else {
3595         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
3596                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
3597                      ofp11_port_h, OFPP_MAX - 1,
3598                      (uint32_t) OFPP11_MAX, UINT32_MAX);
3599         return OFPERR_OFPBAC_BAD_OUT_PORT;
3600     }
3601 }
3602
3603 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
3604  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
3605  *
3606  * See the definition of OFP11_MAX for an explanation of the mapping. */
3607 ovs_be32
3608 ofputil_port_to_ofp11(uint16_t ofp10_port)
3609 {
3610     return htonl(ofp10_port < OFPP_MAX
3611                  ? ofp10_port
3612                  : ofp10_port + OFPP11_OFFSET);
3613 }
3614
3615 /* Checks that 'port' is a valid output port for the OFPAT10_OUTPUT action, given
3616  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
3617  * 'port' is valid, otherwise an OpenFlow return code. */
3618 enum ofperr
3619 ofputil_check_output_port(uint16_t port, int max_ports)
3620 {
3621     switch (port) {
3622     case OFPP_IN_PORT:
3623     case OFPP_TABLE:
3624     case OFPP_NORMAL:
3625     case OFPP_FLOOD:
3626     case OFPP_ALL:
3627     case OFPP_CONTROLLER:
3628     case OFPP_NONE:
3629     case OFPP_LOCAL:
3630         return 0;
3631
3632     default:
3633         if (port < max_ports) {
3634             return 0;
3635         }
3636         return OFPERR_OFPBAC_BAD_OUT_PORT;
3637     }
3638 }
3639
3640 #define OFPUTIL_NAMED_PORTS                     \
3641         OFPUTIL_NAMED_PORT(IN_PORT)             \
3642         OFPUTIL_NAMED_PORT(TABLE)               \
3643         OFPUTIL_NAMED_PORT(NORMAL)              \
3644         OFPUTIL_NAMED_PORT(FLOOD)               \
3645         OFPUTIL_NAMED_PORT(ALL)                 \
3646         OFPUTIL_NAMED_PORT(CONTROLLER)          \
3647         OFPUTIL_NAMED_PORT(LOCAL)               \
3648         OFPUTIL_NAMED_PORT(NONE)
3649
3650 /* Stores the port number represented by 's' into '*portp'.  's' may be an
3651  * integer or, for reserved ports, the standard OpenFlow name for the port
3652  * (e.g. "LOCAL").
3653  *
3654  * Returns true if successful, false if 's' is not a valid OpenFlow port number
3655  * or name.  The caller should issue an error message in this case, because
3656  * this function usually does not.  (This gives the caller an opportunity to
3657  * look up the port name another way, e.g. by contacting the switch and listing
3658  * the names of all its ports).
3659  *
3660  * This function accepts OpenFlow 1.0 port numbers.  It also accepts a subset
3661  * of OpenFlow 1.1+ port numbers, mapping those port numbers into the 16-bit
3662  * range as described in include/openflow/openflow-1.1.h. */
3663 bool
3664 ofputil_port_from_string(const char *s, uint16_t *portp)
3665 {
3666     unsigned int port32;
3667
3668     *portp = 0;
3669     if (str_to_uint(s, 10, &port32)) {
3670         if (port32 < OFPP_MAX) {
3671             *portp = port32;
3672             return true;
3673         } else if (port32 < OFPP_FIRST_RESV) {
3674             VLOG_WARN("port %u is a reserved OF1.0 port number that will "
3675                       "be translated to %u when talking to an OF1.1 or "
3676                       "later controller", port32, port32 + OFPP11_OFFSET);
3677             *portp = port32;
3678             return true;
3679         } else if (port32 <= OFPP_LAST_RESV) {
3680             struct ds s;
3681
3682             ds_init(&s);
3683             ofputil_format_port(port32, &s);
3684             VLOG_WARN_ONCE("referring to port %s as %u is deprecated for "
3685                            "compatibility with future versions of OpenFlow",
3686                            ds_cstr(&s), port32);
3687             ds_destroy(&s);
3688
3689             *portp = port32;
3690             return true;
3691         } else if (port32 < OFPP11_MAX) {
3692             VLOG_WARN("port %u is outside the supported range 0 through "
3693                       "%"PRIx16"or 0x%x through 0x%"PRIx32, port32,
3694                       UINT16_MAX, (unsigned int) OFPP11_MAX, UINT32_MAX);
3695             return false;
3696         } else {
3697             *portp = port32 - OFPP11_OFFSET;
3698             return true;
3699         }
3700     } else {
3701         struct pair {
3702             const char *name;
3703             uint16_t value;
3704         };
3705         static const struct pair pairs[] = {
3706 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
3707             OFPUTIL_NAMED_PORTS
3708 #undef OFPUTIL_NAMED_PORT
3709         };
3710         const struct pair *p;
3711
3712         for (p = pairs; p < &pairs[ARRAY_SIZE(pairs)]; p++) {
3713             if (!strcasecmp(s, p->name)) {
3714                 *portp = p->value;
3715                 return true;
3716             }
3717         }
3718         return false;
3719     }
3720 }
3721
3722 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
3723  * Most ports' string representation is just the port number, but for special
3724  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
3725 void
3726 ofputil_format_port(uint16_t port, struct ds *s)
3727 {
3728     const char *name;
3729
3730     switch (port) {
3731 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
3732         OFPUTIL_NAMED_PORTS
3733 #undef OFPUTIL_NAMED_PORT
3734
3735     default:
3736         ds_put_format(s, "%"PRIu16, port);
3737         return;
3738     }
3739     ds_put_cstr(s, name);
3740 }
3741
3742 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3743  * 'ofp_version', tries to pull the first element from the array.  If
3744  * successful, initializes '*pp' with an abstract representation of the
3745  * port and returns 0.  If no ports remain to be decoded, returns EOF.
3746  * On an error, returns a positive OFPERR_* value. */
3747 int
3748 ofputil_pull_phy_port(enum ofp_version ofp_version, struct ofpbuf *b,
3749                       struct ofputil_phy_port *pp)
3750 {
3751     switch (ofp_version) {
3752     case OFP10_VERSION: {
3753         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
3754         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
3755     }
3756     case OFP11_VERSION:
3757     case OFP12_VERSION: {
3758         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
3759         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
3760     }
3761     default:
3762         NOT_REACHED();
3763     }
3764 }
3765
3766 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3767  * 'ofp_version', returns the number of elements. */
3768 size_t ofputil_count_phy_ports(uint8_t ofp_version, struct ofpbuf *b)
3769 {
3770     return b->size / ofputil_get_phy_port_size(ofp_version);
3771 }
3772
3773 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
3774  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1 if
3775  * 'name' is not the name of any action.
3776  *
3777  * ofp-util.def lists the mapping from names to action. */
3778 int
3779 ofputil_action_code_from_name(const char *name)
3780 {
3781     static const char *names[OFPUTIL_N_ACTIONS] = {
3782         NULL,
3783 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)             NAME,
3784 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
3785 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)   NAME,
3786 #include "ofp-util.def"
3787     };
3788
3789     const char **p;
3790
3791     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
3792         if (*p && !strcasecmp(name, *p)) {
3793             return p - names;
3794         }
3795     }
3796     return -1;
3797 }
3798
3799 /* Appends an action of the type specified by 'code' to 'buf' and returns the
3800  * action.  Initializes the parts of 'action' that identify it as having type
3801  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
3802  * have variable length, the length used and cleared is that of struct
3803  * <STRUCT>.  */
3804 void *
3805 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
3806 {
3807     switch (code) {
3808     case OFPUTIL_ACTION_INVALID:
3809         NOT_REACHED();
3810
3811 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                  \
3812     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3813 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)      \
3814     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3815 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
3816     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3817 #include "ofp-util.def"
3818     }
3819     NOT_REACHED();
3820 }
3821
3822 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
3823     void                                                        \
3824     ofputil_init_##ENUM(struct STRUCT *s)                       \
3825     {                                                           \
3826         memset(s, 0, sizeof *s);                                \
3827         s->type = htons(ENUM);                                  \
3828         s->len = htons(sizeof *s);                              \
3829     }                                                           \
3830                                                                 \
3831     struct STRUCT *                                             \
3832     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
3833     {                                                           \
3834         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
3835         ofputil_init_##ENUM(s);                                 \
3836         return s;                                               \
3837     }
3838 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) \
3839     OFPAT10_ACTION(ENUM, STRUCT, NAME)
3840 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
3841     void                                                        \
3842     ofputil_init_##ENUM(struct STRUCT *s)                       \
3843     {                                                           \
3844         memset(s, 0, sizeof *s);                                \
3845         s->type = htons(OFPAT10_VENDOR);                        \
3846         s->len = htons(sizeof *s);                              \
3847         s->vendor = htonl(NX_VENDOR_ID);                        \
3848         s->subtype = htons(ENUM);                               \
3849     }                                                           \
3850                                                                 \
3851     struct STRUCT *                                             \
3852     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
3853     {                                                           \
3854         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
3855         ofputil_init_##ENUM(s);                                 \
3856         return s;                                               \
3857     }
3858 #include "ofp-util.def"
3859
3860 static void
3861 ofputil_normalize_match__(struct match *match, bool may_log)
3862 {
3863     enum {
3864         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
3865         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
3866         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
3867         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
3868         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
3869         MAY_ARP_THA     = 1 << 5, /* arp_tha */
3870         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
3871         MAY_ND_TARGET   = 1 << 7  /* nd_target */
3872     } may_match;
3873
3874     struct flow_wildcards wc;
3875
3876     /* Figure out what fields may be matched. */
3877     if (match->flow.dl_type == htons(ETH_TYPE_IP)) {
3878         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
3879         if (match->flow.nw_proto == IPPROTO_TCP ||
3880             match->flow.nw_proto == IPPROTO_UDP ||
3881             match->flow.nw_proto == IPPROTO_ICMP) {
3882             may_match |= MAY_TP_ADDR;
3883         }
3884     } else if (match->flow.dl_type == htons(ETH_TYPE_IPV6)) {
3885         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
3886         if (match->flow.nw_proto == IPPROTO_TCP ||
3887             match->flow.nw_proto == IPPROTO_UDP) {
3888             may_match |= MAY_TP_ADDR;
3889         } else if (match->flow.nw_proto == IPPROTO_ICMPV6) {
3890             may_match |= MAY_TP_ADDR;
3891             if (match->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
3892                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
3893             } else if (match->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
3894                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
3895             }
3896         }
3897     } else if (match->flow.dl_type == htons(ETH_TYPE_ARP) ||
3898                match->flow.dl_type == htons(ETH_TYPE_RARP)) {
3899         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
3900     } else {
3901         may_match = 0;
3902     }
3903
3904     /* Clear the fields that may not be matched. */
3905     wc = match->wc;
3906     if (!(may_match & MAY_NW_ADDR)) {
3907         wc.masks.nw_src = wc.masks.nw_dst = htonl(0);
3908     }
3909     if (!(may_match & MAY_TP_ADDR)) {
3910         wc.masks.tp_src = wc.masks.tp_dst = htons(0);
3911     }
3912     if (!(may_match & MAY_NW_PROTO)) {
3913         wc.masks.nw_proto = 0;
3914     }
3915     if (!(may_match & MAY_IPVx)) {
3916         wc.masks.nw_tos = 0;
3917         wc.masks.nw_ttl = 0;
3918     }
3919     if (!(may_match & MAY_ARP_SHA)) {
3920         memset(wc.masks.arp_sha, 0, ETH_ADDR_LEN);
3921     }
3922     if (!(may_match & MAY_ARP_THA)) {
3923         memset(wc.masks.arp_tha, 0, ETH_ADDR_LEN);
3924     }
3925     if (!(may_match & MAY_IPV6)) {
3926         wc.masks.ipv6_src = wc.masks.ipv6_dst = in6addr_any;
3927         wc.masks.ipv6_label = htonl(0);
3928     }
3929     if (!(may_match & MAY_ND_TARGET)) {
3930         wc.masks.nd_target = in6addr_any;
3931     }
3932
3933     /* Log any changes. */
3934     if (!flow_wildcards_equal(&wc, &match->wc)) {
3935         bool log = may_log && !VLOG_DROP_INFO(&bad_ofmsg_rl);
3936         char *pre = log ? match_to_string(match, OFP_DEFAULT_PRIORITY) : NULL;
3937
3938         match->wc = wc;
3939         match_zero_wildcarded_fields(match);
3940
3941         if (log) {
3942             char *post = match_to_string(match, OFP_DEFAULT_PRIORITY);
3943             VLOG_INFO("normalization changed ofp_match, details:");
3944             VLOG_INFO(" pre: %s", pre);
3945             VLOG_INFO("post: %s", post);
3946             free(pre);
3947             free(post);
3948         }
3949     }
3950 }
3951
3952 /* "Normalizes" the wildcards in 'match'.  That means:
3953  *
3954  *    1. If the type of level N is known, then only the valid fields for that
3955  *       level may be specified.  For example, ARP does not have a TOS field,
3956  *       so nw_tos must be wildcarded if 'match' specifies an ARP flow.
3957  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
3958  *       ipv6_dst (and other fields) must be wildcarded if 'match' specifies an
3959  *       IPv4 flow.
3960  *
3961  *    2. If the type of level N is not known (or not understood by Open
3962  *       vSwitch), then no fields at all for that level may be specified.  For
3963  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
3964  *       L4 fields tp_src and tp_dst must be wildcarded if 'match' specifies an
3965  *       SCTP flow.
3966  *
3967  * If this function changes 'match', it logs a rate-limited informational
3968  * message. */
3969 void
3970 ofputil_normalize_match(struct match *match)
3971 {
3972     ofputil_normalize_match__(match, true);
3973 }
3974
3975 /* Same as ofputil_normalize_match() without the logging.  Thus, this function
3976  * is suitable for a program's internal use, whereas ofputil_normalize_match()
3977  * sense for use on flows received from elsewhere (so that a bug in the program
3978  * that sent them can be reported and corrected). */
3979 void
3980 ofputil_normalize_match_quiet(struct match *match)
3981 {
3982     ofputil_normalize_match__(match, false);
3983 }
3984
3985 /* Parses a key or a key-value pair from '*stringp'.
3986  *
3987  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
3988  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
3989  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
3990  * are substrings of '*stringp' created by replacing some of its bytes by null
3991  * terminators.  Returns true.
3992  *
3993  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
3994  * NULL and returns false. */
3995 bool
3996 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
3997 {
3998     char *pos, *key, *value;
3999     size_t key_len;
4000
4001     pos = *stringp;
4002     pos += strspn(pos, ", \t\r\n");
4003     if (*pos == '\0') {
4004         *keyp = *valuep = NULL;
4005         return false;
4006     }
4007
4008     key = pos;
4009     key_len = strcspn(pos, ":=(, \t\r\n");
4010     if (key[key_len] == ':' || key[key_len] == '=') {
4011         /* The value can be separated by a colon. */
4012         size_t value_len;
4013
4014         value = key + key_len + 1;
4015         value_len = strcspn(value, ", \t\r\n");
4016         pos = value + value_len + (value[value_len] != '\0');
4017         value[value_len] = '\0';
4018     } else if (key[key_len] == '(') {
4019         /* The value can be surrounded by balanced parentheses.  The outermost
4020          * set of parentheses is removed. */
4021         int level = 1;
4022         size_t value_len;
4023
4024         value = key + key_len + 1;
4025         for (value_len = 0; level > 0; value_len++) {
4026             switch (value[value_len]) {
4027             case '\0':
4028                 level = 0;
4029                 break;
4030
4031             case '(':
4032                 level++;
4033                 break;
4034
4035             case ')':
4036                 level--;
4037                 break;
4038             }
4039         }
4040         value[value_len - 1] = '\0';
4041         pos = value + value_len;
4042     } else {
4043         /* There might be no value at all. */
4044         value = key + key_len;  /* Will become the empty string below. */
4045         pos = key + key_len + (key[key_len] != '\0');
4046     }
4047     key[key_len] = '\0';
4048
4049     *stringp = pos;
4050     *keyp = key;
4051     *valuep = value;
4052     return true;
4053 }
4054
4055 /* Encode a dump ports request for 'port', the encoded message
4056  * will be fore Open Flow version 'ofp_version'. Returns message
4057  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
4058 struct ofpbuf *
4059 ofputil_encode_dump_ports_request(enum ofp_version ofp_version, int16_t port)
4060 {
4061     struct ofpbuf *request;
4062
4063     switch (ofp_version) {
4064     case OFP10_VERSION: {
4065         struct ofp10_port_stats_request *req;
4066         request = ofpraw_alloc(OFPRAW_OFPST10_PORT_REQUEST, ofp_version, 0);
4067         req = ofpbuf_put_zeros(request, sizeof *req);
4068         req->port_no = htons(port);
4069         break;
4070     }
4071     case OFP11_VERSION:
4072     case OFP12_VERSION: {
4073         struct ofp11_port_stats_request *req;
4074         request = ofpraw_alloc(OFPRAW_OFPST11_PORT_REQUEST, ofp_version, 0);
4075         req = ofpbuf_put_zeros(request, sizeof *req);
4076         req->port_no = ofputil_port_to_ofp11(port);
4077         break;
4078     }
4079     default:
4080         NOT_REACHED();
4081     }
4082
4083     return request;
4084 }
4085
4086 static void
4087 ofputil_port_stats_to_ofp10(const struct ofputil_port_stats *ops,
4088                             struct ofp10_port_stats *ps10)
4089 {
4090     ps10->port_no = htons(ops->port_no);
4091     memset(ps10->pad, 0, sizeof ps10->pad);
4092     put_32aligned_be64(&ps10->rx_packets, htonll(ops->stats.rx_packets));
4093     put_32aligned_be64(&ps10->tx_packets, htonll(ops->stats.tx_packets));
4094     put_32aligned_be64(&ps10->rx_bytes, htonll(ops->stats.rx_bytes));
4095     put_32aligned_be64(&ps10->tx_bytes, htonll(ops->stats.tx_bytes));
4096     put_32aligned_be64(&ps10->rx_dropped, htonll(ops->stats.rx_dropped));
4097     put_32aligned_be64(&ps10->tx_dropped, htonll(ops->stats.tx_dropped));
4098     put_32aligned_be64(&ps10->rx_errors, htonll(ops->stats.rx_errors));
4099     put_32aligned_be64(&ps10->tx_errors, htonll(ops->stats.tx_errors));
4100     put_32aligned_be64(&ps10->rx_frame_err, htonll(ops->stats.rx_frame_errors));
4101     put_32aligned_be64(&ps10->rx_over_err, htonll(ops->stats.rx_over_errors));
4102     put_32aligned_be64(&ps10->rx_crc_err, htonll(ops->stats.rx_crc_errors));
4103     put_32aligned_be64(&ps10->collisions, htonll(ops->stats.collisions));
4104 }
4105
4106 static void
4107 ofputil_port_stats_to_ofp11(const struct ofputil_port_stats *ops,
4108                             struct ofp11_port_stats *ps11)
4109 {
4110     ps11->port_no = ofputil_port_to_ofp11(ops->port_no);
4111     memset(ps11->pad, 0, sizeof ps11->pad);
4112     ps11->rx_packets = htonll(ops->stats.rx_packets);
4113     ps11->tx_packets = htonll(ops->stats.tx_packets);
4114     ps11->rx_bytes = htonll(ops->stats.rx_bytes);
4115     ps11->tx_bytes = htonll(ops->stats.tx_bytes);
4116     ps11->rx_dropped = htonll(ops->stats.rx_dropped);
4117     ps11->tx_dropped = htonll(ops->stats.tx_dropped);
4118     ps11->rx_errors = htonll(ops->stats.rx_errors);
4119     ps11->tx_errors = htonll(ops->stats.tx_errors);
4120     ps11->rx_frame_err = htonll(ops->stats.rx_frame_errors);
4121     ps11->rx_over_err = htonll(ops->stats.rx_over_errors);
4122     ps11->rx_crc_err = htonll(ops->stats.rx_crc_errors);
4123     ps11->collisions = htonll(ops->stats.collisions);
4124 }
4125
4126 /* Encode a ports stat for 'ops' and append it to 'replies'. */
4127 void
4128 ofputil_append_port_stat(struct list *replies,
4129                          const struct ofputil_port_stats *ops)
4130 {
4131     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
4132     struct ofp_header *oh = msg->data;
4133
4134     switch ((enum ofp_version)oh->version) {
4135     case OFP12_VERSION:
4136     case OFP11_VERSION: {
4137         struct ofp11_port_stats *reply = ofpmp_append(replies, sizeof *reply);
4138         ofputil_port_stats_to_ofp11(ops, reply);
4139         break;
4140     }
4141
4142     case OFP10_VERSION: {
4143         struct ofp10_port_stats *reply = ofpmp_append(replies, sizeof *reply);
4144         ofputil_port_stats_to_ofp10(ops, reply);
4145         break;
4146     }
4147
4148     default:
4149         NOT_REACHED();
4150     }
4151 }
4152
4153 static enum ofperr
4154 ofputil_port_stats_from_ofp10(struct ofputil_port_stats *ops,
4155                               const struct ofp10_port_stats *ps10)
4156 {
4157     memset(ops, 0, sizeof *ops);
4158
4159     ops->port_no = ntohs(ps10->port_no);
4160     ops->stats.rx_packets = ntohll(get_32aligned_be64(&ps10->rx_packets));
4161     ops->stats.tx_packets = ntohll(get_32aligned_be64(&ps10->tx_packets));
4162     ops->stats.rx_bytes = ntohll(get_32aligned_be64(&ps10->rx_bytes));
4163     ops->stats.tx_bytes = ntohll(get_32aligned_be64(&ps10->tx_bytes));
4164     ops->stats.rx_dropped = ntohll(get_32aligned_be64(&ps10->rx_dropped));
4165     ops->stats.tx_dropped = ntohll(get_32aligned_be64(&ps10->tx_dropped));
4166     ops->stats.rx_errors = ntohll(get_32aligned_be64(&ps10->rx_errors));
4167     ops->stats.tx_errors = ntohll(get_32aligned_be64(&ps10->tx_errors));
4168     ops->stats.rx_frame_errors =
4169         ntohll(get_32aligned_be64(&ps10->rx_frame_err));
4170     ops->stats.rx_over_errors = ntohll(get_32aligned_be64(&ps10->rx_over_err));
4171     ops->stats.rx_crc_errors = ntohll(get_32aligned_be64(&ps10->rx_crc_err));
4172     ops->stats.collisions = ntohll(get_32aligned_be64(&ps10->collisions));
4173
4174     return 0;
4175 }
4176
4177 static enum ofperr
4178 ofputil_port_stats_from_ofp11(struct ofputil_port_stats *ops,
4179                               const struct ofp11_port_stats *ps11)
4180 {
4181     enum ofperr error;
4182
4183     memset(ops, 0, sizeof *ops);
4184     error = ofputil_port_from_ofp11(ps11->port_no, &ops->port_no);
4185     if (error) {
4186         return error;
4187     }
4188
4189     ops->stats.rx_packets = ntohll(ps11->rx_packets);
4190     ops->stats.tx_packets = ntohll(ps11->tx_packets);
4191     ops->stats.rx_bytes = ntohll(ps11->rx_bytes);
4192     ops->stats.tx_bytes = ntohll(ps11->tx_bytes);
4193     ops->stats.rx_dropped = ntohll(ps11->rx_dropped);
4194     ops->stats.tx_dropped = ntohll(ps11->tx_dropped);
4195     ops->stats.rx_errors = ntohll(ps11->rx_errors);
4196     ops->stats.tx_errors = ntohll(ps11->tx_errors);
4197     ops->stats.rx_frame_errors = ntohll(ps11->rx_frame_err);
4198     ops->stats.rx_over_errors = ntohll(ps11->rx_over_err);
4199     ops->stats.rx_crc_errors = ntohll(ps11->rx_crc_err);
4200     ops->stats.collisions = ntohll(ps11->collisions);
4201
4202     return 0;
4203 }
4204
4205 /* Returns the number of port stats elements in OFPTYPE_PORT_STATS_REPLY
4206  * message 'oh'. */
4207 size_t
4208 ofputil_count_port_stats(const struct ofp_header *oh)
4209 {
4210     struct ofpbuf b;
4211
4212     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4213     ofpraw_pull_assert(&b);
4214
4215     BUILD_ASSERT(sizeof(struct ofp10_port_stats) ==
4216                  sizeof(struct ofp11_port_stats));
4217     return b.size / sizeof(struct ofp10_port_stats);
4218 }
4219
4220 /* Converts an OFPST_PORT_STATS reply in 'msg' into an abstract
4221  * ofputil_port_stats in 'ps'.
4222  *
4223  * Multiple OFPST_PORT_STATS replies can be packed into a single OpenFlow
4224  * message.  Calling this function multiple times for a single 'msg' iterates
4225  * through the replies.  The caller must initially leave 'msg''s layer pointers
4226  * null and not modify them between calls.
4227  *
4228  * Returns 0 if successful, EOF if no replies were left in this 'msg',
4229  * otherwise a positive errno value. */
4230 int
4231 ofputil_decode_port_stats(struct ofputil_port_stats *ps, struct ofpbuf *msg)
4232 {
4233     enum ofperr error;
4234     enum ofpraw raw;
4235
4236     error = (msg->l2
4237              ? ofpraw_decode(&raw, msg->l2)
4238              : ofpraw_pull(&raw, msg));
4239     if (error) {
4240         return error;
4241     }
4242
4243     if (!msg->size) {
4244         return EOF;
4245     } else if (raw == OFPRAW_OFPST11_PORT_REPLY) {
4246         const struct ofp11_port_stats *ps11;
4247
4248         ps11 = ofpbuf_try_pull(msg, sizeof *ps11);
4249         if (!ps11) {
4250             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_PORT reply has %zu leftover "
4251                          "bytes at end", msg->size);
4252             return OFPERR_OFPBRC_BAD_LEN;
4253         }
4254         return ofputil_port_stats_from_ofp11(ps, ps11);
4255     } else if (raw == OFPRAW_OFPST10_PORT_REPLY) {
4256         const struct ofp10_port_stats *ps10;
4257
4258         ps10 = ofpbuf_try_pull(msg, sizeof *ps10);
4259         if (!ps10) {
4260             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_PORT reply has %zu leftover "
4261                          "bytes at end", msg->size);
4262             return OFPERR_OFPBRC_BAD_LEN;
4263         }
4264         return ofputil_port_stats_from_ofp10(ps, ps10);
4265     } else {
4266         NOT_REACHED();
4267     }
4268
4269 }
4270
4271 /* Parse a port status request message into a 16 bit OpenFlow 1.0
4272  * port number and stores the latter in '*ofp10_port'.
4273  * Returns 0 if successful, otherwise an OFPERR_* number. */
4274 enum ofperr
4275 ofputil_decode_port_stats_request(const struct ofp_header *request,
4276                                   uint16_t *ofp10_port)
4277 {
4278     switch ((enum ofp_version)request->version) {
4279     case OFP12_VERSION:
4280     case OFP11_VERSION: {
4281         const struct ofp11_port_stats_request *psr11 = ofpmsg_body(request);
4282         return ofputil_port_from_ofp11(psr11->port_no, ofp10_port);
4283     }
4284
4285     case OFP10_VERSION: {
4286         const struct ofp10_port_stats_request *psr10 = ofpmsg_body(request);
4287         *ofp10_port = ntohs(psr10->port_no);
4288         return 0;
4289     }
4290
4291     default:
4292         NOT_REACHED();
4293     }
4294 }
4295
4296 /* Parse a queue status request message into 'oqsr'.
4297  * Returns 0 if successful, otherwise an OFPERR_* number. */
4298 enum ofperr
4299 ofputil_decode_queue_stats_request(const struct ofp_header *request,
4300                                    struct ofputil_queue_stats_request *oqsr)
4301 {
4302     switch ((enum ofp_version)request->version) {
4303     case OFP12_VERSION:
4304     case OFP11_VERSION: {
4305         const struct ofp11_queue_stats_request *qsr11 = ofpmsg_body(request);
4306         oqsr->queue_id = ntohl(qsr11->queue_id);
4307         return ofputil_port_from_ofp11(qsr11->port_no, &oqsr->port_no);
4308     }
4309
4310     case OFP10_VERSION: {
4311         const struct ofp10_queue_stats_request *qsr11 = ofpmsg_body(request);
4312         oqsr->queue_id = ntohl(qsr11->queue_id);
4313         oqsr->port_no = ntohs(qsr11->port_no);
4314         return 0;
4315     }
4316
4317     default:
4318         NOT_REACHED();
4319     }
4320 }
4321
4322 /* Encode a queue statsrequest for 'oqsr', the encoded message
4323  * will be fore Open Flow version 'ofp_version'. Returns message
4324  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
4325 struct ofpbuf *
4326 ofputil_encode_queue_stats_request(enum ofp_version ofp_version,
4327                                    const struct ofputil_queue_stats_request *oqsr)
4328 {
4329     struct ofpbuf *request;
4330
4331     switch (ofp_version) {
4332     case OFP11_VERSION:
4333     case OFP12_VERSION: {
4334         struct ofp11_queue_stats_request *req;
4335         request = ofpraw_alloc(OFPRAW_OFPST11_QUEUE_REQUEST, ofp_version, 0);
4336         req = ofpbuf_put_zeros(request, sizeof *req);
4337         req->port_no = ofputil_port_to_ofp11(oqsr->port_no);
4338         req->queue_id = htonl(oqsr->queue_id);
4339         break;
4340     }
4341     case OFP10_VERSION: {
4342         struct ofp10_queue_stats_request *req;
4343         request = ofpraw_alloc(OFPRAW_OFPST10_QUEUE_REQUEST, ofp_version, 0);
4344         req = ofpbuf_put_zeros(request, sizeof *req);
4345         req->port_no = htons(oqsr->port_no);
4346         req->queue_id = htonl(oqsr->queue_id);
4347         break;
4348     }
4349     default:
4350         NOT_REACHED();
4351     }
4352
4353     return request;
4354 }
4355
4356 /* Returns the number of queue stats elements in OFPTYPE_QUEUE_STATS_REPLY
4357  * message 'oh'. */
4358 size_t
4359 ofputil_count_queue_stats(const struct ofp_header *oh)
4360 {
4361     struct ofpbuf b;
4362
4363     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4364     ofpraw_pull_assert(&b);
4365
4366     BUILD_ASSERT(sizeof(struct ofp10_queue_stats) ==
4367                  sizeof(struct ofp11_queue_stats));
4368     return b.size / sizeof(struct ofp10_queue_stats);
4369 }
4370
4371 static enum ofperr
4372 ofputil_queue_stats_from_ofp10(struct ofputil_queue_stats *oqs,
4373                                const struct ofp10_queue_stats *qs10)
4374 {
4375     oqs->port_no = ntohs(qs10->port_no);
4376     oqs->queue_id = ntohl(qs10->queue_id);
4377     oqs->stats.tx_bytes = ntohll(get_32aligned_be64(&qs10->tx_bytes));
4378     oqs->stats.tx_packets = ntohll(get_32aligned_be64(&qs10->tx_packets));
4379     oqs->stats.tx_errors = ntohll(get_32aligned_be64(&qs10->tx_errors));
4380
4381     return 0;
4382 }
4383
4384 static enum ofperr
4385 ofputil_queue_stats_from_ofp11(struct ofputil_queue_stats *oqs,
4386                                const struct ofp11_queue_stats *qs11)
4387 {
4388     enum ofperr error;
4389
4390     error = ofputil_port_from_ofp11(qs11->port_no, &oqs->port_no);
4391     if (error) {
4392         return error;
4393     }
4394
4395     oqs->queue_id = ntohl(qs11->queue_id);
4396     oqs->stats.tx_bytes = ntohll(qs11->tx_bytes);
4397     oqs->stats.tx_packets = ntohll(qs11->tx_packets);
4398     oqs->stats.tx_errors = ntohll(qs11->tx_errors);
4399
4400     return 0;
4401 }
4402
4403 /* Converts an OFPST_QUEUE_STATS reply in 'msg' into an abstract
4404  * ofputil_queue_stats in 'qs'.
4405  *
4406  * Multiple OFPST_QUEUE_STATS replies can be packed into a single OpenFlow
4407  * message.  Calling this function multiple times for a single 'msg' iterates
4408  * through the replies.  The caller must initially leave 'msg''s layer pointers
4409  * null and not modify them between calls.
4410  *
4411  * Returns 0 if successful, EOF if no replies were left in this 'msg',
4412  * otherwise a positive errno value. */
4413 int
4414 ofputil_decode_queue_stats(struct ofputil_queue_stats *qs, struct ofpbuf *msg)
4415 {
4416     enum ofperr error;
4417     enum ofpraw raw;
4418
4419     error = (msg->l2
4420              ? ofpraw_decode(&raw, msg->l2)
4421              : ofpraw_pull(&raw, msg));
4422     if (error) {
4423         return error;
4424     }
4425
4426     if (!msg->size) {
4427         return EOF;
4428     } else if (raw == OFPRAW_OFPST11_QUEUE_REPLY) {
4429         const struct ofp11_queue_stats *qs11;
4430
4431         qs11 = ofpbuf_try_pull(msg, sizeof *qs11);
4432         if (!qs11) {
4433             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_QUEUE reply has %zu leftover "
4434                          "bytes at end", msg->size);
4435             return OFPERR_OFPBRC_BAD_LEN;
4436         }
4437         return ofputil_queue_stats_from_ofp11(qs, qs11);
4438     } else if (raw == OFPRAW_OFPST10_QUEUE_REPLY) {
4439         const struct ofp10_queue_stats *qs10;
4440
4441         qs10 = ofpbuf_try_pull(msg, sizeof *qs10);
4442         if (!qs10) {
4443             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_QUEUE reply has %zu leftover "
4444                          "bytes at end", msg->size);
4445             return OFPERR_OFPBRC_BAD_LEN;
4446         }
4447         return ofputil_queue_stats_from_ofp10(qs, qs10);
4448     } else {
4449         NOT_REACHED();
4450     }
4451 }
4452
4453 static void
4454 ofputil_queue_stats_to_ofp10(const struct ofputil_queue_stats *oqs,
4455                              struct ofp10_queue_stats *qs10)
4456 {
4457     qs10->port_no = htons(oqs->port_no);
4458     memset(qs10->pad, 0, sizeof qs10->pad);
4459     qs10->queue_id = htonl(oqs->queue_id);
4460     put_32aligned_be64(&qs10->tx_bytes, htonll(oqs->stats.tx_bytes));
4461     put_32aligned_be64(&qs10->tx_packets, htonll(oqs->stats.tx_packets));
4462     put_32aligned_be64(&qs10->tx_errors, htonll(oqs->stats.tx_errors));
4463 }
4464
4465 static void
4466 ofputil_queue_stats_to_ofp11(const struct ofputil_queue_stats *oqs,
4467                              struct ofp11_queue_stats *qs11)
4468 {
4469     qs11->port_no = ofputil_port_to_ofp11(oqs->port_no);
4470     qs11->queue_id = htonl(oqs->queue_id);
4471     qs11->tx_bytes = htonll(oqs->stats.tx_bytes);
4472     qs11->tx_packets = htonll(oqs->stats.tx_packets);
4473     qs11->tx_errors = htonll(oqs->stats.tx_errors);
4474 }
4475
4476 /* Encode a queue stat for 'oqs' and append it to 'replies'. */
4477 void
4478 ofputil_append_queue_stat(struct list *replies,
4479                           const struct ofputil_queue_stats *oqs)
4480 {
4481     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
4482     struct ofp_header *oh = msg->data;
4483
4484     switch ((enum ofp_version)oh->version) {
4485     case OFP12_VERSION:
4486     case OFP11_VERSION: {
4487         struct ofp11_queue_stats *reply = ofpmp_append(replies, sizeof *reply);;
4488         ofputil_queue_stats_to_ofp11(oqs, reply);
4489         break;
4490     }
4491
4492     case OFP10_VERSION: {
4493         struct ofp10_queue_stats *reply = ofpmp_append(replies, sizeof *reply);;
4494         ofputil_queue_stats_to_ofp10(oqs, reply);
4495         break;
4496     }
4497
4498     default:
4499         NOT_REACHED();
4500     }
4501 }