classifier: Rename struct cls_table as cls_subtable.
[sliver-openvswitch.git] / lib / classifier.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 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 #include "ovs-thread.h"
29
30 static struct cls_subtable *find_subtable(const struct classifier *,
31                                           const struct minimask *);
32 static struct cls_subtable *insert_subtable(struct classifier *,
33                                             const struct minimask *);
34
35 static void destroy_subtable(struct classifier *, struct cls_subtable *);
36
37 static void update_subtables_after_insertion(struct classifier *,
38                                              struct cls_subtable *,
39                                              unsigned int new_priority);
40 static void update_subtables_after_removal(struct classifier *,
41                                            struct cls_subtable *,
42                                            unsigned int del_priority);
43
44 static struct cls_rule *find_match(const struct cls_subtable *,
45                                    const struct flow *);
46 static struct cls_rule *find_equal(struct cls_subtable *,
47                                    const struct miniflow *, uint32_t hash);
48 static struct cls_rule *insert_rule(struct classifier *,
49                                     struct cls_subtable *, struct cls_rule *);
50
51 /* Iterates RULE over HEAD and all of the cls_rules on HEAD->list. */
52 #define FOR_EACH_RULE_IN_LIST(RULE, HEAD)                               \
53     for ((RULE) = (HEAD); (RULE) != NULL; (RULE) = next_rule_in_list(RULE))
54 #define FOR_EACH_RULE_IN_LIST_SAFE(RULE, NEXT, HEAD)                    \
55     for ((RULE) = (HEAD);                                               \
56          (RULE) != NULL && ((NEXT) = next_rule_in_list(RULE), true);    \
57          (RULE) = (NEXT))
58
59 static struct cls_rule *next_rule_in_list__(struct cls_rule *);
60 static struct cls_rule *next_rule_in_list(struct cls_rule *);
61 \f
62 /* cls_rule. */
63
64 /* Initializes 'rule' to match packets specified by 'match' at the given
65  * 'priority'.  'match' must satisfy the invariant described in the comment at
66  * the definition of struct match.
67  *
68  * The caller must eventually destroy 'rule' with cls_rule_destroy().
69  *
70  * (OpenFlow uses priorities between 0 and UINT16_MAX, inclusive, but
71  * internally Open vSwitch supports a wider range.) */
72 void
73 cls_rule_init(struct cls_rule *rule,
74               const struct match *match, unsigned int priority)
75 {
76     minimatch_init(&rule->match, match);
77     rule->priority = priority;
78 }
79
80 /* Same as cls_rule_init() for initialization from a "struct minimatch". */
81 void
82 cls_rule_init_from_minimatch(struct cls_rule *rule,
83                              const struct minimatch *match,
84                              unsigned int priority)
85 {
86     minimatch_clone(&rule->match, match);
87     rule->priority = priority;
88 }
89
90 /* Initializes 'dst' as a copy of 'src'.
91  *
92  * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
93 void
94 cls_rule_clone(struct cls_rule *dst, const struct cls_rule *src)
95 {
96     minimatch_clone(&dst->match, &src->match);
97     dst->priority = src->priority;
98 }
99
100 /* Initializes 'dst' with the data in 'src', destroying 'src'.
101  *
102  * The caller must eventually destroy 'dst' with cls_rule_destroy(). */
103 void
104 cls_rule_move(struct cls_rule *dst, struct cls_rule *src)
105 {
106     minimatch_move(&dst->match, &src->match);
107     dst->priority = src->priority;
108 }
109
110 /* Frees memory referenced by 'rule'.  Doesn't free 'rule' itself (it's
111  * normally embedded into a larger structure).
112  *
113  * ('rule' must not currently be in a classifier.) */
114 void
115 cls_rule_destroy(struct cls_rule *rule)
116 {
117     minimatch_destroy(&rule->match);
118 }
119
120 /* Returns true if 'a' and 'b' match the same packets at the same priority,
121  * false if they differ in some way. */
122 bool
123 cls_rule_equal(const struct cls_rule *a, const struct cls_rule *b)
124 {
125     return a->priority == b->priority && minimatch_equal(&a->match, &b->match);
126 }
127
128 /* Returns a hash value for 'rule', folding in 'basis'. */
129 uint32_t
130 cls_rule_hash(const struct cls_rule *rule, uint32_t basis)
131 {
132     return minimatch_hash(&rule->match, hash_int(rule->priority, basis));
133 }
134
135 /* Appends a string describing 'rule' to 's'. */
136 void
137 cls_rule_format(const struct cls_rule *rule, struct ds *s)
138 {
139     minimatch_format(&rule->match, s, rule->priority);
140 }
141
142 /* Returns true if 'rule' matches every packet, false otherwise. */
143 bool
144 cls_rule_is_catchall(const struct cls_rule *rule)
145 {
146     return minimask_is_catchall(&rule->match.mask);
147 }
148 \f
149 /* Initializes 'cls' as a classifier that initially contains no classification
150  * rules. */
151 void
152 classifier_init(struct classifier *cls)
153 {
154     cls->n_rules = 0;
155     hmap_init(&cls->subtables);
156     list_init(&cls->subtables_priority);
157     hmap_init(&cls->partitions);
158     ovs_rwlock_init(&cls->rwlock);
159 }
160
161 /* Destroys 'cls'.  Rules within 'cls', if any, are not freed; this is the
162  * caller's responsibility. */
163 void
164 classifier_destroy(struct classifier *cls)
165 {
166     if (cls) {
167         struct cls_subtable *partition, *next_partition;
168         struct cls_subtable *subtable, *next_subtable;
169
170         HMAP_FOR_EACH_SAFE (subtable, next_subtable, hmap_node,
171                             &cls->subtables) {
172             destroy_subtable(cls, subtable);
173         }
174         hmap_destroy(&cls->subtables);
175
176         HMAP_FOR_EACH_SAFE (partition, next_partition, hmap_node,
177                             &cls->partitions) {
178             hmap_remove(&cls->partitions, &partition->hmap_node);
179             free(partition);
180         }
181         hmap_destroy(&cls->partitions);
182         ovs_rwlock_destroy(&cls->rwlock);
183     }
184 }
185
186 /* Returns true if 'cls' contains no classification rules, false otherwise. */
187 bool
188 classifier_is_empty(const struct classifier *cls)
189 {
190     return cls->n_rules == 0;
191 }
192
193 /* Returns the number of rules in 'cls'. */
194 int
195 classifier_count(const struct classifier *cls)
196 {
197     return cls->n_rules;
198 }
199
200 static uint32_t
201 hash_metadata(ovs_be64 metadata_)
202 {
203     uint64_t metadata = (OVS_FORCE uint64_t) metadata_;
204     return hash_2words(metadata, metadata >> 32);
205 }
206
207 static struct cls_partition *
208 find_partition(const struct classifier *cls, ovs_be64 metadata, uint32_t hash)
209 {
210     struct cls_partition *partition;
211
212     HMAP_FOR_EACH_IN_BUCKET (partition, hmap_node, hash, &cls->partitions) {
213         if (partition->metadata == metadata) {
214             return partition;
215         }
216     }
217
218     return NULL;
219 }
220
221 static struct cls_partition *
222 create_partition(struct classifier *cls, struct cls_subtable *subtable,
223                  ovs_be64 metadata)
224 {
225     uint32_t hash = hash_metadata(metadata);
226     struct cls_partition *partition = find_partition(cls, metadata, hash);
227     if (!partition) {
228         partition = xmalloc(sizeof *partition);
229         partition->metadata = metadata;
230         partition->tags = 0;
231         tag_tracker_init(&partition->tracker);
232         hmap_insert(&cls->partitions, &partition->hmap_node, hash);
233     }
234     tag_tracker_add(&partition->tracker, &partition->tags, subtable->tag);
235     return partition;
236 }
237
238 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
239  * must not modify or free it.
240  *
241  * If 'cls' already contains an identical rule (including wildcards, values of
242  * fixed fields, and priority), replaces the old rule by 'rule' and returns the
243  * rule that was replaced.  The caller takes ownership of the returned rule and
244  * is thus responsible for destroying it with cls_rule_destroy(), freeing the
245  * memory block in which it resides, etc., as necessary.
246  *
247  * Returns NULL if 'cls' does not contain a rule with an identical key, after
248  * inserting the new rule.  In this case, no rules are displaced by the new
249  * rule, even rules that cannot have any effect because the new rule matches a
250  * superset of their flows and has higher priority. */
251 struct cls_rule *
252 classifier_replace(struct classifier *cls, struct cls_rule *rule)
253 {
254     struct cls_rule *old_rule;
255     struct cls_subtable *subtable;
256
257     subtable = find_subtable(cls, &rule->match.mask);
258     if (!subtable) {
259         subtable = insert_subtable(cls, &rule->match.mask);
260     }
261
262     old_rule = insert_rule(cls, subtable, rule);
263     if (!old_rule) {
264         if (minimask_get_metadata_mask(&rule->match.mask) == OVS_BE64_MAX) {
265             ovs_be64 metadata = miniflow_get_metadata(&rule->match.flow);
266             rule->partition = create_partition(cls, subtable, metadata);
267         } else {
268             rule->partition = NULL;
269         }
270
271         subtable->n_rules++;
272         cls->n_rules++;
273     } else {
274         rule->partition = old_rule->partition;
275     }
276     return old_rule;
277 }
278
279 /* Inserts 'rule' into 'cls'.  Until 'rule' is removed from 'cls', the caller
280  * must not modify or free it.
281  *
282  * 'cls' must not contain an identical rule (including wildcards, values of
283  * fixed fields, and priority).  Use classifier_find_rule_exactly() to find
284  * such a rule. */
285 void
286 classifier_insert(struct classifier *cls, struct cls_rule *rule)
287 {
288     struct cls_rule *displaced_rule = classifier_replace(cls, rule);
289     ovs_assert(!displaced_rule);
290 }
291
292 /* Removes 'rule' from 'cls'.  It is the caller's responsibility to destroy
293  * 'rule' with cls_rule_destroy(), freeing the memory block in which 'rule'
294  * resides, etc., as necessary. */
295 void
296 classifier_remove(struct classifier *cls, struct cls_rule *rule)
297 {
298     struct cls_partition *partition;
299     struct cls_rule *head;
300     struct cls_subtable *subtable;
301
302     subtable = find_subtable(cls, &rule->match.mask);
303     head = find_equal(subtable, &rule->match.flow, rule->hmap_node.hash);
304     if (head != rule) {
305         list_remove(&rule->list);
306     } else if (list_is_empty(&rule->list)) {
307         hmap_remove(&subtable->rules, &rule->hmap_node);
308     } else {
309         struct cls_rule *next = CONTAINER_OF(rule->list.next,
310                                              struct cls_rule, list);
311
312         list_remove(&rule->list);
313         hmap_replace(&subtable->rules, &rule->hmap_node, &next->hmap_node);
314     }
315
316     partition = rule->partition;
317     if (partition) {
318         tag_tracker_subtract(&partition->tracker, &partition->tags,
319                              subtable->tag);
320         if (!partition->tags) {
321             hmap_remove(&cls->partitions, &partition->hmap_node);
322             free(partition);
323         }
324     }
325
326     if (--subtable->n_rules == 0) {
327         destroy_subtable(cls, subtable);
328     } else {
329         update_subtables_after_removal(cls, subtable, rule->priority);
330     }
331     cls->n_rules--;
332 }
333
334 /* Finds and returns the highest-priority rule in 'cls' that matches 'flow'.
335  * Returns a null pointer if no rules in 'cls' match 'flow'.  If multiple rules
336  * of equal priority match 'flow', returns one arbitrarily.
337  *
338  * If a rule is found and 'wc' is non-null, bitwise-OR's 'wc' with the
339  * set of bits that were significant in the lookup.  At some point
340  * earlier, 'wc' should have been initialized (e.g., by
341  * flow_wildcards_init_catchall()). */
342 struct cls_rule *
343 classifier_lookup(const struct classifier *cls, const struct flow *flow,
344                   struct flow_wildcards *wc)
345 {
346     const struct cls_partition *partition;
347     struct cls_subtable *subtable;
348     struct cls_rule *best;
349     tag_type tags;
350
351     /* Determine 'tags' such that, if 'subtable->tag' doesn't intersect them,
352      * then 'flow' cannot possibly match in 'subtable':
353      *
354      *     - If flow->metadata maps to a given 'partition', then we can use
355      *       'tags' for 'partition->tags'.
356      *
357      *     - If flow->metadata has no partition, then no rule in 'cls' has an
358      *       exact-match for flow->metadata.  That means that we don't need to
359      *       search any subtable that includes flow->metadata in its mask.
360      *
361      * In either case, we always need to search any cls_subtables that do not
362      * include flow->metadata in its mask.  One way to do that would be to
363      * check the "cls_subtable"s explicitly for that, but that would require an
364      * extra branch per subtable.  Instead, we mark such a cls_subtable's
365      * 'tags' as TAG_ALL and make sure that 'tags' is never empty.  This means
366      * that 'tags' always intersects such a cls_subtable's 'tags', so we don't
367      * need a special case.
368      */
369     partition = (hmap_is_empty(&cls->partitions)
370                  ? NULL
371                  : find_partition(cls, flow->metadata,
372                                   hash_metadata(flow->metadata)));
373     tags = partition ? partition->tags : TAG_ARBITRARY;
374
375     best = NULL;
376     LIST_FOR_EACH (subtable, list_node, &cls->subtables_priority) {
377         struct cls_rule *rule;
378
379         if (!tag_intersects(tags, subtable->tag)) {
380             continue;
381         }
382
383         rule = find_match(subtable, flow);
384         if (wc) {
385             flow_wildcards_fold_minimask(wc, &subtable->mask);
386         }
387         if (rule) {
388             best = rule;
389             LIST_FOR_EACH_CONTINUE (subtable, list_node,
390                                     &cls->subtables_priority) {
391                 if (subtable->max_priority <= best->priority) {
392                     /* Subtables are in descending priority order,
393                      * can not find anything better. */
394                     return best;
395                 }
396                 if (!tag_intersects(tags, subtable->tag)) {
397                     continue;
398                 }
399
400                 rule = find_match(subtable, flow);
401                 if (wc) {
402                     flow_wildcards_fold_minimask(wc, &subtable->mask);
403                 }
404                 if (rule && rule->priority > best->priority) {
405                     best = rule;
406                 }
407             }
408             break;
409         }
410     }
411     return best;
412 }
413
414 /* Finds and returns a rule in 'cls' with exactly the same priority and
415  * matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
416  * contain an exact match. */
417 struct cls_rule *
418 classifier_find_rule_exactly(const struct classifier *cls,
419                              const struct cls_rule *target)
420 {
421     struct cls_rule *head, *rule;
422     struct cls_subtable *subtable;
423
424     subtable = find_subtable(cls, &target->match.mask);
425     if (!subtable) {
426         return NULL;
427     }
428
429     /* Skip if there is no hope. */
430     if (target->priority > subtable->max_priority) {
431         return NULL;
432     }
433
434     head = find_equal(subtable, &target->match.flow,
435                       miniflow_hash_in_minimask(&target->match.flow,
436                                                 &target->match.mask, 0));
437     FOR_EACH_RULE_IN_LIST (rule, head) {
438         if (target->priority >= rule->priority) {
439             return target->priority == rule->priority ? rule : NULL;
440         }
441     }
442     return NULL;
443 }
444
445 /* Finds and returns a rule in 'cls' with priority 'priority' and exactly the
446  * same matching criteria as 'target'.  Returns a null pointer if 'cls' doesn't
447  * contain an exact match. */
448 struct cls_rule *
449 classifier_find_match_exactly(const struct classifier *cls,
450                               const struct match *target,
451                               unsigned int priority)
452 {
453     struct cls_rule *retval;
454     struct cls_rule cr;
455
456     cls_rule_init(&cr, target, priority);
457     retval = classifier_find_rule_exactly(cls, &cr);
458     cls_rule_destroy(&cr);
459
460     return retval;
461 }
462
463 /* Checks if 'target' would overlap any other rule in 'cls'.  Two rules are
464  * considered to overlap if both rules have the same priority and a packet
465  * could match both. */
466 bool
467 classifier_rule_overlaps(const struct classifier *cls,
468                          const struct cls_rule *target)
469 {
470     struct cls_subtable *subtable;
471
472     /* Iterate subtables in the descending max priority order. */
473     LIST_FOR_EACH (subtable, list_node, &cls->subtables_priority) {
474         uint32_t storage[FLOW_U32S];
475         struct minimask mask;
476         struct cls_rule *head;
477
478         if (target->priority > subtable->max_priority) {
479             break; /* Can skip this and the rest of the subtables. */
480         }
481
482         minimask_combine(&mask, &target->match.mask, &subtable->mask, storage);
483         HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
484             struct cls_rule *rule;
485
486             FOR_EACH_RULE_IN_LIST (rule, head) {
487                 if (rule->priority < target->priority) {
488                     break; /* Rules in descending priority order. */
489                 }
490                 if (rule->priority == target->priority
491                     && miniflow_equal_in_minimask(&target->match.flow,
492                                                   &rule->match.flow, &mask)) {
493                     return true;
494                 }
495             }
496         }
497     }
498
499     return false;
500 }
501
502 /* Returns true if 'rule' exactly matches 'criteria' or if 'rule' is more
503  * specific than 'criteria'.  That is, 'rule' matches 'criteria' and this
504  * function returns true if, for every field:
505  *
506  *   - 'criteria' and 'rule' specify the same (non-wildcarded) value for the
507  *     field, or
508  *
509  *   - 'criteria' wildcards the field,
510  *
511  * Conversely, 'rule' does not match 'criteria' and this function returns false
512  * if, for at least one field:
513  *
514  *   - 'criteria' and 'rule' specify different values for the field, or
515  *
516  *   - 'criteria' specifies a value for the field but 'rule' wildcards it.
517  *
518  * Equivalently, the truth table for whether a field matches is:
519  *
520  *                                     rule
521  *
522  *                   c         wildcard    exact
523  *                   r        +---------+---------+
524  *                   i   wild |   yes   |   yes   |
525  *                   t   card |         |         |
526  *                   e        +---------+---------+
527  *                   r  exact |    no   |if values|
528  *                   i        |         |are equal|
529  *                   a        +---------+---------+
530  *
531  * This is the matching rule used by OpenFlow 1.0 non-strict OFPT_FLOW_MOD
532  * commands and by OpenFlow 1.0 aggregate and flow stats.
533  *
534  * Ignores rule->priority. */
535 bool
536 cls_rule_is_loose_match(const struct cls_rule *rule,
537                         const struct minimatch *criteria)
538 {
539     return (!minimask_has_extra(&rule->match.mask, &criteria->mask)
540             && miniflow_equal_in_minimask(&rule->match.flow, &criteria->flow,
541                                           &criteria->mask));
542 }
543 \f
544 /* Iteration. */
545
546 static bool
547 rule_matches(const struct cls_rule *rule, const struct cls_rule *target)
548 {
549     return (!target
550             || miniflow_equal_in_minimask(&rule->match.flow,
551                                           &target->match.flow,
552                                           &target->match.mask));
553 }
554
555 static struct cls_rule *
556 search_subtable(const struct cls_subtable *subtable,
557                 const struct cls_rule *target)
558 {
559     if (!target || !minimask_has_extra(&subtable->mask, &target->match.mask)) {
560         struct cls_rule *rule;
561
562         HMAP_FOR_EACH (rule, hmap_node, &subtable->rules) {
563             if (rule_matches(rule, target)) {
564                 return rule;
565             }
566         }
567     }
568     return NULL;
569 }
570
571 /* Initializes 'cursor' for iterating through rules in 'cls':
572  *
573  *     - If 'target' is null, the cursor will visit every rule in 'cls'.
574  *
575  *     - If 'target' is nonnull, the cursor will visit each 'rule' in 'cls'
576  *       such that cls_rule_is_loose_match(rule, target) returns true.
577  *
578  * Ignores target->priority. */
579 void
580 cls_cursor_init(struct cls_cursor *cursor, const struct classifier *cls,
581                 const struct cls_rule *target)
582 {
583     cursor->cls = cls;
584     cursor->target = target && !cls_rule_is_catchall(target) ? target : NULL;
585 }
586
587 /* Returns the first matching cls_rule in 'cursor''s iteration, or a null
588  * pointer if there are no matches. */
589 struct cls_rule *
590 cls_cursor_first(struct cls_cursor *cursor)
591 {
592     struct cls_subtable *subtable;
593
594     HMAP_FOR_EACH (subtable, hmap_node, &cursor->cls->subtables) {
595         struct cls_rule *rule = search_subtable(subtable, cursor->target);
596         if (rule) {
597             cursor->subtable = subtable;
598             return rule;
599         }
600     }
601
602     return NULL;
603 }
604
605 /* Returns the next matching cls_rule in 'cursor''s iteration, or a null
606  * pointer if there are no more matches. */
607 struct cls_rule *
608 cls_cursor_next(struct cls_cursor *cursor, const struct cls_rule *rule_)
609 {
610     struct cls_rule *rule = CONST_CAST(struct cls_rule *, rule_);
611     const struct cls_subtable *subtable;
612     struct cls_rule *next;
613
614     next = next_rule_in_list__(rule);
615     if (next->priority < rule->priority) {
616         return next;
617     }
618
619     /* 'next' is the head of the list, that is, the rule that is included in
620      * the subtable's hmap.  (This is important when the classifier contains
621      * rules that differ only in priority.) */
622     rule = next;
623     HMAP_FOR_EACH_CONTINUE (rule, hmap_node, &cursor->subtable->rules) {
624         if (rule_matches(rule, cursor->target)) {
625             return rule;
626         }
627     }
628
629     subtable = cursor->subtable;
630     HMAP_FOR_EACH_CONTINUE (subtable, hmap_node, &cursor->cls->subtables) {
631         rule = search_subtable(subtable, cursor->target);
632         if (rule) {
633             cursor->subtable = subtable;
634             return rule;
635         }
636     }
637
638     return NULL;
639 }
640 \f
641 static struct cls_subtable *
642 find_subtable(const struct classifier *cls, const struct minimask *mask)
643 {
644     struct cls_subtable *subtable;
645
646     HMAP_FOR_EACH_IN_BUCKET (subtable, hmap_node, minimask_hash(mask, 0),
647                              &cls->subtables) {
648         if (minimask_equal(mask, &subtable->mask)) {
649             return subtable;
650         }
651     }
652     return NULL;
653 }
654
655 static struct cls_subtable *
656 insert_subtable(struct classifier *cls, const struct minimask *mask)
657 {
658     uint32_t hash = minimask_hash(mask, 0);
659     struct cls_subtable *subtable;
660
661     subtable = xzalloc(sizeof *subtable);
662     hmap_init(&subtable->rules);
663     minimask_clone(&subtable->mask, mask);
664     hmap_insert(&cls->subtables, &subtable->hmap_node, minimask_hash(mask, 0));
665     list_push_back(&cls->subtables_priority, &subtable->list_node);
666     subtable->tag = (minimask_get_metadata_mask(mask) == OVS_BE64_MAX
667                      ? tag_create_deterministic(hash)
668                      : TAG_ALL);
669
670     return subtable;
671 }
672
673 static void
674 destroy_subtable(struct classifier *cls, struct cls_subtable *subtable)
675 {
676     minimask_destroy(&subtable->mask);
677     hmap_remove(&cls->subtables, &subtable->hmap_node);
678     hmap_destroy(&subtable->rules);
679     list_remove(&subtable->list_node);
680     free(subtable);
681 }
682
683 /* This function performs the following updates for 'subtable' in 'cls'
684  * following the addition of a new rule with priority 'new_priority' to
685  * 'subtable':
686  *
687  *    - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
688  *
689  *    - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
690  *
691  * This function should only be called after adding a new rule, not after
692  * replacing a rule by an identical one or modifying a rule in-place. */
693 static void
694 update_subtables_after_insertion(struct classifier *cls,
695                                  struct cls_subtable *subtable,
696                                  unsigned int new_priority)
697 {
698     if (new_priority == subtable->max_priority) {
699         ++subtable->max_count;
700     } else if (new_priority > subtable->max_priority) {
701         struct cls_subtable *iter;
702
703         subtable->max_priority = new_priority;
704         subtable->max_count = 1;
705
706         /* Possibly move 'subtable' earlier in the priority list.  If we break
707          * out of the loop, then 'subtable' should be moved just after that
708          * 'iter'.  If the loop terminates normally, then 'iter' will be the
709          * list head and we'll move subtable just after that (e.g. to the front
710          * of the list). */
711         iter = subtable;
712         LIST_FOR_EACH_REVERSE_CONTINUE (iter, list_node,
713                                         &cls->subtables_priority) {
714             if (iter->max_priority >= subtable->max_priority) {
715                 break;
716             }
717         }
718
719         /* Move 'subtable' just after 'iter' (unless it's already there). */
720         if (iter->list_node.next != &subtable->list_node) {
721             list_splice(iter->list_node.next,
722                         &subtable->list_node, subtable->list_node.next);
723         }
724     }
725 }
726
727 /* This function performs the following updates for 'subtable' in 'cls'
728  * following the deletion of a rule with priority 'del_priority' from
729  * 'subtable':
730  *
731  *    - Update 'subtable->max_priority' and 'subtable->max_count' if necessary.
732  *
733  *    - Update 'subtable''s position in 'cls->subtables_priority' if necessary.
734  *
735  * This function should only be called after removing a rule, not after
736  * replacing a rule by an identical one or modifying a rule in-place. */
737 static void
738 update_subtables_after_removal(struct classifier *cls,
739                                struct cls_subtable *subtable,
740                                unsigned int del_priority)
741 {
742     struct cls_subtable *iter;
743
744     if (del_priority == subtable->max_priority && --subtable->max_count == 0) {
745         struct cls_rule *head;
746
747         subtable->max_priority = 0;
748         HMAP_FOR_EACH (head, hmap_node, &subtable->rules) {
749             if (head->priority > subtable->max_priority) {
750                 subtable->max_priority = head->priority;
751                 subtable->max_count = 1;
752             } else if (head->priority == subtable->max_priority) {
753                 ++subtable->max_count;
754             }
755         }
756
757         /* Possibly move 'subtable' later in the priority list.  If we break
758          * out of the loop, then 'subtable' should be moved just before that
759          * 'iter'.  If the loop terminates normally, then 'iter' will be the
760          * list head and we'll move subtable just before that (e.g. to the back
761          * of the list). */
762         iter = subtable;
763         LIST_FOR_EACH_CONTINUE (iter, list_node, &cls->subtables_priority) {
764             if (iter->max_priority <= subtable->max_priority) {
765                 break;
766             }
767         }
768
769         /* Move 'subtable' just before 'iter' (unless it's already there). */
770         if (iter->list_node.prev != &subtable->list_node) {
771             list_splice(&iter->list_node,
772                         &subtable->list_node, subtable->list_node.next);
773         }
774     }
775 }
776
777 static struct cls_rule *
778 find_match(const struct cls_subtable *subtable, const struct flow *flow)
779 {
780     uint32_t hash = flow_hash_in_minimask(flow, &subtable->mask, 0);
781     struct cls_rule *rule;
782
783     HMAP_FOR_EACH_WITH_HASH (rule, hmap_node, hash, &subtable->rules) {
784         if (minimatch_matches_flow(&rule->match, flow)) {
785             return rule;
786         }
787     }
788
789     return NULL;
790 }
791
792 static struct cls_rule *
793 find_equal(struct cls_subtable *subtable, const struct miniflow *flow,
794            uint32_t hash)
795 {
796     struct cls_rule *head;
797
798     HMAP_FOR_EACH_WITH_HASH (head, hmap_node, hash, &subtable->rules) {
799         if (miniflow_equal(&head->match.flow, flow)) {
800             return head;
801         }
802     }
803     return NULL;
804 }
805
806 static struct cls_rule *
807 insert_rule(struct classifier *cls, struct cls_subtable *subtable,
808             struct cls_rule *new)
809 {
810     struct cls_rule *head;
811     struct cls_rule *old = NULL;
812
813     new->hmap_node.hash = miniflow_hash_in_minimask(&new->match.flow,
814                                                     &new->match.mask, 0);
815
816     head = find_equal(subtable, &new->match.flow, new->hmap_node.hash);
817     if (!head) {
818         hmap_insert(&subtable->rules, &new->hmap_node, new->hmap_node.hash);
819         list_init(&new->list);
820         goto out;
821     } else {
822         /* Scan the list for the insertion point that will keep the list in
823          * order of decreasing priority. */
824         struct cls_rule *rule;
825         FOR_EACH_RULE_IN_LIST (rule, head) {
826             if (new->priority >= rule->priority) {
827                 if (rule == head) {
828                     /* 'new' is the new highest-priority flow in the list. */
829                     hmap_replace(&subtable->rules,
830                                  &rule->hmap_node, &new->hmap_node);
831                 }
832
833                 if (new->priority == rule->priority) {
834                     list_replace(&new->list, &rule->list);
835                     old = rule;
836                     goto out;
837                 } else {
838                     list_insert(&rule->list, &new->list);
839                     goto out;
840                 }
841             }
842         }
843
844         /* Insert 'new' at the end of the list. */
845         list_push_back(&head->list, &new->list);
846     }
847
848  out:
849     if (!old) {
850         update_subtables_after_insertion(cls, subtable, new->priority);
851     }
852     return old;
853 }
854
855 static struct cls_rule *
856 next_rule_in_list__(struct cls_rule *rule)
857 {
858     struct cls_rule *next = OBJECT_CONTAINING(rule->list.next, next, list);
859     return next;
860 }
861
862 static struct cls_rule *
863 next_rule_in_list(struct cls_rule *rule)
864 {
865     struct cls_rule *next = next_rule_in_list__(rule);
866     return next->priority < rule->priority ? next : NULL;
867 }