Setting tag sliver-openvswitch-2.2.90-1
[sliver-openvswitch.git] / lib / tag.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 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 "tag.h"
19
20 #define LOG2_N_TAG_BITS (N_TAG_BITS == 32 ? 5 : N_TAG_BITS == 64 ? 6 : 0)
21 BUILD_ASSERT_DECL(LOG2_N_TAG_BITS > 0);
22
23 /* Returns a tag deterministically generated from 'seed'.
24  *
25  * 'seed' should have data in all of its bits; if it has data only in its
26  * low-order bits then the resulting tags will be poorly distributed.  Use a
27  * hash function such as hash_bytes() to generate 'seed' if necessary. */
28 tag_type
29 tag_create_deterministic(uint32_t seed)
30 {
31     int x = seed & (N_TAG_BITS - 1);
32     int y = (seed >> LOG2_N_TAG_BITS) % (N_TAG_BITS - 1);
33     y += y >= x;
34     return (1u << x) | (1u << y);
35 }
36
37 /* Initializes 'tracker'. */
38 void
39 tag_tracker_init(struct tag_tracker *tracker)
40 {
41     memset(tracker, 0, sizeof *tracker);
42 }
43
44 /* Adds 'add' to '*tags' and records the bits added in 'tracker'. */
45 void
46 tag_tracker_add(struct tag_tracker *tracker, tag_type *tags, tag_type add)
47 {
48     *tags |= add;
49     for (; add; add = zero_rightmost_1bit(add)) {
50         tracker->counts[rightmost_1bit_idx(add)]++;
51     }
52 }
53
54 /* Removes 'sub' from 'tracker' and unsets any bits in '*tags' that no
55  * remaining tag includes. */
56 void
57 tag_tracker_subtract(struct tag_tracker *tracker, tag_type *tags, tag_type sub)
58 {
59     for (; sub; sub = zero_rightmost_1bit(sub)) {
60         if (!--tracker->counts[rightmost_1bit_idx(sub)]) {
61             *tags &= ~rightmost_1bit(sub);
62         }
63     }
64 }