system-linux: detect adding and removal of devices
[project/netifd.git] / utils.h
1 #ifndef __NETIFD_UTILS_H
2 #define __NETIFD_UTILS_H
3
4 #include <libubox/list.h>
5 #include <libubox/avl.h>
6
7 #ifdef DEBUG
8 #define DPRINTF(format, ...) fprintf(stderr, "%s(%d): " format, __func__, __LINE__, ## __VA_ARGS__)
9 #else
10 #define DPRINTF(format, ...) no_debug(format, ## __VA_ARGS__)
11 #endif
12
13 static inline void no_debug(const char *fmt, ...)
14 {
15 }
16
17 #define __init __attribute__((constructor))
18
19 struct vlist_tree;
20 struct vlist_node;
21
22 typedef void (*vlist_update_cb)(struct vlist_tree *tree,
23                                 struct vlist_node *node_new,
24                                 struct vlist_node *node_old);
25
26 struct vlist_tree {
27         struct avl_tree avl;
28
29         vlist_update_cb update;
30
31         int data_offset;
32         int data_len;
33
34         int version;
35 };
36
37 struct vlist_node {
38         struct avl_node avl;
39         int version;
40 };
41
42 void __vlist_init(struct vlist_tree *tree, vlist_update_cb update, int offset, int len);
43
44 #define vlist_init(tree, update, type, vlist, first, last) \
45         __vlist_init(tree, update, offsetof(type, first) - offsetof(type, vlist), \
46                      offsetof(type, last) - offsetof(type, first) + sizeof(((type *) 0)->last))
47
48 void vlist_add(struct vlist_tree *tree, struct vlist_node *node);
49 void vlist_delete(struct vlist_tree *tree, struct vlist_node *node);
50 void vlist_flush(struct vlist_tree *tree);
51 void vlist_flush_all(struct vlist_tree *tree);
52
53 #ifdef __linux__
54 static inline int fls(int x)
55 {
56     int r = 32;
57
58     if (!x)
59         return 0;
60     if (!(x & 0xffff0000u)) {
61         x <<= 16;
62         r -= 16;
63     }
64     if (!(x & 0xff000000u)) {
65         x <<= 8;
66         r -= 8;
67     }
68     if (!(x & 0xf0000000u)) {
69         x <<= 4;
70         r -= 4;
71     }
72     if (!(x & 0xc0000000u)) {
73         x <<= 2;
74         r -= 2;
75     }
76     if (!(x & 0x80000000u)) {
77         x <<= 1;
78         r -= 1;
79     }
80     return r;
81 }
82 #endif
83
84 int avl_strcmp(const void *k1, const void *k2, void *ptr);
85
86 #endif