1
0
Fork 0
mirror of https://git.rwth-aachen.de/acs/public/villas/node/ synced 2025-03-30 00:00:11 +01:00

code cleanups

- Use C++ style comments
- Harmonize indentions
- Harmonize comment capitalization

Signed-off-by: Steffen Vogel <post@steffenvogel.de>
This commit is contained in:
Steffen Vogel 2022-12-02 17:16:44 +01:00
parent 958cc83fae
commit e743b42c6f
64 changed files with 550 additions and 444 deletions

78
common/.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,78 @@
{
"files.associations": {
"__bit_reference": "cpp",
"__bits": "cpp",
"__config": "cpp",
"__debug": "cpp",
"__errc": "cpp",
"__hash_table": "cpp",
"__locale": "cpp",
"__mutex_base": "cpp",
"__node_handle": "cpp",
"__nullptr": "cpp",
"__split_buffer": "cpp",
"__string": "cpp",
"__threading_support": "cpp",
"__tree": "cpp",
"__tuple": "cpp",
"array": "cpp",
"atomic": "cpp",
"bitset": "cpp",
"cctype": "cpp",
"chrono": "cpp",
"cinttypes": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"codecvt": "cpp",
"compare": "cpp",
"complex": "cpp",
"concepts": "cpp",
"condition_variable": "cpp",
"csignal": "cpp",
"cstdarg": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"cwctype": "cpp",
"deque": "cpp",
"exception": "cpp",
"fstream": "cpp",
"initializer_list": "cpp",
"iomanip": "cpp",
"ios": "cpp",
"iosfwd": "cpp",
"iostream": "cpp",
"istream": "cpp",
"limits": "cpp",
"list": "cpp",
"locale": "cpp",
"map": "cpp",
"memory": "cpp",
"mutex": "cpp",
"new": "cpp",
"optional": "cpp",
"ostream": "cpp",
"ratio": "cpp",
"regex": "cpp",
"set": "cpp",
"sstream": "cpp",
"stack": "cpp",
"stdexcept": "cpp",
"streambuf": "cpp",
"string": "cpp",
"string_view": "cpp",
"system_error": "cpp",
"thread": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"typeinfo": "cpp",
"unordered_map": "cpp",
"variant": "cpp",
"vector": "cpp",
"algorithm": "cpp"
}
}

View file

@ -8,46 +8,45 @@
#pragma once #pragma once
/* The suffixed of the BOX_ macro a constructed by // The suffixed of the BOX_ macro a constructed by
* combining the following letters in the written order: // combining the following letters in the written order:
* - U for a line facing upwards // - U for a line facing upwards
* - D for a line facing downwards // - D for a line facing downwards
* - L for a line facing leftwards // - L for a line facing leftwards
* - R for a line facing rightwards // - R for a line facing rightwards
* //
* E.g. a cross can be constructed by combining all line fragments: // E.g. a cross can be constructed by combining all line fragments:
* BOX_UDLR // BOX_UDLR
*/ #if 0 // Alternate character set
#if 0 /* Alternate character set */
#define BOX(chr) "\e(0" chr "\e(B" #define BOX(chr) "\e(0" chr "\e(B"
#define BOX_LR BOX("\x71") /**< Boxdrawing: ─ */ #define BOX_LR BOX("\x71") // Boxdrawing: ─
#define BOX_UD BOX("\x78") /**< Boxdrawing: │ */ #define BOX_UD BOX("\x78") // Boxdrawing: │
#define BOX_UDR BOX("\x74") /**< Boxdrawing: ├ */ #define BOX_UDR BOX("\x74") // Boxdrawing: ├
#define BOX_UDLR BOX("\x6E") /**< Boxdrawing: ┼ */ #define BOX_UDLR BOX("\x6E") // Boxdrawing: ┼
#define BOX_UDL BOX("\x75") /**< Boxdrawing: ┤ */ #define BOX_UDL BOX("\x75") // Boxdrawing: ┤
#define BOX_ULR BOX("\x76") /**< Boxdrawing: ┴ */ #define BOX_ULR BOX("\x76") // Boxdrawing: ┴
#define BOX_UL BOX("\x6A") /**< Boxdrawing: ┘ */ #define BOX_UL BOX("\x6A") // Boxdrawing: ┘
#define BOX_DLR BOX("\x77") /**< Boxdrawing: ┘ */ #define BOX_DLR BOX("\x77") // Boxdrawing: ┘
#define BOX_DL BOX("\x6B") /**< Boxdrawing: ┘ */ #define BOX_DL BOX("\x6B") // Boxdrawing: ┘
#elif 1 /* UTF-8 */ #elif 1 // UTF-8
#define BOX_LR "─" /**< Boxdrawing: ─ */ #define BOX_LR "─" // Boxdrawing: ─
#define BOX_UD "│" /**< Boxdrawing: │ */ #define BOX_UD "│" // Boxdrawing: │
#define BOX_UDR "├" /**< Boxdrawing: ├ */ #define BOX_UDR "├" // Boxdrawing: ├
#define BOX_UDLR "┼" /**< Boxdrawing: ┼ */ #define BOX_UDLR "┼" // Boxdrawing: ┼
#define BOX_UDL "┤" /**< Boxdrawing: ┤ */ #define BOX_UDL "┤" // Boxdrawing: ┤
#define BOX_ULR "┴" /**< Boxdrawing: ┴ */ #define BOX_ULR "┴" // Boxdrawing: ┴
#define BOX_UL "┘" /**< Boxdrawing: ┘ */ #define BOX_UL "┘" // Boxdrawing: ┘
#define BOX_DLR "┬" /**< Boxdrawing: ┘ */ #define BOX_DLR "┬" // Boxdrawing: ┘
#define BOX_DL "┐" /**< Boxdrawing: ┘ */ #define BOX_DL "┐" // Boxdrawing: ┘
#define BOX_UR "└" /**< Boxdrawing: └ */ #define BOX_UR "└" // Boxdrawing: └
#else /* ASCII */ #else // ASCII
#define BOX_LR "-" /**< Boxdrawing: ─ */ #define BOX_LR "-" // Boxdrawing: ─
#define BOX_UD "|" /**< Boxdrawing: │ */ #define BOX_UD "|" // Boxdrawing: │
#define BOX_UDR "+" /**< Boxdrawing: ├ */ #define BOX_UDR "+" // Boxdrawing: ├
#define BOX_UDLR "+" /**< Boxdrawing: ┼ */ #define BOX_UDLR "+" // Boxdrawing: ┼
#define BOX_UDL "+" /**< Boxdrawing: ┤ */ #define BOX_UDL "+" // Boxdrawing: ┤
#define BOX_ULR "+" /**< Boxdrawing: ┴ */ #define BOX_ULR "+" // Boxdrawing: ┴
#define BOX_UL "+" /**< Boxdrawing: ┘ */ #define BOX_UL "+" // Boxdrawing: ┘
#define BOX_DLR "+" /**< Boxdrawing: ┘ */ #define BOX_DLR "+" // Boxdrawing: ┘
#define BOX_DL "+" /**< Boxdrawing: ┘ */ #define BOX_DL "+" // Boxdrawing: ┘
#endif #endif

View file

@ -30,10 +30,10 @@ public:
std::vector<char>(count, 0) std::vector<char>(count, 0)
{ } { }
/** Encode JSON document /p j and append it to the buffer */ // Encode JSON document /p j and append it to the buffer
int encode(json_t *j, int flags = 0); int encode(json_t *j, int flags = 0);
/** Decode JSON document from the beginning of the buffer */ // Decode JSON document from the beginning of the buffer
json_t * decode(); json_t * decode();
void append(const char *data, size_t len) void append(const char *data, size_t len)
@ -42,4 +42,4 @@ public:
} }
}; };
} /* namespace villas */ } // namespace villas

View file

@ -8,18 +8,18 @@
#pragma once #pragma once
/* CPP stringification */ // CPP stringification
#define XSTR(x) STR(x) #define XSTR(x) STR(x)
#define STR(x) #x #define STR(x) #x
/* Some color escape codes for pretty log messages */ // Some color escape codes for pretty log messages
#define CLR(clr, str) "\e[" XSTR(clr) "m" str "\e[0m" #define CLR(clr, str) "\e[" XSTR(clr) "m" str "\e[0m"
#define CLR_GRY(str) CLR(30, str) /**< Print str in gray */ #define CLR_GRY(str) CLR(30, str) // Print str in gray
#define CLR_RED(str) CLR(31, str) /**< Print str in red */ #define CLR_RED(str) CLR(31, str) // Print str in red
#define CLR_GRN(str) CLR(32, str) /**< Print str in green */ #define CLR_GRN(str) CLR(32, str) // Print str in green
#define CLR_YEL(str) CLR(33, str) /**< Print str in yellow */ #define CLR_YEL(str) CLR(33, str) // Print str in yellow
#define CLR_BLU(str) CLR(34, str) /**< Print str in blue */ #define CLR_BLU(str) CLR(34, str) // Print str in blue
#define CLR_MAG(str) CLR(35, str) /**< Print str in magenta */ #define CLR_MAG(str) CLR(35, str) // Print str in magenta
#define CLR_CYN(str) CLR(36, str) /**< Print str in cyan */ #define CLR_CYN(str) CLR(36, str) // Print str in cyan
#define CLR_WHT(str) CLR(37, str) /**< Print str in white */ #define CLR_WHT(str) CLR(37, str) // Print str in white
#define CLR_BLD(str) CLR( 1, str) /**< Print str in bold */ #define CLR_BLD(str) CLR( 1, str) // Print str in bold

View file

@ -10,7 +10,7 @@
#include <string> #include <string>
/* Common states for most objects in VILLAScommon (paths, nodes, hooks, plugins) */ // Common states for most objects in VILLAScommon (paths, nodes, hooks, plugins)
enum class State { enum class State {
DESTROYED = 0, DESTROYED = 0,
INITIALIZED = 1, INITIALIZED = 1,

View file

@ -40,4 +40,4 @@ json_t *json_loadfd(int input, size_t flags, json_error_t *error);
#define htobe16(x) OSSwapHostToBigInt16(x) #define htobe16(x) OSSwapHostToBigInt16(x)
#define htobe32(x) OSSwapHostToBigInt32(x) #define htobe32(x) OSSwapHostToBigInt32(x)
#define htobe64(x) OSSwapHostToBigInt64(x) #define htobe64(x) OSSwapHostToBigInt64(x)
#endif /* __MACH__ */ #endif // __MACH__

View file

@ -173,7 +173,7 @@ public:
} }
}; };
} /* namespace utils */ } // namespace utils
} /* namespace villas */ } // namespace villas
#endif #endif

View file

@ -34,5 +34,5 @@ public:
} }
}; };
} /* namespace dsp */ } // namespace dsp
} /* namespace villas */ } // namespace villas

View file

@ -37,5 +37,5 @@ public:
} }
}; };
} /* namespace dsp */ } // namespace dsp
} /* namespace villas */ } // namespace villas

View file

@ -38,5 +38,5 @@ public:
double calculate(double setpoint, double pv); double calculate(double setpoint, double pv);
}; };
} /* namespace dsp */ } // namespace dsp
} /* namespace villas */ } // namespace villas

View file

@ -88,5 +88,5 @@ public:
} }
}; };
} /* namespace dsp */ } // namespace dsp
} /* namespace villas */ } // namespace villas

View file

@ -18,7 +18,6 @@ namespace villas {
namespace dsp { namespace dsp {
template<typename T>// a0 = 1.0, double a1 = 0.0, double a2 = 0.0, double a3 = 0.0, double a4 = 0.0> template<typename T>// a0 = 1.0, double a1 = 0.0, double a2 = 0.0, double a3 = 0.0, double a4 = 0.0>
class CosineWindow : public Window<T> { class CosineWindow : public Window<T> {
@ -113,5 +112,5 @@ public:
CosineWindow<T>(0.3635819, 0.4891775, 0.1365995, 0.0106411, 0., len, i) {} CosineWindow<T>(0.3635819, 0.4891775, 0.1365995, 0.0106411, 0., len, i) {}
}; };
} /* namespace dsp */ } // namespace dsp
} /* namespace villas */ } // namespace villas

View file

@ -169,4 +169,4 @@ public:
} }
}; };
} /* namespace villas */ } // namespace villas

View file

@ -45,7 +45,7 @@ public:
if (vertexId >= vertices.size()) if (vertexId >= vertices.size())
throw std::invalid_argument("vertex doesn't exist"); throw std::invalid_argument("vertex doesn't exist");
// cannot use [] operator, because creates non-existing elements // Cannot use [] operator, because creates non-existing elements
// at() will throw std::out_of_range if element does not exist // at() will throw std::out_of_range if element does not exist
return vertices.at(vertexId); return vertices.at(vertexId);
} }
@ -70,16 +70,20 @@ public:
if (edgeId >= lastEdgeId) if (edgeId >= lastEdgeId)
throw std::invalid_argument("edge doesn't exist"); throw std::invalid_argument("edge doesn't exist");
// cannot use [] operator, because creates non-existing elements // Cannot use [] operator, because creates non-existing elements
// at() will throw std::out_of_range if element does not exist // at() will throw std::out_of_range if element does not exist
return edges.at(edgeId); return edges.at(edgeId);
} }
std::size_t getEdgeCount() const std::size_t getEdgeCount() const
{ return edges.size(); } {
return edges.size();
}
std::size_t getVertexCount() const std::size_t getVertexCount() const
{ return vertices.size(); } {
return vertices.size();
}
VertexIdentifier addVertex(std::shared_ptr<VertexType> vertex) VertexIdentifier addVertex(std::shared_ptr<VertexType> vertex)
{ {
@ -95,19 +99,19 @@ public:
VertexIdentifier fromVertexId, VertexIdentifier fromVertexId,
VertexIdentifier toVertexId) VertexIdentifier toVertexId)
{ {
// allocate edge id // Allocate edge id
edge->id = lastEdgeId++; edge->id = lastEdgeId++;
// connect it // Connect it
edge->from = fromVertexId; edge->from = fromVertexId;
edge->to = toVertexId; edge->to = toVertexId;
logger->debug("New edge {}: {} -> {}", *edge, edge->from, edge->to); logger->debug("New edge {}: {} -> {}", *edge, edge->from, edge->to);
// this is a directed graph, so only push edge to starting vertex // This is a directed graph, so only push edge to starting vertex
getVertex(edge->from)->edges.push_back(edge->id); getVertex(edge->from)->edges.push_back(edge->id);
// add new edge to graph // Add new edge to graph
edges[edge->id] = edge; edges[edge->id] = edge;
return edge->id; return edge->id;
@ -117,7 +121,7 @@ public:
EdgeIdentifier addDefaultEdge(VertexIdentifier fromVertexId, EdgeIdentifier addDefaultEdge(VertexIdentifier fromVertexId,
VertexIdentifier toVertexId) VertexIdentifier toVertexId)
{ {
// create a new edge // Create a new edge
std::shared_ptr<EdgeType> edge(new EdgeType); std::shared_ptr<EdgeType> edge(new EdgeType);
return addEdge(edge, fromVertexId, toVertexId); return addEdge(edge, fromVertexId, toVertexId);
@ -128,7 +132,7 @@ public:
auto edge = getEdge(edgeId); auto edge = getEdge(edgeId);
auto startVertex = getVertex(edge->from); auto startVertex = getVertex(edge->from);
// remove edge only from starting vertex (this is a directed graph) // Remove edge only from starting vertex (this is a directed graph)
logger->debug("Remove edge {} from vertex {}", edgeId, edge->from); logger->debug("Remove edge {} from vertex {}", edgeId, edge->from);
startVertex->edges.remove(edgeId); startVertex->edges.remove(edgeId);
@ -138,7 +142,7 @@ public:
void removeVertex(VertexIdentifier vertexId) void removeVertex(VertexIdentifier vertexId)
{ {
// delete every edge that start or ends at this vertex // Delete every edge that start or ends at this vertex
auto it = edges.begin(); auto it = edges.begin();
while (it != edges.end()) { while (it != edges.end()) {
auto &edgeId = it->first; auto &edgeId = it->first;
@ -159,7 +163,7 @@ public:
if ((edge->from == vertexId) or removeEdge) { if ((edge->from == vertexId) or removeEdge) {
logger->debug("Remove edge {}", edgeId); logger->debug("Remove edge {}", edgeId);
// remove edge from global edge list // Remove edge from global edge list
it = edges.erase(it); it = edges.erase(it);
} }
else else
@ -171,16 +175,18 @@ public:
lastVertexId--; lastVertexId--;
} }
const std::list<EdgeIdentifier>& const std::list<EdgeIdentifier>& vertexGetEdges(VertexIdentifier vertexId) const
vertexGetEdges(VertexIdentifier vertexId) const {
{ return getVertex(vertexId)->edges; } return getVertex(vertexId)->edges;
}
using check_path_fn = std::function<bool(const Path&)>; using check_path_fn = std::function<bool(const Path&)>;
static bool static
checkPath(const Path&) bool checkPath(const Path&)
{ return true; } {
return true;
}
bool getPath(VertexIdentifier fromVertexId, bool getPath(VertexIdentifier fromVertexId,
VertexIdentifier toVertexId, VertexIdentifier toVertexId,
@ -188,7 +194,7 @@ public:
check_path_fn pathCheckFunc = checkPath) check_path_fn pathCheckFunc = checkPath)
{ {
if (fromVertexId == toVertexId) if (fromVertexId == toVertexId)
// arrived at the destination // Arrived at the destination
return true; return true;
else { else {
auto fromVertex = getVertex(fromVertexId); auto fromVertex = getVertex(fromVertexId);
@ -196,7 +202,7 @@ public:
for (auto &edgeId : fromVertex->edges) { for (auto &edgeId : fromVertex->edges) {
auto edgeOfFromVertex = getEdge(edgeId); auto edgeOfFromVertex = getEdge(edgeId);
// loop detection // Loop detection
bool loop = false; bool loop = false;
for (auto &edgeIdInPath : path) { for (auto &edgeIdInPath : path) {
auto edgeInPath = getEdge(edgeIdInPath); auto edgeInPath = getEdge(edgeIdInPath);
@ -211,15 +217,15 @@ public:
continue; continue;
} }
// remember the path we're investigating to detect loops // Remember the path we're investigating to detect loops
path.push_back(edgeId); path.push_back(edgeId);
// recursive, depth-first search // Recursive, depth-first search
if (getPath(edgeOfFromVertex->to, toVertexId, path, pathCheckFunc) and pathCheckFunc(path)) if (getPath(edgeOfFromVertex->to, toVertexId, path, pathCheckFunc) and pathCheckFunc(path))
// path found, we're done // Path found, we're done
return true; return true;
else else
// tear down path that didn't lead to the destination // Tear down path that didn't lead to the destination
path.pop_back(); path.pop_back();
} }
} }
@ -233,7 +239,7 @@ public:
for (auto &v : vertices) { for (auto &v : vertices) {
auto &vertex = v.second; auto &vertex = v.second;
// format connected vertices into a list // Format connected vertices into a list
std::stringstream ssEdges; std::stringstream ssEdges;
for (auto &edge : vertex->edges) { for (auto &edge : vertex->edges) {
ssEdges << getEdge(edge)->to << " "; ssEdges << getEdge(edge)->to << " ";
@ -278,5 +284,5 @@ protected:
Logger logger; Logger logger;
}; };
} /* namespace graph */ } // namespace graph
} /* namespace villas */ } // namespace villas

View file

@ -18,19 +18,26 @@ class Edge {
public: public:
using Identifier = std::size_t; using Identifier = std::size_t;
friend std::ostream& friend
operator<< (std::ostream &stream, const Edge &edge) std::ostream& operator<< (std::ostream &stream, const Edge &edge)
{ return stream << edge.id; } {
return stream << edge.id;
}
bool bool operator==(const Edge &other)
operator==(const Edge &other) {
{ return this->id == other.id; } return this->id == other.id;
}
Vertex::Identifier getVertexTo() const Vertex::Identifier getVertexTo() const
{ return to; } {
return to;
}
Vertex::Identifier getVertexFrom() const Vertex::Identifier getVertexFrom() const
{ return from; } {
return from;
}
private: private:
Identifier id; Identifier id;
@ -38,5 +45,5 @@ private:
Vertex::Identifier to; Vertex::Identifier to;
}; };
} /* namespace graph */ } // namespace graph
} /* namespace villas */ } // namespace villas

View file

@ -18,17 +18,21 @@ class Vertex {
public: public:
using Identifier = std::size_t; using Identifier = std::size_t;
const Identifier& const Identifier& getIdentifier() const
getIdentifier() const {
{ return id; } return id;
}
friend std::ostream& friend
operator<< (std::ostream &stream, const Vertex &vertex) std::ostream& operator<< (std::ostream &stream, const Vertex &vertex)
{ return stream << vertex.id; } {
return stream << vertex.id;
}
bool bool operator==(const Vertex &other)
operator==(const Vertex &other) {
{ return this->id == other.id; } return this->id == other.id;
}
private: private:
Identifier id; Identifier id;
@ -36,5 +40,5 @@ private:
std::list<std::size_t> edges; std::list<std::size_t> edges;
}; };
} /* namespace graph */ } // namespace graph
} /* namespace villas */ } // namespace villas

View file

@ -117,4 +117,4 @@ protected:
double _m[2], _s[2]; /**< Private variables for online variance calculation */ double _m[2], _s[2]; /**< Private variables for online variance calculation */
}; };
} /* namespace villas */ } // namespace villas

View file

@ -65,5 +65,5 @@ int get_cpu_frequency(uint64_t *freq);
/** Set SMP affinity of IRQ */ /** Set SMP affinity of IRQ */
int setIRQAffinity(unsigned irq, uintmax_t aff , uintmax_t *old); int setIRQAffinity(unsigned irq, uintmax_t aff , uintmax_t *old);
} /* namespace villas */ } // namespace villas
} /* namespace kernel */ } // namespace kernel

View file

@ -120,6 +120,6 @@ public:
lookupDevice(const Device &f); lookupDevice(const Device &f);
}; };
} /* namespace pci */ } // namespace pci
} /* namespace kernel */ } // namespace kernel
} /* namespace villas */ } // namespace villas

View file

@ -31,6 +31,6 @@ void setPriority(int priority);
*/ */
bool isPreemptible(); bool isPreemptible();
} /* namespace villas */ } // namespace villas
} /* namespace kernel */ } // namespace kernel
} /* namespace rt */ } // namespace rt

View file

@ -82,6 +82,6 @@ private:
Logger log; Logger log;
}; };
} /* namespace vfio */ } // namespace vfio
} /* namespace kernel */ } // namespace kernel
} /* namespace villas */ } // namespace villas

View file

@ -99,6 +99,6 @@ private:
Logger log; Logger log;
}; };
} /* namespace vfio */ } // namespace vfio
} /* namespace kernel */ } // namespace kernel
} /* namespace villas */ } // namespace villas

View file

@ -74,6 +74,6 @@ private:
Logger log; Logger log;
}; };
} /* namespace vfio */ } // namespace vfio
} /* namespace kernel */ } // namespace kernel
} /* namespace villas */ } // namespace villas

View file

@ -45,10 +45,10 @@ __attribute__((destructor(105))) static void UNIQUE(__dtor)() { \
namespace villas { namespace villas {
/** Callback to search or sort a list. */ // Callback to search or sort a list.
typedef int (*cmp_cb_t)(const void *, const void *); typedef int (*cmp_cb_t)(const void *, const void *);
/* The list data structure. */ // The list data structure.
struct List { struct List {
enum State state; /**< The state of this list. */ enum State state; /**< The state of this list. */
void **array; /**< Array of pointers to list elements */ void **array; /**< Array of pointers to list elements */
@ -133,4 +133,4 @@ ssize_t list_lookup_index(struct List *l, const std::string &name)
return f ? list_index(l, f) : -1; return f ? list_index(l, f) : -1;
} }
} /* namespace villas */ } // namespace villas

View file

@ -21,7 +21,7 @@
namespace villas { namespace villas {
/* Forward declarations */ // Forward declarations
class Log; class Log;
using Logger = std::shared_ptr<spdlog::logger>; using Logger = std::shared_ptr<spdlog::logger>;
@ -80,4 +80,4 @@ public:
std::string getLevelName() const; std::string getLevelName() const;
}; };
} /* namespace villas */ } // namespace villas

View file

@ -38,7 +38,7 @@ protected:
void flush_() override void flush_() override
{ {
/* nothing to do */ // Nothing to do
} }
}; };
@ -46,5 +46,5 @@ using OpalSink_mt = OpalSink<std::mutex>;
using OpalSink_st = OpalSink<spdlog::details::null_mutex>; using OpalSink_st = OpalSink<spdlog::details::null_mutex>;
} /* namespace node */ } // namespace node
} /* namespace villas */ } // namespace villas

View file

@ -49,9 +49,9 @@ public:
} }
protected: protected:
size_t offset; ///< Offset (or address) inside address space size_t offset; // Offset (or address) inside address space
size_t size; ///< Size in bytes of this block size_t size; // Size in bytes of this block
MemoryManager::AddressSpaceId addrSpaceId; ///< Identifier in memory graph MemoryManager::AddressSpaceId addrSpaceId; // Identifier in memory graph
}; };
/** /**
@ -70,13 +70,13 @@ class MemoryAccessor {
public: public:
using Type = T; using Type = T;
// take ownership of the MemoryBlock // Take ownership of the MemoryBlock
MemoryAccessor(std::unique_ptr<MemoryBlock, MemoryBlock::deallocator_fn> mem) : MemoryAccessor(std::unique_ptr<MemoryBlock, MemoryBlock::deallocator_fn> mem) :
translation(MemoryManager::get().getTranslationFromProcess(mem->getAddrSpaceId())), translation(MemoryManager::get().getTranslationFromProcess(mem->getAddrSpaceId())),
memoryBlock(std::move(mem)) memoryBlock(std::move(mem))
{ } { }
// just act as an accessor, do not take ownership of MemoryBlock // Just act as an accessor, do not take ownership of MemoryBlock
MemoryAccessor(const MemoryBlock &mem) : MemoryAccessor(const MemoryBlock &mem) :
translation(MemoryManager::get().getTranslationFromProcess(mem.getAddrSpaceId())) translation(MemoryManager::get().getTranslationFromProcess(mem.getAddrSpaceId()))
{ } { }
@ -113,10 +113,10 @@ public:
} }
private: private:
/// cached memory translation for fast access // Cached memory translation for fast access
MemoryTranslation translation; MemoryTranslation translation;
/// take the unique pointer in case user wants this class to have ownership // Take the unique pointer in case user wants this class to have ownership
std::unique_ptr<MemoryBlock, MemoryBlock::deallocator_fn> memoryBlock; std::unique_ptr<MemoryBlock, MemoryBlock::deallocator_fn> memoryBlock;
}; };
@ -131,7 +131,7 @@ private:
template<typename DerivedAllocator> template<typename DerivedAllocator>
class BaseAllocator { class BaseAllocator {
public: public:
/// memoryAddrSpaceId: memory that is managed by this allocator // memoryAddrSpaceId: memory that is managed by this allocator
BaseAllocator(MemoryManager::AddressSpaceId memoryAddrSpaceId) : BaseAllocator(MemoryManager::AddressSpaceId memoryAddrSpaceId) :
memoryAddrSpaceId(memoryAddrSpaceId) memoryAddrSpaceId(memoryAddrSpaceId)
{ {
@ -140,7 +140,7 @@ public:
std::string loggerName = fmt::format("memory:", derivedAlloc->getName()); std::string loggerName = fmt::format("memory:", derivedAlloc->getName());
logger = logging.get(loggerName); logger = logging.get(loggerName);
// default deallocation callback // Default deallocation callback
free = [&](MemoryBlock* mem) { free = [&](MemoryBlock* mem) {
logger->warn("no free callback defined for addr space {}, not freeing", logger->warn("no free callback defined for addr space {}, not freeing",
mem->getAddrSpaceId()); mem->getAddrSpaceId());
@ -165,7 +165,7 @@ public:
allocate(size_t num) allocate(size_t num)
{ {
if (num == 0) { if (num == 0) {
// doesn't make sense to allocate an empty block // Doesn't make sense to allocate an empty block
logger->error("Trying to allocate empty memory"); logger->error("Trying to allocate empty memory");
throw std::bad_alloc(); throw std::bad_alloc();
} }
@ -202,7 +202,7 @@ protected:
void removeMemoryBlock(const MemoryBlock &mem) void removeMemoryBlock(const MemoryBlock &mem)
{ {
// this will also remove any mapping to and from the memory block // This will also remove any mapping to and from the memory block
auto & mm = MemoryManager::get(); auto & mm = MemoryManager::get();
mm.removeAddressSpace(mem.getAddrSpaceId()); mm.removeAddressSpace(mem.getAddrSpaceId());
} }
@ -215,7 +215,7 @@ protected:
MemoryBlock::deallocator_fn free; MemoryBlock::deallocator_fn free;
Logger logger; Logger logger;
// optional, if allocator should own the memory block // Optional, if allocator should own the memory block
std::unique_ptr<MemoryBlock, MemoryBlock::deallocator_fn> memoryBlock; std::unique_ptr<MemoryBlock, MemoryBlock::deallocator_fn> memoryBlock;
private: private:
@ -268,10 +268,10 @@ private:
return (alignBytes - (addr & alignMask)) & alignMask; return (alignBytes - (addr & alignMask)) & alignMask;
} }
size_t nextFreeAddress; ///< next chunk will be allocated here size_t nextFreeAddress; // Next chunk will be allocated here
size_t memorySize; ///< total size of managed memory size_t memorySize; // Total size of managed memory
size_t internalOffset; ///< offset in address space (usually 0) size_t internalOffset; // Offset in address space (usually 0)
size_t allocationCount; ///< Number of individual allocations present size_t allocationCount; // Number of individual allocations present
}; };
@ -344,4 +344,4 @@ private:
getUdmaBufPhysAddr(int num); getUdmaBufPhysAddr(int num);
}; };
} /* namespace villas */ } // namespace villas

View file

@ -41,18 +41,17 @@ public:
size(size) size(size)
{ } { }
uintptr_t uintptr_t getLocalAddr(uintptr_t addrInForeignAddrSpace) const;
getLocalAddr(uintptr_t addrInForeignAddrSpace) const;
uintptr_t uintptr_t getForeignAddr(uintptr_t addrInLocalAddrSpace) const;
getForeignAddr(uintptr_t addrInLocalAddrSpace) const;
size_t size_t getSize() const
getSize() const {
{ return size; } return size;
}
friend std::ostream& friend
operator<< (std::ostream &stream, const MemoryTranslation &translation) std::ostream& operator<< (std::ostream &stream, const MemoryTranslation &translation)
{ {
return stream << std::hex return stream << std::hex
<< "(src=0x" << translation.src << "(src=0x" << translation.src
@ -61,13 +60,13 @@ public:
<< ")"; << ")";
} }
/// Merge two MemoryTranslations together // Merge two MemoryTranslations together
MemoryTranslation &operator+=(const MemoryTranslation &other); MemoryTranslation &operator+=(const MemoryTranslation &other);
private: private:
uintptr_t src; ///< Base address of local address space uintptr_t src; // Base address of local address space
uintptr_t dst; ///< Base address of foreign address space uintptr_t dst; // Base address of foreign address space
size_t size; ///< Size of "memory window" size_t size; // Size of "memory window"
}; };
@ -115,10 +114,10 @@ private:
*/ */
class Mapping : public graph::Edge { class Mapping : public graph::Edge {
public: public:
std::string name; ///< Human-readable name std::string name; // Human-readable name
uintptr_t src; ///< Base address in "from" address space uintptr_t src; // Base address in "from" address space
uintptr_t dest; ///< Base address in "to" address space uintptr_t dest; // Base address in "to" address space
size_t size; ///< Size of the mapping size_t size; // Size of the mapping
friend std::ostream& friend std::ostream&
operator<< (std::ostream &stream, const Mapping &mapping) operator<< (std::ostream &stream, const Mapping &mapping)
@ -143,7 +142,7 @@ private:
*/ */
class AddressSpace : public graph::Vertex { class AddressSpace : public graph::Vertex {
public: public:
std::string name; ///< Human-readable name std::string name; // Human-readable name
friend std::ostream& friend std::ostream&
operator<< (std::ostream &stream, const AddressSpace &addrSpace) operator<< (std::ostream &stream, const AddressSpace &addrSpace)
@ -153,7 +152,7 @@ private:
} }
}; };
/// Memory graph with custom edges and vertices for address resolution // Memory graph with custom edges and vertices for address resolution
using MemoryGraph = graph::DirectedGraph<AddressSpace, Mapping>; using MemoryGraph = graph::DirectedGraph<AddressSpace, Mapping>;
public: public:
@ -162,92 +161,99 @@ public:
struct InvalidTranslation : public std::exception {}; struct InvalidTranslation : public std::exception {};
/// Get singleton instance // Get singleton instance
static MemoryManager& static MemoryManager&
get(); get();
MemoryGraph & getGraph() MemoryGraph & getGraph()
{ return memoryGraph; } {
return memoryGraph;
}
AddressSpaceId AddressSpaceId getProcessAddressSpace()
getProcessAddressSpace() {
{ return getOrCreateAddressSpace("process"); } return getOrCreateAddressSpace("process");
}
AddressSpaceId AddressSpaceId getPciAddressSpace()
getPciAddressSpace() {
{ return getOrCreateAddressSpace("pcie"); } return getOrCreateAddressSpace("pcie");
}
AddressSpaceId AddressSpaceId getProcessAddressSpaceMemoryBlock(const std::string &memoryBlock)
getProcessAddressSpaceMemoryBlock(const std::string &memoryBlock) {
{ return getOrCreateAddressSpace(getSlaveAddrSpaceName("process", memoryBlock)); } return getOrCreateAddressSpace(getSlaveAddrSpaceName("process", memoryBlock));
}
AddressSpaceId AddressSpaceId getOrCreateAddressSpace(std::string name);
getOrCreateAddressSpace(std::string name);
void void removeAddressSpace(const AddressSpaceId &addrSpaceId)
removeAddressSpace(const AddressSpaceId &addrSpaceId) {
{ memoryGraph.removeVertex(addrSpaceId); } memoryGraph.removeVertex(addrSpaceId);
}
/// Create a default mapping // Create a default mapping
MappingId MappingId createMapping(uintptr_t src, uintptr_t dest, size_t size,
createMapping(uintptr_t src, uintptr_t dest, size_t size,
const std::string &name, const std::string &name,
AddressSpaceId fromAddrSpace, AddressSpaceId fromAddrSpace,
AddressSpaceId toAddrSpace); AddressSpaceId toAddrSpace);
/// Add a mapping // Add a mapping
/// //
/// Can be used to derive from Mapping in order to implement custom // Can be used to derive from Mapping in order to implement custom
/// constructor/destructor. // constructor/destructor.
MappingId MappingId addMapping(std::shared_ptr<Mapping> mapping,
addMapping(std::shared_ptr<Mapping> mapping,
AddressSpaceId fromAddrSpace, AddressSpaceId fromAddrSpace,
AddressSpaceId toAddrSpace); AddressSpaceId toAddrSpace);
AddressSpaceId AddressSpaceId findAddressSpace(const std::string &name);
findAddressSpace(const std::string &name);
std::list<AddressSpaceId> std::list<AddressSpaceId> findPath(const AddressSpaceId &fromAddrSpaceId, const AddressSpaceId &toAddrSpaceId);
findPath(const AddressSpaceId &fromAddrSpaceId, const AddressSpaceId &toAddrSpaceId);
MemoryTranslation MemoryTranslation getTranslation(const AddressSpaceId &fromAddrSpaceId, const AddressSpaceId &toAddrSpaceId);
getTranslation(const AddressSpaceId &fromAddrSpaceId, const AddressSpaceId &toAddrSpaceId);
// cppcheck-suppress passedByValue // cppcheck-suppress passedByValue
MemoryTranslation getTranslationFromProcess(AddressSpaceId foreignAddrSpaceId) MemoryTranslation getTranslationFromProcess(AddressSpaceId foreignAddrSpaceId)
{ return getTranslation(getProcessAddressSpace(), foreignAddrSpaceId); } {
return getTranslation(getProcessAddressSpace(), foreignAddrSpaceId);
}
static std::string static
getSlaveAddrSpaceName(const std::string &ipInstance, const std::string &memoryBlock) std::string getSlaveAddrSpaceName(const std::string &ipInstance, const std::string &memoryBlock)
{ return ipInstance + "/" + memoryBlock; } {
return ipInstance + "/" + memoryBlock;
}
static std::string static
getMasterAddrSpaceName(const std::string &ipInstance, const std::string &busInterface) std::string getMasterAddrSpaceName(const std::string &ipInstance, const std::string &busInterface)
{ return ipInstance + ":" + busInterface; } {
return ipInstance + ":" + busInterface;
}
private: private:
/// Convert a Mapping to MemoryTranslation for calculations // Convert a Mapping to MemoryTranslation for calculations
static MemoryTranslation static
getTranslationFromMapping(const Mapping &mapping) MemoryTranslation getTranslationFromMapping(const Mapping &mapping)
{ return MemoryTranslation(mapping.src, mapping.dest, mapping.size); } {
return MemoryTranslation(mapping.src, mapping.dest, mapping.size);
}
bool bool pathCheck(const MemoryGraph::Path &path);
pathCheck(const MemoryGraph::Path &path);
/// Directed graph that stores address spaces and memory mappings // Directed graph that stores address spaces and memory mappings
MemoryGraph memoryGraph; MemoryGraph memoryGraph;
/// Cache mapping of names to address space ids for fast lookup // Cache mapping of names to address space ids for fast lookup
std::map<std::string, AddressSpaceId> addrSpaceLookup; std::map<std::string, AddressSpaceId> addrSpaceLookup;
/// Logger for universal access in this class // Logger for universal access in this class
Logger logger; Logger logger;
MemoryGraph::check_path_fn pathCheckFunc; MemoryGraph::check_path_fn pathCheckFunc;
/// Static pointer to global instance, because this is a singleton // Static pointer to global instance, because this is a singleton
static MemoryManager* instance; static MemoryManager* instance;
}; };
} /* namespace villas */ } // namespace villas

View file

@ -21,7 +21,7 @@
namespace villas { namespace villas {
namespace plugin { namespace plugin {
/* Forward declarations */ // Forward declarations
class Plugin; class Plugin;
class Registry; class Registry;
@ -65,7 +65,7 @@ public:
plugins.remove(p); plugins.remove(p);
} }
/// Get all plugins including sub-registries // Get all plugins including sub-registries
List<> lookup() { List<> lookup() {
List<> all; List<> all;
@ -80,7 +80,7 @@ public:
return all; return all;
} }
/// Get all plugins of specific type // Get all plugins of specific type
template<typename T = Plugin> template<typename T = Plugin>
List<T> lookup() List<T> lookup()
{ {
@ -92,7 +92,7 @@ public:
list.push_back(t); list.push_back(t);
} }
/* Sort alphabetically */ // Sort alphabetically
list.sort([](const T *a, const T *b) { list.sort([](const T *a, const T *b) {
return a->getName() < b->getName(); return a->getName() < b->getName();
}); });
@ -100,7 +100,7 @@ public:
return list; return list;
} }
/// Get all plugins of specific type and name // Get all plugins of specific type and name
template<typename T = Plugin> template<typename T = Plugin>
T * lookup(const std::string &name) T * lookup(const std::string &name)
{ {
@ -131,18 +131,18 @@ public:
virtual virtual
~Plugin(); ~Plugin();
// copying a plugin doesn't make sense, so explicitly deny it // Copying a plugin doesn't make sense, so explicitly deny it
Plugin(Plugin const&) = delete; Plugin(Plugin const&) = delete;
void operator=(Plugin const&) = delete; void operator=(Plugin const&) = delete;
virtual virtual
void dump(); void dump();
/// Get plugin name // Get plugin name
virtual virtual
std::string getName() const = 0; std::string getName() const = 0;
/// Get plugin type // Get plugin type
virtual virtual
std::string getType() const = 0; std::string getType() const = 0;
@ -182,5 +182,5 @@ Registry::dump()
} }
} }
} /* namespace plugin */ } // namespace plugin
} /* namespace villas */ } // namespace villas

View file

@ -103,8 +103,8 @@ protected:
} output; } output;
}; };
} /* namespace utils */ } // namespace utils
} /* namespace villas */ } // namespace villas
template<typename T> template<typename T>
std::istream &operator>>(villas::utils::PopenStream &po, T &value) std::istream &operator>>(villas::utils::PopenStream &po, T &value)

View file

@ -84,4 +84,4 @@ public:
} }
}; };
} /* namespace villas */ } // namespace villas

View file

@ -33,20 +33,20 @@
#endif #endif
struct Task { struct Task {
int clock; /**< CLOCK_{MONOTONIC,REALTIME} */ int clock; // CLOCK_{MONOTONIC,REALTIME}
#if PERIODIC_TASK_IMPL == RDTSC /* We use cycle counts in RDTSC mode */ #if PERIODIC_TASK_IMPL == RDTSC // We use cycle counts in RDTSC mode
uint64_t period; uint64_t period;
uint64_t next; uint64_t next;
#else #else
struct timespec period; /**< The period of periodic invations of this task */ struct timespec period; // The period of periodic invations of this task
struct timespec next; /**< The timer value for the next invocation */ struct timespec next; // The timer value for the next invocation
#endif #endif
#if PERIODIC_TASK_IMPL == TIMERFD #if PERIODIC_TASK_IMPL == TIMERFD
int fd; /**< The timerfd_create(2) file descriptior. */ int fd; // The timerfd_create(2) file descriptior.
#elif PERIODIC_TASK_IMPL == RDTSC #elif PERIODIC_TASK_IMPL == RDTSC
struct Tsc tsc; /**< Initialized by tsc_init(). */ struct Tsc tsc; // Initialized by tsc_init().
#endif #endif
/** Create a new task with the given rate. */ /** Create a new task with the given rate. */
@ -54,11 +54,10 @@ struct Task {
~Task(); ~Task();
/** Wait until task elapsed // Wait until task elapsed
* //
* @retval 0 An error occured. Maybe the task was stopped. // @retval 0 An error occured. Maybe the task was stopped.
* @retval >0 The nummer of runs this task already fired. // @retval >0 The nummer of runs this task already fired.
*/
uint64_t wait(); uint64_t wait();
void setNext(const struct timespec *next); void setNext(const struct timespec *next);
@ -67,9 +66,8 @@ struct Task {
void stop(); void stop();
/** Returns a poll'able file descriptor which becomes readable when the timer expires. // Returns a poll'able file descriptor which becomes readable when the timer expires.
* //
* Note: currently not supported on all platforms. // Note: currently not supported on all platforms.
*/
int getFD() const; int getFD() const;
}; };

View file

@ -47,4 +47,4 @@ public:
} }
}; };
} /* namespace villas */ } // namespace villas

View file

@ -55,4 +55,4 @@ public:
int run(); int run();
}; };
} /* namespace villas */ } // namespace villas

View file

@ -41,7 +41,7 @@
} while (0) } while (0)
#endif #endif
/* CPP stringification */ // CPP stringification
#define XSTR(x) STR(x) #define XSTR(x) STR(x)
#define STR(x) #x #define STR(x) #x
@ -62,19 +62,19 @@
y = t; \ y = t; \
} while (0) } while (0)
/** Round-up integer division */ // Round-up integer division
#define CEIL(x, y) (((x) + (y) - 1) / (y)) #define CEIL(x, y) (((x) + (y) - 1) / (y))
/** Get nearest up-rounded power of 2 */ // Get nearest up-rounded power of 2
#define LOG2_CEIL(x) (1 << (villas::utils::log2i((x) - 1) + 1)) #define LOG2_CEIL(x) (1 << (villas::utils::log2i((x) - 1) + 1))
/** Check if the number is a power of 2 */ // Check if the number is a power of 2
#define IS_POW2(x) (((x) != 0) && !((x) & ((x) - 1))) #define IS_POW2(x) (((x) != 0) && !((x) & ((x) - 1)))
/** Calculate the number of elements in an array. */ // Calculate the number of elements in an array.
#define ARRAY_LEN(a) ( sizeof (a) / sizeof (a)[0] ) #define ARRAY_LEN(a) ( sizeof (a) / sizeof (a)[0] )
/* Return the bigger value */ // Return the bigger value
#ifdef MAX #ifdef MAX
#undef MAX #undef MAX
#endif #endif
@ -82,7 +82,7 @@
__typeof__ (b) _b = (b); \ __typeof__ (b) _b = (b); \
_a > _b ? _a : _b; }) _a > _b ? _a : _b; })
/* Return the smaller value */ // Return the smaller value
#ifdef MIN #ifdef MIN
#undef MIN #undef MIN
#endif #endif
@ -103,7 +103,7 @@
#define BITS_PER_LONGLONG (sizeof(long long) * 8) #define BITS_PER_LONGLONG (sizeof(long long) * 8)
/* Some helper macros */ // Some helper macros
#define BITMASK(h, l) (((~0ULL) << (l)) & (~0ULL >> (BITS_PER_LONGLONG - 1 - (h)))) #define BITMASK(h, l) (((~0ULL) << (l)) & (~0ULL >> (BITS_PER_LONGLONG - 1 - (h))))
#define BIT(nr) (1UL << (nr)) #define BIT(nr) (1UL << (nr))
@ -204,6 +204,6 @@ using byte = std::uint8_t;
std::string encode(const std::vector<byte> &input); std::string encode(const std::vector<byte> &input);
std::vector<byte> decode(const std::string &input); std::vector<byte> decode(const std::string &input);
} /* namespace base64 */ } // namespace base64
} /* namespace utils */ } // namespace utils
} /* namespace villas */ } // namespace villas

View file

@ -28,5 +28,5 @@ void generateFromJson(uuid_t out, json_t *json, const std::string &ns = "");
/** Generate an UUID by MD5 hashing the serialized representation of the provided JSON object */ /** Generate an UUID by MD5 hashing the serialized representation of the provided JSON object */
int generateFromJson(uuid_t out, json_t *json, const uuid_t ns); int generateFromJson(uuid_t out, json_t *json, const uuid_t ns);
} /* namespace uuid */ } // namespace uuid
} /* namespace villas */ } // namespace villas

View file

@ -26,13 +26,30 @@ public:
Version(int maj, int min = 0, int pat = 0); Version(int maj, int min = 0, int pat = 0);
inline bool operator==(const Version &rhs) { return cmp(*this, rhs) == 0; } inline bool operator==(const Version &rhs) {
inline bool operator!=(const Version &rhs) { return cmp(*this, rhs) != 0; } return cmp(*this, rhs) == 0;
inline bool operator< (const Version &rhs) { return cmp(*this, rhs) < 0; } }
inline bool operator> (const Version &rhs) { return cmp(*this, rhs) > 0; }
inline bool operator<=(const Version &rhs) { return cmp(*this, rhs) <= 0; } inline bool operator!=(const Version &rhs) {
inline bool operator>=(const Version &rhs) { return cmp(*this, rhs) >= 0; } return cmp(*this, rhs) != 0;
}
inline bool operator< (const Version &rhs) {
return cmp(*this, rhs) < 0;
}
inline bool operator> (const Version &rhs) {
return cmp(*this, rhs) > 0;
}
inline bool operator<=(const Version &rhs) {
return cmp(*this, rhs) <= 0;
}
inline bool operator>=(const Version &rhs) {
return cmp(*this, rhs) >= 0;
}
}; };
} /* namespace villas */ } // namespace villas
} /* namespace utils */ } // namespace utils

View file

@ -111,6 +111,6 @@ std::vector<byte> decode(const std::string &input)
return decoded; return decoded;
} }
} /* namespace base64 */ } // namespace base64
} /* namespace utils */ } // namespace utils
} /* namespace villas */ } // namespace villas

View file

@ -19,7 +19,7 @@ json_t * Buffer::decode()
if (!j) if (!j)
return nullptr; return nullptr;
/* Remove decoded JSON document from beginning */ // Remove decoded JSON document from beginning
erase(begin(), begin() + err.position); erase(begin(), begin() + err.position);
return j; return j;
@ -34,7 +34,7 @@ int Buffer::callback(const char *data, size_t len, void *ctx)
{ {
Buffer *b = static_cast<Buffer *>(ctx); Buffer *b = static_cast<Buffer *>(ctx);
/* Append junk of JSON to buffer */ // Append junk of JSON to buffer
b->insert(b->end(), &data[0], &data[len]); b->insert(b->end(), &data[0], &data[len]);
return 0; return 0;

View file

@ -21,7 +21,7 @@ size_t json_dumpb(const json_t *json, char *buffer, size_t size, size_t flags)
if (!str) if (!str)
return 0; return 0;
len = strlen(str); /* not \0 terminated */ len = strlen(str); // Not \0 terminated
if (buffer && len <= size) if (buffer && len <= size)
memcpy(buffer, str, len); memcpy(buffer, str, len);
@ -54,7 +54,7 @@ static int json_dumpfd_callback(const char *buffer, size_t size, void *data)
(void)buffer; (void)buffer;
(void)size; (void)size;
(void)data; (void)data;
#endif /* HAVE_UNISTD_H */ #endif // HAVE_UNISTD_H
return -1; return -1;
} }
@ -63,4 +63,4 @@ int json_dumpfd(const json_t *json, int output, size_t flags)
{ {
return json_dump_callback(json, json_dumpfd_callback, (void *) &output, flags); return json_dump_callback(json, json_dumpfd_callback, (void *) &output, flags);
} }
#endif /* JANSSON_VERSION_HEX < 0x020A00 */ #endif // JANSSON_VERSION_HEX < 0x020A00

View file

@ -113,4 +113,4 @@ CpuSet::operator std::string ()
return ss.str(); return ss.str();
} }
#endif /* __linux__ */ #endif // __linux__

View file

@ -25,30 +25,30 @@ PID::PID(double _dt, double _max, double _min, double _Kp, double _Kd, double _K
double PID::calculate(double setpoint, double pv) double PID::calculate(double setpoint, double pv)
{ {
/* Calculate error */ // Calculate error
double error = setpoint - pv; double error = setpoint - pv;
/* Proportional term */ // Proportional term
double Pout = Kp * error; double Pout = Kp * error;
/* Integral term */ // Integral term
integral += error * dt; integral += error * dt;
double Iout = Ki * integral; double Iout = Ki * integral;
/* Derivative term */ // Derivative term
double derivative = (error - pre_error) / dt; double derivative = (error - pre_error) / dt;
double Dout = Kd * derivative; double Dout = Kd * derivative;
/* Calculate total output */ // Calculate total output
double output = Pout + Iout + Dout; double output = Pout + Iout + Dout;
/* Restrict to max/min */ // Restrict to max/min
if (output > max) if (output > max)
output = max; output = max;
else if (output < min) else if (output < min)
output = min; output = min;
/* Save error to previous error */ // Save error to previous error
pre_error = error; pre_error = error;
return output; return output;

View file

@ -39,7 +39,7 @@ void Hist::put(double value)
{ {
last = value; last = value;
/* Update min/max */ // Update min/max
if (value > highest) if (value > highest)
highest = value; highest = value;
if (value < lowest) if (value < lowest)
@ -47,7 +47,7 @@ void Hist::put(double value)
if (data.size()) { if (data.size()) {
if (total < warmup) { if (total < warmup) {
/* We are still in warmup phase... Waiting for more samples... */ // We are still in warmup phase... Waiting for more samples...
} }
else if (data.size() && total == warmup && warmup != 0) { else if (data.size() && total == warmup && warmup != 0) {
low = getMean() - 3 * getStddev(); low = getMean() - 3 * getStddev();
@ -55,13 +55,13 @@ void Hist::put(double value)
resolution = (high - low) / data.size(); resolution = (high - low) / data.size();
} }
else if (data.size() && (total == warmup) && (warmup == 0)) { else if (data.size() && (total == warmup) && (warmup == 0)) {
// there is no warmup phase // There is no warmup phase
// TODO resolution = ? // TODO resolution = ?
} }
else { else {
idx_t idx = std::round((value - low) / resolution); idx_t idx = std::round((value - low) / resolution);
/* Check bounds and increment */ // Check bounds and increment
if (idx >= (idx_t) data.size()) if (idx >= (idx_t) data.size())
higher++; higher++;
else if (idx < 0) else if (idx < 0)
@ -73,8 +73,8 @@ void Hist::put(double value)
total++; total++;
/* Online / running calculation of variance and mean // Online / running calculation of variance and mean
* by Donald Knuths Art of Computer Programming, Vol 2, page 232, 3rd edition */ // by Donald Knuths Art of Computer Programming, Vol 2, page 232, 3rd edition
if (total == 1) { if (total == 1) {
_m[1] = _m[0] = value; _m[1] = _m[0] = value;
_s[1] = 0.0; _s[1] = 0.0;
@ -83,7 +83,7 @@ void Hist::put(double value)
_m[0] = _m[1] + (value - _m[1]) / total; _m[0] = _m[1] + (value - _m[1]) / total;
_s[0] = _s[1] + (value - _m[1]) * (value - _m[0]); _s[0] = _s[1] + (value - _m[1]) * (value - _m[0]);
/* Set up for next iteration */ // Set up for next iteration
_m[1] = _m[0]; _m[1] = _m[0];
_s[1] = _s[0]; _s[1] = _s[0];
} }
@ -144,7 +144,7 @@ void Hist::print(Logger logger, bool details) const
void Hist::plot(Logger logger) const void Hist::plot(Logger logger) const
{ {
/* Get highest bar */ // Get highest bar
Hist::cnt_t max = *std::max_element(data.begin(), data.end()); Hist::cnt_t max = *std::max_element(data.begin(), data.end());
std::vector<TableColumn> cols = { std::vector<TableColumn> cols = {
@ -155,7 +155,7 @@ void Hist::plot(Logger logger) const
Table table = Table(logger, cols); Table table = Table(logger, cols);
/* Print plot */ // Print plot
table.header(); table.header();
for (size_t i = 0; i < data.size(); i++) { for (size_t i = 0; i < data.size(); i++) {
@ -263,4 +263,4 @@ int Hist::dumpMatlab(FILE *f) const
return 0; return 0;
} }
} /* namespace villas */ } // namespace villas

View file

@ -37,7 +37,7 @@ Version villas::kernel::getVersion()
std::string rel = uts.release; std::string rel = uts.release;
/* Remove release part. E.g. 4.9.93-linuxkit-aufs */ // Remove release part. E.g. 4.9.93-linuxkit-aufs
auto sep = rel.find('-'); auto sep = rel.find('-');
auto ver = rel.substr(0, sep - 1); auto ver = rel.substr(0, sep - 1);
@ -49,7 +49,7 @@ int villas::kernel::getCachelineSize()
#if defined(__linux__) && defined(__x86_64__) && defined(__GLIBC__) #if defined(__linux__) && defined(__x86_64__) && defined(__GLIBC__)
return sysconf(_SC_LEVEL1_ICACHE_LINESIZE); return sysconf(_SC_LEVEL1_ICACHE_LINESIZE);
#elif defined(__MACH__) #elif defined(__MACH__)
/* Open the command for reading. */ // Open the command for reading.
FILE *fp = popen("sysctl -n machdep.cpu.cache.linesize", "r"); FILE *fp = popen("sysctl -n machdep.cpu.cache.linesize", "r");
if (fp == nullptr) if (fp == nullptr)
return -1; return -1;
@ -75,7 +75,7 @@ int villas::kernel::getPageSize()
#error "Unsupported platform" #error "Unsupported platform"
#endif #endif
/* There is no sysconf interface to get the hugepage size */ // There is no sysconf interface to get the hugepage size
int villas::kernel::getHugePageSize() int villas::kernel::getHugePageSize()
{ {
#ifdef __linux__ #ifdef __linux__
@ -146,12 +146,12 @@ int villas::kernel::loadModule(const char *module)
pid_t pid = fork(); pid_t pid = fork();
switch (pid) { switch (pid) {
case -1: /* error */ case -1: // Error
return -1; return -1;
case 0: /* child */ case 0: // Child
execlp("modprobe", "modprobe", module, (char *) 0); execlp("modprobe", "modprobe", module, (char *) 0);
exit(EXIT_FAILURE); /* exec never returns */ exit(EXIT_FAILURE); // exec() never returns
default: default:
wait(&ret); wait(&ret);
@ -210,7 +210,7 @@ int villas::kernel::getCmdlineParam(const char *param, char *buf, size_t len)
if (ret >= 2 && buf) if (ret >= 2 && buf)
snprintf(buf, len, "%s", value); snprintf(buf, len, "%s", value);
return 0; /* found */ return 0; // Found
} }
} }
} while ((tok = strtok_r(nullptr, " \t", &lasts))); } while ((tok = strtok_r(nullptr, " \t", &lasts)));
@ -218,7 +218,7 @@ int villas::kernel::getCmdlineParam(const char *param, char *buf, size_t len)
out: out:
fclose(f); fclose(f);
return -1; /* not found or error */ return -1; // Not found or error
} }
int villas::kernel::getNrHugepages() int villas::kernel::getNrHugepages()
@ -266,7 +266,7 @@ int villas::kernel::setIRQAffinity(unsigned irq, uintmax_t aff, uintmax_t *old)
f = fopen(fn, "w+"); f = fopen(fn, "w+");
if (!f) if (!f)
return -1; /* IRQ does not exist */ return -1; // IRQ does not exist
if (old) if (old)
ret = fscanf(f, "%jx", old); ret = fscanf(f, "%jx", old);
@ -285,7 +285,7 @@ int villas::kernel::get_cpu_frequency(uint64_t *freq)
int ret; int ret;
FILE *f; FILE *f;
/* Try to get CPU frequency from cpufreq module */ // Try to get CPU frequency from cpufreq module
f = fopen(SYSFS_PATH "/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", "r"); f = fopen(SYSFS_PATH "/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", "r");
if (!f) if (!f)
goto cpuinfo; goto cpuinfo;
@ -295,16 +295,16 @@ int villas::kernel::get_cpu_frequency(uint64_t *freq)
if (ret != 1) if (ret != 1)
return -1; return -1;
/* cpufreq reports kHz */ // cpufreq reports kHz
*freq = *freq * 1000; *freq = *freq * 1000;
return 0; return 0;
cpuinfo: cpuinfo:
/* Try to read CPU frequency from /proc/cpuinfo */ // Try to read CPU frequency from /proc/cpuinfo
f = fopen(PROCFS_PATH "/cpuinfo", "r"); f = fopen(PROCFS_PATH "/cpuinfo", "r");
if (!f) if (!f)
return -1; /* We give up here */ return -1; // We give up here
ret = -1; ret = -1;
while (getline(&line, &len, f) >= 0) { while (getline(&line, &len, f) >= 0) {
@ -329,7 +329,7 @@ cpuinfo:
goto out; goto out;
} }
/* Frequency is given in MHz */ // Frequency is given in MHz
*freq = dfreq * 1e6; *freq = dfreq * 1e6;
out: fclose(f); out: fclose(f);
@ -337,4 +337,4 @@ out: fclose(f);
return ret; return ret;
} }
#endif /* __linux__ */ #endif // __linux__

View file

@ -35,7 +35,7 @@ DeviceList::DeviceList()
throw SystemError("Failed to detect PCI devices"); throw SystemError("Failed to detect PCI devices");
while ((e = readdir(dp))) { while ((e = readdir(dp))) {
/* Ignore special entries */ // Ignore special entries
if ((strcmp(e->d_name, ".") == 0) || if ((strcmp(e->d_name, ".") == 0) ||
(strcmp(e->d_name, "..") == 0) ) (strcmp(e->d_name, "..") == 0) )
continue; continue;
@ -48,7 +48,7 @@ DeviceList::DeviceList()
{ "device", &id.device } { "device", &id.device }
}; };
/* Read vendor & device id */ // Read vendor & device id
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
snprintf(path, sizeof(path), "%s/bus/pci/devices/%s/%s", SYSFS_PATH, e->d_name, map[i].s); snprintf(path, sizeof(path), "%s/bus/pci/devices/%s/%s", SYSFS_PATH, e->d_name, map[i].s);
@ -63,7 +63,7 @@ DeviceList::DeviceList()
fclose(f); fclose(f);
} }
/* Get slot id */ // Get slot id
ret = sscanf(e->d_name, "%4x:%2x:%2x.%u", &slot.domain, &slot.bus, &slot.device, &slot.function); ret = sscanf(e->d_name, "%4x:%2x:%2x.%u", &slot.domain, &slot.bus, &slot.device, &slot.function);
if (ret != 4) if (ret != 4)
throw RuntimeError("Failed to parse PCI slot number: {}", e->d_name); throw RuntimeError("Failed to parse PCI slot number: {}", e->d_name);
@ -280,7 +280,7 @@ Device::getRegions() const
int reg_num = 0; int reg_num = 0;
/* Cap to 8 regions, just because we don't know how many may exist. */ // Cap to 8 regions, just because we don't know how many may exist.
while (reg_num < 8 && (bytesRead = getline(&line, &len, f)) != -1) { while (reg_num < 8 && (bytesRead = getline(&line, &len, f)) != -1) {
unsigned long long tokens[3]; unsigned long long tokens[3];
char* s = line; char* s = line;
@ -289,7 +289,7 @@ Device::getRegions() const
tokens[i] = strtoull(s, &end, 16); tokens[i] = strtoull(s, &end, 16);
if (s == end) { if (s == end) {
printf("Error parsing line %d of %s\n", reg_num + 1, sysfs); printf("Error parsing line %d of %s\n", reg_num + 1, sysfs);
tokens[0] = tokens[1] = 0; /* Mark invalid */ tokens[0] = tokens[1] = 0; // Mark invalid
break; break;
} }
s = end; s = end;
@ -297,11 +297,11 @@ Device::getRegions() const
free(line); free(line);
/* Required for getline() to allocate a new buffer on the next iteration. */ // Required for getline() to allocate a new buffer on the next iteration.
line = nullptr; line = nullptr;
len = 0; len = 0;
if (tokens[0] != tokens[1]) { /* This is a valid region */ if (tokens[0] != tokens[1]) { // This is a valid region
Region region; Region region;
region.num = reg_num; region.num = reg_num;
@ -348,7 +348,7 @@ Device::attachDriver(const std::string &driver) const
FILE *f; FILE *f;
char fn[1024]; char fn[1024];
/* Add new ID to driver */ // Add new ID to driver
snprintf(fn, sizeof(fn), "%s/bus/pci/drivers/%s/new_id", SYSFS_PATH, driver.c_str()); snprintf(fn, sizeof(fn), "%s/bus/pci/drivers/%s/new_id", SYSFS_PATH, driver.c_str());
f = fopen(fn, "w"); f = fopen(fn, "w");
if (!f) if (!f)
@ -359,7 +359,7 @@ Device::attachDriver(const std::string &driver) const
fprintf(f, "%04x %04x", id.vendor, id.device); fprintf(f, "%04x %04x", id.vendor, id.device);
fclose(f); fclose(f);
/* Bind to driver */ // Bind to driver
snprintf(fn, sizeof(fn), "%s/bus/pci/drivers/%s/bind", SYSFS_PATH, driver.c_str()); snprintf(fn, sizeof(fn), "%s/bus/pci/drivers/%s/bind", SYSFS_PATH, driver.c_str());
f = fopen(fn, "w"); f = fopen(fn, "w");
if (!f) if (!f)
@ -377,7 +377,7 @@ Device::getIOMMUGroup() const
{ {
int ret; int ret;
char *group; char *group;
// readlink does not add a null terminator! // readlink() does not add a null terminator!
char link[1024] = {0}; char link[1024] = {0};
char sysfs[1024]; char sysfs[1024];

View file

@ -20,7 +20,7 @@
#ifdef __linux__ #ifdef __linux__
using villas::utils::CpuSet; using villas::utils::CpuSet;
#endif /* __linux__ */ #endif // __linux__
namespace villas { namespace villas {
namespace kernel { namespace kernel {
@ -36,7 +36,7 @@ void init(int priority, int affinity)
int is_rt, is_isol; int is_rt, is_isol;
char isolcpus[255]; char isolcpus[255];
/* Use FIFO scheduler with real time priority */ // Use FIFO scheduler with real time priority
is_rt = isPreemptible(); is_rt = isPreemptible();
if (!is_rt) if (!is_rt)
logger->warn("We recommend to use an PREEMPT_RT patched kernel!"); logger->warn("We recommend to use an PREEMPT_RT patched kernel!");
@ -68,7 +68,7 @@ void init(int priority, int affinity)
(void) affinity; (void) affinity;
(void) priority; (void) priority;
#endif /* __linux__ */ #endif // __linux__
} }
#ifdef __linux__ #ifdef __linux__
@ -80,7 +80,7 @@ void setProcessAffinity(int affinity)
Logger logger = logging.get("kernel:rt"); Logger logger = logging.get("kernel:rt");
/* Pin threads to CPUs by setting the affinity */ // Pin threads to CPUs by setting the affinity
CpuSet cset_pin(affinity); CpuSet cset_pin(affinity);
ret = sched_setaffinity(0, cset_pin.size(), cset_pin); ret = sched_setaffinity(0, cset_pin.size(), cset_pin);
@ -127,8 +127,8 @@ bool isPreemptible()
return access(SYSFS_PATH "/kernel/realtime", R_OK) == 0; return access(SYSFS_PATH "/kernel/realtime", R_OK) == 0;
} }
#endif /* __linux__ */ #endif // __linux__
} /* namespace villas */ } // namespace villas
} /* namespace kernel */ } // namespace kernel
} /* namespace rt */ } // namespace rt

View file

@ -144,7 +144,7 @@ bool Device::reset()
if (this->info.flags & VFIO_DEVICE_FLAGS_RESET) if (this->info.flags & VFIO_DEVICE_FLAGS_RESET)
return ioctl(this->fd, VFIO_DEVICE_RESET) == 0; return ioctl(this->fd, VFIO_DEVICE_RESET) == 0;
else else
return false; // not supported by this device return false; // Not supported by this device
} }
void * Device::regionMap(size_t index) void * Device::regionMap(size_t index)

View file

@ -64,7 +64,7 @@ void villas::list_push(struct List *l, void *p)
assert(l->state == State::INITIALIZED); assert(l->state == State::INITIALIZED);
/* Resize array if out of capacity */ // Resize array if out of capacity
if (l->length >= l->capacity) { if (l->length >= l->capacity) {
l->capacity += LIST_CHUNKSIZE; l->capacity += LIST_CHUNKSIZE;
l->array = (void **) realloc(l->array, l->capacity * sizeof(void *)); l->array = (void **) realloc(l->array, l->capacity * sizeof(void *));
@ -116,7 +116,7 @@ int villas::list_insert(struct List *l, size_t idx, void *p)
if (idx >= l->length) if (idx >= l->length)
return -1; return -1;
/* Resize array if out of capacity */ // Resize array if out of capacity
if (l->length + 1 > l->capacity) { if (l->length + 1 > l->capacity) {
l->capacity += LIST_CHUNKSIZE; l->capacity += LIST_CHUNKSIZE;
l->array = (void **) realloc(l->array, l->capacity * sizeof(void *)); l->array = (void **) realloc(l->array, l->capacity * sizeof(void *));
@ -198,7 +198,7 @@ void * villas::list_search(struct List *l, cmp_cb_t cmp, const void *ctx)
goto out; goto out;
} }
e = nullptr; /* not found */ e = nullptr; // Not found
out: pthread_mutex_unlock(&l->lock); out: pthread_mutex_unlock(&l->lock);

View file

@ -65,7 +65,7 @@ Log::Log(Level lvl) :
setLevel(level); setLevel(level);
setFormatter(pattern, p ? p : ""); setFormatter(pattern, p ? p : "");
/* Default sink */ // Default sink
sink = std::make_shared<spdlog::sinks::stderr_color_sink_mt>(); sink = std::make_shared<spdlog::sinks::stderr_color_sink_mt>();
sinks->add_sink(sink); sinks->add_sink(sink);
@ -94,7 +94,7 @@ Logger Log::get(const std::string &name)
for (auto &expr : expressions) { for (auto &expr : expressions) {
int flags = 0; int flags = 0;
#ifdef FNM_EXTMATCH #ifdef FNM_EXTMATCH
/* musl-libc doesnt support this flag yet */ // musl-libc doesnt support this flag yet
flags |= FNM_EXTMATCH; flags |= FNM_EXTMATCH;
#endif #endif
if (!fnmatch(expr.name.c_str(), name.c_str(), flags)) if (!fnmatch(expr.name.c_str(), name.c_str(), flags))

View file

@ -20,7 +20,7 @@ namespace villas {
std::unique_ptr<MemoryBlock, MemoryBlock::deallocator_fn> std::unique_ptr<MemoryBlock, MemoryBlock::deallocator_fn>
HostRam::HostRamAllocator::allocateBlock(size_t size) HostRam::HostRamAllocator::allocateBlock(size_t size)
{ {
/* Align to next bigger page size chunk */ // Align to next bigger page size chunk
if (size & size_t(0xFFF)) { if (size & size_t(0xFFF)) {
size += size_t(0x1000); size += size_t(0x1000);
size &= size_t(~0xFFF); size &= size_t(~0xFFF);
@ -40,7 +40,7 @@ HostRam::HostRamAllocator::allocateBlock(size_t size)
auto &mm = MemoryManager::get(); auto &mm = MemoryManager::get();
/* Assemble name for this block */ // Assemble name for this block
std::stringstream name; std::stringstream name;
name << std::showbase << std::hex << reinterpret_cast<uintptr_t>(addr); name << std::showbase << std::hex << reinterpret_cast<uintptr_t>(addr);
@ -65,7 +65,7 @@ LinearAllocator::LinearAllocator(MemoryManager::AddressSpaceId memoryAddrSpaceId
internalOffset(internalOffset), internalOffset(internalOffset),
allocationCount(0) allocationCount(0)
{ {
/* Make sure to start at aligned offset, reduce size in case we need padding */ // Make sure to start at aligned offset, reduce size in case we need padding
if (const size_t paddingBytes = getAlignmentPadding(internalOffset)) { if (const size_t paddingBytes = getAlignmentPadding(internalOffset)) {
assert(paddingBytes < memorySize); assert(paddingBytes < memorySize);
@ -73,7 +73,7 @@ LinearAllocator::LinearAllocator(MemoryManager::AddressSpaceId memoryAddrSpaceId
memorySize -= paddingBytes; memorySize -= paddingBytes;
} }
/* Deallocation callback */ // Deallocation callback
free = [&](MemoryBlock* mem) { free = [&](MemoryBlock* mem) {
logger->debug("Deallocating memory block at local addr {:#x} (addr space {})", logger->debug("Deallocating memory block at local addr {:#x} (addr space {})",
mem->getOffset(), mem->getAddrSpaceId()); mem->getOffset(), mem->getAddrSpaceId());
@ -84,7 +84,7 @@ LinearAllocator::LinearAllocator(MemoryManager::AddressSpaceId memoryAddrSpaceId
if (allocationCount == 0) { if (allocationCount == 0) {
logger->debug("All allocations are deallocated now, freeing memory"); logger->debug("All allocations are deallocated now, freeing memory");
/* All allocations have been deallocated, free all memory */ // All allocations have been deallocated, free all memory
nextFreeAddress = 0; nextFreeAddress = 0;
} }
@ -113,28 +113,28 @@ LinearAllocator::allocateBlock(size_t size)
throw std::bad_alloc(); throw std::bad_alloc();
} }
/* Assign address */ // Assign address
const uintptr_t localAddr = nextFreeAddress + internalOffset; const uintptr_t localAddr = nextFreeAddress + internalOffset;
/* Reserve memory */ // Reserve memory
nextFreeAddress += size; nextFreeAddress += size;
/* Make sure it is aligned */ // Make sure it is aligned
if (const size_t paddingBytes = getAlignmentPadding(nextFreeAddress)) { if (const size_t paddingBytes = getAlignmentPadding(nextFreeAddress)) {
nextFreeAddress += paddingBytes; nextFreeAddress += paddingBytes;
/* If next free address is outside this block due to padding, cap it */ // If next free address is outside this block due to padding, cap it
nextFreeAddress = std::min(nextFreeAddress, memorySize); nextFreeAddress = std::min(nextFreeAddress, memorySize);
} }
auto &mm = MemoryManager::get(); auto &mm = MemoryManager::get();
/* Assemble name for this block */ // Assemble name for this block
std::stringstream blockName; std::stringstream blockName;
blockName << std::showbase << std::hex << localAddr; blockName << std::showbase << std::hex << localAddr;
/* Create address space */ // Create address space
auto addrSpaceName = mm.getSlaveAddrSpaceName(getName(), blockName.str()); auto addrSpaceName = mm.getSlaveAddrSpaceName(getName(), blockName.str());
auto addrSpaceId = mm.getOrCreateAddressSpace(addrSpaceName); auto addrSpaceId = mm.getOrCreateAddressSpace(addrSpaceName);
@ -144,10 +144,10 @@ LinearAllocator::allocateBlock(size_t size)
std::unique_ptr<MemoryBlock, MemoryBlock::deallocator_fn> std::unique_ptr<MemoryBlock, MemoryBlock::deallocator_fn>
mem(new MemoryBlock(localAddr, size, addrSpaceId), this->free); mem(new MemoryBlock(localAddr, size, addrSpaceId), this->free);
/* Mount block into the memory graph */ // Mount block into the memory graph
insertMemoryBlock(*mem); insertMemoryBlock(*mem);
/* Increase the allocation count */ // Increase the allocation count
allocationCount++; allocationCount++;
return mem; return mem;
@ -219,13 +219,13 @@ HostDmaRam::HostDmaRamAllocator::~HostDmaRamAllocator()
auto translation = mm.getTranslationFromProcess(getAddrSpaceId()); auto translation = mm.getTranslationFromProcess(getAddrSpaceId());
baseVirt = reinterpret_cast<void*>(translation.getLocalAddr(0)); baseVirt = reinterpret_cast<void*>(translation.getLocalAddr(0));
} catch (const std::out_of_range&) { } catch (const std::out_of_range&) {
/* Not mapped, nothing to do */ // Not mapped, nothing to do
return; return;
} }
logger->debug("Unmapping {}", getName()); logger->debug("Unmapping {}", getName());
/* Try to unmap it */ // Try to unmap it
if (::munmap(baseVirt, getSize()) != 0) { if (::munmap(baseVirt, getSize()) != 0) {
logger->warn("munmap() failed for {:p} of size {:#x}", logger->warn("munmap() failed for {:p} of size {:#x}",
baseVirt, getSize()); baseVirt, getSize());
@ -287,4 +287,4 @@ HostDmaRam::HostDmaRamAllocator&HostDmaRam::getAllocator(int num)
return *allocator; return *allocator;
} }
} /* namespace villas */ } // namespace villas

View file

@ -37,14 +37,14 @@ MemoryManager::AddressSpaceId
MemoryManager::getOrCreateAddressSpace(std::string name) MemoryManager::getOrCreateAddressSpace(std::string name)
{ {
try { try {
/* Try fast lookup */ // Try fast lookup
return addrSpaceLookup.at(name); return addrSpaceLookup.at(name);
} catch (const std::out_of_range&) { } catch (const std::out_of_range&) {
/* Does not yet exist, create */ // Does not yet exist, create
std::shared_ptr<AddressSpace> addrSpace(new AddressSpace); std::shared_ptr<AddressSpace> addrSpace(new AddressSpace);
addrSpace->name = name; addrSpace->name = name;
/* Cache it for the next access */ // Cache it for the next access
addrSpaceLookup[name] = memoryGraph.addVertex(addrSpace); addrSpaceLookup[name] = memoryGraph.addVertex(addrSpace);
return addrSpaceLookup[name]; return addrSpaceLookup[name];
@ -93,7 +93,7 @@ MemoryManager::findPath(const MemoryManager::AddressSpaceId &fromAddrSpaceId,
auto fromAddrSpace = memoryGraph.getVertex(fromAddrSpaceId); auto fromAddrSpace = memoryGraph.getVertex(fromAddrSpaceId);
auto toAddrSpace = memoryGraph.getVertex(toAddrSpaceId); auto toAddrSpace = memoryGraph.getVertex(toAddrSpaceId);
/* Find a path through the memory graph */ // Find a path through the memory graph
MemoryGraph::Path pathGraph; MemoryGraph::Path pathGraph;
if (not memoryGraph.getPath(fromAddrSpaceId, toAddrSpaceId, pathGraph, pathCheckFunc)) { if (not memoryGraph.getPath(fromAddrSpaceId, toAddrSpaceId, pathGraph, pathCheckFunc)) {
@ -145,9 +145,8 @@ MemoryManager::pathCheck(const MemoryGraph::Path &path)
// Start with an identity mapping // Start with an identity mapping
MemoryTranslation translation(0, 0, SIZE_MAX); MemoryTranslation translation(0, 0, SIZE_MAX);
/* Try to add all mappings together to a common translation. If this fails // Try to add all mappings together to a common translation. If this fails
* there is a non-overlapping window. // there is a non-overlapping window.
*/
for (auto &mappingId : path) { for (auto &mappingId : path) {
auto mapping = memoryGraph.getEdge(mappingId); auto mapping = memoryGraph.getEdge(mappingId);
try { try {
@ -181,7 +180,7 @@ MemoryTranslation::operator+=(const MemoryTranslation &other)
{ {
Logger logger = logging.get("MemoryTranslation"); Logger logger = logging.get("MemoryTranslation");
/* Set level to debug to enable debug output */ // Set level to debug to enable debug output
logger->set_level(spdlog::level::info); logger->set_level(spdlog::level::info);
const uintptr_t this_dst_high = this->dst + this->size; const uintptr_t this_dst_high = this->dst + this->size;
@ -196,7 +195,7 @@ MemoryTranslation::operator+=(const MemoryTranslation &other)
logger->debug("this_dst_high: {:#x}", this_dst_high); logger->debug("this_dst_high: {:#x}", this_dst_high);
logger->debug("other_src_high: {:#x}", other_src_high); logger->debug("other_src_high: {:#x}", other_src_high);
/* Make sure there is a common memory area */ // Make sure there is a common memory area
assertExcept(other.src < this_dst_high, MemoryManager::InvalidTranslation()); assertExcept(other.src < this_dst_high, MemoryManager::InvalidTranslation());
assertExcept(this->dst < other_src_high, MemoryManager::InvalidTranslation()); assertExcept(this->dst < other_src_high, MemoryManager::InvalidTranslation());
@ -217,25 +216,23 @@ MemoryTranslation::operator+=(const MemoryTranslation &other)
logger->debug("diff_hi: {:#x}", diff_hi); logger->debug("diff_hi: {:#x}", diff_hi);
logger->debug("diff_lo: {:#x}", diff_lo); logger->debug("diff_lo: {:#x}", diff_lo);
/* New size of aperture, can only stay or shrink */ // New size of aperture, can only stay or shrink
this->size = (hi - lo) - diff_hi - diff_lo; this->size = (hi - lo) - diff_hi - diff_lo;
/* New translation will come out other's destination (by default) */ // New translation will come out other's destination (by default)
this->dst = other.dst; this->dst = other.dst;
/* The source stays the same and can only increase with merged translations */ // The source stays the same and can only increase with merged translations
//this->src = this->src; //this->src = this->src;
if (otherSrcIsSmaller) if (otherSrcIsSmaller)
/* Other mapping starts at lower addresses, so we actually arrive at // Other mapping starts at lower addresses, so we actually arrive at
* higher addresses // higher addresses
*/
this->dst += diff_lo; this->dst += diff_lo;
else else
/* Other mapping starts at higher addresses than this, so we have to // Other mapping starts at higher addresses than this, so we have to
* increase the start // increase the start
* NOTE: for addresses equality, this just adds 0 // NOTE: for addresses equality, this just adds 0
*/
this->src += diff_lo; this->src += diff_lo;
logger->debug("result src: {:#x}", this->src); logger->debug("result src: {:#x}", this->src);
@ -245,4 +242,4 @@ MemoryTranslation::operator+=(const MemoryTranslation &other)
return *this; return *this;
} }
} /* namespace villas */ } // namespace villas

View file

@ -80,7 +80,7 @@ void Popen::open()
goto clean_outpipe_out; goto clean_outpipe_out;
if (pid == 0) { if (pid == 0) {
/* Prepare arguments */ // Prepare arguments
if (shell) { if (shell) {
argv.push_back((char *) "sh"); argv.push_back((char *) "sh");
argv.push_back((char *) "-c"); argv.push_back((char *) "-c");
@ -94,7 +94,7 @@ void Popen::open()
} }
} }
/* Prepare environment */ // Prepare environment
for (char **p = environ; *p; p++) for (char **p = environ; *p; p++)
envp.push_back(*p); envp.push_back(*p);
@ -108,7 +108,7 @@ void Popen::open()
argv.push_back(nullptr); argv.push_back(nullptr);
envp.push_back(nullptr); envp.push_back(nullptr);
/* Redirect IO */ // Redirect IO
::close(outpipe[READ]); ::close(outpipe[READ]);
::close(inpipe[WRITE]); ::close(inpipe[WRITE]);
@ -122,7 +122,7 @@ void Popen::open()
::close(outpipe[WRITE]); ::close(outpipe[WRITE]);
} }
/* Change working directory */ // Change working directory
if (!working_dir.empty()) { if (!working_dir.empty()) {
int ret; int ret;
@ -205,5 +205,5 @@ int PopenStream::close()
return ret; return ret;
} }
} /* namespace utils */ } // namespace utils
} /* namespace villas */ } // namespace villas

View file

@ -28,7 +28,7 @@ int Table::resize(int w)
fixed = 0; fixed = 0;
total = width - columns.size() * 2; total = width - columns.size() * 2;
/* Normalize width */ // Normalize width
for (unsigned i = 0; i < columns.size(); i++) { for (unsigned i = 0; i < columns.size(); i++) {
if (columns[i].width > 0) if (columns[i].width > 0)
norm += columns[i].width; norm += columns[i].width;

View file

@ -18,7 +18,7 @@ using namespace villas;
#if PERIODIC_TASK_IMPL == TIMERFD #if PERIODIC_TASK_IMPL == TIMERFD
#include <sys/timerfd.h> #include <sys/timerfd.h>
#endif /* PERIODIC_TASK_IMPL */ #endif // PERIODIC_TASK_IMPL
Task::Task(int clk) : Task::Task(int clk) :
clock(clk) clock(clk)
@ -31,7 +31,7 @@ Task::Task(int clk) :
int ret = tsc_init(&tsc); int ret = tsc_init(&tsc);
if (ret) if (ret)
return ret; return ret;
#endif /* PERIODIC_TASK_IMPL */ #endif // PERIODIC_TASK_IMPL
} }
void Task::setTimeout(double to) void Task::setTimeout(double to)
@ -62,8 +62,8 @@ void Task::setNext(const struct timespec *nxt)
ret = timerfd_settime(fd, TFD_TIMER_ABSTIME, &its, nullptr); ret = timerfd_settime(fd, TFD_TIMER_ABSTIME, &its, nullptr);
if (ret) if (ret)
throw SystemError("Failed to set timerfd"); throw SystemError("Failed to set timerfd");
#endif /* PERIODIC_TASK_IMPL == TIMERFD */ #endif // PERIODIC_TASK_IMPL == TIMERFD
#endif /* PERIODIC_TASK_IMPL != RDTSC */ #endif // PERIODIC_TASK_IMPL != RDTSC
} }
void Task::setRate(double rate) void Task::setRate(double rate)
@ -72,7 +72,7 @@ void Task::setRate(double rate)
period = tsc_rate_to_cycles(&tsc, rate); period = tsc_rate_to_cycles(&tsc, rate);
next = tsc_now(&tsc) + period; next = tsc_now(&tsc) + period;
#else #else
/* A rate of 0 will disarm the timer */ // A rate of 0 will disarm the timer
period = rate ? time_from_double(1.0 / rate) : (struct timespec) { 0, 0 }; period = rate ? time_from_double(1.0 / rate) : (struct timespec) { 0, 0 };
#if PERIODIC_TASK_IMPL == CLOCK_NANOSLEEP || PERIODIC_TASK_IMPL == NANOSLEEP #if PERIODIC_TASK_IMPL == CLOCK_NANOSLEEP || PERIODIC_TASK_IMPL == NANOSLEEP
@ -93,8 +93,8 @@ void Task::setRate(double rate)
ret = timerfd_settime(fd, 0, &its, nullptr); ret = timerfd_settime(fd, 0, &its, nullptr);
if (ret) if (ret)
throw SystemError("Failed to set timerfd"); throw SystemError("Failed to set timerfd");
#endif /* PERIODIC_TASK_IMPL */ #endif // PERIODIC_TASK_IMPL
#endif /* PERIODIC_TASK_IMPL == RDTSC */ #endif // PERIODIC_TASK_IMPL == RDTSC
} }
Task::~Task() Task::~Task()
@ -175,7 +175,7 @@ void Task::stop()
ret = timerfd_settime(fd, 0, &its, nullptr); ret = timerfd_settime(fd, 0, &its, nullptr);
if (ret) if (ret)
throw SystemError("Failed to disarm timerfd"); throw SystemError("Failed to disarm timerfd");
#endif /* PERIODIC_TASK_IMPL == TIMERFD */ #endif // PERIODIC_TASK_IMPL == TIMERFD
} }
int Task::getFD() const int Task::getFD() const

View file

@ -37,7 +37,7 @@ Terminal::Terminal()
if (ret) if (ret)
throw SystemError("Failed to register signal handler"); throw SystemError("Failed to register signal handler");
/* Try to get initial terminal dimensions */ // Try to get initial terminal dimensions
ret = ioctl(STDERR_FILENO, TIOCGWINSZ, &window); ret = ioctl(STDERR_FILENO, TIOCGWINSZ, &window);
if (ret) if (ret)
logger->warn("Failed to get terminal dimensions"); logger->warn("Failed to get terminal dimensions");
@ -45,7 +45,7 @@ Terminal::Terminal()
logger->info("stderr is not associated with a terminal! Using fallback values for window size..."); logger->info("stderr is not associated with a terminal! Using fallback values for window size...");
} }
/* Fallback if for some reason we can not determine a prober window size */ // Fallback if for some reason we can not determine a prober window size
if (window.ws_col == 0) if (window.ws_col == 0)
window.ws_col = 150; window.ws_col = 150;

View file

@ -54,10 +54,10 @@ int Tool::run()
if (ret) if (ret)
throw RuntimeError("Failed to initialize signal subsystem"); throw RuntimeError("Failed to initialize signal subsystem");
/* Parse command line arguments */ // Parse command line arguments
parse(); parse();
/* Run tool */ // Run tool
ret = main(); ret = main();
logger->info(CLR_GRN("Goodbye!")); logger->info(CLR_GRN("Goodbye!"));

View file

@ -49,11 +49,11 @@ std::vector<std::string> tokenize(std::string s, const std::string &delimiter)
const size_t tokenLength = curentPos - lastPos; const size_t tokenLength = curentPos - lastPos;
tokens.push_back(s.substr(lastPos, tokenLength)); tokens.push_back(s.substr(lastPos, tokenLength));
/* Advance in string */ // Advance in string
lastPos = curentPos + delimiter.length(); lastPos = curentPos + delimiter.length();
} }
/* Check if there's a last token behind the last delimiter. */ // Check if there's a last token behind the last delimiter.
if (lastPos != s.length()) { if (lastPos != s.length()) {
const size_t lastTokenLength = s.length() - lastPos; const size_t lastTokenLength = s.length() - lastPos;
tokens.push_back(s.substr(lastPos, lastTokenLength)); tokens.push_back(s.substr(lastPos, lastTokenLength));
@ -85,7 +85,7 @@ ssize_t readRandom(char *buf, size_t len)
return bytes; return bytes;
} }
/* Setup exit handler */ // Setup exit handler
int signalsInit(void (*cb)(int signal, siginfo_t *sinfo, void *ctx), std::list<int> cbSignals, std::list<int> ignoreSignals) int signalsInit(void (*cb)(int signal, siginfo_t *sinfo, void *ctx), std::list<int> cbSignals, std::list<int> ignoreSignals)
{ {
int ret; int ret;
@ -161,7 +161,7 @@ char * decolor(char *str)
void killme(int sig) void killme(int sig)
{ {
/* Send only to main thread in case the ID was initilized by signalsInit() */ // Send only to main thread in case the ID was initilized by signalsInit()
if (main_thread) if (main_thread)
pthread_kill(main_thread, sig); pthread_kill(main_thread, sig);
else else
@ -174,7 +174,7 @@ double boxMuller(float m, float s)
static double y2; static double y2;
static int use_last = 0; static int use_last = 0;
if (use_last) { /* use value from previous call */ if (use_last) { // Use value from previous call
y1 = y2; y1 = y2;
use_last = 0; use_last = 0;
} }
@ -282,14 +282,14 @@ size_t strlenp(const char *str)
else if (c[0] == '\b') else if (c[0] == '\b')
sz--; sz--;
else if (c[0] == '\t') else if (c[0] == '\t')
sz += 4; /* tab width == 4 */ sz += 4; // Tab width == 4
/* CSI sequence */ // CSI sequence
else if (c[0] == '\e' && c[1] == '[') { else if (c[0] == '\e' && c[1] == '[') {
c += 2; c += 2;
while (*c && *c != 'm') while (*c && *c != 'm')
c++; c++;
} }
/* UTF-8 */ // UTF-8
else if (c[0] >= 0xc2 && c[0] <= 0xdf) { else if (c[0] >= 0xc2 && c[0] <= 0xdf) {
sz++; sz++;
c += 1; c += 1;
@ -374,5 +374,5 @@ bool isPrivileged() {
return true; return true;
} }
} /* namespace utils */ } // namespace utils
} /* namespace villas */ } // namespace villas

View file

@ -20,12 +20,12 @@ int villas::uuid::generateFromString(uuid_t out, const std::string &data, const
if (!ret) if (!ret)
return -1; return -1;
/* Namespace */ // Namespace
ret = EVP_DigestUpdate(c, (unsigned char *) ns.c_str(), ns.size()); ret = EVP_DigestUpdate(c, (unsigned char *) ns.c_str(), ns.size());
if (!ret) if (!ret)
return -1; return -1;
/* Data */ // Data
ret = EVP_DigestUpdate(c, (unsigned char *) data.c_str(), data.size()); ret = EVP_DigestUpdate(c, (unsigned char *) data.c_str(), data.size());
if (!ret) if (!ret)
return -1; return -1;
@ -48,12 +48,12 @@ int villas::uuid::generateFromString(uuid_t out, const std::string &data, const
if (!ret) if (!ret)
return -1; return -1;
/* Namespace */ // Namespace
ret = EVP_DigestUpdate(c, (unsigned char *) ns, 16); ret = EVP_DigestUpdate(c, (unsigned char *) ns, 16);
if (!ret) if (!ret)
return -1; return -1;
/* Data */ // Data
ret = EVP_DigestUpdate(c, (unsigned char *) data.c_str(), data.size()); ret = EVP_DigestUpdate(c, (unsigned char *) data.c_str(), data.size());
if (!ret) if (!ret)
return -1; return -1;

View file

@ -21,11 +21,6 @@ static std::vector<byte> vec(const char *str)
return std::vector<byte>((byte *) str, (byte *) str + strlen(str)); return std::vector<byte>((byte *) str, (byte *) str + strlen(str));
} }
// static std::string str(const std::vector<byte> &vec)
// {
// return std::string((char *) vec.data(), vec.size());
// }
Test(base64, encoding) Test(base64, encoding)
{ {
cr_assert(encode(vec("pohy0Aiy1ZaVa5aik2yaiy3ifoh3oole")) == "cG9oeTBBaXkxWmFWYTVhaWsyeWFpeTNpZm9oM29vbGU="); cr_assert(encode(vec("pohy0Aiy1ZaVa5aik2yaiy3ifoh3oole")) == "cG9oeTBBaXkxWmFWYTVhaWsyeWFpeTNpZm9oM29vbGU=");

View file

@ -74,7 +74,7 @@ Test(graph, path, .description = "Find path")
g.addDefaultEdge(v1id, v2id); g.addDefaultEdge(v1id, v2id);
g.addDefaultEdge(v2id, v3id); g.addDefaultEdge(v2id, v3id);
// create circular subgraph // Create circular subgraph
g.addDefaultEdge(v4id, v5id); g.addDefaultEdge(v4id, v5id);
g.addDefaultEdge(v5id, v4id); g.addDefaultEdge(v5id, v4id);
g.addDefaultEdge(v5id, v6id); g.addDefaultEdge(v5id, v6id);

View file

@ -27,7 +27,7 @@ TestSuite(kernel, .description = "Kernel features");
#error "Unsupported architecture" #error "Unsupported architecture"
#endif #endif
/* This test is not portable, but we currently support x86 only */ // This test is not portable, but we currently support x86 only
Test(kernel, sizes) Test(kernel, sizes)
{ {
int sz; int sz;
@ -91,7 +91,7 @@ Test(kernel, frequency)
ret = get_cpu_frequency(&freq); ret = get_cpu_frequency(&freq);
cr_assert_eq(ret, 0); cr_assert_eq(ret, 0);
/* Check for plausability only */ // Check for plausability only
cr_assert(freq > 1e9 && freq < 5e9); cr_assert(freq > 1e9 && freq < 5e9);
} }
#endif #endif

View file

@ -33,13 +33,13 @@ Test(list, list_search)
ret = list_init(&l); ret = list_init(&l);
cr_assert_eq(ret, 0); cr_assert_eq(ret, 0);
/* Fill list */ // Fill list
for (unsigned i = 0; i < ARRAY_LEN(nouns); i++) for (unsigned i = 0; i < ARRAY_LEN(nouns); i++)
list_push(&l, (void *) nouns[i]); list_push(&l, (void *) nouns[i]);
cr_assert_eq(list_length(&l), ARRAY_LEN(nouns)); cr_assert_eq(list_length(&l), ARRAY_LEN(nouns));
/* Declare on stack! */ // Declare on stack!
char positive[] = "woman"; char positive[] = "woman";
char negative[] = "dinosaurrier"; char negative[] = "dinosaurrier";

View file

@ -24,32 +24,32 @@ Test(timing, time_now)
Test(timing, time_diff) Test(timing, time_diff)
{ {
struct timespec ts1 = { .tv_sec = 0, .tv_nsec = 1}; /* Value doesnt matter */ struct timespec ts1 = { .tv_sec = 0, .tv_nsec = 1}; // Value doesnt matter
struct timespec ts2 = { .tv_sec = 1, .tv_nsec = 0}; /* Overflow in nano seconds! */ struct timespec ts2 = { .tv_sec = 1, .tv_nsec = 0}; // Overflow in nano seconds!
struct timespec ts3 = time_diff(&ts1, &ts2); struct timespec ts3 = time_diff(&ts1, &ts2);
/* ts4 == ts2? */ // ts4 == ts2?
cr_assert_eq(ts3.tv_sec, 0); cr_assert_eq(ts3.tv_sec, 0);
cr_assert_eq(ts3.tv_nsec, 999999999); cr_assert_eq(ts3.tv_nsec, 999999999);
} }
Test(timing, time_add) Test(timing, time_add)
{ {
struct timespec ts1 = { .tv_sec = 1, .tv_nsec = 999999999}; /* Value doesnt matter */ struct timespec ts1 = { .tv_sec = 1, .tv_nsec = 999999999}; // Value doesnt matter
struct timespec ts2 = { .tv_sec = 1, .tv_nsec = 1}; /* Overflow in nano seconds! */ struct timespec ts2 = { .tv_sec = 1, .tv_nsec = 1}; // Overflow in nano seconds!
struct timespec ts3 = time_add(&ts1, &ts2); struct timespec ts3 = time_add(&ts1, &ts2);
/* ts4 == ts2? */ // ts4 == ts2?
cr_assert_eq(ts3.tv_sec, 3); cr_assert_eq(ts3.tv_sec, 3);
cr_assert_eq(ts3.tv_nsec, 0); cr_assert_eq(ts3.tv_nsec, 0);
} }
Test(timing, time_delta) Test(timing, time_delta)
{ {
struct timespec ts1 = { .tv_sec = 1, .tv_nsec = 123}; /* Value doesnt matter */ struct timespec ts1 = { .tv_sec = 1, .tv_nsec = 123}; // Value doesnt matter
struct timespec ts2 = { .tv_sec = 5, .tv_nsec = 246}; /* Overflow in nano seconds! */ struct timespec ts2 = { .tv_sec = 5, .tv_nsec = 246}; // Overflow in nano seconds!
double delta = time_delta(&ts1, &ts2); double delta = time_delta(&ts1, &ts2);

View file

@ -18,7 +18,7 @@ using namespace villas::utils;
// cppcheck-suppress unknownMacro // cppcheck-suppress unknownMacro
TestSuite(utils, .description = "Utilities"); TestSuite(utils, .description = "Utilities");
/* Simple normality test for 1,2,3s intervals */ // Simple normality test for 1,2,3s intervals
Test(utils, box_muller) Test(utils, box_muller)
{ {
double n; double n;
@ -40,9 +40,9 @@ Test(utils, box_muller)
(double) sigma[0] / iter); (double) sigma[0] / iter);
#endif #endif
/* The random variable generated by the Box Muller transform is // The random variable generated by the Box Muller transform is
* not an ideal normal distributed variable. // not an ideal normal distributed variable.
* The numbers from below are empirically measured. */ // The numbers from below are empirically measured.
cr_assert_float_eq((double) sigma[2] / iter, 0.045527, 1e-2); cr_assert_float_eq((double) sigma[2] / iter, 0.045527, 1e-2);
cr_assert_float_eq((double) sigma[1] / iter, 0.271644, 1e-2); cr_assert_float_eq((double) sigma[1] / iter, 0.271644, 1e-2);
cr_assert_float_eq((double) sigma[0] / iter, 0.682829, 1e-2); cr_assert_float_eq((double) sigma[0] / iter, 0.682829, 1e-2);
@ -101,7 +101,7 @@ Test(utils, cpuset)
cset1.zero(); cset1.zero();
cr_assert(cset1.empty()); cr_assert(cset1.empty());
} }
#endif /* __linux__ */ #endif // __linux__
Test(utils, memdup) Test(utils, memdup)
{ {
@ -120,11 +120,11 @@ Test(utils, memdup)
Test(utils, is_aligned) Test(utils, is_aligned)
{ {
/* Positive */ // Positive
cr_assert(IS_ALIGNED(1, 1)); cr_assert(IS_ALIGNED(1, 1));
cr_assert(IS_ALIGNED(128, 64)); cr_assert(IS_ALIGNED(128, 64));
/* Negative */ // Negative
cr_assert(!IS_ALIGNED(55, 16)); cr_assert(!IS_ALIGNED(55, 16));
cr_assert(!IS_ALIGNED(55, 55)); cr_assert(!IS_ALIGNED(55, 55));
cr_assert(!IS_ALIGNED(1128, 256)); cr_assert(!IS_ALIGNED(1128, 256));
@ -139,12 +139,12 @@ Test(utils, ceil)
Test(utils, is_pow2) Test(utils, is_pow2)
{ {
/* Positive */ // Positive
cr_assert(IS_POW2(1)); cr_assert(IS_POW2(1));
cr_assert(IS_POW2(2)); cr_assert(IS_POW2(2));
cr_assert(IS_POW2(64)); cr_assert(IS_POW2(64));
/* Negative */ // Negative
cr_assert(!IS_POW2(0)); cr_assert(!IS_POW2(0));
cr_assert(!IS_POW2(3)); cr_assert(!IS_POW2(3));
cr_assert(!IS_POW2(11111)); cr_assert(!IS_POW2(11111));
@ -192,7 +192,7 @@ Test(utils, sha1sum)
unsigned char hash[SHA_DIGEST_LENGTH]; unsigned char hash[SHA_DIGEST_LENGTH];
unsigned char expected[SHA_DIGEST_LENGTH] = { 0x69, 0xdf, 0x29, 0xdf, 0x1f, 0xf2, 0xd2, 0x5d, 0xb8, 0x68, 0x6c, 0x02, 0x8d, 0xdf, 0x40, 0xaf, 0xb3, 0xc1, 0xc9, 0x4d }; unsigned char expected[SHA_DIGEST_LENGTH] = { 0x69, 0xdf, 0x29, 0xdf, 0x1f, 0xf2, 0xd2, 0x5d, 0xb8, 0x68, 0x6c, 0x02, 0x8d, 0xdf, 0x40, 0xaf, 0xb3, 0xc1, 0xc9, 0x4d };
/* Write the first 512 fibonaccia numbers to the file */ // Write the first 512 fibonaccia numbers to the file
for (int i = 0, a = 0, b = 1, c; i < 512; i++, a = b, b = c) { for (int i = 0, a = 0, b = 1, c; i < 512; i++, a = b, b = c) {
c = a + b; c = a + b;