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