2 * test/set flag bits stored in conntrack extension area.
4 * (C) 2013 Astaro GmbH & Co KG
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2 as
8 * published by the Free Software Foundation.
11 #include <linux/export.h>
12 #include <linux/types.h>
14 #include <net/netfilter/nf_conntrack_ecache.h>
15 #include <net/netfilter/nf_conntrack_labels.h>
17 static spinlock_t nf_connlabels_lock
;
19 static unsigned int label_bits(const struct nf_conn_labels
*l
)
21 unsigned int longs
= l
->words
;
22 return longs
* BITS_PER_LONG
;
25 bool nf_connlabel_match(const struct nf_conn
*ct
, u16 bit
)
27 struct nf_conn_labels
*labels
= nf_ct_labels_find(ct
);
32 return bit
< label_bits(labels
) && test_bit(bit
, labels
->bits
);
34 EXPORT_SYMBOL_GPL(nf_connlabel_match
);
36 int nf_connlabel_set(struct nf_conn
*ct
, u16 bit
)
38 struct nf_conn_labels
*labels
= nf_ct_labels_find(ct
);
40 if (!labels
|| bit
>= label_bits(labels
))
43 if (test_bit(bit
, labels
->bits
))
46 if (!test_and_set_bit(bit
, labels
->bits
))
47 nf_conntrack_event_cache(IPCT_LABEL
, ct
);
51 EXPORT_SYMBOL_GPL(nf_connlabel_set
);
53 static void replace_u32(u32
*address
, u32 mask
, u32
new)
59 tmp
= (old
& mask
) ^ new;
60 } while (cmpxchg(address
, old
, tmp
) != old
);
63 int nf_connlabels_replace(struct nf_conn
*ct
,
65 const u32
*mask
, unsigned int words32
)
67 struct nf_conn_labels
*labels
;
71 labels
= nf_ct_labels_find(ct
);
75 size
= labels
->words
* sizeof(long);
76 if (size
< (words32
* sizeof(u32
)))
77 words32
= size
/ sizeof(u32
);
79 dst
= (u32
*) labels
->bits
;
81 for (i
= 0; i
< words32
; i
++)
82 replace_u32(&dst
[i
], mask
? ~mask
[i
] : 0, data
[i
]);
86 for (i
= words32
; i
< size
; i
++) /* pad */
87 replace_u32(&dst
[i
], 0, 0);
89 nf_conntrack_event_cache(IPCT_LABEL
, ct
);
92 EXPORT_SYMBOL_GPL(nf_connlabels_replace
);
94 int nf_connlabels_get(struct net
*net
, unsigned int n_bits
)
98 if (n_bits
> (NF_CT_LABELS_MAX_SIZE
* BITS_PER_BYTE
))
101 words
= BITS_TO_LONGS(n_bits
);
103 spin_lock(&nf_connlabels_lock
);
104 net
->ct
.labels_used
++;
105 if (words
> net
->ct
.label_words
)
106 net
->ct
.label_words
= words
;
107 spin_unlock(&nf_connlabels_lock
);
111 EXPORT_SYMBOL_GPL(nf_connlabels_get
);
113 void nf_connlabels_put(struct net
*net
)
115 spin_lock(&nf_connlabels_lock
);
116 net
->ct
.labels_used
--;
117 if (net
->ct
.labels_used
== 0)
118 net
->ct
.label_words
= 0;
119 spin_unlock(&nf_connlabels_lock
);
121 EXPORT_SYMBOL_GPL(nf_connlabels_put
);
123 static struct nf_ct_ext_type labels_extend __read_mostly
= {
124 .len
= sizeof(struct nf_conn_labels
),
125 .align
= __alignof__(struct nf_conn_labels
),
126 .id
= NF_CT_EXT_LABELS
,
129 int nf_conntrack_labels_init(void)
131 spin_lock_init(&nf_connlabels_lock
);
132 return nf_ct_extend_register(&labels_extend
);
135 void nf_conntrack_labels_fini(void)
137 nf_ct_extend_unregister(&labels_extend
);