View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.channel.unix;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.Unpooled;
20  import io.netty.channel.ChannelOutboundBuffer.MessageProcessor;
21  import io.netty.util.internal.CleanableDirectBuffer;
22  import io.netty.util.internal.PlatformDependent;
23  
24  import java.nio.ByteBuffer;
25  import java.nio.ByteOrder;
26  
27  import static io.netty.channel.unix.Limits.IOV_MAX;
28  import static io.netty.channel.unix.Limits.SSIZE_MAX;
29  import static io.netty.util.internal.ObjectUtil.checkInRange;
30  import static io.netty.util.internal.ObjectUtil.checkPositive;
31  import static java.lang.Math.min;
32  
33  /**
34   * Represent an array of struct array and so can be passed directly over via JNI without the need to do any more
35   * array copies.
36   *
37   * The buffers are written out directly into direct memory to match the struct iov. See also {@code man writev}.
38   *
39   * <pre>
40   * struct iovec {
41   *   void  *iov_base;
42   *   size_t iov_len;
43   * };
44   * </pre>
45   *
46   * See also
47   * <a href="https://rkennke.wordpress.com/2007/07/30/efficient-jni-programming-iv-wrapping-native-data-objects/"
48   * >Efficient JNI programming IV: Wrapping native data objects</a>.
49   */
50  public final class IovArray implements MessageProcessor {
51  
52      /** The size of an address which should be 8 for 64 bits and 4 for 32 bits. */
53      private static final int ADDRESS_SIZE = Buffer.addressSize();
54  
55      /**
56       * The size of an {@code iovec} struct in bytes. This is calculated as we have 2 entries each of the size of the
57       * address.
58       */
59      public static final int IOV_SIZE = 2 * ADDRESS_SIZE;
60  
61      /**
62       * The needed memory to hold up to {@code IOV_MAX} iov entries, where {@code IOV_MAX} signified
63       * the maximum number of {@code iovec} structs that can be passed to {@code writev(...)}.
64       */
65      private static final int MAX_CAPACITY = IOV_MAX * IOV_SIZE;
66  
67      private final long memoryAddress;
68      private final ByteBuf memory;
69      private final CleanableDirectBuffer cleanable;
70      private int count;
71      private long size;
72      private long maxBytes = SSIZE_MAX;
73      private int maxCount;
74  
75      /**
76       * @deprecated Use {@link #IovArray(int)} instead.
77       */
78      @Deprecated
79      public IovArray() {
80          this(IOV_MAX);
81      }
82  
83      /**
84       * Allocate an IovArray with enough room for the given number of <strong>entries</strong> (not bytes).
85       * @param numEntries The desired number of entries in the IovArray.
86       */
87      @SuppressWarnings("deprecation")
88      public IovArray(int numEntries) {
89          int sizeBytes = Math.multiplyExact(checkPositive(numEntries, "numEntries"), IOV_SIZE);
90          cleanable = Buffer.allocateDirectBufferWithNativeOrder(sizeBytes);
91          ByteBuf bbuf = Unpooled.wrappedBuffer(cleanable.buffer()).setIndex(0, 0);
92          memory = PlatformDependent.hasUnsafe() ? bbuf : bbuf.order(
93                  PlatformDependent.BIG_ENDIAN_NATIVE_ORDER ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
94          if (memory.hasMemoryAddress()) {
95              memoryAddress = memory.memoryAddress();
96          } else {
97              // Fallback to using JNI as we were not be able to access the address otherwise.
98  
99              // Use internalNioBuffer to reduce object creation.
100             // It is important to add the position as the returned ByteBuffer might be shared by multiple ByteBuf
101             // instances and so has an address that starts before the start of the ByteBuf itself.
102             ByteBuffer byteBuffer = memory.internalNioBuffer(0, memory.capacity());
103             memoryAddress = Buffer.memoryAddress(byteBuffer) + byteBuffer.position();
104         }
105         maxCount = IOV_MAX;
106     }
107 
108     /**
109      * @param memory The underlying memory.
110      * @deprecated Use {@link #IovArray(int)} instead.
111      */
112     @Deprecated
113     public IovArray(ByteBuf memory) {
114         assert memory.writerIndex() == 0;
115         assert memory.readerIndex() == 0;
116         this.memory = PlatformDependent.hasUnsafe() ? memory : memory.order(
117                 PlatformDependent.BIG_ENDIAN_NATIVE_ORDER ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
118         if (memory.hasMemoryAddress()) {
119             memoryAddress = memory.memoryAddress();
120         } else {
121             // Fallback to using JNI as we were not be able to access the address otherwise.
122 
123             // Use internalNioBuffer to reduce object creation.
124             // It is important to add the position as the returned ByteBuffer might be shared by multiple ByteBuf
125             // instances and so has an address that starts before the start of the ByteBuf itself.
126             ByteBuffer byteBuffer = memory.internalNioBuffer(0, memory.capacity());
127             memoryAddress = Buffer.memoryAddress(byteBuffer) + byteBuffer.position();
128         }
129         cleanable = null;
130         maxCount = IOV_MAX;
131     }
132 
133     public void clear() {
134         count = 0;
135         size = 0;
136         maxCount = IOV_MAX;
137     }
138 
139     /**
140      * @deprecated Use {@link #add(ByteBuf, int, int)}
141      */
142     @Deprecated
143     public boolean add(ByteBuf buf) {
144         return add(buf, buf.readerIndex(), buf.readableBytes());
145     }
146 
147     public boolean add(ByteBuf buf, int offset, int len) {
148         if (count == maxCount) {
149             // No more room!
150             return false;
151         }
152         if (buf.nioBufferCount() == 1) {
153             if (len == 0) {
154                 return true;
155             }
156             if (buf.hasMemoryAddress()) {
157                 return add(memoryAddress, buf.memoryAddress() + offset, len);
158             } else {
159                 ByteBuffer nioBuffer = buf.internalNioBuffer(offset, len);
160                 return add(memoryAddress, Buffer.memoryAddress(nioBuffer) + nioBuffer.position(), len);
161             }
162         } else {
163             ByteBuffer[] buffers = buf.nioBuffers(offset, len);
164             for (ByteBuffer nioBuffer : buffers) {
165                 final int remaining = nioBuffer.remaining();
166                 if (remaining != 0 &&
167                         (!add(memoryAddress, Buffer.memoryAddress(nioBuffer) + nioBuffer.position(), remaining)
168                                 || count == IOV_MAX)) {
169                     return false;
170                 }
171             }
172             return true;
173         }
174     }
175 
176     /**
177      * Return {@code true} if there is no more space left in the {@link IovArray}.
178      *
179      * @return full or not.
180      */
181     public boolean isFull() {
182         return memory.capacity() < (count + 1) * IOV_SIZE || size >= maxBytes;
183     }
184 
185     private boolean add(long memoryAddress, long addr, int len) {
186         assert addr != 0;
187 
188         // If there is at least 1 entry then we enforce the maximum bytes. We want to accept at least one entry so we
189         // will attempt to write some data and make progress.
190         if ((maxBytes - len < size && count > 0) ||
191                 // Check if we have enough space left
192                 memory.capacity() < (count + 1) * IOV_SIZE) {
193             // If the size + len will overflow SSIZE_MAX we stop populate the IovArray. This is done as linux
194             //  not allow to write more bytes then SSIZE_MAX with one writev(...) call and so will
195             // return 'EINVAL', which will raise an IOException.
196             //
197             // See also:
198             // - https://linux.die.net//man/2/writev
199             return false;
200         }
201         final int baseOffset = idx(count);
202         final int lengthOffset = baseOffset + ADDRESS_SIZE;
203 
204         size += len;
205         ++count;
206 
207         if (ADDRESS_SIZE == 8) {
208             // 64bit
209             if (PlatformDependent.hasUnsafe()) {
210                 PlatformDependent.putLong(baseOffset + memoryAddress, addr);
211                 PlatformDependent.putLong(lengthOffset + memoryAddress, len);
212             } else {
213                 memory.setLong(baseOffset, addr);
214                 memory.setLong(lengthOffset, len);
215             }
216         } else {
217             assert ADDRESS_SIZE == 4;
218             if (PlatformDependent.hasUnsafe()) {
219                 PlatformDependent.putInt(baseOffset + memoryAddress, (int) addr);
220                 PlatformDependent.putInt(lengthOffset + memoryAddress, len);
221             } else {
222                 memory.setInt(baseOffset, (int) addr);
223                 memory.setInt(lengthOffset, len);
224             }
225         }
226         return true;
227     }
228 
229     /**
230      * Removes all entries that were added after the first {@code count} entries, so these can be added again in
231      * another way. This doesn't change {@link #maxBytes()} and {@link #maxCount()}.
232      *
233      * @param count the number of entries to keep, as returned by {@link #count()} before the entries were added.
234      */
235     public void truncate(int count) {
236         checkInRange(count, 0, this.count, "count");
237         for (int i = count; i < this.count; i++) {
238             size -= length(i);
239         }
240         this.count = count;
241     }
242 
243     /**
244      * Returns the number of bytes of the entry at the given index.
245      */
246     public long length(int index) {
247         final int lengthOffset = idx(index) + ADDRESS_SIZE;
248         if (ADDRESS_SIZE == 8) {
249             // 64bit
250             return PlatformDependent.hasUnsafe() ?
251                     PlatformDependent.getLong(lengthOffset + memoryAddress) : memory.getLong(lengthOffset);
252         }
253         assert ADDRESS_SIZE == 4;
254         return PlatformDependent.hasUnsafe() ?
255                 PlatformDependent.getInt(lengthOffset + memoryAddress) : memory.getInt(lengthOffset);
256     }
257 
258     /**
259      * Returns the number if iov entries.
260      */
261     public int count() {
262         return count;
263     }
264 
265     /**
266      * Returns the size in bytes
267      */
268     public long size() {
269         return size;
270     }
271 
272     /**
273      * Set the maximum amount of bytes that can be added to this {@link IovArray} via {@link #add(ByteBuf, int, int)}
274      * <p>
275      * This will not impact the existing state of the {@link IovArray}, and only applies to subsequent calls to
276      * {@link #add(ByteBuf)}.
277      * <p>
278      * In order to ensure some progress is made at least one {@link ByteBuf} will be accepted even if it's size exceeds
279      * this value.
280      * @param maxBytes the maximum amount of bytes that can be added to this {@link IovArray}.
281      */
282     public void maxBytes(long maxBytes) {
283         this.maxBytes = min(SSIZE_MAX, checkPositive(maxBytes, "maxBytes"));
284     }
285 
286     /**
287      * Set the maximum amount of buffers that can be added to this {@link IovArray} via {@link #add(ByteBuf, int, int)}
288      * <p>
289      * This will not impact the existing state of the {@link IovArray}, and only applies to subsequent calls to
290      * {@link #add(ByteBuf)}.
291      * <p>
292      * @param maxCount the maximum amount of bytes that can be added to this {@link IovArray}.
293      */
294     public void maxCount(int maxCount) {
295         this.maxCount = min(IOV_MAX, checkPositive(maxCount, "maxCount"));
296     }
297 
298     /**
299      * Get the maximum amount of bytes that can be added to this {@link IovArray}.
300      * @return the maximum amount of bytes that can be added to this {@link IovArray}.
301      */
302     public long maxBytes() {
303         return maxBytes;
304     }
305 
306     /**
307      * Get the maximum amount of buffers that can be added to this {@link IovArray}.
308      * @return the maximum amount of buffers that can be added to this {@link IovArray}.
309      */
310     public int maxCount() {
311         return maxCount;
312     }
313 
314     /**
315      * Returns the {@code memoryAddress} for the given {@code offset}.
316      */
317     public long memoryAddress(int offset) {
318         return memoryAddress + idx(offset);
319     }
320 
321     /**
322      * Release the {@link IovArray}. Once release further using of it may crash the JVM!
323      */
324     public void release() {
325         memory.release();
326         if (cleanable != null) {
327             // The 'cleanable' will be 'null' if the 'IovArray(ByteBuf)' constructor was used.
328             cleanable.clean();
329         }
330     }
331 
332     @Override
333     public boolean processMessage(Object msg) throws Exception {
334         if (msg instanceof ByteBuf) {
335             ByteBuf buffer = (ByteBuf) msg;
336             return add(buffer, buffer.readerIndex(), buffer.readableBytes());
337         }
338         return false;
339     }
340 
341     private static int idx(int index) {
342         return IOV_SIZE * index;
343     }
344 }