1// Copyright 2014 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.
4
5package runtime
6
7import "unsafe"
8
9// Solaris runtime-integrated network poller.
10//
11// Solaris uses event ports for scalable network I/O. Event
12// ports are level-triggered, unlike epoll and kqueue which
13// can be configured in both level-triggered and edge-triggered
14// mode. Level triggering means we have to keep track of a few things
15// ourselves. After we receive an event for a file descriptor,
16// it's our responsibility to ask again to be notified for future
17// events for that descriptor. When doing this we must keep track of
18// what kind of events the goroutines are currently interested in,
19// for example a fd may be open both for reading and writing.
20//
21// A description of the high level operation of this code
22// follows. Networking code will get a file descriptor by some means
23// and will register it with the netpolling mechanism by a code path
24// that eventually calls runtime·netpollopen. runtime·netpollopen
25// calls port_associate with an empty event set. That means that we
26// will not receive any events at this point. The association needs
27// to be done at this early point because we need to process the I/O
28// readiness notification at some point in the future. If I/O becomes
29// ready when nobody is listening, when we finally care about it,
30// nobody will tell us anymore.
31//
32// Beside calling runtime·netpollopen, the networking code paths
33// will call runtime·netpollarm each time goroutines are interested
34// in doing network I/O. Because now we know what kind of I/O we
35// are interested in (reading/writing), we can call port_associate
36// passing the correct type of event set (POLLIN/POLLOUT). As we made
37// sure to have already associated the file descriptor with the port,
38// when we now call port_associate, we will unblock the main poller
39// loop (in runtime·netpoll) right away if the socket is actually
40// ready for I/O.
41//
42// The main poller loop runs in its own thread waiting for events
43// using port_getn. When an event happens, it will tell the scheduler
44// about it using runtime·netpollready. Besides doing this, it must
45// also re-associate the events that were not part of this current
46// notification with the file descriptor. Failing to do this would
47// mean each notification will prevent concurrent code using the
48// same file descriptor in parallel.
49//
50// The logic dealing with re-associations is encapsulated in
51// runtime·netpollupdate. This function takes care to associate the
52// descriptor only with the subset of events that were previously
53// part of the association, except the one that just happened. We
54// can't re-associate with that right away, because event ports
55// are level triggered so it would cause a busy loop. Instead, that
56// association is effected only by the runtime·netpollarm code path,
57// when Go code actually asks for I/O.
58//
59// The open and arming mechanisms are serialized using the lock
60// inside PollDesc. This is required because the netpoll loop runs
61// asynchronously in respect to other Go code and by the time we get
62// to call port_associate to update the association in the loop, the
63// file descriptor might have been closed and reopened already. The
64// lock allows runtime·netpollupdate to be called synchronously from
65// the loop thread while preventing other threads operating to the
66// same PollDesc, so once we unblock in the main loop, until we loop
67// again we know for sure we are always talking about the same file
68// descriptor and can safely access the data we want (the event set).
69
70//extern port_create
71func port_create() int32
72
73//extern port_associate
74func port_associate(port, source int32, object uintptr, events uint32, user uintptr) int32
75
76//extern port_dissociate
77func port_dissociate(port, source int32, object uintptr) int32
78
79//go:noescape
80//extern port_getn
81func port_getn(port int32, evs *portevent, max uint32, nget *uint32, timeout *timespec) int32
82
83//extern port_alert
84func port_alert(port int32, flags, events uint32, user uintptr) int32
85
86var portfd int32 = -1
87
88func netpollinit() {
89	portfd = port_create()
90	if portfd >= 0 {
91		closeonexec(portfd)
92		return
93	}
94
95	print("runtime: port_create failed (errno=", errno(), ")\n")
96	throw("runtime: netpollinit failed")
97}
98
99func netpollIsPollDescriptor(fd uintptr) bool {
100	return fd == uintptr(portfd)
101}
102
103func netpollopen(fd uintptr, pd *pollDesc) int32 {
104	lock(&pd.lock)
105	// We don't register for any specific type of events yet, that's
106	// netpollarm's job. We merely ensure we call port_associate before
107	// asynchronous connect/accept completes, so when we actually want
108	// to do any I/O, the call to port_associate (from netpollarm,
109	// with the interested event set) will unblock port_getn right away
110	// because of the I/O readiness notification.
111	pd.user = 0
112	r := port_associate(portfd, _PORT_SOURCE_FD, fd, 0, uintptr(unsafe.Pointer(pd)))
113	unlock(&pd.lock)
114	if r < 0 {
115		return int32(errno())
116	}
117	return 0
118}
119
120func netpollclose(fd uintptr) int32 {
121	if port_dissociate(portfd, _PORT_SOURCE_FD, fd) < 0 {
122		return int32(errno())
123	}
124	return 0
125}
126
127// Updates the association with a new set of interested events. After
128// this call, port_getn will return one and only one event for that
129// particular descriptor, so this function needs to be called again.
130func netpollupdate(pd *pollDesc, set, clear uint32) {
131	if pd.closing {
132		return
133	}
134
135	old := pd.user
136	events := (old & ^clear) | set
137	if old == events {
138		return
139	}
140
141	if events != 0 && port_associate(portfd, _PORT_SOURCE_FD, pd.fd, events, uintptr(unsafe.Pointer(pd))) != 0 {
142		print("runtime: port_associate failed (errno=", errno(), ")\n")
143		throw("runtime: netpollupdate failed")
144	}
145	pd.user = events
146}
147
148// subscribe the fd to the port such that port_getn will return one event.
149func netpollarm(pd *pollDesc, mode int) {
150	lock(&pd.lock)
151	switch mode {
152	case 'r':
153		netpollupdate(pd, _POLLIN, 0)
154	case 'w':
155		netpollupdate(pd, _POLLOUT, 0)
156	default:
157		throw("runtime: bad mode")
158	}
159	unlock(&pd.lock)
160}
161
162// netpollBreak interrupts a port_getn wait.
163func netpollBreak() {
164	// Use port_alert to put portfd into alert mode.
165	// This will wake up all threads sleeping in port_getn on portfd,
166	// and cause their calls to port_getn to return immediately.
167	// Further, until portfd is taken out of alert mode,
168	// all calls to port_getn will return immediately.
169	if port_alert(portfd, _PORT_ALERT_UPDATE, _POLLHUP, uintptr(unsafe.Pointer(&portfd))) < 0 {
170		if e := errno(); e != _EBUSY {
171			println("runtime: port_alert failed with", e)
172			throw("runtime: netpoll: port_alert failed")
173		}
174	}
175}
176
177// netpoll checks for ready network connections.
178// Returns list of goroutines that become runnable.
179// delay < 0: blocks indefinitely
180// delay == 0: does not block, just polls
181// delay > 0: block for up to that many nanoseconds
182func netpoll(delay int64) gList {
183	if portfd == -1 {
184		return gList{}
185	}
186
187	var wait *timespec
188	var ts timespec
189	if delay < 0 {
190		wait = nil
191	} else if delay == 0 {
192		wait = &ts
193	} else {
194		ts.setNsec(delay)
195		if ts.tv_sec > 1e6 {
196			// An arbitrary cap on how long to wait for a timer.
197			// 1e6 s == ~11.5 days.
198			ts.tv_sec = 1e6
199		}
200		wait = &ts
201	}
202
203	var events [128]portevent
204retry:
205	var n uint32 = 1
206	r := port_getn(portfd, &events[0], uint32(len(events)), &n, wait)
207	e := errno()
208	if r < 0 && e == _ETIME && n > 0 {
209		// As per port_getn(3C), an ETIME failure does not preclude the
210		// delivery of some number of events.  Treat a timeout failure
211		// with delivered events as a success.
212		r = 0
213	}
214	if r < 0 {
215		if e != _EINTR && e != _ETIME {
216			print("runtime: port_getn on fd ", portfd, " failed (errno=", e, ")\n")
217			throw("runtime: netpoll failed")
218		}
219		// If a timed sleep was interrupted and there are no events,
220		// just return to recalculate how long we should sleep now.
221		if delay > 0 {
222			return gList{}
223		}
224		goto retry
225	}
226
227	var toRun gList
228	for i := 0; i < int(n); i++ {
229		ev := &events[i]
230
231		if ev.portev_source == _PORT_SOURCE_ALERT {
232			if ev.portev_events != _POLLHUP || unsafe.Pointer(ev.portev_user) != unsafe.Pointer(&portfd) {
233				throw("runtime: netpoll: bad port_alert wakeup")
234			}
235			if delay != 0 {
236				// Now that a blocking call to netpoll
237				// has seen the alert, take portfd
238				// back out of alert mode.
239				// See the comment in netpollBreak.
240				if port_alert(portfd, 0, 0, 0) < 0 {
241					e := errno()
242					println("runtime: port_alert failed with", e)
243					throw("runtime: netpoll: port_alert failed")
244				}
245			}
246			continue
247		}
248
249		if ev.portev_events == 0 {
250			continue
251		}
252		pd := (*pollDesc)(unsafe.Pointer(ev.portev_user))
253
254		var mode, clear int32
255		if (ev.portev_events & (_POLLIN | _POLLHUP | _POLLERR)) != 0 {
256			mode += 'r'
257			clear |= _POLLIN
258		}
259		if (ev.portev_events & (_POLLOUT | _POLLHUP | _POLLERR)) != 0 {
260			mode += 'w'
261			clear |= _POLLOUT
262		}
263		// To effect edge-triggered events, we need to be sure to
264		// update our association with whatever events were not
265		// set with the event. For example if we are registered
266		// for POLLIN|POLLOUT, and we get POLLIN, besides waking
267		// the goroutine interested in POLLIN we have to not forget
268		// about the one interested in POLLOUT.
269		if clear != 0 {
270			lock(&pd.lock)
271			netpollupdate(pd, 0, uint32(clear))
272			unlock(&pd.lock)
273		}
274
275		if mode != 0 {
276			// TODO(mikio): Consider implementing event
277			// scanning error reporting once we are sure
278			// about the event port on SmartOS.
279			//
280			// See golang.org/x/issue/30840.
281			netpollready(&toRun, pd, mode)
282		}
283	}
284
285	return toRun
286}
287