2014-07-11 Edward Smith-Rowland <3dw4rd@verizon.net>
[official-gcc.git] / libgo / runtime / netpoll_kqueue.c
blobbc38644ac78ecfd9593e820a5a9e107d970a065c
1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // +build darwin dragonfly freebsd netbsd openbsd
7 #include "runtime.h"
8 #include "defs.h"
9 #include "malloc.h"
11 // Integrated network poller (kqueue-based implementation).
13 int32 runtime_kqueue(void);
14 int32 runtime_kevent(int32, Kevent*, int32, Kevent*, int32, Timespec*);
15 void runtime_closeonexec(int32);
17 static int32 kq = -1;
19 void
20 runtime_netpollinit(void)
22 kq = runtime_kqueue();
23 if(kq < 0) {
24 runtime_printf("netpollinit: kqueue failed with %d\n", -kq);
25 runtime_throw("netpollinit: kqueue failed");
27 runtime_closeonexec(kq);
30 int32
31 runtime_netpollopen(uintptr fd, PollDesc *pd)
33 Kevent ev[2];
34 int32 n;
36 // Arm both EVFILT_READ and EVFILT_WRITE in edge-triggered mode (EV_CLEAR)
37 // for the whole fd lifetime. The notifications are automatically unregistered
38 // when fd is closed.
39 ev[0].ident = (uint32)fd;
40 ev[0].filter = EVFILT_READ;
41 ev[0].flags = EV_ADD|EV_CLEAR;
42 ev[0].fflags = 0;
43 ev[0].data = 0;
44 ev[0].udata = (kevent_udata)pd;
45 ev[1] = ev[0];
46 ev[1].filter = EVFILT_WRITE;
47 n = runtime_kevent(kq, ev, 2, nil, 0, nil);
48 if(n < 0)
49 return -n;
50 return 0;
53 int32
54 runtime_netpollclose(uintptr fd)
56 // Don't need to unregister because calling close()
57 // on fd will remove any kevents that reference the descriptor.
58 USED(fd);
59 return 0;
62 void
63 runtime_netpollarm(uintptr fd, int32 mode)
65 USED(fd, mode);
66 runtime_throw("unused");
69 // Polls for ready network connections.
70 // Returns list of goroutines that become runnable.
72 runtime_netpoll(bool block)
74 static int32 lasterr;
75 Kevent events[64], *ev;
76 Timespec ts, *tp;
77 int32 n, i, mode;
78 G *gp;
80 if(kq == -1)
81 return nil;
82 tp = nil;
83 if(!block) {
84 ts.tv_sec = 0;
85 ts.tv_nsec = 0;
86 tp = &ts;
88 gp = nil;
89 retry:
90 n = runtime_kevent(kq, nil, 0, events, nelem(events), tp);
91 if(n < 0) {
92 if(n != -EINTR && n != lasterr) {
93 lasterr = n;
94 runtime_printf("runtime: kevent on fd %d failed with %d\n", kq, -n);
96 goto retry;
98 for(i = 0; i < n; i++) {
99 ev = &events[i];
100 mode = 0;
101 if(ev->filter == EVFILT_READ)
102 mode += 'r';
103 if(ev->filter == EVFILT_WRITE)
104 mode += 'w';
105 if(mode)
106 runtime_netpollready(&gp, (PollDesc*)ev->udata, mode);
108 if(block && gp == nil)
109 goto retry;
110 return gp;
113 void
114 runtime_netpoll_scan(struct Workbuf** wbufp, void (*enqueue1)(struct Workbuf**, Obj))
116 USED(wbufp);
117 USED(enqueue1);