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