classifier: Optimize iteration with a catch-all target rule.
[sliver-openvswitch.git] / lib / classifier.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012 Nicira, Inc.
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 "byte-order.h"
23 #include "dynamic-string.h"
24 #include "flow.h"
25 #include "hash.h"
26 #include "odp-util.h"
27 #include "ofp-util.h"
28 #include "packets.h"
29
30 static struct cls_table *find_table(const struct classifier *,
31                                     const struct flow_wildcards *);
32 static struct cls_table *insert_table(struct classifier *,
33                                       const struct flow_wildcards *);
34
35 static void destroy_table(struct classifier *, struct cls_table *);
36
37 static struct cls_rule *find_match(const struct cls_table *,
38                                    const struct flow *);
39 static struct cls_rule *find_equal(struct cls_table *, const struct flow *,
40                                    uint32_t hash);
41 static struct cls_rule *insert_rule(struct cls_table *, struct cls_rule *);
42
43 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
44 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD)                               \
45     for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
46 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD)                    \
47     for ((RULE) = (HEAD);                                               \
48          (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true);    \
49          (RULE) = (NEXT))
50
51 static struct cls_rule *next_rule_in_list__(struct cls_rule *);
52 static struct cls_rule *next_rule_in_list(struct cls_rule *);
53 \f
54 /* cls_rule. */
55
56 /* Initializes 'rule' to match packets specified by 'match' at the given
57  * 'priority'.
58  *
59  * The caller must eventually destroy 'rule' with cls_rule_destroy().
60  *
61  * 'match' must satisfy the invariant described in the comment at the
62  * definition of struct match.
63  *
64  * (OpenFlow uses priorities between 0 and UINT16_MAX, inclusive, but
65  * internally Open vSwitch supports a wider range.) */
66 void
67 cls_rule_init(struct cls_rule *rule,
68               const struct match *match, unsigned int priority)
69 {
70     rule->match = *match;
71     rule->priority = priority;
72 }
73
74 /* Initializes 'dst' as a copy of 'src'.
75  *
76  * The caller must eventually destroy 'rule' with cls_rule_destroy(). */
77 void
78 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
79 {
80     *dst = *src;
81 }
82
83 /* Frees memory referenced by 'rule'.  Doesn't free 'rule' itself (it's
84  * normally embedded into a larger structure).
85  *
86  * ('rule' must not currently be in a classifier.) */
87 void
88 cls_rule_destroy(struct cls_rule *rule OVS_UNUSED)
89 {
90     /* Nothing to do yet. */
91 }
92
93 /* Returns true if 'a' and 'b' match the same packets at the same priority,
94  * false if they differ in some way. */
95 bool
96 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
97 {
98     return a->priority == b->priority && match_equal(&a->match, &b->match);
99 }
100
101 /* Returns a hash value for 'rule', folding in 'basis'. */
102 uint32_t
103 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
104 {
105     return match_hash(&rule->match, hash_int(rule->priority, basis));
106 }
107
108 /* Appends a string describing 'rule' to 's'. */
109 void
110 cls_rule_format(const struct cls_rule *rule, struct ds *s)
111 {
112     match_format(&rule->match, s, rule->priority);
113 }
114
115 /* Returns true if 'rule' matches every packet, false otherwise. */
116 bool
117 cls_rule_is_catchall(const struct cls_rule *rule)
118 {
119     return flow_wildcards_is_catchall(&rule->match.wc);
120 }
121 \f
122 /* Initializes 'cls' as a classifier that initially contains no classification
123  * rules. */
124 void
125 classifier_init(struct classifier *cls)
126 {
127     cls->n_rules = 0;
128     hmap_init(&cls->tables);
129 }
130
131 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
132  * caller's responsibility. */
133 void
134 classifier_destroy(struct classifier *cls)
135 {
136     if (cls) {
137         struct cls_table *table, *next_table;
138
139         HMAP_FOR_EACH_SAFE (table, next_table, hmap_node, &cls->tables) {
140             hmap_destroy(&table->rules);
141             hmap_remove(&cls->tables, &table->hmap_node);
142             free(table);
143         }
144         hmap_destroy(&cls->tables);
145     }
146 }
147
148 /* Returns true if 'cls' contains no classification rules, false otherwise. */
149 bool
150 classifier_is_empty(const struct classifier *cls)
151 {
152     return cls->n_rules == 0;
153 }
154
155 /* Returns the number of rules in 'cls'. */
156 int
157 classifier_count(const struct classifier *cls)
158 {
159     return cls->n_rules;
160 }
161
162 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
163  * must not modify or free it.
164  *
165  * If 'cls' already contains an identical rule (including wildcards, values of
166  * fixed fields, and priority), replaces the old rule by 'rule' and returns the
167  * rule that was replaced.  The caller takes ownership of the returned rule and
168  * is thus responsible for destroying it with cls_rule_destroy(), freeing the
169  * memory block in which it resides, etc., as necessary.
170  *
171  * Returns NULL if 'cls' does not contain a rule with an identical key, after
172  * inserting the new rule.  In this case, no rules are displaced by the new
173  * rule, even rules that cannot have any effect because the new rule matches a
174  * superset of their flows and has higher priority. */
175 struct cls_rule *
176 classifier_replace(struct classifier *cls, struct cls_rule *rule)
177 {
178     struct cls_rule *old_rule;
179     struct cls_table *table;
180
181     table = find_table(cls, &rule->match.wc);
182     if (!table) {
183         table = insert_table(cls, &rule->match.wc);
184     }
185
186     old_rule = insert_rule(table, rule);
187     if (!old_rule) {
188         table->n_table_rules++;
189         cls->n_rules++;
190     }
191     return old_rule;
192 }
193
194 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
195  * must not modify or free it.
196  *
197  * 'cls' must not contain an identical rule (including wildcards, values of
198  * fixed fields, and priority).  Use classifier_find_rule_exactly() to find
199  * such a rule. */
200 void
201 classifier_insert(struct classifier *cls, struct cls_rule *rule)
202 {
203     struct cls_rule *displaced_rule = classifier_replace(cls, rule);
204     assert(!displaced_rule);
205 }
206
207 /* Removes 'rule' from 'cls'.  It is the caller's responsibility to destroy
208  * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
209  * resides, etc., as necessary. */
210 void
211 classifier_remove(struct classifier *cls, struct cls_rule *rule)
212 {
213     struct cls_rule *head;
214     struct cls_table *table;
215
216     table = find_table(cls, &rule->match.wc);
217     head = find_equal(table, &rule->match.flow, rule->hmap_node.hash);
218     if (head != rule) {
219         list_remove(&rule->list);
220     } else if (list_is_empty(&rule->list)) {
221         hmap_remove(&table->rules, &rule->hmap_node);
222     } else {
223         struct cls_rule *next = CONTAINER_OF(rule->list.next,
224                                              struct cls_rule, list);
225
226         list_remove(&rule->list);
227         hmap_replace(&table->rules, &rule->hmap_node, &next->hmap_node);
228     }
229
230     if (--table->n_table_rules == 0) {
231         destroy_table(cls, table);
232     }
233
234     cls->n_rules--;
235 }
236
237 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
238  * Returns a null pointer if no rules in 'cls' match 'flow'.  If multiple rules
239  * of equal priority match 'flow', returns one arbitrarily. */
240 struct cls_rule *
241 classifier_lookup(const struct classifier *cls, const struct flow *flow)
242 {
243     struct cls_table *table;
244     struct cls_rule *best;
245
246     best = NULL;
247     HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
248         struct cls_rule *rule = find_match(table, flow);
249         if (rule && (!best || rule->priority > best->priority)) {
250             best = rule;
251         }
252     }
253     return best;
254 }
255
256 /* Finds and returns a rule in 'cls' with exactly the same priority and
257  * matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
258  * contain an exact match. */
259 struct cls_rule *
260 classifier_find_rule_exactly(const struct classifier *cls,
261                              const struct cls_rule *target)
262 {
263     struct cls_rule *head, *rule;
264     struct cls_table *table;
265
266     table = find_table(cls, &target->match.wc);
267     if (!table) {
268         return NULL;
269     }
270
271     head = find_equal(table, &target->match.flow,
272                       flow_hash(&target->match.flow, 0));
273     FOR_EACH_RULE_IN_LIST (rule, head) {
274         if (target->priority >= rule->priority) {
275             return target->priority == rule->priority ? rule : NULL;
276         }
277     }
278     return NULL;
279 }
280
281 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
282  * same matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
283  * contain an exact match. */
284 struct cls_rule *
285 classifier_find_match_exactly(const struct classifier *cls,
286                               const struct match *target,
287                               unsigned int priority)
288 {
289     struct cls_rule *retval;
290     struct cls_rule cr;
291
292     cls_rule_init(&cr, target, priority);
293     retval = classifier_find_rule_exactly(cls, &cr);
294     cls_rule_destroy(&cr);
295
296     return retval;
297 }
298
299 /* Checks if 'target' would overlap any other rule in 'cls'.  Two rules are
300  * considered to overlap if both rules have the same priority and a packet
301  * could match both. */
302 bool
303 classifier_rule_overlaps(const struct classifier *cls,
304                          const struct cls_rule *target)
305 {
306     struct cls_table *table;
307
308     HMAP_FOR_EACH (table, hmap_node, &cls->tables) {
309         struct flow_wildcards wc;
310         struct cls_rule *head;
311
312         flow_wildcards_combine(&wc, &target->match.wc, &table->wc);
313         HMAP_FOR_EACH (head, hmap_node, &table->rules) {
314             struct cls_rule *rule;
315
316             FOR_EACH_RULE_IN_LIST (rule, head) {
317                 if (rule->priority == target->priority
318                     && flow_equal_except(&target->match.flow,
319                                          &rule->match.flow, &wc)) {
320                     return true;
321                 }
322             }
323         }
324     }
325
326     return false;
327 }
328
329 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
330  * specific than 'criteria'.  That is, 'rule' matches 'criteria' and this
331  * function returns true if, for every field:
332  *
333  *   - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
334  *     field, or
335  *
336  *   - 'criteria' wildcards the field,
337  *
338  * Conversely, 'rule' does not match 'criteria' and this function returns false
339  * if, for at least one field:
340  *
341  *   - 'criteria' and 'rule' specify different values for the field, or
342  *
343  *   - 'criteria' specifies a value for the field but 'rule' wildcards it.
344  *
345  * Equivalently, the truth table for whether a field matches is:
346  *
347  *                                     rule
348  *
349  *                   c         wildcard    exact
350  *                   r        +---------+---------+
351  *                   i   wild |   yes   |   yes   |
352  *                   t   card |         |         |
353  *                   e        +---------+---------+
354  *                   r  exact |    no   |if values|
355  *                   i        |         |are equal|
356  *                   a        +---------+---------+
357  *
358  * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
359  * commands and by OpenFlow 1.0 aggregate and flow stats.
360  *
361  * Ignores rule->priority. */
362 bool
363 cls_rule_is_loose_match(const struct cls_rule *rule,
364                         const struct match *criteria)
365 {
366     return (!flow_wildcards_has_extra(&rule->match.wc, &criteria->wc)
367             && flow_equal_except(&rule->match.flow, &criteria->flow,
368                                  &criteria->wc));
369 }
370 \f
371 /* Iteration. */
372
373 static bool
374 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
375 {
376     return (!target
377             || flow_equal_except(&rule->match.flow, &target->match.flow,
378                                  &target->match.wc));
379 }
380
381 static struct cls_rule *
382 search_table(const struct cls_table *table, const struct cls_rule *target)
383 {
384     if (!target || !flow_wildcards_has_extra(&table->wc, &target->match.wc)) {
385         struct cls_rule *rule;
386
387         HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
388             if (rule_matches(rule, target)) {
389                 return rule;
390             }
391         }
392     }
393     return NULL;
394 }
395
396 /* Initializes 'cursor' for iterating through rules in 'cls':
397  *
398  *     - If 'target' is null, the cursor will visit every rule in 'cls'.
399  *
400  *     - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
401  *       such that cls_rule_is_loose_match(rule, target) returns true.
402  *
403  * Ignores target->priority. */
404 void
405 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
406                 const struct cls_rule *target)
407 {
408     cursor->cls = cls;
409     cursor->target = target && !cls_rule_is_catchall(target) ? target : NULL;
410 }
411
412 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
413  * pointer if there are no matches. */
414 struct cls_rule *
415 cls_cursor_first(struct cls_cursor *cursor)
416 {
417     struct cls_table *table;
418
419     HMAP_FOR_EACH (table, hmap_node, &cursor->cls->tables) {
420         struct cls_rule *rule = search_table(table, cursor->target);
421         if (rule) {
422             cursor->table = table;
423             return rule;
424         }
425     }
426
427     return NULL;
428 }
429
430 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
431  * pointer if there are no more matches. */
432 struct cls_rule *
433 cls_cursor_next(struct cls_cursor *cursor, struct cls_rule *rule)
434 {
435     const struct cls_table *table;
436     struct cls_rule *next;
437
438     next = next_rule_in_list__(rule);
439     if (next->priority < rule->priority) {
440         return next;
441     }
442
443     /* 'next' is the head of the list, that is, the rule that is included in
444      * the table's hmap.  (This is important when the classifier contains rules
445      * that differ only in priority.) */
446     rule = next;
447     HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->table->rules) {
448         if (rule_matches(rule, cursor->target)) {
449             return rule;
450         }
451     }
452
453     table = cursor->table;
454     HMAP_FOR_EACH_CONTINUE (table, hmap_node, &cursor->cls->tables) {
455         rule = search_table(table, cursor->target);
456         if (rule) {
457             cursor->table = table;
458             return rule;
459         }
460     }
461
462     return NULL;
463 }
464 \f
465 static struct cls_table *
466 find_table(const struct classifier *cls, const struct flow_wildcards *wc)
467 {
468     struct cls_table *table;
469
470     HMAP_FOR_EACH_IN_BUCKET (table, hmap_node, flow_wildcards_hash(wc, 0),
471                              &cls->tables) {
472         if (flow_wildcards_equal(wc, &table->wc)) {
473             return table;
474         }
475     }
476     return NULL;
477 }
478
479 static struct cls_table *
480 insert_table(struct classifier *cls, const struct flow_wildcards *wc)
481 {
482     struct cls_table *table;
483
484     table = xzalloc(sizeof *table);
485     hmap_init(&table->rules);
486     table->wc = *wc;
487     table->is_catchall = flow_wildcards_is_catchall(&table->wc);
488     hmap_insert(&cls->tables, &table->hmap_node, flow_wildcards_hash(wc, 0));
489
490     return table;
491 }
492
493 static void
494 destroy_table(struct classifier *cls, struct cls_table *table)
495 {
496     hmap_remove(&cls->tables, &table->hmap_node);
497     hmap_destroy(&table->rules);
498     free(table);
499 }
500
501 static struct cls_rule *
502 find_match(const struct cls_table *table, const struct flow *flow)
503 {
504     struct cls_rule *rule;
505
506     if (table->is_catchall) {
507         HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
508             return rule;
509         }
510     } else {
511         struct flow f;
512
513         f = *flow;
514         flow_zero_wildcards(&f, &table->wc);
515         HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, flow_hash(&f, 0),
516                                  &table->rules) {
517             if (flow_equal(&f, &rule->match.flow)) {
518                 return rule;
519             }
520         }
521     }
522
523     return NULL;
524 }
525
526 static struct cls_rule *
527 find_equal(struct cls_table *table, const struct flow *flow, uint32_t hash)
528 {
529     struct cls_rule *head;
530
531     HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &table->rules) {
532         if (flow_equal(&head->match.flow, flow)) {
533             return head;
534         }
535     }
536     return NULL;
537 }
538
539 static struct cls_rule *
540 insert_rule(struct cls_table *table, struct cls_rule *new)
541 {
542     struct cls_rule *head;
543
544     new->hmap_node.hash = flow_hash(&new->match.flow, 0);
545
546     head = find_equal(table, &new->match.flow, new->hmap_node.hash);
547     if (!head) {
548         hmap_insert(&table->rules, &new->hmap_node, new->hmap_node.hash);
549         list_init(&new->list);
550         return NULL;
551     } else {
552         /* Scan the list for the insertion point that will keep the list in
553          * order of decreasing priority. */
554         struct cls_rule *rule;
555         FOR_EACH_RULE_IN_LIST (rule, head) {
556             if (new->priority >= rule->priority) {
557                 if (rule == head) {
558                     /* 'new' is the new highest-priority flow in the list. */
559                     hmap_replace(&table->rules,
560                                  &rule->hmap_node, &new->hmap_node);
561                 }
562
563                 if (new->priority == rule->priority) {
564                     list_replace(&new->list, &rule->list);
565                     return rule;
566                 } else {
567                     list_insert(&rule->list, &new->list);
568                     return NULL;
569                 }
570             }
571         }
572
573         /* Insert 'new' at the end of the list. */
574         list_push_back(&head->list, &new->list);
575         return NULL;
576     }
577 }
578
579 static struct cls_rule *
580 next_rule_in_list__(struct cls_rule *rule)
581 {
582     struct cls_rule *next = OBJECT_CONTAINING(rule->list.next, next, list);
583     return next;
584 }
585
586 static struct cls_rule *
587 next_rule_in_list(struct cls_rule *rule)
588 {
589     struct cls_rule *next = next_rule_in_list__(rule);
590     return next->priority < rule->priority ? next : NULL;
591 }