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