Debian Codegraph @

src/sync.c

raw symbols SCIP
1 // nanonext - C level - Synchronization Primitives and Signals -----------------
2
3 #define NANONEXT_SIGNALS
4 #include "nanonext.h"
5
6 // internals -------------------------------------------------------------------
7
8 void nano_load_later(void) {
9
10 SEXP str, call;
11 PROTECT(str = Rf_mkString("later"));
12 PROTECT(call = Rf_lang2(Rf_install("loadNamespace"), str));
13 Rf_eval(call, R_BaseEnv);
14 UNPROTECT(2);
15 eln2 = (void (*)(void (*)(void *), void *, double, int)) R_GetCCallable("later", "execLaterNative2");
16
17 }
18
19 SEXP nano_PreserveObject(const SEXP x) {
20
21 SEXP tail = CDR(nano_precious);
22 SEXP node = Rf_cons(nano_precious, tail);
23 SETCDR(nano_precious, node);
24 if (tail != R_NilValue)
25 SETCAR(tail, node);
26 SET_TAG(node, x);
27
28 return node;
29
30 }
31
32 void nano_ReleaseObject(SEXP node) {
33
34 SET_TAG(node, R_NilValue);
35 SEXP head = CAR(node);
36 SEXP tail = CDR(node);
37 SETCDR(head, tail);
38 if (tail != R_NilValue)
39 SETCAR(tail, head);
40
41 }
42
43 // aio completion callbacks ----------------------------------------------------
44
45
46 void raio_invoke_cb(void *arg) {
47
48 SEXP call, node = (SEXP) arg, x = TAG(node);
49 PROTECT(call = Rf_lcons(nano_ResolveSymbol, Rf_cons(nano_aio_get_msg(x), R_NilValue)));
50 Rf_eval(call, NANO_ENCLOS(x));
51 UNPROTECT(1);
52 nano_ReleaseObject(node);
53
54 }
55
56 void haio_invoke_cb(void *arg) {
57
58 SEXP call, out, node = (SEXP) arg, x = TAG(node);
59 const char *names[] = {"status", "headers", "data", ""};
60 PROTECT(out = Rf_mkNamed(VECSXP, names));
61 SET_VECTOR_ELT(out, 0, nano_aio_http_status(x));
62 SET_VECTOR_ELT(out, 1, nano_findVarInFrame(x, nano_ProtocolSymbol, NULL));
63 SET_VECTOR_ELT(out, 2, nano_findVarInFrame(x, nano_ValueSymbol, NULL));
64 PROTECT(call = Rf_lcons(nano_ResolveSymbol, Rf_cons(out, R_NilValue)));
65 Rf_eval(call, NANO_ENCLOS(x));
66 UNPROTECT(2);
67 nano_ReleaseObject(node);
68
69 }
70
71 static void sendaio_complete(void *arg) {
72
73 nng_aio *aio = ((nano_saio *) arg)->aio;
74 if (nng_aio_result(aio))
75 nng_msg_free(nng_aio_get_msg(aio));
76
77 }
78
79 static void request_complete(void *arg) {
80
81 nano_aio *raio = (nano_aio *) arg;
82 nano_saio *saio = (nano_saio *) raio->cb;
83 int res = nng_aio_result(raio->aio);
84 if (res == 0) {
85 nng_msg *msg = nng_aio_get_msg(raio->aio);
86 raio->data = msg;
87 nng_pipe p = nng_msg_get_pipe(msg);
88 res = - (int) p.id;
89 if (saio->id == 0) {
90 unsigned char *buf = (unsigned char *) nng_msg_body(msg);
91 if (buf[0] == 0x7 && buf[3] == 0x1)
92 nng_pipe_close(p);
93 }
94 } else if (res == 5 && saio->id > 0) {
95 if (saio->disp != NULL) {
96 if (saio->type) {
97 nng_msg *msg = NULL;
98 if (nng_msg_alloc(&msg, 0) ||
99 nng_msg_append_u32(msg, 0) ||
100 nng_msg_append(msg, &saio->id, sizeof(int)) ||
101 nng_ctx_sendmsg(*(nng_ctx *) saio->disp, msg, NNG_FLAG_NONBLOCK)) {
102 nng_msg_free(msg);
103 }
104 } else {
105 dispatch_cancel_direct(saio->disp, saio->id);
106 }
107 }
108 }
109
110 if (raio->next != NULL) {
111 nano_cv *ncv = (nano_cv *) raio->next;
112 nng_cv *cv = ncv->cv;
113 nng_mtx *mtx = ncv->mtx;
114
115 nng_mtx_lock(mtx);
116 raio->result = res;
117 ncv->condition++;
118 nng_cv_wake(cv);
119 nng_mtx_unlock(mtx);
120 } else {
121 raio->result = res;
122 }
123
124 if (saio->cb != NULL)
125 later2(raio_invoke_cb, saio->cb);
126
127 }
128
129 void delayed_sigterm(void *arg) {
130 (void) arg;
131 nng_msleep(NANONEXT_SLEEP_DUR);
132 #ifdef _WIN32
133 raise(SIGTERM);
134 #else
135 kill(getpid(), SIGTERM);
136 #endif
137 }
138
139 void pipe_cb_signal(nng_pipe p, nng_pipe_ev ev, void *arg) {
140
141 int sig;
142 nano_cv *ncv = (nano_cv *) arg;
143 nng_cv *cv = ncv->cv;
144 nng_mtx *mtx = ncv->mtx;
145
146 nng_mtx_lock(mtx);
147 sig = ncv->flag;
148 if (sig > 0) ncv->flag = -1;
149 ncv->condition++;
150 nng_cv_wake(cv);
151 nng_mtx_unlock(mtx);
152 if (sig > 1) {
153 if (sig == SIGTERM) {
154 nng_thread *thr;
155 nng_thread_create(&thr, delayed_sigterm, NULL);
156 } else {
157 #ifdef _WIN32
158 if (sig == SIGINT)
159 UserBreak = 1;
160 raise(sig);
161 #else
162 if (sig == SIGINT)
163 R_interrupts_pending = 1;
164 kill(getpid(), sig);
165 #endif
166 }
167 }
168
169 }
170
171 void pipe_cb_monitor(nng_pipe p, nng_pipe_ev ev, void *arg) {
172
173 nano_monitor *monitor = (nano_monitor *) arg;
174
175 nano_cv *ncv = monitor->cv;
176 nng_cv *cv = ncv->cv;
177 nng_mtx *mtx = ncv->mtx;
178
179 const int id = (int) p.id;
180 if (!id)
181 return;
182
183 nng_mtx_lock(mtx);
184 if (monitor->updates >= monitor->size) {
185 monitor->size += 8;
186 int *ids = realloc(monitor->ids, monitor->size * sizeof(int));
187 if (ids == NULL) {
188 monitor->size -= 8;
189 nng_mtx_unlock(mtx);
190 return;
191 }
192 monitor->ids = ids;
193 }
194 monitor->ids[monitor->updates] = ev == NNG_PIPE_EV_ADD_POST ? id : -id;
195 monitor->updates++;
196 ncv->condition++;
197 nng_cv_wake(cv);
198 nng_mtx_unlock(mtx);
199
200 }
201
202 // finalizers ------------------------------------------------------------------
203
204 static void cv_finalizer(SEXP xptr) {
205
206 if (NANO_PTR(xptr) == NULL) return;
207 nano_cv *xp = (nano_cv *) NANO_PTR(xptr);
208 nng_cv_free(xp->cv);
209 nng_mtx_free(xp->mtx);
210 free(xp);
211
212 }
213
214 static void request_finalizer(SEXP xptr) {
215
216 if (NANO_PTR(xptr) == NULL) return;
217 nano_aio *xp = (nano_aio *) NANO_PTR(xptr);
218 nano_saio *saio = (nano_saio *) xp->cb;
219 nng_aio_free(saio->aio);
220 nng_aio_free(xp->aio);
221 if (xp->data != NULL)
222 nng_msg_free((nng_msg *) xp->data);
223 free(saio);
224 free(xp);
225
226 }
227
228 static void monitor_finalizer(SEXP xptr) {
229
230 if (NANO_PTR(xptr) == NULL) return;
231 nano_monitor *xp = (nano_monitor *) NANO_PTR(xptr);
232 free(xp->ids);
233 free(xp);
234
235 }
236
237 // synchronization primitives --------------------------------------------------
238
239 SEXP rnng_cv_alloc(void) {
240
241 SEXP xp;
242 int xc;
243 nano_cv *cvp = calloc(1, sizeof(nano_cv));
244 NANO_ENSURE_ALLOC(cvp);
245
246 if ((xc = nng_mtx_alloc(&cvp->mtx)))
247 goto fail;
248
249 if ((xc = nng_cv_alloc(&cvp->cv, cvp->mtx)))
250 goto fail;
251
252 PROTECT(xp = R_MakeExternalPtr(cvp, nano_CvSymbol, R_NilValue));
253 R_RegisterCFinalizerEx(xp, cv_finalizer, TRUE);
254 Rf_classgets(xp, Rf_mkString("conditionVariable"));
255
256 UNPROTECT(1);
257 return xp;
258
259 fail:
260 nng_mtx_free(cvp->mtx);
261 free(cvp);
262 failmem:
263 ERROR_OUT(xc);
264
265 }
266
267 SEXP rnng_cv_wait(SEXP cvar) {
268
269 if (NANO_PTR_CHECK(cvar, nano_CvSymbol))
270 Rf_error("`cv` is not a valid Condition Variable");
271
272 nano_cv *ncv = (nano_cv *) NANO_PTR(cvar);
273 nng_cv *cv = ncv->cv;
274 nng_mtx *mtx = ncv->mtx;
275 int flag;
276
277 nng_mtx_lock(mtx);
278 while (ncv->condition == 0)
279 nng_cv_wait(cv);
280 ncv->condition--;
281 flag = ncv->flag;
282 nng_mtx_unlock(mtx);
283
284 return Rf_ScalarLogical(flag >= 0);
285
286 }
287
288 SEXP rnng_cv_until(SEXP cvar, SEXP msec) {
289
290 if (NANO_PTR_CHECK(cvar, nano_CvSymbol))
291 Rf_error("`cv` is not a valid Condition Variable");
292
293 nano_cv *ncv = (nano_cv *) NANO_PTR(cvar);
294 nng_cv *cv = ncv->cv;
295 nng_mtx *mtx = ncv->mtx;
296
297 int signalled = 1;
298 nng_time time = nng_clock();
299 switch (TYPEOF(msec)) {
300 case INTSXP:
301 time = time + (nng_time) NANO_INTEGER(msec);
302 break;
303 case REALSXP:
304 time = time + (nng_time) Rf_asInteger(msec);
305 break;
306 }
307
308 nng_mtx_lock(mtx);
309 while (ncv->condition == 0) {
310 if (nng_cv_until(cv, time) == NNG_ETIMEDOUT) {
311 signalled = 0;
312 break;
313 }
314 }
315 if (signalled) {
316 ncv->condition--;
317 nng_mtx_unlock(mtx);
318 } else {
319 nng_mtx_unlock(mtx);
320 R_CheckUserInterrupt();
321 }
322
323 return Rf_ScalarLogical(signalled);
324
325 }
326
327 SEXP rnng_cv_wait_safe(SEXP cvar) {
328
329 if (NANO_PTR_CHECK(cvar, nano_CvSymbol))
330 Rf_error("`cv` is not a valid Condition Variable");
331
332 nano_cv *ncv = (nano_cv *) NANO_PTR(cvar);
333 nng_cv *cv = ncv->cv;
334 nng_mtx *mtx = ncv->mtx;
335 int signalled;
336 int flag;
337 nng_time time = nng_clock();
338
339 while (1) {
340 time = time + 400;
341 signalled = 1;
342 nng_mtx_lock(mtx);
343 while (ncv->condition == 0) {
344 if (nng_cv_until(cv, time) == NNG_ETIMEDOUT) {
345 signalled = 0;
346 break;
347 }
348 }
349 if (signalled) break;
350 nng_mtx_unlock(mtx);
351 R_CheckUserInterrupt();
352 }
353
354 ncv->condition--;
355 flag = ncv->flag;
356 nng_mtx_unlock(mtx);
357
358 return Rf_ScalarLogical(flag >= 0);
359
360 }
361
362 SEXP rnng_cv_until_safe(SEXP cvar, SEXP msec) {
363
364 if (NANO_PTR_CHECK(cvar, nano_CvSymbol))
365 Rf_error("`cv` is not a valid Condition Variable");
366
367 nano_cv *ncv = (nano_cv *) NANO_PTR(cvar);
368 nng_cv *cv = ncv->cv;
369 nng_mtx *mtx = ncv->mtx;
370 int signalled;
371
372 nng_time time, period, now;
373 switch (TYPEOF(msec)) {
374 case INTSXP:
375 period = (nng_time) NANO_INTEGER(msec);
376 break;
377 case REALSXP:
378 period = (nng_time) Rf_asInteger(msec);
379 break;
380 default:
381 period = 0;
382 }
383
384 now = nng_clock();
385
386 do {
387 time = period > 400 ? now + 400 : now + period;
388 period = period > 400 ? period - 400 : 0;
389 signalled = 1;
390 nng_mtx_lock(mtx);
391 while (ncv->condition == 0) {
392 if (nng_cv_until(cv, time) == NNG_ETIMEDOUT) {
393 signalled = 0;
394 break;
395 }
396 }
397 if (signalled) {
398 ncv->condition--;
399 nng_mtx_unlock(mtx);
400 break;
401 }
402 nng_mtx_unlock(mtx);
403 R_CheckUserInterrupt();
404 now += 400;
405 } while (period > 0);
406
407 return Rf_ScalarLogical(signalled);
408
409 }
410
411 SEXP rnng_cv_reset(SEXP cvar) {
412
413 if (NANO_PTR_CHECK(cvar, nano_CvSymbol))
414 Rf_error("`cv` is not a valid Condition Variable");
415
416 nano_cv *ncv = (nano_cv *) NANO_PTR(cvar);
417 nng_mtx *mtx = ncv->mtx;
418
419 nng_mtx_lock(mtx);
420 ncv->flag = ncv->flag < 0;
421 ncv->condition = 0;
422 nng_mtx_unlock(mtx);
423
424 return nano_success;
425
426 }
427
428 SEXP rnng_cv_value(SEXP cvar) {
429
430 if (NANO_PTR_CHECK(cvar, nano_CvSymbol))
431 Rf_error("`cv` is not a valid Condition Variable");
432
433 nano_cv *ncv = (nano_cv *) NANO_PTR(cvar);
434 nng_mtx *mtx = ncv->mtx;
435 int cond;
436 nng_mtx_lock(mtx);
437 cond = ncv->condition;
438 nng_mtx_unlock(mtx);
439
440 return Rf_ScalarInteger(cond);
441
442 }
443
444 SEXP rnng_cv_signal(SEXP cvar) {
445
446 if (NANO_PTR_CHECK(cvar, nano_CvSymbol))
447 Rf_error("`cv` is not a valid Condition Variable");
448
449 nano_cv *ncv = (nano_cv *) NANO_PTR(cvar);
450 nng_cv *cv = ncv->cv;
451 nng_mtx *mtx = ncv->mtx;
452
453 nng_mtx_lock(mtx);
454 ncv->condition++;
455 nng_cv_wake(cv);
456 nng_mtx_unlock(mtx);
457
458 return nano_success;
459
460 }
461
462 // request ---------------------------------------------------------------------
463
464 SEXP rnng_request(SEXP con, SEXP data, SEXP sendmode, SEXP recvmode, SEXP timeout, SEXP cvar, SEXP msgid, SEXP clo) {
465
466 if (NANO_PTR_CHECK(con, nano_ContextSymbol))
467 Rf_error("`con` is not a valid Context");
468 nng_ctx *ctx = (nng_ctx *) NANO_PTR(con);
469
470 const nng_duration dur = timeout == R_NilValue ? NNG_DURATION_DEFAULT : (nng_duration) nano_integer(timeout);
471 const uint8_t mod = (uint8_t) nano_matcharg(recvmode);
472 const int raw = nano_encode_mode(sendmode);
473 const int id = nng_ctx_id(*ctx);
474 const int signal = cvar != R_NilValue && !NANO_PTR_CHECK(cvar, nano_CvSymbol);
475 int xc;
476
477 nano_cv *ncv = signal ? (nano_cv *) NANO_PTR(cvar) : NULL;
478
479 nano_saio *saio = NULL;
480 nano_aio *raio = NULL;
481 nng_msg *msg = NULL;
482 SEXP aio, env, fun;
483 nano_buf buf;
484
485 if (raw) {
486 nano_encode(&buf, data);
487 } else {
488 nano_serialize(&buf, data, NANO_PROT(con), id);
489 }
490
491 saio = calloc(1, sizeof(nano_saio));
492 NANO_ENSURE_ALLOC(saio);
493
494 raio = calloc(1, sizeof(nano_aio));
495 NANO_ENSURE_ALLOC(raio);
496
497 if (TYPEOF(msgid) == EXTPTRSXP) {
498 saio->disp = NANO_PTR(msgid);
499 } else if (msgid != R_NilValue) {
500 saio->disp = ctx;
501 saio->type = 1;
502 } else {
503 saio->disp = NULL;
504 }
505 saio->id = msgid != R_NilValue ? id : mod != 1 ? -id : 0;
506
507 if ((xc = nng_msg_alloc(&msg, 0)) ||
508 (xc = nng_aio_alloc(&saio->aio, sendaio_complete, saio))) {
509 nng_msg_free(msg);
510 goto fail;
511 }
512
513 nano_msg_set_body(msg, &buf);
514
515 nng_aio_set_msg(saio->aio, msg);
516 nng_ctx_send(*ctx, saio->aio);
517
518 raio->type = signal ? REQAIOS : REQAIO;
519 raio->mode = mod;
520 raio->cb = saio;
521 raio->next = ncv;
522
523 if ((xc = nng_aio_alloc(&raio->aio, request_complete, raio)))
524 goto fail;
525
526 nng_aio_set_timeout(raio->aio, dur);
527 nng_ctx_recv(*ctx, raio->aio);
528 NANO_FREE(buf);
529
530 PROTECT(aio = R_MakeExternalPtr(raio, nano_AioSymbol, NANO_PROT(con)));
531 R_RegisterCFinalizerEx(aio, request_finalizer, TRUE);
532 Rf_setAttrib(aio, nano_ContextSymbol, con);
533
534 PROTECT(env = R_NewEnv(R_NilValue, 0, 0));
535 Rf_classgets(env, nano_reqAio);
536 Rf_setAttrib(env, nano_IdSymbol, Rf_ScalarInteger(id));
537 Rf_defineVar(nano_AioSymbol, aio, env);
538
539 PROTECT(fun = R_mkClosure(R_NilValue, nano_aioFuncMsg, clo));
540 R_MakeActiveBinding(nano_DataSymbol, fun, env);
541
542 UNPROTECT(3);
543 return env;
544
545 fail:
546 nng_aio_free(saio->aio);
547 failmem:
548 free(raio);
549 free(saio);
550 NANO_FREE(buf);
551 return mk_error_data(xc);
552
553 }
554
555 SEXP rnng_set_promise_context(SEXP x, SEXP ctx) {
556
557 if (TYPEOF(x) != ENVSXP)
558 return R_NilValue;
559
560 const SEXP aio = nano_findVarInFrame(x, nano_AioSymbol, NULL);
561 if (NANO_PTR_CHECK(aio, nano_AioSymbol))
562 return R_NilValue;
563
564 nano_aio *raio = (nano_aio *) NANO_PTR(aio);
565
566 if (eln2 == NULL)
567 nano_load_later();
568
569 switch (raio->type) {
570 case REQAIO:
571 case REQAIOS:
572 NANO_SET_ENCLOS(x, ctx);
573 nano_saio *saio = (nano_saio *) raio->cb;
574 saio->cb = nano_PreserveObject(x);
575 break;
576 case RECVAIO:
577 case RECVAIOS:
578 case IOV_RECVAIO:
579 case IOV_RECVAIOS:
580 case HTTP_AIO:
581 NANO_SET_ENCLOS(x, ctx);
582 raio->cb = nano_PreserveObject(x);
583 break;
584 case SENDAIO:
585 case IOV_SENDAIO:
586 break;
587 }
588
589 return R_NilValue;
590
591 }
592
593 // pipes -----------------------------------------------------------------------
594
595 SEXP rnng_pipe_notify(SEXP socket, SEXP cv, SEXP add, SEXP remove, SEXP flag) {
596
597 if (NANO_PTR_CHECK(socket, nano_SocketSymbol))
598 Rf_error("`socket` is not a valid Socket");
599
600 int xc;
601 nng_socket *sock;
602
603 if (cv == R_NilValue) {
604
605 sock = (nng_socket *) NANO_PTR(socket);
606 if (NANO_INTEGER(add) && (xc = nng_pipe_notify(*sock, NNG_PIPE_EV_ADD_POST, NULL, NULL)))
607 ERROR_OUT(xc);
608
609 if (NANO_INTEGER(remove) && (xc = nng_pipe_notify(*sock, NNG_PIPE_EV_REM_POST, NULL, NULL)))
610 ERROR_OUT(xc);
611
612 return nano_success;
613
614 } else if (NANO_PTR_CHECK(cv, nano_CvSymbol)) {
615 Rf_error("`cv` is not a valid Condition Variable");
616 }
617
618 sock = (nng_socket *) NANO_PTR(socket);
619 nano_cv *cvp = (nano_cv *) NANO_PTR(cv);
620 const int flg = nano_integer(flag);
621
622 cvp->flag = flg < 0 ? 1 : flg;
623
624 if (NANO_INTEGER(add) && (xc = nng_pipe_notify(*sock, NNG_PIPE_EV_ADD_POST, pipe_cb_signal, cvp)))
625 ERROR_OUT(xc);
626
627 if (NANO_INTEGER(remove) && (xc = nng_pipe_notify(*sock, NNG_PIPE_EV_REM_POST, pipe_cb_signal, cvp)))
628 ERROR_OUT(xc);
629
630 R_MakeWeakRef(socket, cv, R_NilValue, FALSE);
631 return nano_success;
632
633 }
634
635 // monitors --------------------------------------------------------------------
636
637 SEXP rnng_monitor_create(SEXP socket, SEXP cv) {
638
639 if (NANO_PTR_CHECK(socket, nano_SocketSymbol))
640 Rf_error("`socket` is not a valid Socket");
641
642 if (NANO_PTR_CHECK(cv, nano_CvSymbol))
643 Rf_error("`cv` is not a valid Condition Variable");
644
645 const int n = 8;
646 SEXP xptr;
647 int xc;
648
649 nano_monitor *monitor = calloc(1, sizeof(nano_monitor));
650 NANO_ENSURE_ALLOC(monitor);
651 monitor->ids = calloc(n, sizeof(int));
652 NANO_ENSURE_ALLOC(monitor->ids);
653 monitor->size = n;
654 monitor->cv = (nano_cv *) NANO_PTR(cv);
655 nng_socket *sock = (nng_socket *) NANO_PTR(socket);
656
657 if ((xc = nng_pipe_notify(*sock, NNG_PIPE_EV_ADD_POST, pipe_cb_monitor, monitor)))
658 goto failmem;
659
660 if ((xc = nng_pipe_notify(*sock, NNG_PIPE_EV_REM_POST, pipe_cb_monitor, monitor)))
661 goto failmem;
662
663 PROTECT(xptr = R_MakeExternalPtr(monitor, nano_MonitorSymbol, R_NilValue));
664 R_RegisterCFinalizerEx(xptr, monitor_finalizer, TRUE);
665 NANO_CLASS2(xptr, "nanoMonitor", "nano");
666 Rf_setAttrib(xptr, nano_SocketSymbol, Rf_ScalarInteger(nng_socket_id(*sock)));
667 UNPROTECT(1);
668
669 return xptr;
670
671 failmem:
672 if (monitor != NULL)
673 free(monitor->ids);
674 free(monitor);
675 ERROR_OUT(xc);
676
677 }
678
679 SEXP rnng_monitor_read(SEXP x) {
680
681 if (NANO_PTR_CHECK(x, nano_MonitorSymbol))
682 Rf_error("`x` is not a valid Monitor");
683
684 nano_monitor *monitor = (nano_monitor *) NANO_PTR(x);
685
686 nano_cv *ncv = monitor->cv;
687 nng_mtx *mtx = ncv->mtx;
688
689 SEXP out;
690 nng_mtx_lock(mtx);
691 const int updates = monitor->updates;
692 if (updates) {
693 out = Rf_allocVector(INTSXP, updates);
694 memcpy(NANO_DATAPTR(out), monitor->ids, updates * sizeof(int));
695 monitor->updates = 0;
696 }
697 nng_mtx_unlock(mtx);
698
699 if (!updates)
700 out = R_NilValue;
701
702 return out;
703
704 }