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