sleepy_penguin.git  about / heads / tags
Linux I/O events for Ruby
blob 26995de1ee621720c86aeddfcda6f6870b49bc0b 12787 bytes (raw)
$ git show v1.2.0:ext/sleepy_penguin/epoll.c	# shows this blob on the CLI

  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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
 
#include "sleepy_penguin.h"
#include <sys/epoll.h>
#include <pthread.h>
#ifdef HAVE_RUBY_ST_H
#  include <ruby/st.h>
#else
#  include <st.h>
#endif

#ifndef EPOLL_CLOEXEC
#  define EPOLL_CLOEXEC (int)(02000000)
#endif

#define EP_RECREATE (-2)

#ifndef HAVE_RB_MEMERROR
static void rb_memerror(void)
{
	static const char e[] = "[FATAL] failed to allocate memory\n";
	write(2, e, sizeof(e) - 1);
	abort();
}
#endif
#ifndef HAVE_RB_IO_CLOSE
static VALUE rb_io_close(VALUE io)
{
	return rb_funcall(io, rb_intern("close"), 0);
}
#endif

static st_table *active;
static const int step = 64; /* unlikely to grow unless you're huge */
static VALUE cEpoll_IO;
static ID id_for_fd;

static void pack_event_data(struct epoll_event *event, VALUE obj)
{
	event->data.ptr = (void *)obj;
}

static VALUE unpack_event_data(struct epoll_event *event)
{
	return (VALUE)event->data.ptr;
}

struct rb_epoll {
	int fd;
	int timeout;
	int maxevents;
	int capa;
	struct epoll_event *events;
	VALUE io;
	VALUE marks;
	int flags;
};

static struct rb_epoll *ep_get(VALUE self)
{
	struct rb_epoll *ep;

	Data_Get_Struct(self, struct rb_epoll, ep);

	return ep;
}

#ifndef HAVE_EPOLL_CREATE1
/*
 * fake epoll_create1() since some systems don't have it.
 * Don't worry about thread-safety since current Ruby 1.9 won't
 * call this without GVL.
 */
static int epoll_create1(int flags)
{
	int fd = epoll_create(1024); /* size ignored since 2.6.8 */

	if (fd < 0 || flags == 0)
		return fd;

	if ((flags & EPOLL_CLOEXEC) && (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1))
		goto err;
	return fd;
err:
	{
		int saved_errno = errno;
		close(fd);
		errno = saved_errno;
		return -1;
	}
}
#endif

static void gcmark(void *ptr)
{
	struct rb_epoll *ep = ptr;

	rb_gc_mark(ep->io);
	rb_gc_mark(ep->marks);
}

static void gcfree(void *ptr)
{
	struct rb_epoll *ep = ptr;

	xfree(ep->events);
	if (ep->fd >= 0) {
		st_data_t key = ep->fd;
		st_delete(active, &key, NULL);
	}
	if (NIL_P(ep->io) && ep->fd >= 0) {
		/* can't raise during GC */
		(void)close(ep->fd);
		errno = 0;
	}
	/* let GC take care of the underlying IO object if there is one */

	xfree(ep);
}

static VALUE alloc(VALUE klass)
{
	struct rb_epoll *ep;
	VALUE self;

	self = Data_Make_Struct(klass, struct rb_epoll, gcmark, gcfree, ep);
	ep->fd = -1;
	ep->io = Qnil;
	ep->marks = rb_ary_new();
	ep->capa = step;
	ep->flags = EPOLL_CLOEXEC;
	ep->events = xmalloc(sizeof(struct epoll_event) * ep->capa);

	return self;
}

static void my_epoll_create(struct rb_epoll *ep)
{
	ep->fd = epoll_create1(ep->flags);

	if (ep->fd == -1) {
		if (errno == EMFILE || errno == ENFILE || errno == ENOMEM) {
			rb_gc();
			ep->fd = epoll_create1(ep->flags);
		}
		if (ep->fd == -1)
			rb_sys_fail("epoll_create1");
	}
	st_insert(active, (st_data_t)ep->fd, (st_data_t)ep);
}

static void ep_check(struct rb_epoll *ep)
{
	if (ep->fd == EP_RECREATE)
		my_epoll_create(ep);
	if (ep->fd == -1)
		rb_raise(rb_eIOError, "closed");
}

/*
 * creates a new Epoll object with an optional +flags+ argument.
 * +flags+ may currently be +Epoll::CLOEXEC+ or 0 (or nil)
 */
static VALUE init(int argc, VALUE *argv, VALUE self)
{
	int flags;
	struct rb_epoll *ep = ep_get(self);
	VALUE fl;

	rb_scan_args(argc, argv, "01", &fl);
	if (NIL_P(fl)) {
		flags = EPOLL_CLOEXEC;
	} else {
		switch (TYPE(fl)) {
		case T_FIXNUM:
		case T_BIGNUM:
			flags = NUM2INT(fl);
			break;
		default:
			rb_raise(rb_eArgError, "flags must be an integer");
		}
	}
	ep->flags = flags;
	my_epoll_create(ep);

	return self;
}

static VALUE ctl(VALUE self, VALUE io, VALUE flags, int op)
{
	struct epoll_event event;
	struct rb_epoll *ep = ep_get(self);
	int fd = my_fileno(io);
	int rv;

	ep_check(ep);
	event.events = NUM2UINT(flags);
	pack_event_data(&event, io);

	rv = epoll_ctl(ep->fd, op, fd, &event);
	if (rv == -1) {
		if (errno == ENOMEM) {
			rb_gc();
			rv = epoll_ctl(ep->fd, op, fd, &event);
		}
		if (rv == -1)
			rb_sys_fail("epoll_ctl");
	}
	if (op == EPOLL_CTL_ADD)
		rb_ary_store(ep->marks, fd, io);

	return INT2NUM(rv);
}

/*
 * used to avoid exceptions when your app is too lazy to check
 * what state a descriptor is in
 */
static VALUE set(VALUE self, VALUE io, VALUE flags)
{
	struct epoll_event event;
	struct rb_epoll *ep = ep_get(self);
	int fd = my_fileno(io);
	int rv;

	ep_check(ep);
	event.events = NUM2UINT(flags);
	pack_event_data(&event, io);

	rv = epoll_ctl(ep->fd, EPOLL_CTL_MOD, fd, &event);
	if (rv == -1) {
		if (errno == ENOENT) {
			rv = epoll_ctl(ep->fd, EPOLL_CTL_ADD, fd, &event);
			if (rv == -1)
				rb_sys_fail("epoll_ctl - add");

			rb_ary_store(ep->marks, fd, io);
			return INT2NUM(rv);
		}
		rb_sys_fail("epoll_ctl - mod");
	}

	return INT2NUM(rv);
}

/*
 * Deletes an +io+ from an epoll set, but returns nil
 * on ENOENT instead of raising an error.  This is useful
 * for apps that do not care to track the status of an
 * epoll object itself.
 */
static VALUE delete(VALUE self, VALUE io)
{
	struct rb_epoll *ep = ep_get(self);
	int fd = my_fileno(io);
	int rv;

	ep_check(ep);
	rv = epoll_ctl(ep->fd, EPOLL_CTL_DEL, fd, NULL);
	if (rv == -1) {
		if (errno != ENOENT)
			rb_sys_fail("epoll_ctl - del");
		errno = 0;
		return Qnil;
	}
	return INT2NUM(rv);
}

static VALUE epwait_result(struct rb_epoll *ep, int n)
{
	int i;
	struct epoll_event *epoll_event = ep->events;
	VALUE obj_events, obj;

	if (n == -1)
		rb_sys_fail("epoll_wait");

	for (i = n; --i >= 0; epoll_event++) {
		obj_events = UINT2NUM(epoll_event->events);
		obj = unpack_event_data(epoll_event);
		rb_yield_values(2, obj_events, obj);
	}

	/* grow our event buffer for the next epoll_wait call */
	if (n == ep->capa) {
		xfree(ep->events);
		ep->capa += step;
		ep->events = xmalloc(sizeof(struct epoll_event) * ep->capa);
	}

	return INT2NUM(n);
}

#if defined(HAVE_RB_THREAD_BLOCKING_REGION)
static VALUE nogvl_wait(void *args)
{
	struct rb_epoll *ep = args;
	int n = epoll_wait(ep->fd, ep->events, ep->maxevents, ep->timeout);

	return (VALUE)n;
}

static VALUE real_epwait(struct rb_epoll *ep)
{
	int n;

	do {
		n = (int)rb_thread_blocking_region(nogvl_wait, ep,
		                                   RUBY_UBF_IO, 0);
	} while (n == -1 && errno == EINTR);

	return epwait_result(ep, n);
}
#else /* 1.8 Green thread compatible code */
/*
 * we have to worry about green threads and always pass zero
 * as the timeout for epoll_wait :(
 */
# include <rubysig.h>
# include <sys/time.h>

/* in case _BSD_SOURCE doesn't give us this macro */
#ifndef timersub
#  define timersub(a, b, result) \
do { \
	(result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
	(result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
	if ((result)->tv_usec < 0) { \
		--(result)->tv_sec; \
		(result)->tv_usec += 1000000; \
	} \
} while (0)
#endif

static int safe_epoll_wait(struct rb_epoll *ep)
{
	int n;

	TRAP_BEG;
	n = epoll_wait(ep->fd, ep->events, ep->maxevents, 0);
	TRAP_END;

	return n;
}

static int epwait_forever(struct rb_epoll *ep)
{
	int n;

	do {
		(void)rb_io_wait_readable(ep->fd);
		n = safe_epoll_wait(ep);
	} while (n == 0 || (n == -1 && errno == EINTR));

	return n;
}

static int epwait_timed(struct rb_epoll *ep)
{
	struct timeval tv;

	tv.tv_sec = ep->timeout / 1000;
	tv.tv_usec = (ep->timeout % 1000) * 1000;

	for (;;) {
		struct timeval t0, now, diff;
		int n;
		fd_set rfds;

		FD_ZERO(&rfds);
		FD_SET(ep->fd, &rfds);

		gettimeofday(&t0, NULL);
		(void)rb_thread_select(ep->fd + 1, &rfds, NULL, NULL, &tv);
		n = safe_epoll_wait(ep);

		/*
		 * if we got EINTR from epoll_wait /and/ timed out
		 * just consider it a timeout and don't raise an error
		 */

		if (n > 0 || (n == -1 && errno != EINTR))
			return n;

		gettimeofday(&now, NULL);
		timersub(&now, &t0, &diff);
		timersub(&tv, &diff, &tv);

		if (tv.tv_usec < 0 || tv.tv_sec < 0)
			return (n == -1) ? 0 : n;
	}

	assert("should never get here (epwait_timed)");
	return -1;
}

static VALUE real_epwait(struct rb_epoll *ep)
{
	int n;

	if (ep->timeout == -1)
		n = epwait_forever(ep);
	else if (ep->timeout == 0)
		n = safe_epoll_wait(ep);
	else
		n = epwait_timed(ep);

	return epwait_result(ep, n);
}
#endif /* 1.8 Green thread compatibility code */

/*
 * Calls epoll_wait(2) and yields
 *
 * :call-seq:
 *
 *	epoll.wait(64, 1000) { |flags, obj| ... }
 */
static VALUE epwait(int argc, VALUE *argv, VALUE self)
{
	VALUE timeout, maxevents;
	struct rb_epoll *ep = ep_get(self);

	ep_check(ep);
	rb_need_block();
	rb_scan_args(argc, argv, "02", &maxevents, &timeout);
	ep->timeout = NIL_P(timeout) ? -1 : NUM2INT(timeout);
	ep->maxevents = NIL_P(maxevents) ? ep->capa : NUM2INT(maxevents);

	if (ep->maxevents > ep->capa) {
		xfree(ep->events);
		ep->capa = ep->maxevents;
		ep->events = xmalloc(sizeof(struct epoll_event) * ep->capa);
	}

	return real_epwait(ep);
}

/* adds +io+ object the +self+ with +flags+ */
static VALUE add(VALUE self, VALUE io, VALUE flags)
{
	return ctl(self, io, flags, EPOLL_CTL_ADD);
}

/* adds +io+ object the +self+ with +flags+ */
static VALUE del(VALUE self, VALUE io)
{
	return ctl(self, io, INT2NUM(0), EPOLL_CTL_DEL);
}

static VALUE mod(VALUE self, VALUE io, VALUE flags)
{
	return ctl(self, io, flags, EPOLL_CTL_MOD);
}

static VALUE to_io(VALUE self)
{
	struct rb_epoll *ep = ep_get(self);

	ep_check(ep);

	if (NIL_P(ep->io))
		ep->io = rb_funcall(cEpoll_IO, id_for_fd, 1, INT2NUM(ep->fd));

	return ep->io;
}

static VALUE epclose(VALUE self)
{
	struct rb_epoll *ep = ep_get(self);

	if (ep->fd >= 0) {
		st_data_t key = ep->fd;
		st_delete(active, &key, NULL);
	}

	if (NIL_P(ep->io)) {
		if (ep->fd == EP_RECREATE) {
			ep->fd = -1;
		} else if (ep->fd == -1) {
			rb_raise(rb_eIOError, "closed");
		} else {
			int e = close(ep->fd);

			ep->fd = -1;
			if (e == -1)
				rb_sys_fail("close");
		}
	} else {
		ep->fd = -1;
		rb_io_close(ep->io);
	}

	return Qnil;
}

static VALUE epclosed(VALUE self)
{
	struct rb_epoll *ep = ep_get(self);

	return ep->fd == -1 ? Qtrue : Qfalse;
}

static int cloexec_dup(struct rb_epoll *ep)
{
#ifdef F_DUPFD_CLOEXEC
	int flags = ep->flags & EPOLL_CLOEXEC ? F_DUPFD_CLOEXEC : F_DUPFD;
	int fd = fcntl(ep->fd, flags, 0);
#else
	int fd = dup(ep->fd);
	if (fd >= 0)
		(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
#endif
	return fd;
}

static VALUE init_copy(VALUE copy, VALUE orig)
{
	struct rb_epoll *a = ep_get(orig);
	struct rb_epoll *b = ep_get(copy);

	assert(a->events && b->events && a->events != b->events &&
	       NIL_P(b->io) && "Ruby broken?");

	ep_check(a);
	b->marks = a->marks;
	b->flags = a->flags;
	b->fd = cloexec_dup(a);
	if (b->fd == -1) {
		if (errno == ENFILE || errno == EMFILE) {
			rb_gc();
			b->fd = cloexec_dup(a);
		}
		if (b->fd == -1)
			rb_sys_fail("dup");
	}
	st_insert(active, (st_data_t)b->fd, (st_data_t)b);

	return copy;
}

/*
 * we close (or lose to GC) epoll descriptors at fork to avoid leakage
 * and invalid objects being referenced later in the child
 */
static int ep_atfork(st_data_t key, st_data_t value, void *ignored)
{
	struct rb_epoll *ep = (struct rb_epoll *)value;

	if (NIL_P(ep->io)) {
		if (ep->fd >= 0)
			(void)close(ep->fd);
	} else {
		ep->io = Qnil; /* must let GC take care of it later :< */
	}
	ep->fd = EP_RECREATE;

	return ST_CONTINUE;
}

static void atfork_child(void)
{
	st_table *old = active;

	active = st_init_numtable();
	st_foreach(old, ep_atfork, (st_data_t)NULL);
	st_free_table(old);
}

void sleepy_penguin_init_epoll(void)
{
	VALUE mSleepyPenguin, cEpoll;

	mSleepyPenguin = rb_define_module("SleepyPenguin");
	cEpoll = rb_define_class_under(mSleepyPenguin, "Epoll", rb_cObject);
	cEpoll_IO = rb_define_class_under(cEpoll, "IO", rb_cIO);
	rb_define_method(cEpoll, "initialize", init, -1);
	rb_define_method(cEpoll, "initialize_copy", init_copy, 1);
	rb_define_alloc_func(cEpoll, alloc);
	rb_define_method(cEpoll, "to_io", to_io, 0);
	rb_define_method(cEpoll, "close", epclose, 0);
	rb_define_method(cEpoll, "closed?", epclosed, 0);
	rb_define_method(cEpoll, "add", add, 2);
	rb_define_method(cEpoll, "mod", mod, 2);
	rb_define_method(cEpoll, "del", del, 1);
	rb_define_method(cEpoll, "delete", delete, 1);
	rb_define_method(cEpoll, "set", set, 2);
	rb_define_method(cEpoll, "wait", epwait, -1);
	rb_define_const(cEpoll, "CLOEXEC", INT2NUM(EPOLL_CLOEXEC));
	rb_define_const(cEpoll, "IN", INT2NUM(EPOLLIN));
	rb_define_const(cEpoll, "OUT", INT2NUM(EPOLLOUT));
	rb_define_const(cEpoll, "RDHUP", INT2NUM(EPOLLRDHUP));
	rb_define_const(cEpoll, "PRI", INT2NUM(EPOLLPRI));
	rb_define_const(cEpoll, "ERR", INT2NUM(EPOLLERR));
	rb_define_const(cEpoll, "HUP", INT2NUM(EPOLLHUP));
	rb_define_const(cEpoll, "ET", INT2NUM(EPOLLET));
	rb_define_const(cEpoll, "ONESHOT", INT2NUM(EPOLLONESHOT));
	id_for_fd = rb_intern("for_fd");
	active = st_init_numtable();

	if (pthread_atfork(NULL, NULL, atfork_child) != 0) {
		rb_gc();
		if (pthread_atfork(NULL, NULL, atfork_child) != 0)
			rb_memerror();
	}
}

git clone https://yhbt.net/sleepy_penguin.git