summaryrefslogtreecommitdiff
path: root/gnu/java/nio/EpollSelectorImpl.java
blob: 2b3c9bbb1b64cb7787524e226a5a4f81644abfc3 (plain)
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
/* EpollSelectorImpl.java -- selector implementation using epoll
   Copyright (C) 2006 Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package gnu.java.nio;

import gnu.classpath.Configuration;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.spi.AbstractSelectableChannel;
import java.nio.channels.spi.AbstractSelector;
import java.nio.channels.spi.SelectorProvider;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * An implementation of {@link Selector} that uses the epoll event
 * notification mechanism on GNU/Linux.
 *
 * @author Casey Marshall (csm@gnu.org)
 */
public class EpollSelectorImpl extends AbstractSelector
{
  // XXX is this reasonable? Does it matter?
  private static final int DEFAULT_EPOLL_SIZE = 128;
  private static final int sizeof_struct_epoll_event;
  
  private static final int OP_ACCEPT  = SelectionKey.OP_ACCEPT;
  private static final int OP_CONNECT = SelectionKey.OP_CONNECT;
  private static final int OP_READ    = SelectionKey.OP_READ;
  private static final int OP_WRITE   = SelectionKey.OP_WRITE;
  
  /** our epoll file descriptor. */
  private int epoll_fd;
  
  private final HashMap keys;
  private Set selectedKeys;
  private Thread waitingThread;
  private ByteBuffer events;
  
  private static final int INITIAL_CAPACITY;
  private static final int MAX_DOUBLING_CAPACITY;
  private static final int CAPACITY_INCREMENT;

  static
  {
    if (Configuration.INIT_LOAD_LIBRARY)
      System.loadLibrary("javanio");
    
    if (epoll_supported())
      sizeof_struct_epoll_event = sizeof_struct();
    else
      sizeof_struct_epoll_event = -1;
    
    INITIAL_CAPACITY = 64 * sizeof_struct_epoll_event;
    MAX_DOUBLING_CAPACITY = 1024 * sizeof_struct_epoll_event;
    CAPACITY_INCREMENT = 128 * sizeof_struct_epoll_event;
  }
  
  public EpollSelectorImpl(SelectorProvider provider)
    throws IOException
  {
    super(provider);
    epoll_fd = epoll_create(DEFAULT_EPOLL_SIZE);
    keys = new HashMap();
    selectedKeys = null;
    events = ByteBuffer.allocateDirect(INITIAL_CAPACITY);
  }

  /* (non-Javadoc)
   * @see java.nio.channels.Selector#keys()
   */
  public Set keys()
  {
    return new HashSet(keys.values());
  }

  /* (non-Javadoc)
   * @see java.nio.channels.Selector#select()
   */
  public int select() throws IOException
  {
    return doSelect(-1);
  }

  /* (non-Javadoc)
   * @see java.nio.channels.Selector#select(long)
   */
  public int select(long timeout) throws IOException
  {
    if (timeout > Integer.MAX_VALUE)
      throw new IllegalArgumentException("timeout is too large");
    if (timeout < 0)
      throw new IllegalArgumentException("invalid timeout");
    return doSelect((int) timeout);
  }
    
  private int doSelect(int timeout) throws IOException
  {
    synchronized (keys)
    {
      Set cancelledKeys = cancelledKeys();
      synchronized (cancelledKeys)
      {
        for (Iterator it = cancelledKeys.iterator(); it.hasNext(); )
          {
            EpollSelectionKeyImpl key = (EpollSelectionKeyImpl) it.next();
            epoll_delete(epoll_fd, key.fd);
            key.valid = false;
            keys.remove(Integer.valueOf(key.fd));
            it.remove();
            deregister(key);
          }
        
        // Clear out closed channels. The fds are removed from the epoll
        // fd when closed, so there is no need to remove them manually.
        for (Iterator it = keys.values().iterator(); it.hasNext(); )
          {
            EpollSelectionKeyImpl key = (EpollSelectionKeyImpl) it.next();
            SelectableChannel ch = key.channel();
            if (ch instanceof VMChannelOwner)
              {
                if (!((VMChannelOwner) ch).getVMChannel().getState().isValid())
                  it.remove();
              }
          }
        
        // Don't bother if we have nothing to select.
        if (keys.isEmpty())
          return 0;

        int ret;
        try
          {
            begin();
            waitingThread = Thread.currentThread();
            ret = epoll_wait(epoll_fd, events, keys.size(), timeout);
          }
        finally
          {
            Thread.interrupted();
            waitingThread = null;
            end();
          }
      
        HashSet s = new HashSet(ret);
        for (int i = 0; i < ret; i++)
          {
            events.position(i * sizeof_struct_epoll_event);
            ByteBuffer b = events.slice();
            int fd = selected_fd(b);
            EpollSelectionKeyImpl key
              = (EpollSelectionKeyImpl) keys.get(Integer.valueOf(fd));
            if (key == null)
              throw new IOException("fd was selected, but no key found");
            key.selectedOps = selected_ops(b) & key.interestOps;
            s.add(key);
          }
        
        reallocateBuffer();
        
        selectedKeys = s;
        return ret;
      }
    }
  }

  /* (non-Javadoc)
   * @see java.nio.channels.Selector#selectedKeys()
   */
  public Set selectedKeys()
  {
    if (selectedKeys == null)
      return Collections.EMPTY_SET;
    return selectedKeys;
  }

  /* (non-Javadoc)
   * @see java.nio.channels.Selector#selectNow()
   */
  public int selectNow() throws IOException
  {
    return doSelect(0);
  }

  /* (non-Javadoc)
   * @see java.nio.channels.Selector#wakeup()
   */
  public Selector wakeup()
  {
    try
      {
        waitingThread.interrupt();
      }
    catch (NullPointerException npe)
      {
        // Ignored, thrown if we are not in a blocking op.
      }
    return this;
  }
  
  /* (non-Javadoc)
   * @see java.nio.channels.spi.AbstractSelector#implCloseSelector()
   */
  protected void implCloseSelector() throws IOException
  {
    VMChannel.close(epoll_fd);
  }

  /* (non-Javadoc)
   * @see java.nio.channels.spi.AbstractSelector#register(java.nio.channels.spi.AbstractSelectableChannel, int, java.lang.Object)
   */
  protected SelectionKey register(AbstractSelectableChannel ch, int ops, Object att)
  {
    if (!(ch instanceof VMChannelOwner))
      throw new IllegalArgumentException("unsupported channel type");

    VMChannel channel = ((VMChannelOwner) ch).getVMChannel();
    try
      {
        int native_fd = channel.getState().getNativeFD();
        synchronized (keys)
        {
          if (keys.containsKey(Integer.valueOf(native_fd)))
            throw new IllegalArgumentException("channel already registered");
          EpollSelectionKeyImpl result =
            new EpollSelectionKeyImpl(this, ch, native_fd);
          if ((ops & ~(ch.validOps())) != 0)
            throw new IllegalArgumentException("invalid ops for channel");
          result.interestOps = ops;
          result.selectedOps = 0;
          result.valid = true;
          result.attach(att);
          result.key = System.identityHashCode(result);
          epoll_add(epoll_fd, result.fd, ops);
          keys.put(Integer.valueOf(native_fd), result);
	  reallocateBuffer();
          return result;
        }
      }
    catch (IOException ioe)
      {
        throw new IllegalArgumentException(ioe);
      }
  }
  
  private void reallocateBuffer()
  {
    // Ensure we have enough space for all potential events that may be
    // returned.
    if (events.capacity() < keys.size() * sizeof_struct_epoll_event)
      {
        int cap = events.capacity();
        if (cap < MAX_DOUBLING_CAPACITY)
          cap <<= 1;
        else
          cap += CAPACITY_INCREMENT;
        events = ByteBuffer.allocateDirect(cap);
      }
    // Ensure that the events buffer is not too large, given the number of
    // events registered.
    else if (events.capacity() > keys.size() * sizeof_struct_epoll_event * 2 + 1
	     && events.capacity() > INITIAL_CAPACITY)
      {
        int cap = events.capacity() >>> 1;
        events = ByteBuffer.allocateDirect(cap);
      }
  }
  
  void epoll_modify(EpollSelectionKeyImpl key, int ops) throws IOException
  {
    epoll_modify(epoll_fd, key.fd, ops);
  }
  
  /**
   * Tell if epoll is supported by this system, and support was compiled in.
   *
   * @return True if this system supports event notification with epoll.
   */
  public static native boolean epoll_supported();


  /**
   * Returns the size of `struct epoll_event'.
   *
   * @return The size of `struct epoll_event'.
   */
  private static native int sizeof_struct();
  
 
  /**
   * Open a new epoll file descriptor.
   *
   * @param size The size hint for the new epoll descriptor.
   * @return The new file descriptor integer.
   * @throws IOException If allocating a new epoll descriptor fails.
   */
  private static native int epoll_create(int size) throws IOException;
  
  /**
   * Add a file descriptor to this selector.
   *
   * @param efd The epoll file descriptor.
   * @param fd  The file descriptor to add (or modify).
   * @param ops The interest opts.
   */
  private static native void epoll_add(int efd, int fd, int ops)
    throws IOException;
  
  /**
   * Modify the interest ops of the key selecting for the given FD.
   *
   * @param efd The epoll file descriptor.
   * @param fd  The file descriptor to modify.
   * @param ops The ops.
   * @throws IOException
   */
  private static native void epoll_modify(int efd, int fd, int ops)
    throws IOException;
  
  /**
   * Remove a file descriptor from this selector.
   *
   * @param efd The epoll file descriptor.
   * @param fd  The file descriptor.
   * @throws IOException
   */
  private static native void epoll_delete(int efd, int fd) throws IOException;
  
  /**
   * Select events.
   *
   * @param efd     The epoll file descriptor.
   * @param state   The buffer to hold selected events.
   * @param n       The number of events that may be put in `state'.
   * @param timeout The timeout.
   * @return The number of events selected.
   * @throws IOException
   */
  private static native int epoll_wait(int efd, ByteBuffer state, int n, int timeout)
    throws IOException;
  
  /**
   * Fetch the fd value from a selected struct epoll_event.
   *
   * @param struct The direct buffer holding the struct.
   * @return The fd value.
   */
  private static native int selected_fd(ByteBuffer struct);
  
  /**
   * Fetch the enabled operations from a selected struct epoll_event.
   *
   * @param struct The direct buffer holding the struct.
   * @return The selected operations.
   */
  private static native int selected_ops(ByteBuffer struct);
}