datapath: Add NULL check for mask pointer.
[cascardo/ovs.git] / datapath / flow_table.c
1 /*
2  * Copyright (c) 2007-2013 Nicira, Inc.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of version 2 of the GNU General Public
6  * License as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program; if not, write to the Free Software
15  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16  * 02110-1301, USA
17  */
18
19 #include "flow.h"
20 #include "datapath.h"
21 #include <linux/uaccess.h>
22 #include <linux/netdevice.h>
23 #include <linux/etherdevice.h>
24 #include <linux/if_ether.h>
25 #include <linux/if_vlan.h>
26 #include <net/llc_pdu.h>
27 #include <linux/kernel.h>
28 #include <linux/hash.h>
29 #include <linux/jiffies.h>
30 #include <linux/llc.h>
31 #include <linux/module.h>
32 #include <linux/in.h>
33 #include <linux/rcupdate.h>
34 #include <linux/if_arp.h>
35 #include <linux/ip.h>
36 #include <linux/ipv6.h>
37 #include <linux/sctp.h>
38 #include <linux/tcp.h>
39 #include <linux/udp.h>
40 #include <linux/icmp.h>
41 #include <linux/icmpv6.h>
42 #include <linux/rculist.h>
43 #include <net/ip.h>
44 #include <net/ipv6.h>
45 #include <net/ndisc.h>
46
47 #include "vlan.h"
48
49 #define TBL_MIN_BUCKETS         1024
50 #define MASK_ARRAY_SIZE_MIN     16
51 #define REHASH_INTERVAL         (10 * 60 * HZ)
52
53 #define MC_HASH_SHIFT           8
54 #define MC_HASH_ENTRIES         (1u << MC_HASH_SHIFT)
55 #define MC_HASH_SEGS            ((sizeof(uint32_t) * 8) / MC_HASH_SHIFT)
56
57 static struct kmem_cache *flow_cache;
58 struct kmem_cache *flow_stats_cache __read_mostly;
59
60 static u16 range_n_bytes(const struct sw_flow_key_range *range)
61 {
62         return range->end - range->start;
63 }
64
65 void ovs_flow_mask_key(struct sw_flow_key *dst, const struct sw_flow_key *src,
66                        const struct sw_flow_mask *mask)
67 {
68         const long *m = (const long *)((const u8 *)&mask->key +
69                                 mask->range.start);
70         const long *s = (const long *)((const u8 *)src +
71                                 mask->range.start);
72         long *d = (long *)((u8 *)dst + mask->range.start);
73         int i;
74
75         /* The memory outside of the 'mask->range' are not set since
76          * further operations on 'dst' only uses contents within
77          * 'mask->range'.
78          */
79         for (i = 0; i < range_n_bytes(&mask->range); i += sizeof(long))
80                 *d++ = *s++ & *m++;
81 }
82
83 struct sw_flow *ovs_flow_alloc(void)
84 {
85         struct sw_flow *flow;
86         struct flow_stats *stats;
87         int node;
88
89         flow = kmem_cache_alloc(flow_cache, GFP_KERNEL);
90         if (!flow)
91                 return ERR_PTR(-ENOMEM);
92
93         flow->sf_acts = NULL;
94         flow->mask = NULL;
95         flow->stats_last_writer = NUMA_NO_NODE;
96
97         /* Initialize the default stat node. */
98         stats = kmem_cache_alloc_node(flow_stats_cache,
99                                       GFP_KERNEL | __GFP_ZERO, 0);
100         if (!stats)
101                 goto err;
102
103         spin_lock_init(&stats->lock);
104
105         RCU_INIT_POINTER(flow->stats[0], stats);
106
107         for_each_node(node)
108                 if (node != 0)
109                         RCU_INIT_POINTER(flow->stats[node], NULL);
110
111         return flow;
112 err:
113         kmem_cache_free(flow_cache, flow);
114         return ERR_PTR(-ENOMEM);
115 }
116
117 int ovs_flow_tbl_count(struct flow_table *table)
118 {
119         return table->count;
120 }
121
122 static struct flex_array *alloc_buckets(unsigned int n_buckets)
123 {
124         struct flex_array *buckets;
125         int i, err;
126
127         buckets = flex_array_alloc(sizeof(struct hlist_head),
128                                    n_buckets, GFP_KERNEL);
129         if (!buckets)
130                 return NULL;
131
132         err = flex_array_prealloc(buckets, 0, n_buckets, GFP_KERNEL);
133         if (err) {
134                 flex_array_free(buckets);
135                 return NULL;
136         }
137
138         for (i = 0; i < n_buckets; i++)
139                 INIT_HLIST_HEAD((struct hlist_head *)
140                                         flex_array_get(buckets, i));
141
142         return buckets;
143 }
144
145 static void flow_free(struct sw_flow *flow)
146 {
147         int node;
148
149         kfree((struct sw_flow_actions __force *)flow->sf_acts);
150         for_each_node(node)
151                 if (flow->stats[node])
152                         kmem_cache_free(flow_stats_cache,
153                                         (struct flow_stats __force *)flow->stats[node]);
154         kmem_cache_free(flow_cache, flow);
155 }
156
157 static void rcu_free_flow_callback(struct rcu_head *rcu)
158 {
159         struct sw_flow *flow = container_of(rcu, struct sw_flow, rcu);
160
161         flow_free(flow);
162 }
163
164 static void rcu_free_sw_flow_mask_cb(struct rcu_head *rcu)
165 {
166         struct sw_flow_mask *mask = container_of(rcu, struct sw_flow_mask, rcu);
167
168         kfree(mask);
169 }
170
171 void ovs_flow_free(struct sw_flow *flow, bool deferred)
172 {
173         if (!flow)
174                 return;
175
176         if (deferred)
177                 call_rcu(&flow->rcu, rcu_free_flow_callback);
178         else
179                 flow_free(flow);
180 }
181
182 static void free_buckets(struct flex_array *buckets)
183 {
184         flex_array_free(buckets);
185 }
186
187
188 static void __table_instance_destroy(struct table_instance *ti)
189 {
190         free_buckets(ti->buckets);
191         kfree(ti);
192 }
193
194 static struct table_instance *table_instance_alloc(int new_size)
195 {
196         struct table_instance *ti = kmalloc(sizeof(*ti), GFP_KERNEL);
197
198         if (!ti)
199                 return NULL;
200
201         ti->buckets = alloc_buckets(new_size);
202
203         if (!ti->buckets) {
204                 kfree(ti);
205                 return NULL;
206         }
207         ti->n_buckets = new_size;
208         ti->node_ver = 0;
209         ti->keep_flows = false;
210         get_random_bytes(&ti->hash_seed, sizeof(u32));
211
212         return ti;
213 }
214
215 static void mask_array_rcu_cb(struct rcu_head *rcu)
216 {
217         struct mask_array *ma = container_of(rcu, struct mask_array, rcu);
218
219         kfree(ma);
220 }
221
222 static struct mask_array *tbl_mask_array_alloc(int size)
223 {
224         struct mask_array *new;
225
226         new = kzalloc(sizeof(struct mask_array) +
227                       sizeof(struct sw_flow_mask *) * size, GFP_KERNEL);
228         if (!new)
229                 return NULL;
230
231         new->count = 0;
232         new->max = size;
233
234         return new;
235 }
236
237 static int tbl_mask_array_realloc(struct flow_table *tbl, int size)
238 {
239         struct mask_array *old;
240         struct mask_array *new;
241
242         new = tbl_mask_array_alloc(size);
243         if (!new)
244                 return -ENOMEM;
245
246         old = ovsl_dereference(tbl->mask_array);
247         if (old) {
248                 int i;
249
250                 for (i = 0; i < old->max; i++)
251                         new->masks[i] = old->masks[i];
252
253                 new->count = old->count;
254         }
255         rcu_assign_pointer(tbl->mask_array, new);
256
257         if (old)
258                 call_rcu(&old->rcu, mask_array_rcu_cb);
259
260         return 0;
261 }
262
263 static void tbl_mask_array_delete_mask(struct mask_array *ma,
264                                        const struct sw_flow_mask *mask)
265 {
266         int i = 0;
267
268         /* Delete a mask pointer from the valid section.
269          *
270          * Also move the last entry in its place, so there is no
271          * whole in the valid section.
272          *
273          * Notice the last entry still points to the original mask.
274          *
275          * <Note>: there is a small race window that may cause a mask
276          * to be missed in a search. Imaging a core is
277          * walking through the array, passing the index of deleting mask.
278          * But before reaching the last entry, it is overwritten,
279          * by another core that is adding a new mask, now the last entry
280          * will point to the new mask. In this case, the moved up last
281          * entry can be missed by the core walking the mask array.
282          *
283          * In case this missed mask would have led to successful
284          * lookup, Hitting the race window could cause a packet to miss
285          * kernel flow cache, and be sent to the user space.
286          * </Note>
287          */
288         for (i = 0; i < ma->count; i++)
289                 if (mask == ovsl_dereference(ma->masks[i])) {
290                         struct sw_flow_mask *last;
291
292                         last = ovsl_dereference(ma->masks[ma->count - 1]);
293                         rcu_assign_pointer(ma->masks[i], last);
294                         ma->count--;
295                         break;
296                 }
297
298         /* Remove the deleted mask pointers from the invalid section. */
299         for (i = ma->count; i < ma->max; i++)
300                 if (mask == ovsl_dereference(ma->masks[i]))
301                         RCU_INIT_POINTER(ma->masks[i], NULL);
302 }
303
304 int ovs_flow_tbl_init(struct flow_table *table)
305 {
306         struct table_instance *ti;
307         struct mask_array *ma;
308
309         table->mask_cache = __alloc_percpu(sizeof(struct mask_cache_entry) *
310                                           MC_HASH_ENTRIES, __alignof__(struct mask_cache_entry));
311         if (!table->mask_cache)
312                 return -ENOMEM;
313
314         ma = tbl_mask_array_alloc(MASK_ARRAY_SIZE_MIN);
315         if (!ma)
316                 goto free_mask_cache;
317
318         ti = table_instance_alloc(TBL_MIN_BUCKETS);
319         if (!ti)
320                 goto free_mask_array;
321
322         rcu_assign_pointer(table->ti, ti);
323         rcu_assign_pointer(table->mask_array, ma);
324         table->last_rehash = jiffies;
325         table->count = 0;
326         return 0;
327
328 free_mask_array:
329         kfree((struct mask_array __force *)table->mask_array);
330 free_mask_cache:
331         free_percpu(table->mask_cache);
332         return -ENOMEM;
333 }
334
335 static void flow_tbl_destroy_rcu_cb(struct rcu_head *rcu)
336 {
337         struct table_instance *ti = container_of(rcu, struct table_instance, rcu);
338
339         __table_instance_destroy(ti);
340 }
341
342 static void table_instance_destroy(struct table_instance *ti, bool deferred)
343 {
344         int i;
345
346         if (!ti)
347                 return;
348
349         if (ti->keep_flows)
350                 goto skip_flows;
351
352         for (i = 0; i < ti->n_buckets; i++) {
353                 struct sw_flow *flow;
354                 struct hlist_head *head = flex_array_get(ti->buckets, i);
355                 struct hlist_node *n;
356                 int ver = ti->node_ver;
357
358                 hlist_for_each_entry_safe(flow, n, head, hash_node[ver]) {
359                         hlist_del_rcu(&flow->hash_node[ver]);
360                         ovs_flow_free(flow, deferred);
361                 }
362         }
363
364 skip_flows:
365         if (deferred)
366                 call_rcu(&ti->rcu, flow_tbl_destroy_rcu_cb);
367         else
368                 __table_instance_destroy(ti);
369 }
370
371 /* No need for locking this function is called from RCU callback or
372  * error path. */
373 void ovs_flow_tbl_destroy(struct flow_table *table)
374 {
375         struct table_instance *ti = (struct table_instance __force *)table->ti;
376
377         free_percpu(table->mask_cache);
378         kfree((struct mask_array __force *)table->mask_array);
379         table_instance_destroy(ti, false);
380 }
381
382 struct sw_flow *ovs_flow_tbl_dump_next(struct table_instance *ti,
383                                        u32 *bucket, u32 *last)
384 {
385         struct sw_flow *flow;
386         struct hlist_head *head;
387         int ver;
388         int i;
389
390         ver = ti->node_ver;
391         while (*bucket < ti->n_buckets) {
392                 i = 0;
393                 head = flex_array_get(ti->buckets, *bucket);
394                 hlist_for_each_entry_rcu(flow, head, hash_node[ver]) {
395                         if (i < *last) {
396                                 i++;
397                                 continue;
398                         }
399                         *last = i + 1;
400                         return flow;
401                 }
402                 (*bucket)++;
403                 *last = 0;
404         }
405
406         return NULL;
407 }
408
409 static struct hlist_head *find_bucket(struct table_instance *ti, u32 hash)
410 {
411         hash = jhash_1word(hash, ti->hash_seed);
412         return flex_array_get(ti->buckets,
413                                 (hash & (ti->n_buckets - 1)));
414 }
415
416 static void table_instance_insert(struct table_instance *ti, struct sw_flow *flow)
417 {
418         struct hlist_head *head;
419
420         head = find_bucket(ti, flow->hash);
421         hlist_add_head_rcu(&flow->hash_node[ti->node_ver], head);
422 }
423
424 static void flow_table_copy_flows(struct table_instance *old,
425                                   struct table_instance *new)
426 {
427         int old_ver;
428         int i;
429
430         old_ver = old->node_ver;
431         new->node_ver = !old_ver;
432
433         /* Insert in new table. */
434         for (i = 0; i < old->n_buckets; i++) {
435                 struct sw_flow *flow;
436                 struct hlist_head *head;
437
438                 head = flex_array_get(old->buckets, i);
439
440                 hlist_for_each_entry(flow, head, hash_node[old_ver])
441                         table_instance_insert(new, flow);
442         }
443
444         old->keep_flows = true;
445 }
446
447 static struct table_instance *table_instance_rehash(struct table_instance *ti,
448                                             int n_buckets)
449 {
450         struct table_instance *new_ti;
451
452         new_ti = table_instance_alloc(n_buckets);
453         if (!new_ti)
454                 return NULL;
455
456         flow_table_copy_flows(ti, new_ti);
457
458         return new_ti;
459 }
460
461 int ovs_flow_tbl_flush(struct flow_table *flow_table)
462 {
463         struct table_instance *old_ti;
464         struct table_instance *new_ti;
465
466         old_ti = ovsl_dereference(flow_table->ti);
467         new_ti = table_instance_alloc(TBL_MIN_BUCKETS);
468         if (!new_ti)
469                 return -ENOMEM;
470
471         rcu_assign_pointer(flow_table->ti, new_ti);
472         flow_table->last_rehash = jiffies;
473         flow_table->count = 0;
474
475         table_instance_destroy(old_ti, true);
476         return 0;
477 }
478
479 static u32 flow_hash(const struct sw_flow_key *key, int key_start,
480                      int key_end)
481 {
482         const u32 *hash_key = (const u32 *)((const u8 *)key + key_start);
483         int hash_u32s = (key_end - key_start) >> 2;
484
485         /* Make sure number of hash bytes are multiple of u32. */
486         BUILD_BUG_ON(sizeof(long) % sizeof(u32));
487
488         return arch_fast_hash2(hash_key, hash_u32s, 0);
489 }
490
491 static int flow_key_start(const struct sw_flow_key *key)
492 {
493         if (key->tun_key.ipv4_dst)
494                 return 0;
495         else
496                 return rounddown(offsetof(struct sw_flow_key, phy),
497                                           sizeof(long));
498 }
499
500 static bool cmp_key(const struct sw_flow_key *key1,
501                     const struct sw_flow_key *key2,
502                     int key_start, int key_end)
503 {
504         const long *cp1 = (const long *)((const u8 *)key1 + key_start);
505         const long *cp2 = (const long *)((const u8 *)key2 + key_start);
506         long diffs = 0;
507         int i;
508
509         for (i = key_start; i < key_end;  i += sizeof(long))
510                 diffs |= *cp1++ ^ *cp2++;
511
512         return diffs == 0;
513 }
514
515 static bool flow_cmp_masked_key(const struct sw_flow *flow,
516                                 const struct sw_flow_key *key,
517                                 int key_start, int key_end)
518 {
519         return cmp_key(&flow->key, key, key_start, key_end);
520 }
521
522 bool ovs_flow_cmp_unmasked_key(const struct sw_flow *flow,
523                                struct sw_flow_match *match)
524 {
525         struct sw_flow_key *key = match->key;
526         int key_start = flow_key_start(key);
527         int key_end = match->range.end;
528
529         return cmp_key(&flow->unmasked_key, key, key_start, key_end);
530 }
531
532 static struct sw_flow *masked_flow_lookup(struct table_instance *ti,
533                                           const struct sw_flow_key *unmasked,
534                                           struct sw_flow_mask *mask,
535                                           u32 *n_mask_hit)
536 {
537         struct sw_flow *flow;
538         struct hlist_head *head;
539         int key_start = mask->range.start;
540         int key_end = mask->range.end;
541         u32 hash;
542         struct sw_flow_key masked_key;
543
544         ovs_flow_mask_key(&masked_key, unmasked, mask);
545         hash = flow_hash(&masked_key, key_start, key_end);
546         head = find_bucket(ti, hash);
547         (*n_mask_hit)++;
548         hlist_for_each_entry_rcu(flow, head, hash_node[ti->node_ver]) {
549                 if (flow->mask == mask && flow->hash == hash &&
550                     flow_cmp_masked_key(flow, &masked_key,
551                                           key_start, key_end))
552                         return flow;
553         }
554         return NULL;
555 }
556
557 static struct sw_flow *flow_lookup(struct flow_table *tbl,
558                                    struct table_instance *ti,
559                                    struct mask_array *ma,
560                                    const struct sw_flow_key *key,
561                                    u32 *n_mask_hit,
562                                    u32 *index)
563 {
564         struct sw_flow *flow;
565         int i;
566
567         for (i = 0; i < ma->max; i++) {
568                 struct sw_flow_mask *mask;
569
570                 mask = rcu_dereference_ovsl(ma->masks[i]);
571                 if (!mask)
572                         break;
573
574                 flow = masked_flow_lookup(ti, key, mask, n_mask_hit);
575                 if (flow) { /* Found */
576                         *index = i;
577                         return flow;
578                 }
579         }
580
581         return NULL;
582 }
583
584 /*
585  * mask_cache maps flow to probable mask. This cache is not tightly
586  * coupled cache, It means updates to  mask list can result in inconsistent
587  * cache entry in mask cache.
588  * This is per cpu cache and is divided in MC_HASH_SEGS segments.
589  * In case of a hash collision the entry is hashed in next segment.
590  * */
591 struct sw_flow *ovs_flow_tbl_lookup_stats(struct flow_table *tbl,
592                                           const struct sw_flow_key *key,
593                                           u32 skb_hash,
594                                           u32 *n_mask_hit)
595 {
596         struct mask_array *ma = rcu_dereference(tbl->mask_array);
597         struct table_instance *ti = rcu_dereference(tbl->ti);
598         struct mask_cache_entry *entries, *ce;
599         struct sw_flow *flow;
600         u32 hash = skb_hash;
601         int seg;
602
603         *n_mask_hit = 0;
604         if (unlikely(!skb_hash)) {
605                 u32 __always_unused mask_index;
606
607                 return flow_lookup(tbl, ti, ma, key, n_mask_hit, &mask_index);
608         }
609
610         ce = NULL;
611         entries = this_cpu_ptr(tbl->mask_cache);
612
613         /* Find the cache entry 'ce' to operate on. */
614         for (seg = 0; seg < MC_HASH_SEGS; seg++) {
615                 int index = hash & (MC_HASH_ENTRIES - 1);
616                 struct mask_cache_entry *e;
617
618                 e = &entries[index];
619                 if (e->skb_hash == skb_hash) {
620                         struct sw_flow_mask *cache;
621                         int i = e->mask_index;
622
623                         if (likely(i < ma->max)) {
624                                 cache = rcu_dereference(ma->masks[i]);
625                                 if (cache) {
626                                         flow = masked_flow_lookup(ti, key,
627                                                         cache, n_mask_hit);
628                                         if (flow)
629                                                 return flow;
630                                 }
631                         }
632
633                         /* Cache miss. This is the best cache
634                          * replacement candidate.  */
635                         e->skb_hash = 0;
636                         ce = e;
637                         break;
638                 }
639
640                 if (!ce || e->skb_hash < ce->skb_hash)
641                         ce = e;  /* A better replacement cache candidate. */
642
643                 hash >>= MC_HASH_SHIFT;
644         }
645
646         /* Cache miss, do full lookup. */
647         flow = flow_lookup(tbl, ti, ma, key, n_mask_hit, &ce->mask_index);
648         if (flow)
649                 ce->skb_hash = skb_hash;
650
651         return flow;
652 }
653
654 struct sw_flow *ovs_flow_tbl_lookup(struct flow_table *tbl,
655                                     const struct sw_flow_key *key)
656 {
657         struct table_instance *ti = rcu_dereference_ovsl(tbl->ti);
658         struct mask_array *ma = rcu_dereference_ovsl(tbl->mask_array);
659         u32 __always_unused n_mask_hit;
660         u32 __always_unused index;
661
662         return flow_lookup(tbl, ti, ma, key, &n_mask_hit, &index);
663 }
664
665 struct sw_flow *ovs_flow_tbl_lookup_exact(struct flow_table *tbl,
666                                           struct sw_flow_match *match)
667 {
668         struct table_instance *ti = rcu_dereference_ovsl(tbl->ti);
669         struct mask_array *ma = rcu_dereference_ovsl(tbl->mask_array);
670         struct sw_flow *flow;
671         u32 __always_unused n_mask_hit;
672         int i;
673
674         /* Always called under ovs-mutex. */
675         for (i = 0; i < ma->count; i++) {
676                 struct sw_flow_mask *mask;
677
678                 mask = ovsl_dereference(ma->masks[i]);
679                 if (mask) {
680                         flow = masked_flow_lookup(ti, match->key, mask, &n_mask_hit);
681                         if (flow && ovs_flow_cmp_unmasked_key(flow, match)) { /* Found */
682                                 return flow;
683                         }
684                 }
685         }
686         return NULL;
687 }
688
689 int ovs_flow_tbl_num_masks(const struct flow_table *table)
690 {
691         struct mask_array *ma;
692
693         ma = rcu_dereference_ovsl(table->mask_array);
694         return ma->count;
695 }
696
697 static struct table_instance *table_instance_expand(struct table_instance *ti)
698 {
699         return table_instance_rehash(ti, ti->n_buckets * 2);
700 }
701
702 /* Remove 'mask' from the mask list, if it is not needed any more. */
703 static void flow_mask_remove(struct flow_table *tbl, struct sw_flow_mask *mask)
704 {
705         if (mask) {
706                 /* ovs-lock is required to protect mask-refcount and
707                  * mask list.
708                  */
709                 ASSERT_OVSL();
710                 BUG_ON(!mask->ref_count);
711                 mask->ref_count--;
712
713                 if (!mask->ref_count) {
714                         struct mask_array *ma;
715
716                         ma = ovsl_dereference(tbl->mask_array);
717                         /* Shrink the mask array if necessary. */
718                         if (ma->max > MASK_ARRAY_SIZE_MIN * 2
719                                 && ma->count <= ma->max / 4) {
720
721                                 tbl_mask_array_realloc(tbl, ma->max / 2);
722                                 ma = ovsl_dereference(tbl->mask_array);
723                         }
724
725                         tbl_mask_array_delete_mask(ma, mask);
726                         call_rcu(&mask->rcu, rcu_free_sw_flow_mask_cb);
727                 }
728         }
729 }
730
731 /* Must be called with OVS mutex held. */
732 void ovs_flow_tbl_remove(struct flow_table *table, struct sw_flow *flow)
733 {
734         struct table_instance *ti = ovsl_dereference(table->ti);
735
736         BUG_ON(table->count == 0);
737         hlist_del_rcu(&flow->hash_node[ti->node_ver]);
738         table->count--;
739
740         /* RCU delete the mask. 'flow->mask' is not NULLed, as it should be
741          * accessible as long as the RCU read lock is held. */
742         flow_mask_remove(table, flow->mask);
743 }
744
745 static struct sw_flow_mask *mask_alloc(void)
746 {
747         struct sw_flow_mask *mask;
748
749         mask = kmalloc(sizeof(*mask), GFP_KERNEL);
750         if (mask)
751                 mask->ref_count = 1;
752
753         return mask;
754 }
755
756 static bool mask_equal(const struct sw_flow_mask *a,
757                        const struct sw_flow_mask *b)
758 {
759         const u8 *a_ = (const u8 *)&a->key + a->range.start;
760         const u8 *b_ = (const u8 *)&b->key + b->range.start;
761
762         return  (a->range.end == b->range.end)
763                 && (a->range.start == b->range.start)
764                 && (memcmp(a_, b_, range_n_bytes(&a->range)) == 0);
765 }
766
767 static struct sw_flow_mask *flow_mask_find(const struct flow_table *tbl,
768                                            const struct sw_flow_mask *mask)
769 {
770         struct mask_array *ma;
771         int i;
772
773         ma = ovsl_dereference(tbl->mask_array);
774         for (i = 0; i < ma->count; i++) {
775                 struct sw_flow_mask *t;
776
777                 t = ovsl_dereference(ma->masks[i]);
778                 if (t && mask_equal(mask, t))
779                         return t;
780         }
781
782         return NULL;
783 }
784
785 /* Add 'mask' into the mask list, if it is not already there. */
786 static int flow_mask_insert(struct flow_table *tbl, struct sw_flow *flow,
787                             struct sw_flow_mask *new)
788 {
789         struct sw_flow_mask *mask;
790
791         mask = flow_mask_find(tbl, new);
792         if (!mask) {
793                 struct mask_array *ma;
794
795                 /* Allocate a new mask if none exsits. */
796                 mask = mask_alloc();
797                 if (!mask)
798                         return -ENOMEM;
799
800                 mask->key = new->key;
801                 mask->range = new->range;
802
803                 /* Add mask to mask-list. */
804                 ma = ovsl_dereference(tbl->mask_array);
805                 if (ma->count >= ma->max) {
806                         int err;
807
808                         err = tbl_mask_array_realloc(tbl, ma->max +
809                                                         MASK_ARRAY_SIZE_MIN);
810                         if (err) {
811                                 kfree(mask);
812                                 return err;
813                         }
814                         ma = ovsl_dereference(tbl->mask_array);
815                 }
816
817                 rcu_assign_pointer(ma->masks[ma->count], mask);
818                 ma->count++;
819         } else {
820                 BUG_ON(!mask->ref_count);
821                 mask->ref_count++;
822         }
823
824         flow->mask = mask;
825         return 0;
826 }
827
828 /* Must be called with OVS mutex held. */
829 int ovs_flow_tbl_insert(struct flow_table *table, struct sw_flow *flow,
830                         struct sw_flow_mask *mask)
831 {
832         struct table_instance *new_ti = NULL;
833         struct table_instance *ti;
834         int err;
835
836         err = flow_mask_insert(table, flow, mask);
837         if (err)
838                 return err;
839
840         flow->hash = flow_hash(&flow->key, flow->mask->range.start,
841                         flow->mask->range.end);
842         ti = ovsl_dereference(table->ti);
843         table_instance_insert(ti, flow);
844         table->count++;
845
846         /* Expand table, if necessary, to make room. */
847         if (table->count > ti->n_buckets)
848                 new_ti = table_instance_expand(ti);
849         else if (time_after(jiffies, table->last_rehash + REHASH_INTERVAL))
850                 new_ti = table_instance_rehash(ti, ti->n_buckets);
851
852         if (new_ti) {
853                 rcu_assign_pointer(table->ti, new_ti);
854                 table_instance_destroy(ti, true);
855                 table->last_rehash = jiffies;
856         }
857         return 0;
858 }
859
860 /* Initializes the flow module.
861  * Returns zero if successful or a negative error code. */
862 int ovs_flow_init(void)
863 {
864         BUILD_BUG_ON(__alignof__(struct sw_flow_key) % __alignof__(long));
865         BUILD_BUG_ON(sizeof(struct sw_flow_key) % sizeof(long));
866
867         flow_cache = kmem_cache_create("sw_flow", sizeof(struct sw_flow)
868                                        + (num_possible_nodes()
869                                           * sizeof(struct flow_stats *)),
870                                        0, 0, NULL);
871         if (flow_cache == NULL)
872                 return -ENOMEM;
873
874         flow_stats_cache
875                 = kmem_cache_create("sw_flow_stats", sizeof(struct flow_stats),
876                                     0, SLAB_HWCACHE_ALIGN, NULL);
877         if (flow_stats_cache == NULL) {
878                 kmem_cache_destroy(flow_cache);
879                 flow_cache = NULL;
880                 return -ENOMEM;
881         }
882
883         return 0;
884 }
885
886 /* Uninitializes the flow module. */
887 void ovs_flow_exit(void)
888 {
889         kmem_cache_destroy(flow_stats_cache);
890         kmem_cache_destroy(flow_cache);
891 }