hmap: Rename hmap_moved() to hmap_node_moved().
[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 "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     assert(flow->reserved == 0);
59     rule->flow = *flow;
60     flow_wildcards_init(&rule->wc, wildcards);
61     rule->priority = priority;
62     rule->table_idx = table_idx_from_wildcards(rule->wc.wildcards);
63 }
64
65 /* Converts the ofp_match in 'match' into a cls_rule in 'rule', with the given
66  * 'priority'. */
67 void
68 cls_rule_from_match(struct cls_rule *rule, const struct ofp_match *match,
69                     unsigned int priority)
70 {
71     uint32_t wildcards;
72     flow_from_match(&rule->flow, &wildcards, match);
73     flow_wildcards_init(&rule->wc, wildcards);
74     rule->priority = rule->wc.wildcards ? priority : UINT16_MAX;
75     rule->table_idx = table_idx_from_wildcards(rule->wc.wildcards);
76 }
77
78 /* Prints cls_rule 'rule', for debugging.
79  *
80  * (The output could be improved and expanded, but this was good enough to
81  * debug the classifier.) */
82 void
83 cls_rule_print(const struct cls_rule *rule)
84 {
85     printf("wildcards=%x priority=%u ", rule->wc.wildcards, rule->priority);
86     flow_print(stdout, &rule->flow);
87     putc('\n', stdout);
88 }
89
90 /* Adjusts pointers around 'old', which must be in classifier 'cls', to
91  * compensate for it having been moved in memory to 'new' (e.g. due to
92  * realloc()).
93  *
94  * This function cannot be realized in all possible flow classifier
95  * implementations, so we will probably have to change the interface if we
96  * change the implementation.  Shouldn't be a big deal though. */
97 void
98 cls_rule_moved(struct classifier *cls, struct cls_rule *old,
99                struct cls_rule *new)
100 {
101     if (old != new) {
102         if (new->wc.wildcards) {
103             list_moved(&new->node.list);
104         } else {
105             hmap_node_moved(&cls->exact_table,
106                             &old->node.hmap, &new->node.hmap);
107         }
108     }
109 }
110
111 /* Replaces 'old', which must be in classifier 'cls', by 'new' (e.g. due to
112  * realloc()); that is, after calling this function 'new' will be in 'cls' in
113  * place of 'old'.
114  *
115  * 'new' and 'old' must be exactly the same: wildcard the same fields, have the
116  * same fixed values for non-wildcarded fields, and have the same priority.
117  *
118  * The caller takes ownership of 'old' and is thus responsible for freeing it,
119  * etc., as necessary.
120  *
121  * This function cannot be realized in all possible flow classifier
122  * implementations, so we will probably have to change the interface if we
123  * change the implementation.  Shouldn't be a big deal though. */
124 void
125 cls_rule_replace(struct classifier *cls, const struct cls_rule *old,
126                  struct cls_rule *new)
127 {
128     assert(old != new);
129     assert(old->wc.wildcards == new->wc.wildcards);
130     assert(old->priority == new->priority);
131
132     if (new->wc.wildcards) {
133         list_replace(&new->node.list, &old->node.list);
134     } else {
135         hmap_replace(&cls->exact_table, &old->node.hmap, &new->node.hmap);
136     }
137 }
138 \f
139 /* Initializes 'cls' as a classifier that initially contains no classification
140  * rules. */
141 void
142 classifier_init(struct classifier *cls)
143 {
144     int i;
145
146     cls->n_rules = 0;
147     for (i = 0; i < ARRAY_SIZE(cls->tables); i++) {
148         hmap_init(&cls->tables[i]);
149     }
150     hmap_init(&cls->exact_table);
151 }
152
153 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
154  * caller's responsibility. */
155 void
156 classifier_destroy(struct classifier *cls)
157 {
158     if (cls) {
159         struct cls_bucket *bucket, *next_bucket;
160         struct hmap *tbl;
161
162         for (tbl = &cls->tables[0]; tbl < &cls->tables[CLS_N_FIELDS]; tbl++) {
163             HMAP_FOR_EACH_SAFE (bucket, next_bucket,
164                                 struct cls_bucket, hmap_node, tbl) {
165                 free(bucket);
166             }
167             hmap_destroy(tbl);
168         }
169         hmap_destroy(&cls->exact_table);
170     }
171 }
172
173 /* Returns true if 'cls' does not contain any classification rules, false
174  * otherwise. */
175 bool
176 classifier_is_empty(const struct classifier *cls)
177 {
178     return cls->n_rules == 0;
179 }
180
181 /* Returns the number of rules in 'classifier'. */
182 int
183 classifier_count(const struct classifier *cls)
184 {
185     return cls->n_rules;
186 }
187
188 /* Returns the number of rules in 'classifier' that have no wildcards. */
189 int
190 classifier_count_exact(const struct classifier *cls)
191 {
192     return hmap_count(&cls->exact_table);
193 }
194
195 /* Inserts 'rule' into 'cls'.  Transfers ownership of 'rule' to 'cls'.
196  *
197  * If 'cls' already contains an identical rule (including wildcards, values of
198  * fixed fields, and priority), replaces the old rule by 'rule' and returns the
199  * rule that was replaced.  The caller takes ownership of the returned rule and
200  * is thus responsible for freeing it, etc., as necessary.
201  *
202  * Returns NULL if 'cls' does not contain a rule with an identical key, after
203  * inserting the new rule.  In this case, no rules are displaced by the new
204  * rule, even rules that cannot have any effect because the new rule matches a
205  * superset of their flows and has higher priority. */
206 struct cls_rule *
207 classifier_insert(struct classifier *cls, struct cls_rule *rule)
208 {
209     struct cls_rule *old;
210     assert((rule->wc.wildcards == 0) == (rule->table_idx == CLS_F_IDX_EXACT));
211     old = (rule->wc.wildcards
212            ? table_insert(&cls->tables[rule->table_idx], rule)
213            : insert_exact_rule(cls, rule));
214     if (!old) {
215         cls->n_rules++;
216     }
217     return old;
218 }
219
220 /* Inserts 'rule' into 'cls'.  Transfers ownership of 'rule' to 'cls'.
221  *
222  * 'rule' must be an exact-match rule (rule->wc.wildcards must be 0) and 'cls'
223  * must not contain any rule with an identical key. */
224 void
225 classifier_insert_exact(struct classifier *cls, struct cls_rule *rule)
226 {
227     hmap_insert(&cls->exact_table, &rule->node.hmap,
228                 flow_hash(&rule->flow, 0));
229     cls->n_rules++;
230 }
231
232 /* Removes 'rule' from 'cls'.  It is caller's responsibility to free 'rule', if
233  * this is desirable. */
234 void
235 classifier_remove(struct classifier *cls, struct cls_rule *rule)
236 {
237     if (rule->wc.wildcards) {
238         /* Remove 'rule' from bucket.  If that empties the bucket, remove the
239          * bucket from its table. */
240         struct hmap *table = &cls->tables[rule->table_idx];
241         struct list *rules = list_remove(&rule->node.list);
242         if (list_is_empty(rules)) {
243             /* This code is a little tricky.  list_remove() returns the list
244              * element just after the one removed.  Since the list is now
245              * empty, this will be the address of the 'rules' member of the
246              * bucket that was just emptied, so pointer arithmetic (via
247              * CONTAINER_OF) can find that bucket. */
248             struct cls_bucket *bucket;
249             bucket = CONTAINER_OF(rules, struct cls_bucket, rules);
250             hmap_remove(table, &bucket->hmap_node);
251             free(bucket);
252         }
253     } else {
254         /* Remove 'rule' from cls->exact_table. */
255         hmap_remove(&cls->exact_table, &rule->node.hmap);
256     }
257     cls->n_rules--;
258 }
259
260 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
261  * Returns a null pointer if no rules in 'cls' match 'flow'.  If multiple rules
262  * of equal priority match 'flow', returns one arbitrarily.
263  *
264  * (When multiple rules of equal priority happen to fall into the same bucket,
265  * rules added more recently take priority over rules added less recently, but
266  * this is subject to change and should not be depended upon.) */
267 struct cls_rule *
268 classifier_lookup(const struct classifier *cls, const flow_t *flow)
269 {
270     struct cls_rule *rule = classifier_lookup_exact(cls, flow);
271     if (!rule) {
272         rule = classifier_lookup_wild(cls, flow);
273     }
274     return rule;
275 }
276
277 struct cls_rule *
278 classifier_lookup_exact(const struct classifier *cls, const flow_t *flow)
279 {
280     return (!hmap_is_empty(&cls->exact_table)
281             ? search_exact_table(cls, flow_hash(flow, 0), flow)
282             : NULL);
283 }
284
285 struct cls_rule *
286 classifier_lookup_wild(const struct classifier *cls, const flow_t *flow)
287 {
288     struct cls_rule *best = NULL;
289     if (cls->n_rules > hmap_count(&cls->exact_table)) {
290         struct cls_rule target;
291         int i;
292
293         cls_rule_from_flow(&target, flow, 0, 0);
294         for (i = 0; i < CLS_N_FIELDS; i++) {
295             struct cls_rule *rule = search_table(&cls->tables[i], i, &target);
296             if (rule && (!best || rule->priority > best->priority)) {
297                 best = rule;
298             }
299         }
300     }
301     return best;
302 }
303
304 struct cls_rule *
305 classifier_find_rule_exactly(const struct classifier *cls,
306                              const flow_t *target, uint32_t wildcards,
307                              unsigned int priority)
308 {
309     struct cls_bucket *bucket;
310     int table_idx;
311     uint32_t hash;
312
313     if (!wildcards) {
314         /* Ignores 'priority'. */
315         return search_exact_table(cls, flow_hash(target, 0), target);
316     }
317
318     assert(wildcards == (wildcards & OFPFW_ALL));
319     table_idx = table_idx_from_wildcards(wildcards);
320     hash = hash_fields(target, table_idx);
321     HMAP_FOR_EACH_WITH_HASH (bucket, struct cls_bucket, hmap_node, hash,
322                              &cls->tables[table_idx]) {
323         if (equal_fields(&bucket->fixed, target, table_idx)) {
324             struct cls_rule *pos;
325             LIST_FOR_EACH (pos, struct cls_rule, node.list, &bucket->rules) {
326                 if (pos->priority < priority) {
327                     return NULL;
328                 } else if (pos->priority == priority &&
329                            pos->wc.wildcards == wildcards &&
330                            flow_equal(target, &pos->flow)) {
331                     return pos;
332                 }
333             }
334         }
335     }
336     return NULL;
337 }
338
339 /* Ignores target->priority.
340  *
341  * 'callback' is allowed to delete the rule that is passed as its argument, but
342  * it must not delete (or move) any other rules in 'cls' that are in the same
343  * table as the argument rule.  Two rules are in the same table if their
344  * cls_rule structs have the same table_idx; as a special case, a rule with
345  * wildcards and an exact-match rule will never be in the same table. */
346 void
347 classifier_for_each_match(const struct classifier *cls,
348                           const struct cls_rule *target,
349                           int include, cls_cb_func *callback, void *aux)
350 {
351     if (include & CLS_INC_WILD) {
352         const struct hmap *table;
353
354         for (table = &cls->tables[0]; table < &cls->tables[CLS_N_FIELDS];
355              table++) {
356             struct cls_bucket *bucket, *next_bucket;
357
358             HMAP_FOR_EACH_SAFE (bucket, next_bucket,
359                                 struct cls_bucket, hmap_node, table) {
360                 /* XXX there is a bit of room for optimization here based on
361                  * rejecting entire buckets on their fixed fields, but it will
362                  * only be worthwhile for big buckets (which we hope we won't
363                  * get anyway, but...) */
364                 struct cls_rule *prev_rule, *rule;
365
366                 /* We can't just use LIST_FOR_EACH_SAFE here because, if the
367                  * callback deletes the last rule in the bucket, then the
368                  * bucket itself will be destroyed.  The bucket contains the
369                  * list head so that's a use-after-free error. */
370                 prev_rule = NULL;
371                 LIST_FOR_EACH (rule, struct cls_rule, node.list,
372                                &bucket->rules) {
373                     if (rules_match_1wild(rule, target, 0)) {
374                         if (prev_rule) {
375                             callback(prev_rule, aux);
376                         }
377                         prev_rule = rule;
378                     }
379                 }
380                 if (prev_rule) {
381                     callback(prev_rule, aux);
382                 }
383             }
384         }
385     }
386
387     if (include & CLS_INC_EXACT) {
388         if (target->wc.wildcards) {
389             struct cls_rule *rule, *next_rule;
390
391             HMAP_FOR_EACH_SAFE (rule, next_rule, struct cls_rule, node.hmap,
392                                 &cls->exact_table) {
393                 if (rules_match_1wild(rule, target, 0)) {
394                     callback(rule, aux);
395                 }
396             }
397         } else {
398             /* Optimization: there can be at most one match in the exact
399              * table. */
400             size_t hash = flow_hash(&target->flow, 0);
401             struct cls_rule *rule = search_exact_table(cls, hash,
402                                                        &target->flow);
403             if (rule) {
404                 callback(rule, aux);
405             }
406         }
407     }
408 }
409
410 /* 'callback' is allowed to delete the rule that is passed as its argument, but
411  * it must not delete (or move) any other rules in 'cls' that are in the same
412  * table as the argument rule.  Two rules are in the same table if their
413  * cls_rule structs have the same table_idx; as a special case, a rule with
414  * wildcards and an exact-match rule will never be in the same table. */
415 void
416 classifier_for_each(const struct classifier *cls, int include,
417                     void (*callback)(struct cls_rule *, void *aux),
418                     void *aux)
419 {
420     if (include & CLS_INC_WILD) {
421         const struct hmap *tbl;
422
423         for (tbl = &cls->tables[0]; tbl < &cls->tables[CLS_N_FIELDS]; tbl++) {
424             struct cls_bucket *bucket, *next_bucket;
425
426             HMAP_FOR_EACH_SAFE (bucket, next_bucket,
427                                 struct cls_bucket, hmap_node, tbl) {
428                 struct cls_rule *prev_rule, *rule;
429
430                 /* We can't just use LIST_FOR_EACH_SAFE here because, if the
431                  * callback deletes the last rule in the bucket, then the
432                  * bucket itself will be destroyed.  The bucket contains the
433                  * list head so that's a use-after-free error. */
434                 prev_rule = NULL;
435                 LIST_FOR_EACH (rule, struct cls_rule, node.list,
436                                &bucket->rules) {
437                     if (prev_rule) {
438                         callback(prev_rule, aux);
439                     }
440                     prev_rule = rule;
441                 }
442                 if (prev_rule) {
443                     callback(prev_rule, aux);
444                 }
445             }
446         }
447     }
448
449     if (include & CLS_INC_EXACT) {
450         struct cls_rule *rule, *next_rule;
451
452         HMAP_FOR_EACH_SAFE (rule, next_rule,
453                             struct cls_rule, node.hmap, &cls->exact_table) {
454             callback(rule, aux);
455         }
456     }
457 }
458 \f
459 static struct cls_bucket *create_bucket(struct hmap *, size_t hash,
460                                         const flow_t *fixed);
461 static struct cls_rule *bucket_insert(struct cls_bucket *, struct cls_rule *);
462
463 static inline bool equal_bytes(const void *, const void *, size_t n);
464
465 /* Returns a hash computed across the fields in 'flow' whose field indexes
466  * (CLS_F_IDX_*) are less than 'table_idx'.  (If 'table_idx' is
467  * CLS_F_IDX_EXACT, hashes all the fields in 'flow'). */
468 static uint32_t
469 hash_fields(const flow_t *flow, int table_idx)
470 {
471     /* I just know I'm going to hell for writing code this way.
472      *
473      * GCC generates pretty good code here, with only a single taken
474      * conditional jump per execution.  Now the question is, would we be better
475      * off marking this function ALWAYS_INLINE and writing a wrapper that
476      * switches on the value of 'table_idx' to get rid of all the conditional
477      * jumps entirely (except for one in the wrapper)?  Honestly I really,
478      * really hope that it doesn't matter in practice.
479      *
480      * We could do better by calculating hashes incrementally, instead of
481      * starting over from the top each time.  But that would be even uglier. */
482     uint32_t a, b, c;
483     uint32_t tmp[3];
484     size_t n;
485
486     a = b = c = 0xdeadbeef + table_idx;
487     n = 0;
488
489 #define CLS_FIELD(WILDCARDS, MEMBER, NAME)                      \
490     if (table_idx == CLS_F_IDX_##NAME) {                        \
491         /* Done. */                                             \
492         memset((uint8_t *) tmp + n, 0, sizeof tmp - n);         \
493         goto finish;                                            \
494     } else {                                                    \
495         const size_t size = sizeof flow->MEMBER;                \
496         const uint8_t *p1 = (const uint8_t *) &flow->MEMBER;    \
497         const size_t p1_size = MIN(sizeof tmp - n, size);       \
498         const uint8_t *p2 = p1 + p1_size;                       \
499         const size_t p2_size = size - p1_size;                  \
500                                                                 \
501         /* Append to 'tmp' as much data as will fit. */         \
502         memcpy((uint8_t *) tmp + n, p1, p1_size);               \
503         n += p1_size;                                           \
504                                                                 \
505         /* If 'tmp' is full, mix. */                            \
506         if (n == sizeof tmp) {                                  \
507             a += tmp[0];                                        \
508             b += tmp[1];                                        \
509             c += tmp[2];                                        \
510             HASH_MIX(a, b, c);                                  \
511             n = 0;                                              \
512         }                                                       \
513                                                                 \
514         /* Append to 'tmp' any data that didn't fit. */         \
515         memcpy(tmp, p2, p2_size);                               \
516         n += p2_size;                                           \
517     }
518     CLS_FIELDS
519 #undef CLS_FIELD
520
521 finish:
522     a += tmp[0];
523     b += tmp[1];
524     c += tmp[2];
525     HASH_FINAL(a, b, c);
526     return c;
527 }
528
529 /* Compares the fields in 'a' and 'b' whose field indexes (CLS_F_IDX_*) are
530  * less than 'table_idx'.  (If 'table_idx' is CLS_F_IDX_EXACT, compares all the
531  * fields in 'a' and 'b').
532  *
533  * Returns true if all the compared fields are equal, false otherwise. */
534 static bool
535 equal_fields(const flow_t *a, const flow_t *b, int table_idx)
536 {
537     /* XXX The generated code could be better here. */
538 #define CLS_FIELD(WILDCARDS, MEMBER, NAME)                              \
539     if (table_idx == CLS_F_IDX_##NAME) {                                \
540         return true;                                                    \
541     } else if (!equal_bytes(&a->MEMBER, &b->MEMBER, sizeof a->MEMBER)) { \
542         return false;                                                   \
543     }
544     CLS_FIELDS
545 #undef CLS_FIELD
546
547     return true;
548 }
549
550 static int
551 table_idx_from_wildcards(uint32_t wildcards)
552 {
553     if (!wildcards) {
554         return CLS_F_IDX_EXACT;
555     }
556 #define CLS_FIELD(WILDCARDS, MEMBER, NAME) \
557     if (wildcards & WILDCARDS) {           \
558         return CLS_F_IDX_##NAME;           \
559     }
560     CLS_FIELDS
561 #undef CLS_FIELD
562     NOT_REACHED();
563 }
564
565 /* Inserts 'rule' into 'table'.  Returns the rule, if any, that was displaced
566  * in favor of 'rule'. */
567 static struct cls_rule *
568 table_insert(struct hmap *table, struct cls_rule *rule)
569 {
570     struct cls_bucket *bucket;
571     size_t hash;
572
573     hash = hash_fields(&rule->flow, rule->table_idx);
574     bucket = find_bucket(table, hash, rule);
575     if (!bucket) {
576         bucket = create_bucket(table, hash, &rule->flow);
577     }
578
579     return bucket_insert(bucket, rule);
580 }
581
582 /* Inserts 'rule' into 'bucket', given that 'field' is the first wildcarded
583  * field in 'rule'.
584  *
585  * Returns the rule, if any, that was displaced in favor of 'rule'. */
586 static struct cls_rule *
587 bucket_insert(struct cls_bucket *bucket, struct cls_rule *rule)
588 {
589     struct cls_rule *pos;
590     LIST_FOR_EACH (pos, struct cls_rule, node.list, &bucket->rules) {
591         if (pos->priority <= rule->priority) {
592             if (pos->priority == rule->priority
593                 && 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             break;
600         }
601     }
602     list_insert(&pos->node.list, &rule->node.list);
603     return NULL;
604 }
605
606 static struct cls_rule *
607 insert_exact_rule(struct classifier *cls, struct cls_rule *rule)
608 {
609     struct cls_rule *old_rule;
610     size_t hash;
611
612     hash = flow_hash(&rule->flow, 0);
613     old_rule = search_exact_table(cls, hash, &rule->flow);
614     if (old_rule) {
615         hmap_remove(&cls->exact_table, &old_rule->node.hmap);
616     }
617     hmap_insert(&cls->exact_table, &rule->node.hmap, hash);
618     return old_rule;
619 }
620
621 /* Returns the bucket in 'table' that has the given 'hash' and the same fields
622  * as 'rule->flow' (up to 'rule->table_idx'), or a null pointer if no bucket
623  * matches. */
624 static struct cls_bucket *
625 find_bucket(struct hmap *table, size_t hash, const struct cls_rule *rule)
626 {
627     struct cls_bucket *bucket;
628     HMAP_FOR_EACH_WITH_HASH (bucket, struct cls_bucket, hmap_node, hash,
629                              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 flow_t *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 flow_t *a_, const flow_t *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(flow_t, 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 /* Searches 'bucket' for a rule that matches 'target'.  Returns the
768  * highest-priority match, if one is found, or a null pointer if there is no
769  * match.
770  *
771  * 'field_idx' must be the index of the first wildcarded field in 'bucket'. */
772 static struct cls_rule *
773 search_bucket(struct cls_bucket *bucket, int field_idx,
774               const struct cls_rule *target)
775 {
776     struct cls_rule *pos;
777
778     if (!equal_fields(&bucket->fixed, &target->flow, field_idx)) {
779         return NULL;
780     }
781
782     LIST_FOR_EACH (pos, struct cls_rule, node.list, &bucket->rules) {
783         if (rules_match_1wild(target, pos, field_idx)) {
784             return pos;
785         }
786     }
787     return NULL;
788 }
789
790 /* Searches 'table' for a rule that matches 'target'.  Returns the
791  * highest-priority match, if one is found, or a null pointer if there is no
792  * match.
793  *
794  * 'field_idx' must be the index of the first wildcarded field in 'table'. */
795 static struct cls_rule *
796 search_table(const struct hmap *table, int field_idx,
797              const struct cls_rule *target)
798 {
799     struct cls_bucket *bucket;
800
801     switch (hmap_count(table)) {
802         /* In these special cases there's no need to hash.  */
803     case 0:
804         return NULL;
805     case 1:
806         bucket = CONTAINER_OF(hmap_first(table), struct cls_bucket, hmap_node);
807         return search_bucket(bucket, field_idx, target);
808     }
809
810     HMAP_FOR_EACH_WITH_HASH (bucket, struct cls_bucket, hmap_node,
811                              hash_fields(&target->flow, field_idx), table) {
812         struct cls_rule *rule = search_bucket(bucket, field_idx, target);
813         if (rule) {
814             return rule;
815         }
816     }
817     return NULL;
818 }
819
820 static struct cls_rule *
821 search_exact_table(const struct classifier *cls, size_t hash,
822                    const flow_t *target)
823 {
824     struct cls_rule *rule;
825
826     HMAP_FOR_EACH_WITH_HASH (rule, struct cls_rule, node.hmap,
827                              hash, &cls->exact_table) {
828         if (flow_equal(&rule->flow, target)) {
829             return rule;
830         }
831     }
832     return NULL;
833 }