6 #if defined(__FreeBSD__) || defined(__APPLE__)
8 # define MADV_DONTFORK INHERIT_NONE
9 #endif /* __FreeBSD__ || __APPLE__*/
11 char *global_host_prefix = "";
14 volatile sig_atomic_t netdata_exit = 0;
15 const char *os_type = NETDATA_OS_TYPE;
17 // ----------------------------------------------------------------------------
18 // memory allocation functions that handle failures
20 // although netdata does not use memory allocations too often (netdata tries to
21 // maintain its memory footprint stable during runtime, i.e. all buffers are
22 // allocated during initialization and are adapted to current use throughout
23 // its lifetime), these can be used to override the default system allocation
26 #ifdef NETDATA_LOG_ALLOCATIONS
27 static struct memory_statistics {
28 volatile size_t malloc_calls_made;
29 volatile size_t calloc_calls_made;
30 volatile size_t realloc_calls_made;
31 volatile size_t strdup_calls_made;
32 volatile size_t free_calls_made;
33 volatile size_t memory_calls_made;
34 volatile size_t allocated_memory;
35 volatile size_t mmapped_memory;
38 static inline void print_allocations(const char *file, const char *function, const unsigned long line) {
39 static struct memory_statistics old = { 0, 0, 0, 0, 0, 0, 0, 0 };
41 //if(unlikely(!(memory_statistics.memory_calls_made % 5))) {
42 fprintf(stderr, "(%04lu@%-10.10s:%-15.15s): Allocated %zu KB (+%zu B), mmapped %zu KB (+%zu B): malloc %zu (+%zu), calloc %zu (+%zu), realloc %zu (+%zu), strdup %zu (+%zu), free %zu (+%zu)\n",
44 (memory_statistics.allocated_memory + 512) / 1024, memory_statistics.allocated_memory - old.allocated_memory,
45 (memory_statistics.mmapped_memory + 512) / 1024, memory_statistics.mmapped_memory - old.mmapped_memory,
46 memory_statistics.malloc_calls_made, memory_statistics.malloc_calls_made - old.malloc_calls_made,
47 memory_statistics.calloc_calls_made, memory_statistics.calloc_calls_made - old.calloc_calls_made,
48 memory_statistics.realloc_calls_made, memory_statistics.realloc_calls_made - old.realloc_calls_made,
49 memory_statistics.strdup_calls_made, memory_statistics.strdup_calls_made - old.strdup_calls_made,
50 memory_statistics.free_calls_made, memory_statistics.free_calls_made - old.free_calls_made
53 memcpy(&old, &memory_statistics, sizeof(struct memory_statistics));
57 static inline void malloc_accounting(const char *file, const char *function, const unsigned long line, size_t size) {
58 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
59 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
60 __atomic_fetch_add(&memory_statistics.malloc_calls_made, 1, __ATOMIC_SEQ_CST);
61 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
63 // this is for debugging - we don't care locking it
64 memory_statistics.memory_calls_made++;
65 memory_statistics.malloc_calls_made++;
66 memory_statistics.allocated_memory += size;
68 print_allocations(file, function, line);
71 static inline void mmap_accounting(size_t size) {
72 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
73 __atomic_fetch_add(&memory_statistics.malloc_calls_made, 1, __ATOMIC_SEQ_CST);
74 __atomic_fetch_add(&memory_statistics.mmapped_memory, size, __ATOMIC_SEQ_CST);
76 // this is for debugging - we don't care locking it
77 memory_statistics.memory_calls_made++;
78 memory_statistics.mmapped_memory += size;
82 static inline void calloc_accounting(const char *file, const char *function, const unsigned long line, size_t size) {
83 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
84 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
85 __atomic_fetch_add(&memory_statistics.calloc_calls_made, 1, __ATOMIC_SEQ_CST);
86 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
88 // this is for debugging - we don't care locking it
89 memory_statistics.memory_calls_made++;
90 memory_statistics.calloc_calls_made++;
91 memory_statistics.allocated_memory += size;
93 print_allocations(file, function, line);
96 static inline void realloc_accounting(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) {
99 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
100 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
101 __atomic_fetch_add(&memory_statistics.realloc_calls_made, 1, __ATOMIC_SEQ_CST);
102 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
104 // this is for debugging - we don't care locking it
105 memory_statistics.memory_calls_made++;
106 memory_statistics.realloc_calls_made++;
107 memory_statistics.allocated_memory += size;
109 print_allocations(file, function, line);
112 static inline void strdup_accounting(const char *file, const char *function, const unsigned long line, const char *s) {
113 size_t size = strlen(s) + 1;
115 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
116 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
117 __atomic_fetch_add(&memory_statistics.strdup_calls_made, 1, __ATOMIC_SEQ_CST);
118 __atomic_fetch_add(&memory_statistics.allocated_memory, size, __ATOMIC_SEQ_CST);
120 // this is for debugging - we don't care locking it
121 memory_statistics.memory_calls_made++;
122 memory_statistics.strdup_calls_made++;
123 memory_statistics.allocated_memory += size;
125 print_allocations(file, function, line);
128 static inline void free_accounting(const char *file, const char *function, const unsigned long line, void *ptr) {
134 #if defined(HAVE_C___ATOMIC) && !defined(NETDATA_NO_ATOMIC_INSTRUCTIONS)
135 __atomic_fetch_add(&memory_statistics.memory_calls_made, 1, __ATOMIC_SEQ_CST);
136 __atomic_fetch_add(&memory_statistics.free_calls_made, 1, __ATOMIC_SEQ_CST);
138 // this is for debugging - we don't care locking it
139 memory_statistics.memory_calls_made++;
140 memory_statistics.free_calls_made++;
146 #ifdef NETDATA_LOG_ALLOCATIONS
147 char *strdupz_int(const char *file, const char *function, const unsigned long line, const char *s) {
148 strdup_accounting(file, function, line, s);
150 char *strdupz(const char *s) {
154 if (unlikely(!t)) fatal("Cannot strdup() string '%s'", s);
158 #ifdef NETDATA_LOG_ALLOCATIONS
159 void *mallocz_int(const char *file, const char *function, const unsigned long line, size_t size) {
160 malloc_accounting(file, function, line, size);
162 void *mallocz(size_t size) {
165 void *p = malloc(size);
166 if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", size);
170 #ifdef NETDATA_LOG_ALLOCATIONS
171 void *callocz_int(const char *file, const char *function, const unsigned long line, size_t nmemb, size_t size) {
172 calloc_accounting(file, function, line, nmemb * size);
174 void *callocz(size_t nmemb, size_t size) {
177 void *p = calloc(nmemb, size);
178 if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", nmemb * size);
182 #ifdef NETDATA_LOG_ALLOCATIONS
183 void *reallocz_int(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) {
184 realloc_accounting(file, function, line, ptr, size);
186 void *reallocz(void *ptr, size_t size) {
189 void *p = realloc(ptr, size);
190 if (unlikely(!p)) fatal("Cannot re-allocate memory to %zu bytes.", size);
194 #ifdef NETDATA_LOG_ALLOCATIONS
195 void freez_int(const char *file, const char *function, const unsigned long line, void *ptr) {
196 free_accounting(file, function, line, ptr);
198 void freez(void *ptr) {
204 void json_escape_string(char *dst, const char *src, size_t size) {
206 char *d = dst, *e = &dst[size - 1];
208 for(t = src; *t && d < e ;t++) {
209 if(unlikely(*t == '\\' || *t == '"')) {
210 if(unlikely(d + 1 >= e)) break;
219 int sleep_usec(usec_t usec) {
221 #ifndef NETDATA_WITH_USLEEP
222 // we expect microseconds (1.000.000 per second)
223 // but timespec is nanoseconds (1.000.000.000 per second)
224 struct timespec rem, req = {
225 .tv_sec = (time_t) (usec / 1000000),
226 .tv_nsec = (suseconds_t) ((usec % 1000000) * 1000)
229 while (nanosleep(&req, &rem) == -1) {
230 if (likely(errno == EINTR)) {
231 debug(D_SYSTEM, "nanosleep() interrupted (while sleeping for %llu microseconds).", usec);
232 req.tv_sec = rem.tv_sec;
233 req.tv_nsec = rem.tv_nsec;
235 error("Cannot nanosleep() for %llu microseconds.", usec);
242 int ret = usleep(usec);
243 if(unlikely(ret == -1 && errno == EINVAL)) {
244 // on certain systems, usec has to be up to 999999
246 int counter = usec / 999999;
250 usleep(usec % 999999);
253 error("Cannot usleep() for %llu microseconds.", usec);
259 error("usleep() failed for %llu microseconds.", usec);
265 unsigned char netdata_map_chart_names[256] = {
358 [92] = '/', // backslash
524 // make sure the supplied string
525 // is good for a netdata chart/dimension ID/NAME
526 void netdata_fix_chart_name(char *s) {
527 while ((*s = netdata_map_chart_names[(unsigned char) *s])) s++;
530 unsigned char netdata_map_chart_ids[256] = {
623 [92] = '/', // backslash
789 // make sure the supplied string
790 // is good for a netdata chart/dimension ID/NAME
791 void netdata_fix_chart_id(char *s) {
792 while ((*s = netdata_map_chart_ids[(unsigned char) *s])) s++;
796 // http://stackoverflow.com/questions/7666509/hash-function-for-string
797 uint32_t simple_hash(const char *name)
799 const char *s = name;
800 uint32_t hash = 5381;
803 while((i = *s++)) hash = ((hash << 5) + hash) + i;
805 // fprintf(stderr, "HASH: %lu %s\n", hash, name);
812 // http://isthe.com/chongo/tech/comp/fnv/#FNV-1a
813 uint32_t simple_hash(const char *name) {
814 unsigned char *s = (unsigned char *) name;
815 uint32_t hval = 0x811c9dc5;
819 // multiply by the 32 bit FNV magic prime mod 2^32
820 // NOTE: No need to optimize with left shifts.
821 // GCC will use imul instruction anyway.
822 // Tested with 'gcc -O3 -S'
823 //hval += (hval<<1) + (hval<<4) + (hval<<7) + (hval<<8) + (hval<<24);
826 // xor the bottom with the current octet
827 hval ^= (uint32_t) *s++;
830 // fprintf(stderr, "HASH: %u = %s\n", hval, name);
834 uint32_t simple_uhash(const char *name) {
835 unsigned char *s = (unsigned char *) name;
836 uint32_t hval = 0x811c9dc5, c;
840 if (unlikely(c >= 'A' && c <= 'Z')) c += 'a' - 'A';
849 // http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
850 // one at a time hash
851 uint32_t simple_hash(const char *name) {
852 unsigned char *s = (unsigned char *)name;
865 // fprintf(stderr, "HASH: %u = %s\n", h, name);
871 void strreverse(char *begin, char *end) {
872 while (end > begin) {
880 char *mystrsep(char **ptr, char *s) {
882 while (p && !p[0] && *ptr) p = strsep(ptr, s);
886 char *trim(char *s) {
887 // skip leading spaces
888 // and 'comments' as well!?
889 while (*s && isspace(*s)) s++;
890 if (!*s || *s == '#') return NULL;
892 // skip tailing spaces
893 // this way is way faster. Writes only one NUL char.
894 ssize_t l = strlen(s);
897 while (p > s && isspace(*p)) p--;
901 if (!*s) return NULL;
906 void *mymmap(const char *filename, size_t size, int flags, int ksm) {
907 static int log_madvise_1 = 1;
908 #ifdef MADV_MERGEABLE
909 static int log_madvise_2 = 1, log_madvise_3 = 1;
914 int fd = open(filename, O_RDWR | O_CREAT | O_NOATIME, 0664);
916 if (lseek(fd, size, SEEK_SET) == (off_t) size) {
917 if (write(fd, "", 1) == 1) {
918 if (ftruncate(fd, size))
919 error("Cannot truncate file '%s' to size %zu. Will use the larger file.", filename, size);
921 #ifdef MADV_MERGEABLE
922 if (flags & MAP_SHARED || !enable_ksm || !ksm) {
924 mem = mmap(NULL, size, PROT_READ | PROT_WRITE, flags, fd, 0);
925 if (mem == MAP_FAILED) {
926 error("Cannot allocate SHARED memory for file '%s'.", filename);
930 #ifdef NETDATA_LOG_ALLOCATIONS
931 mmap_accounting(size);
933 int advise = MADV_SEQUENTIAL | MADV_DONTFORK;
934 if (flags & MAP_SHARED) advise |= MADV_WILLNEED;
936 if (madvise(mem, size, advise) != 0 && log_madvise_1) {
937 error("Cannot advise the kernel about the memory usage of file '%s'.", filename);
941 #ifdef MADV_MERGEABLE
945 // test - load the file into memory
946 mem = calloc(1, size);
948 if(lseek(fd, 0, SEEK_SET) == 0) {
949 if(read(fd, mem, size) != (ssize_t)size)
950 error("Cannot read from file '%s'", filename);
953 error("Cannot seek to beginning of file '%s'.", filename);
956 mem = mmap(NULL, size, PROT_READ | PROT_WRITE, flags | MAP_ANONYMOUS, -1, 0);
957 if (mem == MAP_FAILED) {
958 error("Cannot allocate PRIVATE ANONYMOUS memory for KSM for file '%s'.", filename);
962 #ifdef NETDATA_LOG_ALLOCATIONS
963 mmap_accounting(size);
965 if (lseek(fd, 0, SEEK_SET) == 0) {
966 if (read(fd, mem, size) != (ssize_t) size)
967 error("Cannot read from file '%s'", filename);
969 error("Cannot seek to beginning of file '%s'.", filename);
971 // don't use MADV_SEQUENTIAL|MADV_DONTFORK, they disable MADV_MERGEABLE
972 if (madvise(mem, size, MADV_SEQUENTIAL | MADV_DONTFORK) != 0 && log_madvise_2) {
973 error("Cannot advise the kernel about the memory usage (MADV_SEQUENTIAL|MADV_DONTFORK) of file '%s'.",
978 if (madvise(mem, size, MADV_MERGEABLE) != 0 && log_madvise_3) {
979 error("Cannot advise the kernel about the memory usage (MADV_MERGEABLE) of file '%s'.",
988 error("Cannot write to file '%s' at position %zu.", filename, size);
991 error("Cannot seek file '%s' to size %zu.", filename, size);
996 error("Cannot create/open file '%s'.", filename);
1001 int savememory(const char *filename, void *mem, size_t size) {
1002 char tmpfilename[FILENAME_MAX + 1];
1004 snprintfz(tmpfilename, FILENAME_MAX, "%s.%ld.tmp", filename, (long) getpid());
1006 int fd = open(tmpfilename, O_RDWR | O_CREAT | O_NOATIME, 0664);
1008 error("Cannot create/open file '%s'.", filename);
1012 if (write(fd, mem, size) != (ssize_t) size) {
1013 error("Cannot write to file '%s' %ld bytes.", filename, (long) size);
1020 if (rename(tmpfilename, filename)) {
1021 error("Cannot rename '%s' to '%s'", tmpfilename, filename);
1028 int fd_is_valid(int fd) {
1029 return fcntl(fd, F_GETFD) != -1 || errno != EBADF;
1032 pid_t gettid(void) {
1034 return (pid_t)pthread_getthreadid_np();
1035 #elif defined(__APPLE__)
1036 uint64_t curthreadid;
1037 pthread_threadid_np(NULL, &curthreadid);
1038 return (pid_t)curthreadid;
1040 return (pid_t)syscall(SYS_gettid);
1041 #endif /* __FreeBSD__, __APPLE__*/
1044 char *fgets_trim_len(char *buf, size_t buf_size, FILE *fp, size_t *len) {
1045 char *s = fgets(buf, (int)buf_size, fp);
1046 if (!s) return NULL;
1050 // find the string end
1051 while (*++t != '\0');
1053 // trim trailing spaces/newlines/tabs
1054 while (--t > s && *t == '\n')
1064 int vsnprintfz(char *dst, size_t n, const char *fmt, va_list args) {
1065 int size = vsnprintf(dst, n, fmt, args);
1067 if (unlikely((size_t) size > n)) {
1076 int snprintfz(char *dst, size_t n, const char *fmt, ...) {
1079 va_start(args, fmt);
1080 int ret = vsnprintfz(dst, n, fmt, args);
1086 // ----------------------------------------------------------------------------
1088 // to retrieve settings of the system
1091 long get_system_cpus(void) {
1095 int32_t tmp_processors;
1097 if (unlikely(GETSYSCTL("hw.logicalcpu", tmp_processors))) {
1098 error("Assuming system has %d processors.", processors);
1100 processors = tmp_processors;
1105 int32_t tmp_processors;
1107 if (unlikely(GETSYSCTL("hw.ncpu", tmp_processors))) {
1108 error("Assuming system has %d processors.", processors);
1110 processors = tmp_processors;
1116 char filename[FILENAME_MAX + 1];
1117 snprintfz(filename, FILENAME_MAX, "%s/proc/stat", global_host_prefix);
1119 procfile *ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);
1121 error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1125 ff = procfile_readall(ff);
1127 error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);
1133 for(i = 0; i < procfile_lines(ff); i++) {
1134 if(!procfile_linewords(ff, i)) continue;
1136 if(strncmp(procfile_lineword(ff, i, 0), "cpu", 3) == 0) processors++;
1139 if(processors < 1) processors = 1;
1143 debug(D_SYSTEM, "System has %d processors.", processors);
1146 #endif /* __APPLE__, __FreeBSD__ */
1149 pid_t pid_max = 32768;
1150 pid_t get_system_pid_max(void) {
1152 // As we currently do not know a solution to query pid_max from the os
1153 // we use the number defined in bsd/sys/proc_internal.h in XNU sources
1157 int32_t tmp_pid_max;
1159 if (unlikely(GETSYSCTL("kern.pid_max", tmp_pid_max))) {
1161 error("Assuming system's maximum pid is %d.", pid_max);
1163 pid_max = tmp_pid_max;
1169 static char read = 0;
1170 if(unlikely(read)) return pid_max;
1173 char filename[FILENAME_MAX + 1];
1174 snprintfz(filename, FILENAME_MAX, "%s/proc/sys/kernel/pid_max", global_host_prefix);
1176 unsigned long long max = 0;
1177 if(read_single_number_file(filename, &max) != 0) {
1178 error("Cannot open file '%s'. Assuming system supports %d pids.", filename, pid_max);
1183 error("Cannot parse file '%s'. Assuming system supports %d pids.", filename, pid_max);
1187 pid_max = (pid_t) max;
1190 #endif /* __APPLE__, __FreeBSD__ */
1194 void get_system_HZ(void) {
1197 if ((ticks = sysconf(_SC_CLK_TCK)) == -1) {
1198 error("Cannot get system clock ticks");
1201 hz = (unsigned int) ticks;
1205 // poor man cycle counting
1206 static unsigned long tsc;
1207 void begin_tsc(void) {
1209 asm volatile ("cpuid\nrdtsc" : "=a" (a), "=d" (d) : "0" (0) : "ebx", "ecx");
1210 tsc = ((unsigned long)d << 32) | (unsigned long)a;
1212 unsigned long end_tsc(void) {
1214 asm volatile ("rdtscp" : "=a" (a), "=d" (d) : : "ecx");
1215 return (((unsigned long)d << 32) | (unsigned long)a) - tsc;