1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.channel.kqueue;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.ByteBufAllocator;
20 import io.netty.channel.Channel;
21 import io.netty.channel.ChannelConfig;
22 import io.netty.channel.ChannelFuture;
23 import io.netty.channel.ChannelFutureListener;
24 import io.netty.channel.ChannelMetadata;
25 import io.netty.channel.ChannelOutboundBuffer;
26 import io.netty.channel.ChannelPipeline;
27 import io.netty.channel.ChannelPromise;
28 import io.netty.channel.DefaultFileRegion;
29 import io.netty.channel.EventLoop;
30 import io.netty.channel.FileRegion;
31 import io.netty.channel.internal.ChannelUtils;
32 import io.netty.channel.socket.DuplexChannel;
33 import io.netty.channel.unix.IovArray;
34 import io.netty.channel.unix.SocketWritableByteChannel;
35 import io.netty.channel.unix.UnixChannelUtil;
36 import io.netty.util.internal.StringUtil;
37 import io.netty.util.internal.UnstableApi;
38 import io.netty.util.internal.logging.InternalLogger;
39 import io.netty.util.internal.logging.InternalLoggerFactory;
40
41 import java.io.IOException;
42 import java.net.SocketAddress;
43 import java.nio.ByteBuffer;
44 import java.nio.channels.FileChannel;
45 import java.nio.channels.WritableByteChannel;
46 import java.util.concurrent.Executor;
47
48 import static io.netty.channel.internal.ChannelUtils.MAX_BYTES_PER_GATHERING_WRITE_ATTEMPTED_LOW_THRESHOLD;
49 import static io.netty.channel.internal.ChannelUtils.WRITE_STATUS_SNDBUF_FULL;
50
51 public abstract class AbstractKQueueStreamChannel extends AbstractKQueueChannel implements DuplexChannel {
52 private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractKQueueStreamChannel.class);
53 private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16);
54 private static final String EXPECTED_TYPES =
55 " (expected: " + StringUtil.simpleClassName(ByteBuf.class) + ", " +
56 StringUtil.simpleClassName(DefaultFileRegion.class) + ')';
57 private WritableByteChannel byteChannel;
58 private final Runnable flushTask = new Runnable() {
59 @Override
60 public void run() {
61
62
63 ((AbstractKQueueUnsafe) unsafe()).flush0();
64 }
65 };
66
67 AbstractKQueueStreamChannel(Channel parent, BsdSocket fd, boolean active) {
68 super(parent, fd, active);
69 }
70
71 AbstractKQueueStreamChannel(Channel parent, BsdSocket fd, SocketAddress remote) {
72 super(parent, fd, remote);
73 }
74
75 AbstractKQueueStreamChannel(BsdSocket fd) {
76 this(null, fd, isSoErrorZero(fd));
77 }
78
79 @Override
80 protected AbstractKQueueUnsafe newUnsafe() {
81 return new KQueueStreamUnsafe();
82 }
83
84 @Override
85 public ChannelMetadata metadata() {
86 return METADATA;
87 }
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103 private int writeBytes(ChannelOutboundBuffer in, ByteBuf buf) throws Exception {
104 int readableBytes = buf.readableBytes();
105 if (readableBytes == 0) {
106 in.remove();
107 return 0;
108 }
109
110 if (buf.hasMemoryAddress() || buf.nioBufferCount() == 1) {
111 return doWriteBytes(in, buf);
112 } else {
113 ByteBuffer[] nioBuffers = buf.nioBuffers();
114 return writeBytesMultiple(in, nioBuffers, nioBuffers.length, readableBytes,
115 config().getMaxBytesPerGatheringWrite());
116 }
117 }
118
119 private void adjustMaxBytesPerGatheringWrite(long attempted, long written, long oldMaxBytesPerGatheringWrite) {
120
121
122
123 if (attempted == written) {
124 if (attempted << 1 > oldMaxBytesPerGatheringWrite) {
125 config().setMaxBytesPerGatheringWrite(attempted << 1);
126 }
127 } else if (attempted > MAX_BYTES_PER_GATHERING_WRITE_ATTEMPTED_LOW_THRESHOLD && written < attempted >>> 1) {
128 config().setMaxBytesPerGatheringWrite(attempted >>> 1);
129 }
130 }
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147 private int writeBytesMultiple(ChannelOutboundBuffer in, IovArray array) throws IOException {
148 final long expectedWrittenBytes = array.size();
149 assert expectedWrittenBytes != 0;
150 final int cnt = array.count();
151 assert cnt != 0;
152
153 final long localWrittenBytes = socket.writevAddresses(array.memoryAddress(0), cnt);
154 if (localWrittenBytes > 0) {
155 adjustMaxBytesPerGatheringWrite(expectedWrittenBytes, localWrittenBytes, array.maxBytes());
156 in.removeBytes(localWrittenBytes);
157 return 1;
158 }
159 return WRITE_STATUS_SNDBUF_FULL;
160 }
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180 private int writeBytesMultiple(
181 ChannelOutboundBuffer in, ByteBuffer[] nioBuffers, int nioBufferCnt, long expectedWrittenBytes,
182 long maxBytesPerGatheringWrite) throws IOException {
183 assert expectedWrittenBytes != 0;
184 if (expectedWrittenBytes > maxBytesPerGatheringWrite) {
185 expectedWrittenBytes = maxBytesPerGatheringWrite;
186 }
187
188 final long localWrittenBytes = socket.writev(nioBuffers, 0, nioBufferCnt, expectedWrittenBytes);
189 if (localWrittenBytes > 0) {
190 adjustMaxBytesPerGatheringWrite(expectedWrittenBytes, localWrittenBytes, maxBytesPerGatheringWrite);
191 in.removeBytes(localWrittenBytes);
192 return 1;
193 }
194 return WRITE_STATUS_SNDBUF_FULL;
195 }
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211 private int writeDefaultFileRegion(ChannelOutboundBuffer in, DefaultFileRegion region) throws Exception {
212 final long regionCount = region.count();
213 final long offset = region.transferred();
214
215 if (offset >= regionCount) {
216 in.remove();
217 return 0;
218 }
219
220 final long flushedAmount = socket.sendFile(region, region.position(), offset, regionCount - offset);
221 if (flushedAmount > 0) {
222 in.progress(flushedAmount);
223 if (region.transferred() >= regionCount) {
224 in.remove();
225 }
226 return 1;
227 } else if (flushedAmount == 0) {
228 validateFileRegion(region, offset);
229 }
230 return WRITE_STATUS_SNDBUF_FULL;
231 }
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247 private int writeFileRegion(ChannelOutboundBuffer in, FileRegion region) throws Exception {
248 if (region.transferred() >= region.count()) {
249 in.remove();
250 return 0;
251 }
252
253 if (byteChannel == null) {
254 byteChannel = new KQueueSocketWritableByteChannel();
255 }
256 final long flushedAmount = region.transferTo(byteChannel, region.transferred());
257 if (flushedAmount > 0) {
258 in.progress(flushedAmount);
259 if (region.transferred() >= region.count()) {
260 in.remove();
261 }
262 return 1;
263 }
264 return WRITE_STATUS_SNDBUF_FULL;
265 }
266
267 @Override
268 protected void doWrite(ChannelOutboundBuffer in) throws Exception {
269
270 removeFastOpenData();
271 int writeSpinCount = config().getWriteSpinCount();
272 do {
273 final int msgCount = in.size();
274
275 if (msgCount > 1 && in.current() instanceof ByteBuf) {
276 writeSpinCount -= doWriteMultiple(in);
277 } else if (msgCount == 0) {
278
279 writeFilter(false);
280
281 return;
282 } else {
283 writeSpinCount -= doWriteSingle(in);
284 }
285
286
287
288
289 } while (writeSpinCount > 0);
290
291 if (writeSpinCount == 0) {
292
293
294
295
296 writeFilter(false);
297
298
299 eventLoop().execute(flushTask);
300 } else {
301
302
303 writeFilter(true);
304 }
305 }
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321 protected int doWriteSingle(ChannelOutboundBuffer in) throws Exception {
322
323 Object msg = in.current();
324 if (msg instanceof ByteBuf) {
325 return writeBytes(in, (ByteBuf) msg);
326 } else if (msg instanceof DefaultFileRegion) {
327 DefaultFileRegion region = (DefaultFileRegion) msg;
328 FileChannel channel = fileChannel(region);
329
330 if (channel == null || UnixChannelUtil.isFileChannelImpl(channel)) {
331 return writeDefaultFileRegion(in, region);
332 }
333 return writeFileRegion(in, region);
334 } else if (msg instanceof FileRegion) {
335 return writeFileRegion(in, (FileRegion) msg);
336 } else {
337
338 throw new Error();
339 }
340 }
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356 private int doWriteMultiple(ChannelOutboundBuffer in) throws Exception {
357 final long maxBytesPerGatheringWrite = config().getMaxBytesPerGatheringWrite();
358 IovArray array = ((KQueueEventLoop) eventLoop()).cleanArray();
359 array.maxBytes(maxBytesPerGatheringWrite);
360 in.forEachFlushedMessage(array);
361
362 if (array.count() >= 1) {
363
364 return writeBytesMultiple(in, array);
365 }
366
367 in.removeBytes(0);
368 return 0;
369 }
370
371 @Override
372 protected Object filterOutboundMessage(Object msg) {
373 if (msg instanceof ByteBuf) {
374 ByteBuf buf = (ByteBuf) msg;
375 return UnixChannelUtil.isBufferCopyNeededForWrite(buf)? newDirectBuffer(buf) : buf;
376 }
377
378 if (msg instanceof FileRegion) {
379 return msg;
380 }
381
382 throw new UnsupportedOperationException(
383 "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
384 }
385
386 @UnstableApi
387 @Override
388 protected final void doShutdownOutput() throws Exception {
389
390 removeFastOpenData();
391 socket.shutdown(false, true);
392 }
393
394 @Override
395 public boolean isOutputShutdown() {
396 return socket.isOutputShutdown();
397 }
398
399 @Override
400 public boolean isInputShutdown() {
401 return socket.isInputShutdown();
402 }
403
404 @Override
405 public boolean isShutdown() {
406 return socket.isShutdown();
407 }
408
409 @Override
410 public ChannelFuture shutdownOutput() {
411 return shutdownOutput(newPromise());
412 }
413
414 @Override
415 public ChannelFuture shutdownOutput(final ChannelPromise promise) {
416 EventLoop loop = eventLoop();
417 if (loop.inEventLoop()) {
418 ((AbstractUnsafe) unsafe()).shutdownOutput(promise);
419 } else {
420 loop.execute(new Runnable() {
421 @Override
422 public void run() {
423 ((AbstractUnsafe) unsafe()).shutdownOutput(promise);
424 }
425 });
426 }
427 return promise;
428 }
429
430 @Override
431 public ChannelFuture shutdownInput() {
432 return shutdownInput(newPromise());
433 }
434
435 @Override
436 public ChannelFuture shutdownInput(final ChannelPromise promise) {
437 EventLoop loop = eventLoop();
438 if (loop.inEventLoop()) {
439 shutdownInput0(promise);
440 } else {
441 loop.execute(new Runnable() {
442 @Override
443 public void run() {
444 shutdownInput0(promise);
445 }
446 });
447 }
448 return promise;
449 }
450
451 private void shutdownInput0(ChannelPromise promise) {
452 try {
453 socket.shutdown(true, false);
454 } catch (Throwable cause) {
455 promise.setFailure(cause);
456 return;
457 }
458 promise.setSuccess();
459 }
460
461 @Override
462 public ChannelFuture shutdown() {
463 return shutdown(newPromise());
464 }
465
466 @Override
467 public ChannelFuture shutdown(final ChannelPromise promise) {
468 ChannelFuture shutdownOutputFuture = shutdownOutput();
469 if (shutdownOutputFuture.isDone()) {
470 shutdownOutputDone(shutdownOutputFuture, promise);
471 } else {
472 shutdownOutputFuture.addListener(new ChannelFutureListener() {
473 @Override
474 public void operationComplete(final ChannelFuture shutdownOutputFuture) throws Exception {
475 shutdownOutputDone(shutdownOutputFuture, promise);
476 }
477 });
478 }
479 return promise;
480 }
481
482 private void shutdownOutputDone(final ChannelFuture shutdownOutputFuture, final ChannelPromise promise) {
483 ChannelFuture shutdownInputFuture = shutdownInput();
484 if (shutdownInputFuture.isDone()) {
485 shutdownDone(shutdownOutputFuture, shutdownInputFuture, promise);
486 } else {
487 shutdownInputFuture.addListener(new ChannelFutureListener() {
488 @Override
489 public void operationComplete(ChannelFuture shutdownInputFuture) throws Exception {
490 shutdownDone(shutdownOutputFuture, shutdownInputFuture, promise);
491 }
492 });
493 }
494 }
495
496 private static void shutdownDone(ChannelFuture shutdownOutputFuture,
497 ChannelFuture shutdownInputFuture,
498 ChannelPromise promise) {
499 Throwable shutdownOutputCause = shutdownOutputFuture.cause();
500 Throwable shutdownInputCause = shutdownInputFuture.cause();
501 if (shutdownOutputCause != null) {
502 if (shutdownInputCause != null) {
503 logger.debug("Exception suppressed because a previous exception occurred.",
504 shutdownInputCause);
505 }
506 promise.setFailure(shutdownOutputCause);
507 } else if (shutdownInputCause != null) {
508 promise.setFailure(shutdownInputCause);
509 } else {
510 promise.setSuccess();
511 }
512 }
513
514 class KQueueStreamUnsafe extends AbstractKQueueUnsafe {
515
516 @Override
517 protected Executor prepareToClose() {
518
519 removeFastOpenData();
520 return super.prepareToClose();
521 }
522
523 @Override
524 void readReady(final KQueueRecvByteAllocatorHandle allocHandle) {
525 final ChannelConfig config = config();
526 if (shouldBreakReadReady(config)) {
527 clearReadFilter0();
528 return;
529 }
530 final ChannelPipeline pipeline = pipeline();
531 final ByteBufAllocator allocator = config.getAllocator();
532 allocHandle.reset(config);
533
534 ByteBuf byteBuf = null;
535 boolean close = false;
536 try {
537 do {
538
539
540 byteBuf = allocHandle.allocate(allocator);
541 allocHandle.lastBytesRead(doReadBytes(byteBuf));
542 if (allocHandle.lastBytesRead() <= 0) {
543
544 byteBuf.release();
545 byteBuf = null;
546 close = allocHandle.lastBytesRead() < 0;
547 if (close) {
548
549 readPending = false;
550 }
551 break;
552 }
553 allocHandle.incMessagesRead(1);
554 readPending = false;
555 pipeline.fireChannelRead(byteBuf);
556 byteBuf = null;
557
558 if (shouldBreakReadReady(config)) {
559
560
561
562
563
564
565
566
567
568
569
570 break;
571 }
572 } while (allocHandle.continueReading());
573
574 allocHandle.readComplete();
575 pipeline.fireChannelReadComplete();
576
577 if (close || allocHandle.isReadEOF()) {
578 shutdownInput(false);
579 }
580 } catch (Throwable t) {
581 handleReadException(pipeline, byteBuf, t, close, allocHandle);
582 } finally {
583 if (shouldStopReading(config)) {
584 clearReadFilter0();
585 }
586 }
587 }
588
589 private void handleReadException(ChannelPipeline pipeline, ByteBuf byteBuf, Throwable cause, boolean close,
590 KQueueRecvByteAllocatorHandle allocHandle) {
591 if (byteBuf != null) {
592 if (byteBuf.isReadable()) {
593 readPending = false;
594 pipeline.fireChannelRead(byteBuf);
595 } else {
596 byteBuf.release();
597 }
598 }
599 if (!failConnectPromise(cause)) {
600 allocHandle.readComplete();
601 pipeline.fireChannelReadComplete();
602 pipeline.fireExceptionCaught(cause);
603
604
605
606 if (close || cause instanceof OutOfMemoryError || cause instanceof IOException) {
607 shutdownInput(false);
608 }
609 }
610 }
611 }
612
613 private final class KQueueSocketWritableByteChannel extends SocketWritableByteChannel {
614 KQueueSocketWritableByteChannel() {
615 super(socket);
616 }
617
618 @Override
619 protected ByteBufAllocator alloc() {
620 return AbstractKQueueStreamChannel.this.alloc();
621 }
622 }
623 }