SolarisEventPort.java 8.4 KB
Newer Older
1
/*
2
 * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code 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
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
24 25 26 27 28 29 30 31 32 33
 */

package sun.nio.ch;

import java.nio.channels.spi.AsynchronousChannelProvider;
import java.util.concurrent.RejectedExecutionException;
import java.io.IOException;
import sun.misc.Unsafe;

/**
34 35
 * Provides an AsynchronousChannelGroup implementation based on the Solaris 10
 * event port framework and also provides direct access to that framework.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
 */

class SolarisEventPort
    extends Port
{
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final int addressSize = unsafe.addressSize();

    private static int dependsArch(int value32, int value64) {
        return (addressSize == 4) ? value32 : value64;
    }

    /*
     * typedef struct port_event {
     *     int             portev_events;
     *     ushort_t        portev_source;
     *     ushort_t        portev_pad;
     *     uintptr_t       portev_object;
     *     void            *portev_user;
     * } port_event_t;
     */
57 58 59 60
    static final int SIZEOF_PORT_EVENT  = dependsArch(16, 24);
    static final int OFFSETOF_EVENTS    = 0;
    static final int OFFSETOF_SOURCE    = 4;
    static final int OFFSETOF_OBJECT    = 8;
61 62

    // port sources
63 64
    static final short PORT_SOURCE_USER     = 3;
    static final short PORT_SOURCE_FD       = 4;
65 66 67 68 69 70 71 72 73 74 75 76 77

    // file descriptor to event port.
    private final int port;

    // true when port is closed
    private boolean closed;

    SolarisEventPort(AsynchronousChannelProvider provider, ThreadPool pool)
        throws IOException
    {
        super(provider, pool);

        // create event port
78
        this.port = port_create();
79 80 81 82 83 84 85 86 87 88 89 90 91 92
    }

    SolarisEventPort start() {
        startThreads(new EventHandlerTask());
        return this;
    }

    // releass resources
    private void implClose() {
        synchronized (this) {
            if (closed)
                return;
            closed = true;
        }
93
        port_close(port);
94 95 96 97
    }

    private void wakeup() {
        try {
98
            port_send(port, 0);
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
        } catch (IOException x) {
            throw new AssertionError(x);
        }
    }

    @Override
    void executeOnHandlerTask(Runnable task) {
        synchronized (this) {
            if (closed)
                throw new RejectedExecutionException();
            offerTask(task);
            wakeup();
        }
    }

    @Override
    void shutdownHandlerTasks() {
       /*
         * If no tasks are running then just release resources; otherwise
         * write to the one end of the socketpair to wakeup any polling threads..
         */
        int nThreads = threadCount();
        if (nThreads == 0) {
            implClose();
        } else {
            // send user event to wakeup each thread
            while (nThreads-- > 0) {
                try {
127
                    port_send(port, 0);
128 129 130 131 132 133 134 135 136 137 138 139
                } catch (IOException x) {
                    throw new AssertionError(x);
                }
            }
        }
    }

    @Override
    void startPoll(int fd, int events) {
        // (re-)associate file descriptor
        // no need to translate events
        try {
140
            port_associate(port, PORT_SOURCE_FD, fd, events);
141 142 143 144 145 146 147 148 149 150 151 152 153
        } catch (IOException x) {
            throw new AssertionError();     // should not happen
        }
    }

    /*
     * Task to read a single event from the port and dispatch it to the
     * channel's onEvent handler.
     */
    private class EventHandlerTask implements Runnable {
        public void run() {
            Invoker.GroupAndInvokeCount myGroupAndInvokeCount =
                Invoker.getGroupAndInvokeCount();
154
            final boolean isPooledThread = (myGroupAndInvokeCount != null);
155 156 157 158 159
            boolean replaceMe = false;
            long address = unsafe.allocateMemory(SIZEOF_PORT_EVENT);
            try {
                for (;;) {
                    // reset invoke count
160
                    if (isPooledThread)
161 162 163 164 165 166
                        myGroupAndInvokeCount.resetInvokeCount();

                    // wait for I/O completion event
                    // A error here is fatal (thread will not be replaced)
                    replaceMe = false;
                    try {
167
                        port_get(port, address);
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
                    } catch (IOException x) {
                        x.printStackTrace();
                        return;
                    }

                    // event source
                    short source = unsafe.getShort(address + OFFSETOF_SOURCE);
                    if (source != PORT_SOURCE_FD) {
                        // user event is trigger to invoke task or shutdown
                        if (source == PORT_SOURCE_USER) {
                            Runnable task = pollTask();
                            if (task == null) {
                                // shutdown request
                                return;
                            }
                            // run task (may throw error/exception)
                            replaceMe = true;
                            task.run();
                        }
                        // ignore
                        continue;
                    }

                    // pe->portev_object is file descriptor
                    int fd = (int)unsafe.getAddress(address + OFFSETOF_OBJECT);
                    // pe->portev_events
                    int events = unsafe.getInt(address + OFFSETOF_EVENTS);

                    // lookup channel
                    PollableChannel ch;
                    fdToChannelLock.readLock().lock();
                    try {
                        ch = fdToChannel.get(fd);
                    } finally {
                        fdToChannelLock.readLock().unlock();
                    }

                    // notify channel
                    if (ch != null) {
                        replaceMe = true;
                        // no need to translate events
209
                        ch.onEvent(events, isPooledThread);
210 211 212 213 214 215 216 217 218 219 220 221 222
                    }
                }
            } finally {
                // free per-thread resources
                unsafe.freeMemory(address);
                // last task to exit when shutdown release resources
                int remaining = threadExit(this, replaceMe);
                if (remaining == 0 && isShutdown())
                    implClose();
            }
        }
    }

223 224 225 226
    /**
     * Creates an event port
     */
    static native int port_create() throws IOException;
227

228 229 230 231 232
    /**
     * Associates specific events of a given object with a port
     */
    static native boolean port_associate(int port, int source, long object, int events)
        throws IOException;
233

234 235 236 237 238
    /**
     * Removes the association of an object with a port.
     */
    static native boolean port_dissociate(int port, int source, long object)
        throws IOException;
239

240 241 242 243
    /**
     * Retrieves a single event from a port
     */
    static native void port_get(int port, long pe) throws IOException;
244

245 246 247 248
    /**
     * Retrieves at most {@code max} events from a port.
     */
    static native int port_getn(int port, long address, int max, long timeout)
249 250
        throws IOException;

251 252 253 254 255 256 257 258 259
    /**
     * Sends a user-defined eventto a specified  port.
     */
    static native void port_send(int port, int events) throws IOException;

    /**
     * Closes a port.
     */
    static native void port_close(int port);
260 261 262


    static {
263
        IOUtil.load();
264 265
    }
}