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