classifier: Maintain tables in descending priority order.
[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     list_init(&cls->tables_priority);
138 }
139
140 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
141  * caller's responsibility. */
142 void
143 classifier_destroy(struct classifier *cls)
144 {
145     if (cls) {
146         struct cls_table *table, *next_table;
147
148         HMAP_FOR_EACH_SAFE (table, next_table, hmap_node, &cls->tables) {
149             destroy_table(cls, table);
150         }
151         hmap_destroy(&cls->tables);
152     }
153 }
154
155 /* Returns true if 'cls' contains no classification rules, false otherwise. */
156 bool
157 classifier_is_empty(const struct classifier *cls)
158 {
159     return cls->n_rules == 0;
160 }
161
162 /* Returns the number of rules in 'cls'. */
163 int
164 classifier_count(const struct classifier *cls)
165 {
166     return cls->n_rules;
167 }
168
169 static void
170 classifier_update_table_max_priority(struct classifier *cls,
171                                      struct cls_table *table,
172                                      unsigned int priority)
173 {
174     struct cls_table *iter = table;
175
176     if (priority > table->max_priority) {
177         /* Possibly move 'table' earlier in the priority list.  If we break out
178          * of the loop, then 'table' should be moved just after that 'iter'.
179          * If the loop terminates normally, then 'iter' will be the list head
180          * and we'll move table just after that (e.g. to the front of the
181          * list). */
182         LIST_FOR_EACH_REVERSE_CONTINUE (iter, list_node,
183                                         &cls->tables_priority) {
184             if (iter->max_priority >= priority) {
185                 break;
186             }
187         }
188
189         /* Move 'table' just after 'iter' (unless it's already there). */
190         if (iter->list_node.next != &table->list_node) {
191             list_splice(iter->list_node.next,
192                         &table->list_node, table->list_node.next);
193         }
194     } else if (priority < table->max_priority) {
195         /* Possibly move 'table' earlier in the priority list.  If we break out
196          * of the loop, then 'table' should be moved just before that 'iter'.
197          * If the loop terminates normally, then 'iter' will be the list head
198          * and we'll move table just before that (e.g. to the back of the
199          * list). */
200         LIST_FOR_EACH_CONTINUE (iter, list_node, &cls->tables_priority) {
201             if (iter->max_priority <= priority) {
202                 break;
203             }
204         }
205
206         /* Move 'table' just before 'iter' (unless it's already there). */
207         if (iter->list_node.prev != &table->list_node) {
208             list_splice(&iter->list_node,
209                         &table->list_node, table->list_node.next);
210         }
211     }
212     table->max_priority = priority;
213 }
214
215 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
216  * must not modify or free it.
217  *
218  * If 'cls' already contains an identical rule (including wildcards, values of
219  * fixed fields, and priority), replaces the old rule by 'rule' and returns the
220  * rule that was replaced.  The caller takes ownership of the returned rule and
221  * is thus responsible for destroying it with cls_rule_destroy(), freeing the
222  * memory block in which it resides, etc., as necessary.
223  *
224  * Returns NULL if 'cls' does not contain a rule with an identical key, after
225  * inserting the new rule.  In this case, no rules are displaced by the new
226  * rule, even rules that cannot have any effect because the new rule matches a
227  * superset of their flows and has higher priority. */
228 struct cls_rule *
229 classifier_replace(struct classifier *cls, struct cls_rule *rule)
230 {
231     struct cls_rule *old_rule;
232     struct cls_table *table;
233
234     table = find_table(cls, &rule->match.mask);
235     if (!table) {
236         table = insert_table(cls, &rule->match.mask);
237     }
238
239     old_rule = insert_rule(table, rule);
240
241     if (rule->priority > table->max_priority) {
242         classifier_update_table_max_priority(cls, table, rule->priority);
243         table->max_count = 1;
244     } else if (!old_rule && rule->priority == table->max_priority) {
245         /* Only if we are not replacing an old entry. */
246         ++table->max_count;
247     }
248
249     if (!old_rule) {
250         table->n_table_rules++;
251         cls->n_rules++;
252     }
253     return old_rule;
254 }
255
256 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
257  * must not modify or free it.
258  *
259  * 'cls' must not contain an identical rule (including wildcards, values of
260  * fixed fields, and priority).  Use classifier_find_rule_exactly() to find
261  * such a rule. */
262 void
263 classifier_insert(struct classifier *cls, struct cls_rule *rule)
264 {
265     struct cls_rule *displaced_rule = classifier_replace(cls, rule);
266     ovs_assert(!displaced_rule);
267 }
268
269 /* Removes 'rule' from 'cls'.  It is the caller's responsibility to destroy
270  * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
271  * resides, etc., as necessary. */
272 void
273 classifier_remove(struct classifier *cls, struct cls_rule *rule)
274 {
275     struct cls_rule *head;
276     struct cls_table *table;
277
278     table = find_table(cls, &rule->match.mask);
279     head = find_equal(table, &rule->match.flow, rule->hmap_node.hash);
280     if (head != rule) {
281         list_remove(&rule->list);
282     } else if (list_is_empty(&rule->list)) {
283         hmap_remove(&table->rules, &rule->hmap_node);
284     } else {
285         struct cls_rule *next = CONTAINER_OF(rule->list.next,
286                                              struct cls_rule, list);
287
288         list_remove(&rule->list);
289         hmap_replace(&table->rules, &rule->hmap_node, &next->hmap_node);
290     }
291
292     if (--table->n_table_rules == 0) {
293         destroy_table(cls, table);
294     } else if (rule->priority == table->max_priority
295                && --table->max_count == 0) {
296         /* Maintain table's max_priority. */
297         struct cls_rule *head;
298         unsigned int new_max_priority = 0;
299         HMAP_FOR_EACH (head, hmap_node, &table->rules) {
300             if (head->priority > new_max_priority) {
301                 new_max_priority = head->priority;
302                 table->max_count = 1;
303             } else if (head->priority == new_max_priority) {
304                 ++table->max_count;
305             }
306         }
307         classifier_update_table_max_priority(cls, table, new_max_priority);
308     }
309     cls->n_rules--;
310 }
311
312 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
313  * Returns a null pointer if no rules in 'cls' match 'flow'.  If multiple rules
314  * of equal priority match 'flow', returns one arbitrarily. */
315 struct cls_rule *
316 classifier_lookup(const struct classifier *cls, const struct flow *flow)
317 {
318     struct cls_table *table;
319     struct cls_rule *best;
320
321     best = NULL;
322     LIST_FOR_EACH (table, list_node, &cls->tables_priority) {
323         struct cls_rule *rule = find_match(table, flow);
324         if (rule) {
325             best = rule;
326             LIST_FOR_EACH_CONTINUE (table, list_node, &cls->tables_priority) {
327                 if (table->max_priority <= best->priority) {
328                     /* Tables in descending priority order,
329                      * can not find anything better. */
330                     return best;
331                 }
332                 rule = find_match(table, flow);
333                 if (rule && rule->priority > best->priority) {
334                     best = rule;
335                 }
336             }
337             break;
338         }
339     }
340     return best;
341 }
342
343 /* Finds and returns a rule in 'cls' with exactly the same priority and
344  * matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
345  * contain an exact match. */
346 struct cls_rule *
347 classifier_find_rule_exactly(const struct classifier *cls,
348                              const struct cls_rule *target)
349 {
350     struct cls_rule *head, *rule;
351     struct cls_table *table;
352
353     table = find_table(cls, &target->match.mask);
354     if (!table) {
355         return NULL;
356     }
357
358     /* Skip if there is no hope. */
359     if (target->priority > table->max_priority) {
360         return NULL;
361     }
362
363     head = find_equal(table, &target->match.flow,
364                       miniflow_hash_in_minimask(&target->match.flow,
365                                                 &target->match.mask, 0));
366     FOR_EACH_RULE_IN_LIST (rule, head) {
367         if (target->priority >= rule->priority) {
368             return target->priority == rule->priority ? rule : NULL;
369         }
370     }
371     return NULL;
372 }
373
374 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
375  * same matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
376  * contain an exact match. */
377 struct cls_rule *
378 classifier_find_match_exactly(const struct classifier *cls,
379                               const struct match *target,
380                               unsigned int priority)
381 {
382     struct cls_rule *retval;
383     struct cls_rule cr;
384
385     cls_rule_init(&cr, target, priority);
386     retval = classifier_find_rule_exactly(cls, &cr);
387     cls_rule_destroy(&cr);
388
389     return retval;
390 }
391
392 /* Checks if 'target' would overlap any other rule in 'cls'.  Two rules are
393  * considered to overlap if both rules have the same priority and a packet
394  * could match both. */
395 bool
396 classifier_rule_overlaps(const struct classifier *cls,
397                          const struct cls_rule *target)
398 {
399     struct cls_table *table;
400
401     /* Iterate tables in the descending max priority order. */
402     LIST_FOR_EACH (table, list_node, &cls->tables_priority) {
403         uint32_t storage[FLOW_U32S];
404         struct minimask mask;
405         struct cls_rule *head;
406
407         if (target->priority > table->max_priority) {
408             break; /* Can skip this and the rest of the tables. */
409         }
410
411         minimask_combine(&mask, &target->match.mask, &table->mask, storage);
412         HMAP_FOR_EACH (head, hmap_node, &table->rules) {
413             struct cls_rule *rule;
414
415             FOR_EACH_RULE_IN_LIST (rule, head) {
416                 if (rule->priority < target->priority) {
417                     break; /* Rules in descending priority order. */
418                 }
419                 if (rule->priority == target->priority
420                     && miniflow_equal_in_minimask(&target->match.flow,
421                                                   &rule->match.flow, &mask)) {
422                     return true;
423                 }
424             }
425         }
426     }
427
428     return false;
429 }
430
431 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
432  * specific than 'criteria'.  That is, 'rule' matches 'criteria' and this
433  * function returns true if, for every field:
434  *
435  *   - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
436  *     field, or
437  *
438  *   - 'criteria' wildcards the field,
439  *
440  * Conversely, 'rule' does not match 'criteria' and this function returns false
441  * if, for at least one field:
442  *
443  *   - 'criteria' and 'rule' specify different values for the field, or
444  *
445  *   - 'criteria' specifies a value for the field but 'rule' wildcards it.
446  *
447  * Equivalently, the truth table for whether a field matches is:
448  *
449  *                                     rule
450  *
451  *                   c         wildcard    exact
452  *                   r        +---------+---------+
453  *                   i   wild |   yes   |   yes   |
454  *                   t   card |         |         |
455  *                   e        +---------+---------+
456  *                   r  exact |    no   |if values|
457  *                   i        |         |are equal|
458  *                   a        +---------+---------+
459  *
460  * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
461  * commands and by OpenFlow 1.0 aggregate and flow stats.
462  *
463  * Ignores rule->priority. */
464 bool
465 cls_rule_is_loose_match(const struct cls_rule *rule,
466                         const struct minimatch *criteria)
467 {
468     return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
469             && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
470                                           &criteria->mask));
471 }
472 \f
473 /* Iteration. */
474
475 static bool
476 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
477 {
478     return (!target
479             || miniflow_equal_in_minimask(&rule->match.flow,
480                                           &target->match.flow,
481                                           &target->match.mask));
482 }
483
484 static struct cls_rule *
485 search_table(const struct cls_table *table, const struct cls_rule *target)
486 {
487     if (!target || !minimask_has_extra(&table->mask, &target->match.mask)) {
488         struct cls_rule *rule;
489
490         HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
491             if (rule_matches(rule, target)) {
492                 return rule;
493             }
494         }
495     }
496     return NULL;
497 }
498
499 /* Initializes 'cursor' for iterating through rules in 'cls':
500  *
501  *     - If 'target' is null, the cursor will visit every rule in 'cls'.
502  *
503  *     - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
504  *       such that cls_rule_is_loose_match(rule, target) returns true.
505  *
506  * Ignores target->priority. */
507 void
508 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
509                 const struct cls_rule *target)
510 {
511     cursor->cls = cls;
512     cursor->target = target && !cls_rule_is_catchall(target) ? target : NULL;
513 }
514
515 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
516  * pointer if there are no matches. */
517 struct cls_rule *
518 cls_cursor_first(struct cls_cursor *cursor)
519 {
520     struct cls_table *table;
521
522     HMAP_FOR_EACH (table, hmap_node, &cursor->cls->tables) {
523         struct cls_rule *rule = search_table(table, cursor->target);
524         if (rule) {
525             cursor->table = table;
526             return rule;
527         }
528     }
529
530     return NULL;
531 }
532
533 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
534  * pointer if there are no more matches. */
535 struct cls_rule *
536 cls_cursor_next(struct cls_cursor *cursor, struct cls_rule *rule)
537 {
538     const struct cls_table *table;
539     struct cls_rule *next;
540
541     next = next_rule_in_list__(rule);
542     if (next->priority < rule->priority) {
543         return next;
544     }
545
546     /* 'next' is the head of the list, that is, the rule that is included in
547      * the table's hmap.  (This is important when the classifier contains rules
548      * that differ only in priority.) */
549     rule = next;
550     HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->table->rules) {
551         if (rule_matches(rule, cursor->target)) {
552             return rule;
553         }
554     }
555
556     table = cursor->table;
557     HMAP_FOR_EACH_CONTINUE (table, hmap_node, &cursor->cls->tables) {
558         rule = search_table(table, cursor->target);
559         if (rule) {
560             cursor->table = table;
561             return rule;
562         }
563     }
564
565     return NULL;
566 }
567 \f
568 static struct cls_table *
569 find_table(const struct classifier *cls, const struct minimask *mask)
570 {
571     struct cls_table *table;
572
573     HMAP_FOR_EACH_IN_BUCKET (table, hmap_node, minimask_hash(mask, 0),
574                              &cls->tables) {
575         if (minimask_equal(mask, &table->mask)) {
576             return table;
577         }
578     }
579     return NULL;
580 }
581
582 static struct cls_table *
583 insert_table(struct classifier *cls, const struct minimask *mask)
584 {
585     struct cls_table *table;
586
587     table = xzalloc(sizeof *table);
588     hmap_init(&table->rules);
589     minimask_clone(&table->mask, mask);
590     hmap_insert(&cls->tables, &table->hmap_node, minimask_hash(mask, 0));
591     list_push_back(&cls->tables_priority, &table->list_node);
592
593     return table;
594 }
595
596 static void
597 destroy_table(struct classifier *cls, struct cls_table *table)
598 {
599     minimask_destroy(&table->mask);
600     hmap_remove(&cls->tables, &table->hmap_node);
601     hmap_destroy(&table->rules);
602     list_remove(&table->list_node);
603     free(table);
604 }
605
606 static struct cls_rule *
607 find_match(const struct cls_table *table, const struct flow *flow)
608 {
609     uint32_t hash = flow_hash_in_minimask(flow, &table->mask, 0);
610     struct cls_rule *rule;
611
612     HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &table->rules) {
613         if (miniflow_equal_flow_in_minimask(&rule->match.flow, flow,
614                                             &table->mask)) {
615             return rule;
616         }
617     }
618
619     return NULL;
620 }
621
622 static struct cls_rule *
623 find_equal(struct cls_table *table, const struct miniflow *flow, uint32_t hash)
624 {
625     struct cls_rule *head;
626
627     HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &table->rules) {
628         if (miniflow_equal(&head->match.flow, flow)) {
629             return head;
630         }
631     }
632     return NULL;
633 }
634
635 static struct cls_rule *
636 insert_rule(struct cls_table *table, struct cls_rule *new)
637 {
638     struct cls_rule *head;
639
640     new->hmap_node.hash = miniflow_hash_in_minimask(&new->match.flow,
641                                                     &new->match.mask, 0);
642
643     head = find_equal(table, &new->match.flow, new->hmap_node.hash);
644     if (!head) {
645         hmap_insert(&table->rules, &new->hmap_node, new->hmap_node.hash);
646         list_init(&new->list);
647         return NULL;
648     } else {
649         /* Scan the list for the insertion point that will keep the list in
650          * order of decreasing priority. */
651         struct cls_rule *rule;
652         FOR_EACH_RULE_IN_LIST (rule, head) {
653             if (new->priority >= rule->priority) {
654                 if (rule == head) {
655                     /* 'new' is the new highest-priority flow in the list. */
656                     hmap_replace(&table->rules,
657                                  &rule->hmap_node, &new->hmap_node);
658                 }
659
660                 if (new->priority == rule->priority) {
661                     list_replace(&new->list, &rule->list);
662                     return rule;
663                 } else {
664                     list_insert(&rule->list, &new->list);
665                     return NULL;
666                 }
667             }
668         }
669
670         /* Insert 'new' at the end of the list. */
671         list_push_back(&head->list, &new->list);
672         return NULL;
673     }
674 }
675
676 static struct cls_rule *
677 next_rule_in_list__(struct cls_rule *rule)
678 {
679     struct cls_rule *next = OBJECT_CONTAINING(rule->list.next, next, list);
680     return next;
681 }
682
683 static struct cls_rule *
684 next_rule_in_list(struct cls_rule *rule)
685 {
686     struct cls_rule *next = next_rule_in_list__(rule);
687     return next->priority < rule->priority ? next : NULL;
688 }