-
Notifications
You must be signed in to change notification settings - Fork 108
/
sqUnixHeartbeat.c
448 lines (391 loc) · 13.7 KB
/
sqUnixHeartbeat.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/****************************************************************************
* PROJECT: Unix (pthread) heartbeat logic for Stack/Cog VM
* FILE: sqUnixHeartbeat.c
* CONTENT:
*
* AUTHOR: Eliot Miranda
* ADDRESS:
* EMAIL: eliot.miranda@gmail.com
* RCSID: $Id$
*
* NOTES:
* Feb 1st, 2012, EEM refactored into three separate files.
* July 31st, 2008, EEM added heart-beat thread.
* Aug 20th, 2009, EEM added 64-bit microsecond clock support code
*
*****************************************************************************/
#if ITIMER_HEARTBEAT
# if VM_TICKER
# include "sqUnixITimerTickerHeartbeat.c"
# else
# include "sqUnixITimerHeartbeat.c"
# endif
#else /* ITIMER_HEARTBEAT */
#include "sq.h"
#include "sqAssert.h"
#include "sqMemoryFence.h"
#include "sqSCCSVersion.h"
#include <errno.h>
#include <pthread.h>
#include <stdio.h> /* for fprintf */
#include <sys/types.h>
#include <sys/time.h>
#include "sqaio.h"
#define SecondsFrom1901To1970 2177452800LL
#define MicrosecondsFrom1901To1970 2177452800000000LL
#define MicrosecondsPerSecond 1000000LL
#define MillisecondsPerSecond 1000LL
#define MicrosecondsPerMillisecond 1000LL
static volatile usqLong utcMicrosecondClock;
static volatile usqLong localMicrosecondClock;
static volatile unsigned long millisecondClock; /* for the ioMSecs clock. */
static usqLong utcStartMicroseconds; /* for the ioMSecs clock. */
static sqLong vmGMTOffset = 0;
static usqLong frequencyMeasureStart = 0;
static unsigned long heartbeats;
#define microToMilliseconds(usecs) ((((usecs) - utcStartMicroseconds) \
/ MicrosecondsPerMillisecond) \
& MillisecondClockMask)
#define LOG_CLOCK 1
#if LOG_CLOCK
# define LOGSIZE 1024
static usqLong useclog[LOGSIZE];
static unsigned long mseclog[LOGSIZE];
static int logClock = 0;
static unsigned int ulogidx = (unsigned int)-1;
static unsigned int mlogidx = (unsigned int)-1;
# define logusecs(usecs) do { sqLowLevelMFence(); \
if (logClock) useclog[++ulogidx % LOGSIZE] = (usecs); \
} while (0)
# define logmsecs(msecs) do { sqLowLevelMFence(); \
if (logClock) mseclog[++mlogidx % LOGSIZE] = (msecs); \
} while (0)
void
ioGetClockLogSizeUsecsIdxMsecsIdx(sqInt *runInNOutp, void **usecsp, sqInt *uip, void **msecsp, sqInt *mip)
{
logClock = *runInNOutp;
sqLowLevelMFence();
*runInNOutp = LOGSIZE;
*usecsp = useclog;
*uip = ulogidx % LOGSIZE;
*msecsp = mseclog;
*mip = mlogidx % LOGSIZE;
}
#else /* LOG_CLOCK */
# define logusecs(usecs) 0
# define logmsecs(msecs) 0
void
ioGetClockLogSizeUsecsIdxMsecsIdx(sqInt *np, void **usecsp, sqInt *uip, void **msecsp, sqInt *mip)
{
*np = *uip = *mip = 0;
*usecsp = *msecsp = 0;
}
#endif /* LOG_CLOCK */
/* Compute the current VM time basis, the number of microseconds from 1901. */
static usqLong
currentUTCMicroseconds()
{
struct timeval utcNow;
gettimeofday(&utcNow,0);
return ((utcNow.tv_sec * MicrosecondsPerSecond) + utcNow.tv_usec)
+ MicrosecondsFrom1901To1970;
}
/*
* Update the utc and local microsecond clocks, and the millisecond clock.
* Since this is invoked from interupt code, and since the clocks are 64-bit values
* that are read concurrently by the VM, care must be taken to access these values
* atomically on 32-bit systems. If they are not accessed atomically there is a
* possibility of fetching the two halves of the clock from different ticks which
* would cause a jump in the clock of 2^32 microseconds (1 hr, 11 mins, 34 secs).
*
* Since an interrupt could occur between any two instructions the clock must be
* read atomically as well as written atomically. If possible this can be
* implemented without locks using atomic 64-bit reads and writes.
*/
#include "sqAtomicOps.h"
static void
updateMicrosecondClock()
{
usqLong newUtcMicrosecondClock;
usqLong newLocalMicrosecondClock;
newUtcMicrosecondClock = currentUTCMicroseconds();
/* The native clock may go backwards, e.g. due to NTP adjustments, although
* why it can't avoid small backward steps itself, I don't know. Simply
* ignore backward steps and wait until the clock catches up again. Of
* course this will cause problems if the clock is manually adjusted. To
* which the doctor says, "don't do that".
*/
if (!asserta(newUtcMicrosecondClock >= utcMicrosecondClock)) {
logusecs(0); /* if logging log a backward step as 0 */
return;
}
newLocalMicrosecondClock = newUtcMicrosecondClock + vmGMTOffset;
set64(utcMicrosecondClock,newUtcMicrosecondClock);
set64(localMicrosecondClock,newLocalMicrosecondClock);
millisecondClock = microToMilliseconds(newUtcMicrosecondClock);
logusecs(newUtcMicrosecondClock);
logmsecs(millisecondClock);
}
void
ioUpdateVMTimezone()
{
updateMicrosecondClock();
#ifdef HAVE_TM_GMTOFF
time_t utctt;
utctt = (get64(utcMicrosecondClock) - MicrosecondsFrom1901To1970)
/ MicrosecondsPerSecond;
vmGMTOffset = localtime(&utctt)->tm_gmtoff * MicrosecondsPerSecond;
#else
# ifdef HAVE_TIMEZONE
extern time_t timezone, altzone;
extern int daylight;
vmGMTOffset = -1 * (daylight ? altzone : timezone) * MicrosecondsPerSecond;
# else
# error: cannot determine timezone correction
# endif
#endif
}
sqLong
ioHighResClock(void)
{
/* return the value of the high performance counter */
sqLong value = 0;
#if (defined(__GNUC__) || defined(__SUNPRO_C)) && (defined(i386) || defined(__i386) || defined(__i386__))
__asm__ __volatile__ ("rdtsc" : "=A"(value));
#elif (defined(__GNUC__) || defined(__SUNPRO_C)) && (defined(x86_64) || defined(__x86_64) || defined (__x86_64__))
__asm__ __volatile__ ("rdtsc\n\t" // Returns the time in EDX:EAX.
"shl $32, %%rdx\n\t" // Shift the upper bits left.
"or %%rdx, %0" // 'Or' in the lower bits.
: "=a" (value)
:
: "rdx");
#elif defined(__ARM_ARCH_ISA_A64) || defined(__arm64__) || defined(__aarch64__) || defined(ARM64)
__asm__ __volatile__ ("MRS %0, CNTVCT_EL0" : "=r"(value));
#elif defined(__arm__) && (defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_7A__))
/* tpr - do nothing for now; needs input from eliot to decide further */
/* Tim, not sure I have input beyond:
Is there a 64-bit clock on ARM? If so, access it here :-)
*/
#elif defined(__riscv64__)
__asm__ __volatile__ ("rdcycle a0" : "=r"(value));
#else
# error "no high res clock defined"
#endif
return value;
}
usqLong
ioUTCMicroseconds() { return get64(utcMicrosecondClock); }
usqLong
ioLocalMicroseconds() { return get64(localMicrosecondClock); }
sqInt
ioLocalSecondsOffset() { return vmGMTOffset / MicrosecondsPerSecond; }
/* This is an expensive interface for use by Smalltalk or vm profiling code that
* wants the time now rather than as of the last heartbeat.
*/
usqLong
ioUTCMicrosecondsNow() { return currentUTCMicroseconds(); }
usqLong
ioUTCStartMicroseconds() { return utcStartMicroseconds; }
usqLong
ioLocalMicrosecondsNow() { return currentUTCMicroseconds() + vmGMTOffset; };
/* ioMSecs answers the millisecondClock as of the last tick. */
unsigned int
ioMSecs() { return millisecondClock; }
/* ioMicroMSecs answers the millisecondClock right now */
unsigned int
ioMicroMSecs(void) { return microToMilliseconds(currentUTCMicroseconds());}
/* returns the local wall clock time */
sqInt
ioSeconds(void) { return get64(localMicrosecondClock) / MicrosecondsPerSecond; }
sqInt
ioSecondsNow(void) { return ioLocalMicrosecondsNow() / MicrosecondsPerSecond; }
sqInt
ioUTCSeconds(void) { return get64(utcMicrosecondClock) / MicrosecondsPerSecond; }
sqInt
ioUTCSecondsNow(void) { return currentUTCMicroseconds() / MicrosecondsPerSecond; }
/*
* On Mac OS X use the following.
* On Unix use dpy->ioRelinquishProcessorForMicroseconds
*/
#if macintoshSqueak
sqInt
ioRelinquishProcessorForMicroseconds(sqInt microSeconds)
{
usqLong realTimeToWait;
extern usqLong getNextWakeupUsecs();
usqLong nextWakeupUsecs = getNextWakeupUsecs();
usqLong utcNow = get64(utcMicrosecondClock);
if (nextWakeupUsecs <= utcNow) {
/* if nextWakeupUsecs is non-zero the next wakeup time has already
* passed and we should not wait.
*/
if (nextWakeupUsecs != 0)
return 0;
realTimeToWait = microSeconds;
}
else {
realTimeToWait = nextWakeupUsecs - utcNow;
if (realTimeToWait > microSeconds)
realTimeToWait = microSeconds;
}
aioSleepForUsecs(realTimeToWait);
return 0;
}
#endif /* !macintoshSqueak */
void
ioInitTime(void)
{
ioUpdateVMTimezone(); /* does updateMicrosecondClock as a side-effect */
updateMicrosecondClock(); /* this can now compute localUTCMicroseconds */
utcStartMicroseconds = utcMicrosecondClock;
}
static void
heartbeat()
{
int saved_errno = errno;
updateMicrosecondClock();
if (get64(frequencyMeasureStart) == 0) {
set64(frequencyMeasureStart,utcMicrosecondClock);
heartbeats = 0;
}
else
heartbeats += 1;
checkHighPriorityTickees(utcMicrosecondClock);
forceInterruptCheckFromHeartbeat();
errno = saved_errno;
}
typedef enum { dead, condemned, nascent, quiescent, active } machine_state;
#define UNDEFINED 0xBADF00D
static int stateMachinePolicy = UNDEFINED;
static struct sched_param stateMachinePriority;
static volatile machine_state beatState = nascent;
#if !defined(DEFAULT_BEAT_MS)
# define DEFAULT_BEAT_MS 2
#endif
static int beatMilliseconds = DEFAULT_BEAT_MS;
static struct timespec beatperiod = { 0, DEFAULT_BEAT_MS * 1000 * 1000 };
static void *
beatStateMachine(void *careLess)
{
int er;
if ((er = pthread_setschedparam(pthread_self(),
stateMachinePolicy,
&stateMachinePriority))) {
/* Linux pthreads as of 2009 does not support setting the priority of
* threads other than with real-time scheduling policies. But such
* policies are only available to processes with superuser privileges.
* Linux kernels >= 2.6.13 support different thread priorities, but
* require a suitable /etc/security/limits.d/VMNAME.conf.
*/
extern char *revisionAsString();
errno = er;
perror("pthread_setschedparam failed");
#if PharoVM
# define VMNAME "pharo"
#elif NewspeakVM
# define VMNAME "nsvm"
#else
# define VMNAME "squeak"
#endif
fprintf(stderr, "This VM uses a separate heartbeat thread to update its internal clock\n");
fprintf(stderr, "and handle events. For best operation, this thread should run at a\n");
fprintf(stderr, "higher priority, however the VM was unable to change the priority. The\n");
fprintf(stderr, "effect is that heavily loaded systems may experience some latency\n");
fprintf(stderr, "issues. If this occurs, please create the appropriate configuration\n");
fprintf(stderr, "file in /etc/security/limits.d/ as shown below:\n\n");
fprintf(stderr, "cat <<END | sudo tee /etc/security/limits.d/%s.conf\n", VMNAME);
fprintf(stderr, "* hard rtprio 2\n");
fprintf(stderr, "* soft rtprio 2\n");
fprintf(stderr, "END\n");
fprintf(stderr, "\nand report to the %s mailing list whether this improves behaviour.\n", VMNAME);
fprintf(stderr, "\nYou will need to log out and log back in for the limits to take effect.\n");
fprintf(stderr, "For more information please see\n");
fprintf(stderr, "https://github.com/OpenSmalltalk/opensmalltalk-vm/releases/tag/r3732#linux\n");
// exit(errno);
// The VM may have issues with clock jitter due to the heartbeat thread
// not running at elevated priority. An exit may be appropriate in some
// cases, but for most users the above warning is sufficient.
// exit(errno);
}
beatState = active;
while (beatState != condemned) {
# define MINSLEEPNS 2000 /* don't bother sleeping for short times */
struct timespec naptime = beatperiod;
while (nanosleep(&naptime, &naptime) == -1
&& naptime.tv_sec >= 0 /* oversleeps can return tv_sec < 0 */
&& (naptime.tv_sec > 0 || naptime.tv_nsec > MINSLEEPNS)) /*repeat*/
if (errno != EINTR) {
perror("nanosleep");
exit(1);
}
heartbeat();
}
beatState = dead;
return 0;
}
void
ioInitHeartbeat()
{
int er;
struct timespec halfAMo;
pthread_t careLess;
/* First time through choose a policy and priority for the heartbeat thread,
* and install ioInitHeartbeat via pthread_atfork to be run again in a forked
* child, restarting the heartbeat in a forked child.
*/
if (stateMachinePolicy == UNDEFINED) {
if ((er = pthread_getschedparam(pthread_self(),
&stateMachinePolicy,
&stateMachinePriority))) {
errno = er;
perror("pthread_getschedparam failed");
exit(errno);
}
assert(stateMachinePolicy != UNDEFINED);
++stateMachinePriority.sched_priority;
/* If the priority isn't appropriate for the policy (typically
* SCHED_OTHER) then change policy.
*/
if (sched_get_priority_max(stateMachinePolicy) < stateMachinePriority.sched_priority)
stateMachinePolicy = SCHED_FIFO;
pthread_atfork(0, /*prepare*/ 0, /*parent*/ ioInitHeartbeat /*child*/);
}
else /* subsequently (in the child) init beatState before creating thread */
beatState = nascent;
halfAMo.tv_sec = 0;
halfAMo.tv_nsec = 1000 * 100;
if ((er= pthread_create(&careLess,
(const pthread_attr_t *)0,
beatStateMachine,
0))) {
errno = er;
perror("beat thread creation failed");
exit(errno);
}
while (beatState == nascent)
nanosleep(&halfAMo, 0);
}
void
ioSetHeartbeatMilliseconds(int ms)
{
beatMilliseconds = ms;
beatperiod.tv_sec = beatMilliseconds / 1000;
beatperiod.tv_nsec = (beatMilliseconds % 1000) * 1000 * 1000;
}
int
ioHeartbeatMilliseconds() { return beatMilliseconds; }
/* Answer the average heartbeats per second since the stats were last reset.
*/
unsigned long
ioHeartbeatFrequency(int resetStats)
{
unsigned long duration = (ioUTCMicroseconds() - get64(frequencyMeasureStart))
/ MicrosecondsPerSecond;
unsigned long frequency = duration ? heartbeats / duration : 0;
if (resetStats) {
usqLong zero = 0;
set64(frequencyMeasureStart,zero);
}
return frequency;
}
#endif /* ITIMER_HEARTBEAT */