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