my_fileno: use FIX2INT instead of NUM2INT
[ruby_io_splice.git] / ext / io_splice / io_splice_ext.c
blob4396fb05efaaaf27aa9d7f993ce55c93604fa541
1 #include "ruby.h"
2 #ifdef HAVE_RUBY_IO_H
3 # include "ruby/io.h"
4 #else
5 # include "rubyio.h"
6 #endif
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <assert.h>
10 #include <sys/uio.h>
11 #include <limits.h>
12 #include <alloca.h>
13 #include <sys/utsname.h>
15 static VALUE sym_EAGAIN;
17 #ifndef F_LINUX_SPECIFIC_BASE
18 # define F_LINUX_SPECIFIC_BASE 1024
19 #endif
21 #ifndef F_GETPIPE_SZ
22 # define F_SETPIPE_SZ (F_LINUX_SPECIFIC_BASE + 7)
23 # define F_GETPIPE_SZ (F_LINUX_SPECIFIC_BASE + 8)
24 #endif
26 #if ! HAVE_RB_IO_T
27 # define rb_io_t OpenFile
28 #endif
30 #ifdef GetReadFile
31 # define FPTR_TO_FD(fptr) (fileno(GetReadFile(fptr)))
32 #else
33 # if !HAVE_RB_IO_T || (RUBY_VERSION_MAJOR == 1 && RUBY_VERSION_MINOR == 8)
34 # define FPTR_TO_FD(fptr) fileno(fptr->f)
35 # else
36 # define FPTR_TO_FD(fptr) fptr->fd
37 # endif
38 #endif
40 static int my_fileno(VALUE io)
42 rb_io_t *fptr;
44 for (;;) {
45 switch (TYPE(io)) {
46 case T_FIXNUM: return FIX2INT(io);
47 case T_FILE: {
48 GetOpenFile(io, fptr);
49 return FPTR_TO_FD(fptr);
51 default:
52 io = rb_convert_type(io, T_FILE, "IO", "to_io");
53 /* retry */
57 #ifndef HAVE_RB_THREAD_BLOCKING_REGION
58 /* partial emulation of the 1.9 rb_thread_blocking_region under 1.8 */
59 # include <rubysig.h>
60 # define RUBY_UBF_IO ((rb_unblock_function_t *)-1)
61 typedef void rb_unblock_function_t(void *);
62 typedef VALUE rb_blocking_function_t(void *);
63 static VALUE
64 rb_thread_blocking_region(
65 rb_blocking_function_t *fn, void *data1,
66 rb_unblock_function_t *ubf, void *data2)
68 VALUE rv;
70 assert(RUBY_UBF_IO == ubf && "RUBY_UBF_IO required for emulation");
72 TRAP_BEG;
73 rv = fn(data1);
74 TRAP_END;
76 return rv;
78 #endif /* ! HAVE_RB_THREAD_BLOCKING_REGION */
80 #ifndef RSTRING_PTR
81 # define RSTRING_PTR(s) (RSTRING(s)->ptr)
82 #endif
83 #ifndef RSTRING_LEN
84 # define RSTRING_LEN(s) (RSTRING(s)->len)
85 #endif
86 #ifndef RARRAY_PTR
87 # define RARRAY_PTR(s) (RARRAY(s)->ptr)
88 #endif
89 #ifndef RARRAY_LEN
90 # define RARRAY_LEN(s) (RARRAY(s)->len)
91 #endif
93 static VALUE io_run(rb_blocking_function_t *fn, void *data)
95 ssize_t n;
96 retry:
97 n = (ssize_t)rb_thread_blocking_region(fn, data, RUBY_UBF_IO, 0);
98 if (n == -1 && errno == EINTR)
99 goto retry;
100 return (VALUE)n;
103 struct splice_args {
104 int fd_in;
105 off_t *off_in;
106 int fd_out;
107 off_t *off_out;
108 size_t len;
109 unsigned flags;
112 static VALUE nogvl_splice(void *ptr)
114 struct splice_args *a = ptr;
116 return (VALUE)splice(a->fd_in, a->off_in, a->fd_out, a->off_out,
117 a->len, a->flags);
120 static long do_splice(int argc, VALUE *argv, unsigned dflags)
122 off_t i, o;
123 VALUE fd_in, off_in, fd_out, off_out, len, flags;
124 struct splice_args a;
126 rb_scan_args(argc, argv, "51",
127 &fd_in, &off_in, &fd_out, &off_out, &len, &flags);
129 a.off_in = NIL_P(off_in) ? NULL : (i = NUM2OFFT(off_in), &i);
130 a.off_out = NIL_P(off_out) ? NULL : (o = NUM2OFFT(off_out), &o);
131 a.fd_in = my_fileno(fd_in);
132 a.fd_out = my_fileno(fd_out);
133 a.len = (size_t)NUM2ULONG(len);
134 a.flags = NIL_P(flags) ? dflags : NUM2UINT(flags) | dflags;
136 return (long)io_run(nogvl_splice, &a);
140 * call-seq:
141 * IO.splice(fd_in, off_in, fd_out, off_out, len) => integer
142 * IO.splice(fd_in, off_in, fd_out, off_out, len, flags) => integer
144 * Splice +len+ bytes from/to a pipe. Either +fd_in+ or +fd_out+
145 * MUST be a pipe. +fd_in+ and +fd_out+ may BOTH be pipes as of
146 * Linux 2.6.31 or later.
148 * +off_in+ and +off_out+ if non-nil may be used to
149 * specify an offset for the non-pipe file descriptor.
151 * +flags+ defaults to zero if unspecified.
152 * +flags+ may be a bitmask of the following flags:
154 * IO::Splice::F_MOVE, IO::Splice::F_NONBLOCK, IO::Splice::F_MORE
156 * Returns the number of bytes spliced.
157 * Raises EOFError when +fd_in+ has reached end of file.
158 * Raises Errno::EAGAIN if the IO::Splice::F_NONBLOCK flag is set
159 * and the pipe has no data to read from or space to write to. May
160 * also raise Errno::EAGAIN if the non-pipe descriptor has no data
161 * to read from or space to write to.
163 * rd, wr = (pipe = IO.pipe).map { |io| io.fileno }
164 * src_io, dst_io = File.open("/path/to/src"), File.open("/path/to/dst")
165 * src, dst = src_io.fileno, dst_io.fileno
167 * nr = IO.splice(src, nil, wr, nil, IO::Splice::PIPE_CAPA, 0)
168 * IO.splice(rd, nil, dst, nil, nr, 0)
170 * As splice never exposes buffers to userspace, it will not take
171 * into account userspace buffering done by Ruby or stdio. It is
172 * also not subject to encoding/decoding filters under Ruby 1.9.
174 * Consider using IO.trysplice if you are using non-blocking I/O on
175 * both descriptors as it avoids the cost of raising common Errno::EAGAIN
176 * exceptions.
178 * See manpage for full documentation:
179 * http://kernel.org/doc/man-pages/online/pages/man2/splice.2.html
181 static VALUE my_splice(int argc, VALUE *argv, VALUE self)
183 long n = do_splice(argc, argv, 0);
185 if (n == 0)
186 rb_eof_error();
187 if (n < 0)
188 rb_sys_fail("splice");
189 return LONG2NUM(n);
193 * call-seq:
194 * IO.trysplice(fd_in, off_in, fd_out, off_out, len) => integer
195 * IO.trysplice(fd_in, off_in, fd_out, off_out, len, flags) => integer
197 * Exactly like IO.splice, except +:EAGAIN+ is returned when either
198 * the read or write end would block instead of raising Errno::EAGAIN.
200 * IO::Splice::F_NONBLOCK is always passed for the pipe descriptor,
201 * but this can still block if the non-pipe descriptor is blocking.
203 * See IO.splice documentation for more details.
205 static VALUE trysplice(int argc, VALUE *argv, VALUE self)
207 long n = do_splice(argc, argv, SPLICE_F_NONBLOCK);
209 if (n == 0)
210 return Qnil;
211 if (n < 0) {
212 if (errno == EAGAIN)
213 return sym_EAGAIN;
214 rb_sys_fail("splice");
216 return LONG2NUM(n);
219 struct tee_args {
220 int fd_in;
221 int fd_out;
222 size_t len;
223 unsigned flags;
226 /* runs without GVL */
227 static VALUE nogvl_tee(void *ptr)
229 struct tee_args *a = ptr;
231 return (VALUE)tee(a->fd_in, a->fd_out, a->len, a->flags);
234 static long do_tee(int argc, VALUE *argv, unsigned dflags)
236 VALUE fd_in, fd_out, len, flags;
237 struct tee_args a;
239 rb_scan_args(argc, argv, "31", &fd_in, &fd_out, &len, &flags);
240 a.fd_in = my_fileno(fd_in);
241 a.fd_out = my_fileno(fd_out);
242 a.len = (size_t)NUM2ULONG(len);
243 a.flags = NIL_P(flags) ? dflags : NUM2UINT(flags) | dflags;
245 return (long)io_run(nogvl_tee, &a);
249 * call-seq:
250 * IO.tee(fd_in, fd_out, len) => integer
251 * IO.tee(fd_in, fd_out, len, flags) => integer
253 * Copies up to +len+ bytes of data from +fd_in+ to +fd_out+. +fd_in+
254 * and +fd_out+ must both refer to pipe descriptors. +fd_in+ and +fd_out+
255 * may not be endpoints of the same pipe.
257 * +flags+ may be zero (the default) or IO::Splice::F_NONBLOCK
258 * Other IO::Splice flags are currently unimplemented or have no effect.
260 * Returns the number of bytes duplicated if successful.
261 * Raises EOFError when +fd_in+ is closed and emptied.
262 * Raises Errno::EAGAIN when +fd_in+ is empty and/or +fd_out+ is full
263 * and +flags+ contains IO::Splice::F_NONBLOCK
265 * Consider using IO.trytee if you are using IO::Splice::F_NONBLOCK
266 * as it avoids the cost of raising common Errno::EAGAIN exceptions.
268 * See manpage for full documentation:
269 * http://kernel.org/doc/man-pages/online/pages/man2/tee.2.html
271 static VALUE my_tee(int argc, VALUE *argv, VALUE self)
273 long n = do_tee(argc, argv, 0);
275 if (n == 0)
276 rb_eof_error();
277 if (n < 0)
278 rb_sys_fail("tee");
280 return LONG2NUM(n);
284 * call-seq:
285 * IO.trytee(fd_in, fd_out, len) => integer
286 * IO.trytee(fd_in, fd_out, len, flags) => integer
288 * Exactly like IO.tee, except +:EAGAIN+ is returned when either
289 * the read or write end would block instead of raising Errno::EAGAIN.
291 * IO::Splice::F_NONBLOCK is always passed for the pipe descriptor,
292 * but this can still block if the non-pipe descriptor is blocking.
294 * See IO.tee documentation for more details.
296 static VALUE trytee(int argc, VALUE *argv, VALUE self)
298 long n = do_tee(argc, argv, SPLICE_F_NONBLOCK);
300 if (n == 0)
301 return Qnil;
302 if (n < 0) {
303 if (errno == EAGAIN)
304 return sym_EAGAIN;
305 rb_sys_fail("tee");
308 return LONG2NUM(n);
311 struct vmsplice_args {
312 int fd;
313 struct iovec *iov;
314 unsigned long nr_segs;
315 unsigned flags;
318 static VALUE nogvl_vmsplice(void *ptr)
320 struct vmsplice_args *a = ptr;
322 return (VALUE)vmsplice(a->fd, a->iov, a->nr_segs, a->flags);
325 /* this can't be a function since we use alloca() */
326 #define ARY2IOVEC(iov,iovcnt,expect,ary) \
327 do { \
328 VALUE *cur; \
329 struct iovec *tmp; \
330 long n; \
331 cur = RARRAY_PTR(ary); \
332 n = RARRAY_LEN(ary); \
333 if (n > IOV_MAX) \
334 rb_raise(rb_eArgError, "array is larger than IOV_MAX"); \
335 iov = tmp = alloca(sizeof(struct iovec) * n); \
336 expect = 0; \
337 iovcnt = n; \
338 for (; --n >= 0; tmp++, cur++) { \
339 Check_Type(*cur, T_STRING); \
340 tmp->iov_base = RSTRING_PTR(*cur); \
341 tmp->iov_len = RSTRING_LEN(*cur); \
342 expect += tmp->iov_len; \
344 } while (0)
346 static void advance_vmsplice_args(struct vmsplice_args *a, long n)
348 struct iovec *new_iov = a->iov;
349 unsigned long i;
351 /* skip over iovecs we've already written completely */
352 for (i = 0; i < a->nr_segs; i++, new_iov++) {
353 if (n == 0)
354 break;
356 * partially written iov,
357 * modify and retry with current iovec in
358 * front
360 if (new_iov->iov_len > (size_t)n) {
361 VALUE base = (VALUE)new_iov->iov_base;
363 new_iov->iov_len -= n;
364 new_iov->iov_base = (void *)(base + n);
365 break;
368 n -= new_iov->iov_len;
371 /* setup to retry without the already-written iovecs */
372 a->nr_segs -= i;
373 a->iov = new_iov;
377 * call-seq:
378 * IO.vmsplice(fd, string_array) => integer
379 * IO.vmsplice(fd, string_array, flags) => integer
380 * IO.vmsplice(fd, string) => integer
381 * IO.vmsplice(fd, string, flags) => integer
383 * Transfers an array of strings into the pipe descriptor given by fd.
384 * +fd+ must be the writable end of a pipe.
386 * This may allow the kernel to avoid data copies in some cases.
387 * but is (probably) of limited usefulness in Ruby. If you have
388 * use cases or ideas for making this more useful for Ruby users,
389 * please tell us at ruby.io.splice@librelist.com!
391 * Also consider the "sendfile" RubyGem or IO.copy_stream in Ruby 1.9
392 * if you want to do zero-copy file transfers to pipes or sockets. As
393 * of Linux 2.6.33, sendfile(2) can copy to any output descriptor,
394 * not just sockets.
396 * See manpage for full documentation:
397 * http://kernel.org/doc/man-pages/online/pages/man2/vmsplice.2.html
399 static VALUE my_vmsplice(int argc, VALUE * argv, VALUE self)
401 long rv = 0;
402 ssize_t left;
403 struct vmsplice_args a;
404 VALUE fd, data, flags;
406 rb_scan_args(argc, argv, "21", &fd, &data, &flags);
408 switch (TYPE(data)) {
409 case T_STRING: {
410 struct iovec iov;
412 iov.iov_base = RSTRING_PTR(data);
413 iov.iov_len = (size_t)(left = (ssize_t)RSTRING_LEN(data));
414 a.iov = &iov;
415 a.nr_segs = 1;
417 break;
418 case T_ARRAY:
419 ARY2IOVEC(a.iov, a.nr_segs, left, data);
420 break;
421 default:
422 rb_raise(rb_eTypeError, "wrong argument type %s "
423 "(expected a String or Array of strings)",
424 rb_obj_classname(data));
426 a.fd = my_fileno(fd);
427 a.flags = NIL_P(flags) ? 0 : NUM2UINT(flags);
429 for (;;) {
430 long n = (long)io_run(nogvl_vmsplice, &a);
432 if (n < 0) {
433 if (errno == EAGAIN) {
434 if (a.flags & SPLICE_F_NONBLOCK)
435 rb_sys_fail("vmsplice");
436 else if (rb_io_wait_writable(a.fd))
437 continue;
438 /* fall through on error */
441 * unlikely to hit this case, return the
442 * already written bytes, we'll let the next
443 * write (or close) fail instead
445 if (rv > 0)
446 break;
447 rb_sys_fail("vmsplice");
450 rv += n;
451 left -= n;
452 if (left == 0)
453 break;
454 advance_vmsplice_args(&a, n);
457 return LONG2NUM(rv);
461 * call-seq:
462 * reader, writer = IO.pipe
463 * reader.pipe_size => integer
465 * Returns the pipe capacity of the underlying pipe in bytes. The
466 * default capacity is 65536 bytes since Linux 2.6.11, and 4096 bytes
467 * in previous kernels.
469 * Since the pipe is a circular buffer in the same kernel, the size
470 * of the reader is exactly the same as the size of the writer.
472 * This method is only exposed on Linux 2.6.35 or later.
474 static VALUE pipe_size(VALUE self)
476 int size = fcntl(my_fileno(self), F_GETPIPE_SZ);
478 if (size < 0)
479 rb_sys_fail("fcntl(F_GETPIPE_SZ)");
481 return INT2NUM(size);
485 * call-seq:
486 * reader, writer = IO.pipe
487 * reader.pipe_size = integer
489 * Sets and returns the pipe capacity of the underlying pipe in bytes.
491 * This MUST be a power-of-two, or Errno::EINVAL will be raised.
492 * Linux will silently increase this to be equal to the page size
493 * (4096 bytes on most architectures) if the specified value is
494 * less than the size of a page.
496 * For users without CAP_SYS_RESOURCE, this raises Errno::EPERM when
497 * attempting to specify a value greater than the value in
498 * /proc/sys/fs/pipe-max-size.
500 * Since the pipe is a circular buffer in the same kernel, the size
501 * of the reader is exactly the same as the size of the writer.
503 * Raises Errno::EBUSY if the assigned value is less than
504 * the currently filled portion of the pipe.
506 * This method is only exposed on Linux 2.6.35 or later.
508 static VALUE set_pipe_size(VALUE self, VALUE size)
510 int fd = my_fileno(self);
511 int bytes = NUM2INT(size);
512 int rv = fcntl(fd, F_SETPIPE_SZ, bytes);
514 if (rv < 0) {
515 if (errno == ENOMEM) {
516 rb_gc();
517 rv = fcntl(fd, F_SETPIPE_SZ, bytes);
519 if (rv < 0)
520 rb_sys_fail("fcntl(F_SETPIPE_SZ)");
523 return size;
526 void Init_io_splice_ext(void)
528 VALUE mSplice = rb_define_module_under(rb_cIO, "Splice");
529 struct utsname utsname;
531 rb_define_singleton_method(rb_cIO, "splice", my_splice, -1);
532 rb_define_singleton_method(rb_cIO, "trysplice", trysplice, -1);
533 rb_define_singleton_method(rb_cIO, "tee", my_tee, -1);
534 rb_define_singleton_method(rb_cIO, "trytee", trytee, -1);
535 rb_define_singleton_method(rb_cIO, "vmsplice", my_vmsplice, -1);
538 * Attempt to move pages instead of copying. This is only a hint
539 * and support for it was removed in Linux 2.6.21. It will be
540 * re-added for FUSE filesystems only in Linux 2.6.35.
542 rb_define_const(mSplice, "F_MOVE", UINT2NUM(SPLICE_F_MOVE));
545 * Do not block on pipe I/O. This flag only affects the pipe(s)
546 * being spliced from/to and has no effect on the non-pipe
547 * descriptor (which requires non-blocking operation to be set
548 * explicitly).
550 * The non-blocking flag (O_NONBLOCK) on the pipe descriptors
551 * themselves are ignored by this family of functions, and
552 * using this flag is the only way to get non-blocking operation
553 * out of them.
555 rb_define_const(mSplice, "F_NONBLOCK", UINT2NUM(SPLICE_F_NONBLOCK));
558 * Indicate that there may be more data coming into the outbound
559 * descriptor. This can allow the kernel to avoid sending partial
560 * frames from sockets. Currently only used with splice.
562 rb_define_const(mSplice, "F_MORE", UINT2NUM(SPLICE_F_MORE));
565 * Only usable by vmsplice. This flag probably not useful in the
566 * context of Ruby applications which cannot control alignment.
568 rb_define_const(mSplice, "F_GIFT", UINT2NUM(SPLICE_F_GIFT));
571 * The maximum size of an atomic write to a pipe
572 * POSIX requires this to be at least 512 bytes.
573 * Under Linux, this is 4096 bytes.
575 rb_define_const(mSplice, "PIPE_BUF", UINT2NUM(PIPE_BUF));
577 if (uname(&utsname) == -1)
578 rb_sys_fail("uname");
580 /* includes 2.6.35-rc[1-6] */
581 if (strcmp(utsname.release, "2.6.35") >= 0) {
582 rb_define_method(rb_cIO, "pipe_size", pipe_size, 0);
583 rb_define_method(rb_cIO, "pipe_size=", set_pipe_size, 1);
586 * fcntl() command constant used to return the size of a pipe.
587 * This constant is only defined when running Linux 2.6.35
588 * or later. For convenience, use IO#pipe_size instead.
590 rb_define_const(mSplice, "F_GETPIPE_SZ",
591 UINT2NUM(F_GETPIPE_SZ));
594 * fcntl() command constant used to set the size of a pipe.
595 * This constant is only defined when running Linux 2.6.35
596 * or later. For convenience, use IO#pipe_size= instead.
598 rb_define_const(mSplice, "F_SETPIPE_SZ",
599 UINT2NUM(F_SETPIPE_SZ));
602 sym_EAGAIN = ID2SYM(rb_intern("EAGAIN"));