Merge "[l2l3 stack] implements new nd state machine & nd buffering"
[samplevnf.git] / VNFs / DPPD-PROX / tools / flow_extract / allocator.cpp
1 /*
2 // Copyright (c) 2010-2017 Intel Corporation
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 <iostream>
18 #include <sys/mman.h>
19 #include <unistd.h>
20 #include <sys/stat.h>
21 #include <fcntl.h>
22 #include <cerrno>
23 #include <cstdio>
24 #include <cstdlib>
25 #include <cstring>
26
27 #define USEHP
28
29 using namespace std;
30
31 #include "allocator.hpp"
32
33 Allocator::Allocator(size_t size, size_t threshold)
34         : m_size(size), m_threshold(threshold), m_alloc_offset(0)
35 {
36 #ifdef USEHP
37         int fd = open("/mnt/huge/hp", O_CREAT | O_RDWR, 0755);
38         if (fd < 0) {
39                 cerr << "Allocator failed to open huge page file descriptor: " << strerror(errno) << endl;
40                 exit(EXIT_FAILURE);
41         }
42         m_mem = (uint8_t *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
43         if (m_mem == MAP_FAILED) {
44                 perror("mmap");
45                 unlink("/mnt/huge");
46                 cerr << "Allocator mmap failed: " << strerror(errno) << endl;
47                 exit (EXIT_FAILURE);
48         }
49 #else
50         m_mem = new uint8_t[size];
51 #endif
52 }
53
54 Allocator::~Allocator()
55 {
56 #ifdef USEHP
57         munmap((void *)m_mem, m_size);
58 #else
59         delete[] m_mem;
60 #endif
61 }
62
63 void *Allocator::alloc(size_t size)
64 {
65         void *ret = &m_mem[m_alloc_offset];
66
67         m_alloc_offset += size;
68         return ret;
69 }
70
71 void Allocator::reset()
72 {
73         m_alloc_offset = 0;
74 }
75
76 size_t Allocator::getFreeSize() const
77 {
78         return m_size - m_alloc_offset;
79 }
80
81 bool Allocator::lowThresholdReached() const
82 {
83         return (m_size - m_alloc_offset) < m_threshold;
84 }