flow: Get rid of flow_t typedef.
[sliver-openvswitch.git] / lib / classifier.c
1 /*
2  * Copyright (c) 2009, 2010 Nicira Networks.
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 "classifier.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <netinet/in.h>
22 #include "dynamic-string.h"
23 #include "flow.h"
24 #include "hash.h"
25
26 const struct cls_field cls_fields[CLS_N_FIELDS + 1] = {
27 #define CLS_FIELD(WILDCARDS, MEMBER, NAME)      \
28     { offsetof(struct flow, MEMBER),            \
29       sizeof ((struct flow *)0)->MEMBER,        \
30       WILDCARDS,                                \
31       #NAME },
32     CLS_FIELDS
33 #undef CLS_FIELD
34     { sizeof(struct flow), 0, 0, "exact" },
35 };
36
37 static uint32_t hash_fields(const struct flow *, int table_idx);
38 static bool equal_fields(const struct flow *, const struct flow *,
39                          int table_idx);
40
41 static int table_idx_from_wildcards(uint32_t wildcards);
42 static struct cls_rule *table_insert(struct hmap *, struct cls_rule *);
43 static struct cls_rule *insert_exact_rule(struct classifier *,
44                                           struct cls_rule *);
45 static struct cls_bucket *find_bucket(struct hmap *, size_t hash,
46                                       const struct cls_rule *);
47 static struct cls_rule *search_table(const struct hmap *table, int field_idx,
48                                      const struct cls_rule *);
49 static struct cls_rule *search_exact_table(const struct classifier *,
50                                            size_t hash, const struct flow *);
51 static bool rules_match_1wild(const struct cls_rule *fixed,
52                               const struct cls_rule *wild, int field_idx);
53 static bool rules_match_2wild(const struct cls_rule *wild1,
54                               const struct cls_rule *wild2, int field_idx);
55
56 /* Converts the flow in 'flow' into a cls_rule in 'rule', with the given
57  * 'wildcards' and 'priority'.*/
58 void
59 cls_rule_from_flow(const struct flow *flow, uint32_t wildcards,
60                    unsigned int priority, struct cls_rule *rule)
61 {
62     rule->flow = *flow;
63     flow_wildcards_init(&rule->wc, wildcards);
64     rule->priority = priority;
65     rule->table_idx = table_idx_from_wildcards(rule->wc.wildcards);
66 }
67
68 /* Converts the ofp_match in 'match' into a cls_rule in 'rule', with the given
69  * 'priority'.  If 'tun_id_from_cookie' is set then the upper 32 bits of
70  * 'cookie' are stored in the rule as the tunnel ID. */
71 void
72 cls_rule_from_match(const struct ofp_match *match, unsigned int priority,
73                     bool tun_id_from_cookie, uint64_t cookie,
74                     struct cls_rule *rule)
75 {
76     uint32_t wildcards;
77     flow_from_match(match, tun_id_from_cookie, cookie, &rule->flow, &wildcards);
78     flow_wildcards_init(&rule->wc, wildcards);
79     rule->priority = rule->wc.wildcards ? priority : UINT16_MAX;
80     rule->table_idx = table_idx_from_wildcards(rule->wc.wildcards);
81 }
82
83 /* Converts 'rule' to a string and returns the string.  The caller must free
84  * the string (with free()). */
85 char *
86 cls_rule_to_string(const struct cls_rule *rule)
87 {
88     struct ds s = DS_EMPTY_INITIALIZER;
89     ds_put_format(&s, "wildcards=%x priority=%u ",
90                   rule->wc.wildcards, rule->priority);
91     flow_format(&s, &rule->flow);
92     return ds_cstr(&s);
93 }
94
95 /* Prints cls_rule 'rule', for debugging.
96  *
97  * (The output could be improved and expanded, but this was good enough to
98  * debug the classifier.) */
99 void
100 cls_rule_print(const struct cls_rule *rule)
101 {
102     printf("wildcards=%x priority=%u ", rule->wc.wildcards, rule->priority);
103     flow_print(stdout, &rule->flow);
104     putc('\n', stdout);
105 }
106
107 /* Adjusts pointers around 'old', which must be in classifier 'cls', to
108  * compensate for it having been moved in memory to 'new' (e.g. due to
109  * realloc()).
110  *
111  * This function cannot be realized in all possible flow classifier
112  * implementations, so we will probably have to change the interface if we
113  * change the implementation.  Shouldn't be a big deal though. */
114 void
115 cls_rule_moved(struct classifier *cls, struct cls_rule *old,
116                struct cls_rule *new)
117 {
118     if (old != new) {
119         if (new->wc.wildcards) {
120             list_moved(&new->node.list);
121         } else {
122             hmap_node_moved(&cls->exact_table,
123                             &old->node.hmap, &new->node.hmap);
124         }
125     }
126 }
127
128 /* Replaces 'old', which must be in classifier 'cls', by 'new' (e.g. due to
129  * realloc()); that is, after calling this function 'new' will be in 'cls' in
130  * place of 'old'.
131  *
132  * 'new' and 'old' must be exactly the same: wildcard the same fields, have the
133  * same fixed values for non-wildcarded fields, and have the same priority.
134  *
135  * The caller takes ownership of 'old' and is thus responsible for freeing it,
136  * etc., as necessary.
137  *
138  * This function cannot be realized in all possible flow classifier
139  * implementations, so we will probably have to change the interface if we
140  * change the implementation.  Shouldn't be a big deal though. */
141 void
142 cls_rule_replace(struct classifier *cls, const struct cls_rule *old,
143                  struct cls_rule *new)
144 {
145     assert(old != new);
146     assert(old->wc.wildcards == new->wc.wildcards);
147     assert(old->priority == new->priority);
148
149     if (new->wc.wildcards) {
150         list_replace(&new->node.list, &old->node.list);
151     } else {
152         hmap_replace(&cls->exact_table, &old->node.hmap, &new->node.hmap);
153     }
154 }
155 \f
156 /* Initializes 'cls' as a classifier that initially contains no classification
157  * rules. */
158 void
159 classifier_init(struct classifier *cls)
160 {
161     int i;
162
163     cls->n_rules = 0;
164     for (i = 0; i < ARRAY_SIZE(cls->tables); i++) {
165         hmap_init(&cls->tables[i]);
166     }
167     hmap_init(&cls->exact_table);
168 }
169
170 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
171  * caller's responsibility. */
172 void
173 classifier_destroy(struct classifier *cls)
174 {
175     if (cls) {
176         struct cls_bucket *bucket, *next_bucket;
177         struct hmap *tbl;
178
179         for (tbl = &cls->tables[0]; tbl < &cls->tables[CLS_N_FIELDS]; tbl++) {
180             HMAP_FOR_EACH_SAFE (bucket, next_bucket, hmap_node, tbl) {
181                 free(bucket);
182             }
183             hmap_destroy(tbl);
184         }
185         hmap_destroy(&cls->exact_table);
186     }
187 }
188
189 /* Returns true if 'cls' does not contain any classification rules, false
190  * otherwise. */
191 bool
192 classifier_is_empty(const struct classifier *cls)
193 {
194     return cls->n_rules == 0;
195 }
196
197 /* Returns the number of rules in 'classifier'. */
198 int
199 classifier_count(const struct classifier *cls)
200 {
201     return cls->n_rules;
202 }
203
204 /* Returns the number of rules in 'classifier' that have no wildcards. */
205 int
206 classifier_count_exact(const struct classifier *cls)
207 {
208     return hmap_count(&cls->exact_table);
209 }
210
211 /* Inserts 'rule' into 'cls'.  Transfers ownership of 'rule' to 'cls'.
212  *
213  * If 'cls' already contains an identical rule (including wildcards, values of
214  * fixed fields, and priority), replaces the old rule by 'rule' and returns the
215  * rule that was replaced.  The caller takes ownership of the returned rule and
216  * is thus responsible for freeing it, etc., as necessary.
217  *
218  * Returns NULL if 'cls' does not contain a rule with an identical key, after
219  * inserting the new rule.  In this case, no rules are displaced by the new
220  * rule, even rules that cannot have any effect because the new rule matches a
221  * superset of their flows and has higher priority. */
222 struct cls_rule *
223 classifier_insert(struct classifier *cls, struct cls_rule *rule)
224 {
225     struct cls_rule *old;
226     assert((rule->wc.wildcards == 0) == (rule->table_idx == CLS_F_IDX_EXACT));
227     old = (rule->wc.wildcards
228            ? table_insert(&cls->tables[rule->table_idx], rule)
229            : insert_exact_rule(cls, rule));
230     if (!old) {
231         cls->n_rules++;
232     }
233     return old;
234 }
235
236 /* Inserts 'rule' into 'cls'.  Transfers ownership of 'rule' to 'cls'.
237  *
238  * 'rule' must be an exact-match rule (rule->wc.wildcards must be 0) and 'cls'
239  * must not contain any rule with an identical key. */
240 void
241 classifier_insert_exact(struct classifier *cls, struct cls_rule *rule)
242 {
243     hmap_insert(&cls->exact_table, &rule->node.hmap,
244                 flow_hash(&rule->flow, 0));
245     cls->n_rules++;
246 }
247
248 /* Removes 'rule' from 'cls'.  It is caller's responsibility to free 'rule', if
249  * this is desirable. */
250 void
251 classifier_remove(struct classifier *cls, struct cls_rule *rule)
252 {
253     if (rule->wc.wildcards) {
254         /* Remove 'rule' from bucket.  If that empties the bucket, remove the
255          * bucket from its table. */
256         struct hmap *table = &cls->tables[rule->table_idx];
257         struct list *rules = list_remove(&rule->node.list);
258         if (list_is_empty(rules)) {
259             /* This code is a little tricky.  list_remove() returns the list
260              * element just after the one removed.  Since the list is now
261              * empty, this will be the address of the 'rules' member of the
262              * bucket that was just emptied, so pointer arithmetic (via
263              * CONTAINER_OF) can find that bucket. */
264             struct cls_bucket *bucket;
265             bucket = CONTAINER_OF(rules, struct cls_bucket, rules);
266             hmap_remove(table, &bucket->hmap_node);
267             free(bucket);
268         }
269     } else {
270         /* Remove 'rule' from cls->exact_table. */
271         hmap_remove(&cls->exact_table, &rule->node.hmap);
272     }
273     cls->n_rules--;
274 }
275
276 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
277  * Returns a null pointer if no rules in 'cls' match 'flow'.  If multiple rules
278  * of equal priority match 'flow', returns one arbitrarily.
279  *
280  * (When multiple rules of equal priority happen to fall into the same bucket,
281  * rules added more recently take priority over rules added less recently, but
282  * this is subject to change and should not be depended upon.) */
283 struct cls_rule *
284 classifier_lookup(const struct classifier *cls, const struct flow *flow)
285 {
286     struct cls_rule *rule = classifier_lookup_exact(cls, flow);
287     if (!rule) {
288         rule = classifier_lookup_wild(cls, flow);
289     }
290     return rule;
291 }
292
293 struct cls_rule *
294 classifier_lookup_exact(const struct classifier *cls, const struct flow *flow)
295 {
296     return (!hmap_is_empty(&cls->exact_table)
297             ? search_exact_table(cls, flow_hash(flow, 0), flow)
298             : NULL);
299 }
300
301 struct cls_rule *
302 classifier_lookup_wild(const struct classifier *cls, const struct flow *flow)
303 {
304     struct cls_rule *best = NULL;
305     if (cls->n_rules > hmap_count(&cls->exact_table)) {
306         struct cls_rule target;
307         int i;
308
309         cls_rule_from_flow(flow, 0, 0, &target);
310         for (i = 0; i < CLS_N_FIELDS; i++) {
311             struct cls_rule *rule = search_table(&cls->tables[i], i, &target);
312             if (rule && (!best || rule->priority > best->priority)) {
313                 best = rule;
314             }
315         }
316     }
317     return best;
318 }
319
320 struct cls_rule *
321 classifier_find_rule_exactly(const struct classifier *cls,
322                              const struct flow *target, uint32_t wildcards,
323                              unsigned int priority)
324 {
325     struct cls_bucket *bucket;
326     int table_idx;
327     uint32_t hash;
328
329     if (!wildcards) {
330         /* Ignores 'priority'. */
331         return search_exact_table(cls, flow_hash(target, 0), target);
332     }
333
334     assert(wildcards == (wildcards & OVSFW_ALL));
335     table_idx = table_idx_from_wildcards(wildcards);
336     hash = hash_fields(target, table_idx);
337     HMAP_FOR_EACH_WITH_HASH (bucket, hmap_node, hash,
338                              &cls->tables[table_idx]) {
339         if (equal_fields(&bucket->fixed, target, table_idx)) {
340             struct cls_rule *pos;
341             LIST_FOR_EACH (pos, node.list, &bucket->rules) {
342                 if (pos->priority < priority) {
343                     return NULL;
344                 } else if (pos->priority == priority &&
345                            pos->wc.wildcards == wildcards &&
346                            flow_equal(target, &pos->flow)) {
347                     return pos;
348                 }
349             }
350         }
351     }
352     return NULL;
353 }
354
355 /* Checks if the flow defined by 'target' with 'wildcards' at 'priority'
356  * overlaps with any other rule at the same priority in the classifier.
357  * Two rules are considered overlapping if a packet could match both. */
358 bool
359 classifier_rule_overlaps(const struct classifier *cls,
360                          const struct flow *target, uint32_t wildcards,
361                          unsigned int priority)
362 {
363     struct cls_rule target_rule;
364     const struct hmap *tbl;
365
366     if (!wildcards) {
367         return search_exact_table(cls, flow_hash(target, 0), target) ?
368             true : false;
369     }
370
371     cls_rule_from_flow(target, wildcards, priority, &target_rule);
372
373     for (tbl = &cls->tables[0]; tbl < &cls->tables[CLS_N_FIELDS]; tbl++) {
374         struct cls_bucket *bucket;
375
376         HMAP_FOR_EACH (bucket, hmap_node, tbl) {
377             struct cls_rule *rule;
378
379             LIST_FOR_EACH (rule, node.list, &bucket->rules) {
380                 if (rule->priority == priority
381                     && rules_match_2wild(rule, &target_rule, 0)) {
382                     return true;
383                 }
384             }
385         }
386     }
387
388     return false;
389 }
390
391 /* Ignores target->priority.
392  *
393  * 'callback' is allowed to delete the rule that is passed as its argument, but
394  * it must not delete (or move) any other rules in 'cls' that are in the same
395  * table as the argument rule.  Two rules are in the same table if their
396  * cls_rule structs have the same table_idx; as a special case, a rule with
397  * wildcards and an exact-match rule will never be in the same table. */
398 void
399 classifier_for_each_match(const struct classifier *cls,
400                           const struct cls_rule *target,
401                           int include, cls_cb_func *callback, void *aux)
402 {
403     if (include & CLS_INC_WILD) {
404         const struct hmap *table;
405
406         for (table = &cls->tables[0]; table < &cls->tables[CLS_N_FIELDS];
407              table++) {
408             struct cls_bucket *bucket, *next_bucket;
409
410             HMAP_FOR_EACH_SAFE (bucket, next_bucket, hmap_node, table) {
411                 /* XXX there is a bit of room for optimization here based on
412                  * rejecting entire buckets on their fixed fields, but it will
413                  * only be worthwhile for big buckets (which we hope we won't
414                  * get anyway, but...) */
415                 struct cls_rule *prev_rule, *rule;
416
417                 /* We can't just use LIST_FOR_EACH_SAFE here because, if the
418                  * callback deletes the last rule in the bucket, then the
419                  * bucket itself will be destroyed.  The bucket contains the
420                  * list head so that's a use-after-free error. */
421                 prev_rule = NULL;
422                 LIST_FOR_EACH (rule, node.list, &bucket->rules) {
423                     if (rules_match_1wild(rule, target, 0)) {
424                         if (prev_rule) {
425                             callback(prev_rule, aux);
426                         }
427                         prev_rule = rule;
428                     }
429                 }
430                 if (prev_rule) {
431                     callback(prev_rule, aux);
432                 }
433             }
434         }
435     }
436
437     if (include & CLS_INC_EXACT) {
438         if (target->wc.wildcards) {
439             struct cls_rule *rule, *next_rule;
440
441             HMAP_FOR_EACH_SAFE (rule, next_rule, node.hmap,
442                                 &cls->exact_table) {
443                 if (rules_match_1wild(rule, target, 0)) {
444                     callback(rule, aux);
445                 }
446             }
447         } else {
448             /* Optimization: there can be at most one match in the exact
449              * table. */
450             size_t hash = flow_hash(&target->flow, 0);
451             struct cls_rule *rule = search_exact_table(cls, hash,
452                                                        &target->flow);
453             if (rule) {
454                 callback(rule, aux);
455             }
456         }
457     }
458 }
459
460 /* 'callback' is allowed to delete the rule that is passed as its argument, but
461  * it must not delete (or move) any other rules in 'cls' that are in the same
462  * table as the argument rule.  Two rules are in the same table if their
463  * cls_rule structs have the same table_idx; as a special case, a rule with
464  * wildcards and an exact-match rule will never be in the same table.
465  *
466  * If 'include' is CLS_INC_EXACT then CLASSIFIER_FOR_EACH_EXACT_RULE(_SAFE) is
467  * probably easier to use. */
468 void
469 classifier_for_each(const struct classifier *cls, int include,
470                     void (*callback)(struct cls_rule *, void *aux),
471                     void *aux)
472 {
473     if (include & CLS_INC_WILD) {
474         const struct hmap *tbl;
475
476         for (tbl = &cls->tables[0]; tbl < &cls->tables[CLS_N_FIELDS]; tbl++) {
477             struct cls_bucket *bucket, *next_bucket;
478
479             HMAP_FOR_EACH_SAFE (bucket, next_bucket, hmap_node, tbl) {
480                 struct cls_rule *prev_rule, *rule;
481
482                 /* We can't just use LIST_FOR_EACH_SAFE here because, if the
483                  * callback deletes the last rule in the bucket, then the
484                  * bucket itself will be destroyed.  The bucket contains the
485                  * list head so that's a use-after-free error. */
486                 prev_rule = NULL;
487                 LIST_FOR_EACH (rule, node.list, &bucket->rules) {
488                     if (prev_rule) {
489                         callback(prev_rule, aux);
490                     }
491                     prev_rule = rule;
492                 }
493                 if (prev_rule) {
494                     callback(prev_rule, aux);
495                 }
496             }
497         }
498     }
499
500     if (include & CLS_INC_EXACT) {
501         struct cls_rule *rule, *next_rule;
502
503         HMAP_FOR_EACH_SAFE (rule, next_rule, node.hmap, &cls->exact_table) {
504             callback(rule, aux);
505         }
506     }
507 }
508 \f
509 static struct cls_bucket *create_bucket(struct hmap *, size_t hash,
510                                         const struct flow *fixed);
511 static struct cls_rule *bucket_insert(struct cls_bucket *, struct cls_rule *);
512
513 static inline bool equal_bytes(const void *, const void *, size_t n);
514
515 /* Returns a hash computed across the fields in 'flow' whose field indexes
516  * (CLS_F_IDX_*) are less than 'table_idx'.  (If 'table_idx' is
517  * CLS_F_IDX_EXACT, hashes all the fields in 'flow'). */
518 static uint32_t
519 hash_fields(const struct flow *flow, int table_idx)
520 {
521     /* I just know I'm going to hell for writing code this way.
522      *
523      * GCC generates pretty good code here, with only a single taken
524      * conditional jump per execution.  Now the question is, would we be better
525      * off marking this function ALWAYS_INLINE and writing a wrapper that
526      * switches on the value of 'table_idx' to get rid of all the conditional
527      * jumps entirely (except for one in the wrapper)?  Honestly I really,
528      * really hope that it doesn't matter in practice.
529      *
530      * We could do better by calculating hashes incrementally, instead of
531      * starting over from the top each time.  But that would be even uglier. */
532     uint32_t a, b, c;
533     uint32_t tmp[3];
534     size_t n;
535
536     a = b = c = 0xdeadbeef + table_idx;
537     n = 0;
538
539 #define CLS_FIELD(WILDCARDS, MEMBER, NAME)                      \
540     if (table_idx == CLS_F_IDX_##NAME) {                        \
541         /* Done. */                                             \
542         memset((uint8_t *) tmp + n, 0, sizeof tmp - n);         \
543         goto finish;                                            \
544     } else {                                                    \
545         const size_t size = sizeof flow->MEMBER;                \
546         const uint8_t *p1 = (const uint8_t *) &flow->MEMBER;    \
547         const size_t p1_size = MIN(sizeof tmp - n, size);       \
548         const uint8_t *p2 = p1 + p1_size;                       \
549         const size_t p2_size = size - p1_size;                  \
550                                                                 \
551         /* Append to 'tmp' as much data as will fit. */         \
552         memcpy((uint8_t *) tmp + n, p1, p1_size);               \
553         n += p1_size;                                           \
554                                                                 \
555         /* If 'tmp' is full, mix. */                            \
556         if (n == sizeof tmp) {                                  \
557             a += tmp[0];                                        \
558             b += tmp[1];                                        \
559             c += tmp[2];                                        \
560             HASH_MIX(a, b, c);                                  \
561             n = 0;                                              \
562         }                                                       \
563                                                                 \
564         /* Append to 'tmp' any data that didn't fit. */         \
565         memcpy(tmp, p2, p2_size);                               \
566         n += p2_size;                                           \
567     }
568     CLS_FIELDS
569 #undef CLS_FIELD
570
571 finish:
572     a += tmp[0];
573     b += tmp[1];
574     c += tmp[2];
575     HASH_FINAL(a, b, c);
576     return c;
577 }
578
579 /* Compares the fields in 'a' and 'b' whose field indexes (CLS_F_IDX_*) are
580  * less than 'table_idx'.  (If 'table_idx' is CLS_F_IDX_EXACT, compares all the
581  * fields in 'a' and 'b').
582  *
583  * Returns true if all the compared fields are equal, false otherwise. */
584 static bool
585 equal_fields(const struct flow *a, const struct flow *b, int table_idx)
586 {
587     /* XXX The generated code could be better here. */
588 #define CLS_FIELD(WILDCARDS, MEMBER, NAME)                              \
589     if (table_idx == CLS_F_IDX_##NAME) {                                \
590         return true;                                                    \
591     } else if (!equal_bytes(&a->MEMBER, &b->MEMBER, sizeof a->MEMBER)) { \
592         return false;                                                   \
593     }
594     CLS_FIELDS
595 #undef CLS_FIELD
596
597     return true;
598 }
599
600 static int
601 table_idx_from_wildcards(uint32_t wildcards)
602 {
603     if (!wildcards) {
604         return CLS_F_IDX_EXACT;
605     }
606 #define CLS_FIELD(WILDCARDS, MEMBER, NAME) \
607     if (wildcards & WILDCARDS) {           \
608         return CLS_F_IDX_##NAME;           \
609     }
610     CLS_FIELDS
611 #undef CLS_FIELD
612     NOT_REACHED();
613 }
614
615 /* Inserts 'rule' into 'table'.  Returns the rule, if any, that was displaced
616  * in favor of 'rule'. */
617 static struct cls_rule *
618 table_insert(struct hmap *table, struct cls_rule *rule)
619 {
620     struct cls_bucket *bucket;
621     size_t hash;
622
623     hash = hash_fields(&rule->flow, rule->table_idx);
624     bucket = find_bucket(table, hash, rule);
625     if (!bucket) {
626         bucket = create_bucket(table, hash, &rule->flow);
627     }
628
629     return bucket_insert(bucket, rule);
630 }
631
632 /* Inserts 'rule' into 'bucket', given that 'field' is the first wildcarded
633  * field in 'rule'.
634  *
635  * Returns the rule, if any, that was displaced in favor of 'rule'. */
636 static struct cls_rule *
637 bucket_insert(struct cls_bucket *bucket, struct cls_rule *rule)
638 {
639     struct cls_rule *pos;
640     LIST_FOR_EACH (pos, node.list, &bucket->rules) {
641         if (pos->priority == rule->priority) {
642             if (pos->wc.wildcards == rule->wc.wildcards
643                 && rules_match_1wild(pos, rule, rule->table_idx))
644             {
645                 list_replace(&rule->node.list, &pos->node.list);
646                 return pos;
647             }
648         } else if (pos->priority < rule->priority) {
649             break;
650         }
651     }
652     list_insert(&pos->node.list, &rule->node.list);
653     return NULL;
654 }
655
656 static struct cls_rule *
657 insert_exact_rule(struct classifier *cls, struct cls_rule *rule)
658 {
659     struct cls_rule *old_rule;
660     size_t hash;
661
662     hash = flow_hash(&rule->flow, 0);
663     old_rule = search_exact_table(cls, hash, &rule->flow);
664     if (old_rule) {
665         hmap_remove(&cls->exact_table, &old_rule->node.hmap);
666     }
667     hmap_insert(&cls->exact_table, &rule->node.hmap, hash);
668     return old_rule;
669 }
670
671 /* Returns the bucket in 'table' that has the given 'hash' and the same fields
672  * as 'rule->flow' (up to 'rule->table_idx'), or a null pointer if no bucket
673  * matches. */
674 static struct cls_bucket *
675 find_bucket(struct hmap *table, size_t hash, const struct cls_rule *rule)
676 {
677     struct cls_bucket *bucket;
678     HMAP_FOR_EACH_WITH_HASH (bucket, hmap_node, hash, table) {
679         if (equal_fields(&bucket->fixed, &rule->flow, rule->table_idx)) {
680             return bucket;
681         }
682     }
683     return NULL;
684 }
685
686 /* Creates a bucket and inserts it in 'table' with the given 'hash' and 'fixed'
687  * values.  Returns the new bucket. */
688 static struct cls_bucket *
689 create_bucket(struct hmap *table, size_t hash, const struct flow *fixed)
690 {
691     struct cls_bucket *bucket = xmalloc(sizeof *bucket);
692     list_init(&bucket->rules);
693     bucket->fixed = *fixed;
694     hmap_insert(table, &bucket->hmap_node, hash);
695     return bucket;
696 }
697
698 /* Returns true if the 'n' bytes in 'a' and 'b' are equal, false otherwise. */
699 static inline bool ALWAYS_INLINE
700 equal_bytes(const void *a, const void *b, size_t n)
701 {
702 #ifdef __i386__
703     /* For some reason GCC generates stupid code for memcmp() of small
704      * constant integer lengths.  Help it out.
705      *
706      * This function is always inlined, and it is always called with 'n' as a
707      * compile-time constant, so the switch statement gets optimized out and
708      * this whole function just expands to an instruction or two. */
709     switch (n) {
710     case 1:
711         return *(uint8_t *) a == *(uint8_t *) b;
712
713     case 2:
714         return *(uint16_t *) a == *(uint16_t *) b;
715
716     case 4:
717         return *(uint32_t *) a == *(uint32_t *) b;
718
719     case 6:
720         return (*(uint32_t *) a == *(uint32_t *) b
721                 && ((uint16_t *) a)[2] == ((uint16_t *) b)[2]);
722
723     default:
724         abort();
725     }
726 #else
727     /* I hope GCC is smarter on your platform. */
728     return !memcmp(a, b, n);
729 #endif
730 }
731
732 /* Returns the 32-bit unsigned integer at 'p'. */
733 static inline uint32_t
734 read_uint32(const void *p)
735 {
736     /* GCC optimizes this into a single machine instruction on x86. */
737     uint32_t x;
738     memcpy(&x, p, sizeof x);
739     return x;
740 }
741
742 /* Compares the specified field in 'a' and 'b'.  Returns true if the fields are
743  * equal, or if the ofp_match wildcard bits in 'wildcards' are set such that
744  * non-equal values may be ignored.  'nw_src_mask' and 'nw_dst_mask' must be
745  * those that would be set for 'wildcards' by cls_rule_set_masks().
746  *
747  * The compared field is the one with wildcard bit or bits 'field_wc', offset
748  * 'rule_ofs' within cls_rule's "fields" member, and length 'len', in bytes. */
749 static inline bool ALWAYS_INLINE
750 field_matches(const struct flow *a_, const struct flow *b_,
751               uint32_t wildcards, uint32_t nw_src_mask, uint32_t nw_dst_mask,
752               uint32_t field_wc, int ofs, int len)
753 {
754     /* This function is always inlined, and it is always called with 'field_wc'
755      * as a compile-time constant, so the "if" conditionals here generate no
756      * code. */
757     const void *a = (const uint8_t *) a_ + ofs;
758     const void *b = (const uint8_t *) b_ + ofs;
759     if (!(field_wc & (field_wc - 1))) {
760         /* Handle all the single-bit wildcard cases. */
761         return wildcards & field_wc || equal_bytes(a, b, len);
762     } else if (field_wc == OFPFW_NW_SRC_MASK ||
763                field_wc == OFPFW_NW_DST_MASK) {
764         uint32_t a_ip = read_uint32(a);
765         uint32_t b_ip = read_uint32(b);
766         uint32_t mask = (field_wc == OFPFW_NW_SRC_MASK
767                          ? nw_src_mask : nw_dst_mask);
768         return ((a_ip ^ b_ip) & mask) == 0;
769     } else {
770         abort();
771     }
772 }
773
774 /* Returns true if 'a' and 'b' match, ignoring fields for which the wildcards
775  * in 'wildcards' are set.  'nw_src_mask' and 'nw_dst_mask' must be those that
776  * would be set for 'wildcards' by cls_rule_set_masks().  'field_idx' is the
777  * index of the first field to be compared; fields before 'field_idx' are
778  * assumed to match.  (Always returns true if 'field_idx' is CLS_N_FIELDS.) */
779 static bool
780 rules_match(const struct cls_rule *a, const struct cls_rule *b,
781             uint32_t wildcards, uint32_t nw_src_mask, uint32_t nw_dst_mask,
782             int field_idx)
783 {
784     /* This is related to Duff's device (see
785      * http://en.wikipedia.org/wiki/Duff's_device).  */
786     switch (field_idx) {
787 #define CLS_FIELD(WILDCARDS, MEMBER, NAME)                          \
788         case CLS_F_IDX_##NAME:                                      \
789             if (!field_matches(&a->flow, &b->flow,                  \
790                                wildcards, nw_src_mask, nw_dst_mask, \
791                                WILDCARDS, offsetof(struct flow, MEMBER), \
792                                sizeof a->flow.MEMBER)) {            \
793                 return false;                                       \
794             }                                                       \
795         /* Fall though */
796         CLS_FIELDS
797 #undef CLS_FIELD
798     }
799     return true;
800 }
801
802 /* Returns true if 'fixed' and 'wild' match.  All fields in 'fixed' must have
803  * fixed values; 'wild' may contain wildcards.
804  *
805  * 'field_idx' is the index of the first field to be compared; fields before
806  * 'field_idx' are assumed to match.  Always returns true if 'field_idx' is
807  * CLS_N_FIELDS. */
808 static bool
809 rules_match_1wild(const struct cls_rule *fixed, const struct cls_rule *wild,
810                   int field_idx)
811 {
812     return rules_match(fixed, wild, wild->wc.wildcards, wild->wc.nw_src_mask,
813                        wild->wc.nw_dst_mask, field_idx);
814 }
815
816 /* Returns true if 'wild1' and 'wild2' match, that is, if their fields
817  * are equal modulo wildcards in 'wild1' or 'wild2'.
818  *
819  * 'field_idx' is the index of the first field to be compared; fields before
820  * 'field_idx' are assumed to match.  Always returns true if 'field_idx' is
821  * CLS_N_FIELDS. */
822 static bool
823 rules_match_2wild(const struct cls_rule *wild1, const struct cls_rule *wild2,
824                   int field_idx)
825 {
826     return rules_match(wild1, wild2,
827                        wild1->wc.wildcards | wild2->wc.wildcards,
828                        wild1->wc.nw_src_mask & wild2->wc.nw_src_mask,
829                        wild1->wc.nw_dst_mask & wild2->wc.nw_dst_mask,
830                        field_idx);
831 }
832
833 /* Searches 'bucket' for a rule that matches 'target'.  Returns the
834  * highest-priority match, if one is found, or a null pointer if there is no
835  * match.
836  *
837  * 'field_idx' must be the index of the first wildcarded field in 'bucket'. */
838 static struct cls_rule *
839 search_bucket(struct cls_bucket *bucket, int field_idx,
840               const struct cls_rule *target)
841 {
842     struct cls_rule *pos;
843
844     if (!equal_fields(&bucket->fixed, &target->flow, field_idx)) {
845         return NULL;
846     }
847
848     LIST_FOR_EACH (pos, node.list, &bucket->rules) {
849         if (rules_match_1wild(target, pos, field_idx)) {
850             return pos;
851         }
852     }
853     return NULL;
854 }
855
856 /* Searches 'table' for a rule that matches 'target'.  Returns the
857  * highest-priority match, if one is found, or a null pointer if there is no
858  * match.
859  *
860  * 'field_idx' must be the index of the first wildcarded field in 'table'. */
861 static struct cls_rule *
862 search_table(const struct hmap *table, int field_idx,
863              const struct cls_rule *target)
864 {
865     struct cls_bucket *bucket;
866
867     switch (hmap_count(table)) {
868         /* In these special cases there's no need to hash.  */
869     case 0:
870         return NULL;
871     case 1:
872         bucket = CONTAINER_OF(hmap_first(table), struct cls_bucket, hmap_node);
873         return search_bucket(bucket, field_idx, target);
874     }
875
876     HMAP_FOR_EACH_WITH_HASH (bucket, hmap_node,
877                              hash_fields(&target->flow, field_idx), table) {
878         struct cls_rule *rule = search_bucket(bucket, field_idx, target);
879         if (rule) {
880             return rule;
881         }
882     }
883     return NULL;
884 }
885
886 static struct cls_rule *
887 search_exact_table(const struct classifier *cls, size_t hash,
888                    const struct flow *target)
889 {
890     struct cls_rule *rule;
891
892     HMAP_FOR_EACH_WITH_HASH (rule, node.hmap, hash, &cls->exact_table) {
893         if (flow_equal(&rule->flow, target)) {
894             return rule;
895         }
896     }
897     return NULL;
898 }