77e662f4e185dbcc0e2d7ebdc29d1092cc73de52
[platform/upstream/nodejs.git] / deps / uv / src / unix / darwin.c
1 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
2  * Permission is hereby granted, free of charge, to any person obtaining a copy
3  * of this software and associated documentation files (the "Software"), to
4  * deal in the Software without restriction, including without limitation the
5  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
6  * sell copies of the Software, and to permit persons to whom the Software is
7  * furnished to do so, subject to the following conditions:
8  *
9  * The above copyright notice and this permission notice shall be included in
10  * all copies or substantial portions of the Software.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
17  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
18  * IN THE SOFTWARE.
19  */
20
21 #include "uv.h"
22 #include "internal.h"
23
24 #include <assert.h>
25 #include <stdint.h>
26 #include <errno.h>
27
28 #include <ifaddrs.h>
29 #include <net/if.h>
30
31 #include <CoreFoundation/CFRunLoop.h>
32
33 #include <mach/mach.h>
34 #include <mach/mach_time.h>
35 #include <mach-o/dyld.h> /* _NSGetExecutablePath */
36 #include <sys/resource.h>
37 #include <sys/sysctl.h>
38 #include <unistd.h>  /* sysconf */
39
40 /* Forward declarations */
41 static void uv__cf_loop_runner(void* arg);
42 static void uv__cf_loop_cb(void* arg);
43
44 typedef struct uv__cf_loop_signal_s uv__cf_loop_signal_t;
45 struct uv__cf_loop_signal_s {
46   void* arg;
47   cf_loop_signal_cb cb;
48   ngx_queue_t member;
49 };
50
51
52 int uv__platform_loop_init(uv_loop_t* loop, int default_loop) {
53   CFRunLoopSourceContext ctx;
54   int r;
55
56   if (uv__kqueue_init(loop))
57     return -1;
58
59   loop->cf_loop = NULL;
60   if ((r = uv_mutex_init(&loop->cf_mutex)))
61     return r;
62   if ((r = uv_sem_init(&loop->cf_sem, 0)))
63     return r;
64   ngx_queue_init(&loop->cf_signals);
65
66   memset(&ctx, 0, sizeof(ctx));
67   ctx.info = loop;
68   ctx.perform = uv__cf_loop_cb;
69   loop->cf_cb = CFRunLoopSourceCreate(NULL, 0, &ctx);
70
71   if ((r = uv_thread_create(&loop->cf_thread, uv__cf_loop_runner, loop)))
72     return r;
73
74   /* Synchronize threads */
75   uv_sem_wait(&loop->cf_sem);
76   assert(ACCESS_ONCE(CFRunLoopRef, loop->cf_loop) != NULL);
77
78   return 0;
79 }
80
81
82 void uv__platform_loop_delete(uv_loop_t* loop) {
83   ngx_queue_t* item;
84   uv__cf_loop_signal_t* s;
85
86   assert(loop->cf_loop != NULL);
87   uv__cf_loop_signal(loop, NULL, NULL);
88   uv_thread_join(&loop->cf_thread);
89
90   uv_sem_destroy(&loop->cf_sem);
91   uv_mutex_destroy(&loop->cf_mutex);
92
93   /* Free any remaining data */
94   while (!ngx_queue_empty(&loop->cf_signals)) {
95     item = ngx_queue_head(&loop->cf_signals);
96
97     s = ngx_queue_data(item, uv__cf_loop_signal_t, member);
98
99     ngx_queue_remove(item);
100     free(s);
101   }
102 }
103
104
105 static void uv__cf_loop_runner(void* arg) {
106   uv_loop_t* loop;
107
108   loop = arg;
109
110   /* Get thread's loop */
111   ACCESS_ONCE(CFRunLoopRef, loop->cf_loop) = CFRunLoopGetCurrent();
112
113   CFRunLoopAddSource(loop->cf_loop,
114                      loop->cf_cb,
115                      kCFRunLoopDefaultMode);
116
117   uv_sem_post(&loop->cf_sem);
118
119   CFRunLoopRun();
120
121   CFRunLoopRemoveSource(loop->cf_loop,
122                         loop->cf_cb,
123                         kCFRunLoopDefaultMode);
124 }
125
126
127 static void uv__cf_loop_cb(void* arg) {
128   uv_loop_t* loop;
129   ngx_queue_t* item;
130   ngx_queue_t split_head;
131   uv__cf_loop_signal_t* s;
132
133   loop = arg;
134
135   uv_mutex_lock(&loop->cf_mutex);
136   ngx_queue_init(&split_head);
137   if (!ngx_queue_empty(&loop->cf_signals)) {
138     ngx_queue_t* split_pos = ngx_queue_next(&loop->cf_signals);
139     ngx_queue_split(&loop->cf_signals, split_pos, &split_head);
140   }
141   uv_mutex_unlock(&loop->cf_mutex);
142
143   while (!ngx_queue_empty(&split_head)) {
144     item = ngx_queue_head(&split_head);
145
146     s = ngx_queue_data(item, uv__cf_loop_signal_t, member);
147
148     /* This was a termination signal */
149     if (s->cb == NULL)
150       CFRunLoopStop(loop->cf_loop);
151     else
152       s->cb(s->arg);
153
154     ngx_queue_remove(item);
155     free(s);
156   }
157 }
158
159
160 void uv__cf_loop_signal(uv_loop_t* loop, cf_loop_signal_cb cb, void* arg) {
161   uv__cf_loop_signal_t* item;
162
163   item = malloc(sizeof(*item));
164   /* XXX: Fail */
165   if (item == NULL)
166     abort();
167
168   item->arg = arg;
169   item->cb = cb;
170
171   uv_mutex_lock(&loop->cf_mutex);
172   ngx_queue_insert_tail(&loop->cf_signals, &item->member);
173   uv_mutex_unlock(&loop->cf_mutex);
174
175   assert(loop->cf_loop != NULL);
176   CFRunLoopSourceSignal(loop->cf_cb);
177   CFRunLoopWakeUp(loop->cf_loop);
178 }
179
180
181 uint64_t uv__hrtime(void) {
182     mach_timebase_info_data_t info;
183
184     if (mach_timebase_info(&info) != KERN_SUCCESS)
185       abort();
186
187     return mach_absolute_time() * info.numer / info.denom;
188 }
189
190
191 int uv_exepath(char* buffer, size_t* size) {
192   uint32_t usize;
193   int result;
194   char* path;
195   char* fullpath;
196
197   if (!buffer || !size) {
198     return -1;
199   }
200
201   usize = *size;
202   result = _NSGetExecutablePath(buffer, &usize);
203   if (result) return result;
204
205   path = (char*)malloc(2 * PATH_MAX);
206   fullpath = realpath(buffer, path);
207
208   if (fullpath == NULL) {
209     free(path);
210     return -1;
211   }
212
213   strncpy(buffer, fullpath, *size);
214   free(fullpath);
215   *size = strlen(buffer);
216   return 0;
217 }
218
219
220 uint64_t uv_get_free_memory(void) {
221   vm_statistics_data_t info;
222   mach_msg_type_number_t count = sizeof(info) / sizeof(integer_t);
223
224   if (host_statistics(mach_host_self(), HOST_VM_INFO,
225                       (host_info_t)&info, &count) != KERN_SUCCESS) {
226     return -1;
227   }
228
229   return (uint64_t) info.free_count * sysconf(_SC_PAGESIZE);
230 }
231
232
233 uint64_t uv_get_total_memory(void) {
234   uint64_t info;
235   int which[] = {CTL_HW, HW_MEMSIZE};
236   size_t size = sizeof(info);
237
238   if (sysctl(which, 2, &info, &size, NULL, 0) < 0) {
239     return -1;
240   }
241
242   return (uint64_t) info;
243 }
244
245
246 void uv_loadavg(double avg[3]) {
247   struct loadavg info;
248   size_t size = sizeof(info);
249   int which[] = {CTL_VM, VM_LOADAVG};
250
251   if (sysctl(which, 2, &info, &size, NULL, 0) < 0) return;
252
253   avg[0] = (double) info.ldavg[0] / info.fscale;
254   avg[1] = (double) info.ldavg[1] / info.fscale;
255   avg[2] = (double) info.ldavg[2] / info.fscale;
256 }
257
258
259 uv_err_t uv_resident_set_memory(size_t* rss) {
260   mach_msg_type_number_t count;
261   task_basic_info_data_t info;
262   kern_return_t err;
263
264   count = TASK_BASIC_INFO_COUNT;
265   err = task_info(mach_task_self(),
266                   TASK_BASIC_INFO,
267                   (task_info_t) &info,
268                   &count);
269   (void) &err;
270   /* task_info(TASK_BASIC_INFO) cannot really fail. Anything other than
271    * KERN_SUCCESS implies a libuv bug.
272    */
273   assert(err == KERN_SUCCESS);
274   *rss = info.resident_size;
275
276   return uv_ok_;
277 }
278
279
280 uv_err_t uv_uptime(double* uptime) {
281   time_t now;
282   struct timeval info;
283   size_t size = sizeof(info);
284   static int which[] = {CTL_KERN, KERN_BOOTTIME};
285
286   if (sysctl(which, 2, &info, &size, NULL, 0) < 0) {
287     return uv__new_sys_error(errno);
288   }
289   now = time(NULL);
290
291   *uptime = (double)(now - info.tv_sec);
292
293   return uv_ok_;
294 }
295
296 uv_err_t uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
297   unsigned int ticks = (unsigned int)sysconf(_SC_CLK_TCK),
298                multiplier = ((uint64_t)1000L / ticks);
299   char model[512];
300   uint64_t cpuspeed;
301   size_t size;
302   unsigned int i;
303   natural_t numcpus;
304   mach_msg_type_number_t msg_type;
305   processor_cpu_load_info_data_t *info;
306   uv_cpu_info_t* cpu_info;
307
308   size = sizeof(model);
309   if (sysctlbyname("machdep.cpu.brand_string", &model, &size, NULL, 0) < 0 &&
310       sysctlbyname("hw.model", &model, &size, NULL, 0) < 0) {
311     return uv__new_sys_error(errno);
312   }
313   size = sizeof(cpuspeed);
314   if (sysctlbyname("hw.cpufrequency", &cpuspeed, &size, NULL, 0) < 0) {
315     return uv__new_sys_error(errno);
316   }
317
318   if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numcpus,
319                           (processor_info_array_t*)&info,
320                           &msg_type) != KERN_SUCCESS) {
321     return uv__new_sys_error(errno);
322   }
323
324   *cpu_infos = (uv_cpu_info_t*)malloc(numcpus * sizeof(uv_cpu_info_t));
325   if (!(*cpu_infos)) {
326     return uv__new_artificial_error(UV_ENOMEM);
327   }
328
329   *count = numcpus;
330
331   for (i = 0; i < numcpus; i++) {
332     cpu_info = &(*cpu_infos)[i];
333
334     cpu_info->cpu_times.user = (uint64_t)(info[i].cpu_ticks[0]) * multiplier;
335     cpu_info->cpu_times.nice = (uint64_t)(info[i].cpu_ticks[3]) * multiplier;
336     cpu_info->cpu_times.sys = (uint64_t)(info[i].cpu_ticks[1]) * multiplier;
337     cpu_info->cpu_times.idle = (uint64_t)(info[i].cpu_ticks[2]) * multiplier;
338     cpu_info->cpu_times.irq = 0;
339
340     cpu_info->model = strdup(model);
341     cpu_info->speed = cpuspeed/1000000;
342   }
343   vm_deallocate(mach_task_self(), (vm_address_t)info, msg_type);
344
345   return uv_ok_;
346 }
347
348
349 void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) {
350   int i;
351
352   for (i = 0; i < count; i++) {
353     free(cpu_infos[i].model);
354   }
355
356   free(cpu_infos);
357 }
358
359
360 uv_err_t uv_interface_addresses(uv_interface_address_t** addresses,
361   int* count) {
362   struct ifaddrs *addrs, *ent;
363   char ip[INET6_ADDRSTRLEN];
364   uv_interface_address_t* address;
365
366   if (getifaddrs(&addrs) != 0) {
367     return uv__new_sys_error(errno);
368   }
369
370   *count = 0;
371
372   /* Count the number of interfaces */
373   for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
374     if (!(ent->ifa_flags & IFF_UP && ent->ifa_flags & IFF_RUNNING) ||
375         (ent->ifa_addr == NULL) ||
376         (ent->ifa_addr->sa_family == AF_LINK)) {
377       continue;
378     }
379
380     (*count)++;
381   }
382
383   *addresses = (uv_interface_address_t*)
384     malloc(*count * sizeof(uv_interface_address_t));
385   if (!(*addresses)) {
386     return uv__new_artificial_error(UV_ENOMEM);
387   }
388
389   address = *addresses;
390
391   for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
392     bzero(&ip, sizeof (ip));
393     if (!(ent->ifa_flags & IFF_UP && ent->ifa_flags & IFF_RUNNING)) {
394       continue;
395     }
396
397     if (ent->ifa_addr == NULL) {
398       continue;
399     }
400
401     /*
402      * On Mac OS X getifaddrs returns information related to Mac Addresses for
403      * various devices, such as firewire, etc. These are not relevant here.
404      */
405     if (ent->ifa_addr->sa_family == AF_LINK) {
406       continue;
407     }
408
409     address->name = strdup(ent->ifa_name);
410
411     if (ent->ifa_addr->sa_family == AF_INET6) {
412       address->address.address6 = *((struct sockaddr_in6 *)ent->ifa_addr);
413     } else {
414       address->address.address4 = *((struct sockaddr_in *)ent->ifa_addr);
415     }
416
417     address->is_internal = ent->ifa_flags & IFF_LOOPBACK ? 1 : 0;
418
419     address++;
420   }
421
422   freeifaddrs(addrs);
423
424   return uv_ok_;
425 }
426
427
428 void uv_free_interface_addresses(uv_interface_address_t* addresses,
429   int count) {
430   int i;
431
432   for (i = 0; i < count; i++) {
433     free(addresses[i].name);
434   }
435
436   free(addresses);
437 }