Commit c6ae9896 authored by jan.koester's avatar jan.koester
Browse files

bsd optimize

parent 7ccc3c56
Loading
Loading
Loading
Loading
+78 −82
Changes for src/event/kqueue.cpp: 78 added lines, 82 removed lines.
Original line number Diff line number Diff line
@@ -100,47 +100,61 @@ namespace netplus {
    #define KQUEUE_EV_ERROR  4
    #define KQUEUE_EV_EOF    8

    // RAII Rearm (kqueue EV_ONESHOT) - more efficient than level-triggered
    // Since we batch send operations, re-arming syscalls are amortized
    class KqueueArmGuard {
    // Batch kevent changes to reduce syscall overhead
    class KeventBatch {
    public:
        KqueueArmGuard(int fd, std::shared_ptr<con> c, pollapi* pptr)
            : _fd(fd), _con(std::move(c)), _pptr(pptr) {}
        static constexpr int MAX_CHANGES = 256;
        
        ~KqueueArmGuard() {
            if (!_armed) return;
            if (!_con || !_con->csock) return;
        KeventBatch(int kqfd) : _kqfd(kqfd) {}
        
            int next = 0;
        ~KeventBatch() {
            flush();
        }
        
            // during handshake => need READ, and WRITE only if pending writes
            if (!_con->csock->getHandshakeDone()) {
                next |= KQUEUE_EV_READ;
                if (_con->csock->hasPendingWrite())
                    next |= KQUEUE_EV_WRITE;
            } else {
                next |= KQUEUE_EV_READ;
                if (!_con->SendData.empty() || _con->csock->hasPendingWrite())
                    next |= KQUEUE_EV_WRITE;
                // If TLS has buffered data, trigger EVFILT_WRITE to force a wakeup
                if (_con->csock->hasBufferedData())
                    next |= KQUEUE_EV_WRITE;
        void add_change(int fd, int filter, int flags) {
            if (_count >= MAX_CHANGES)
                flush();
            EV_SET(&_changes[_count], fd, filter, flags, 0, 0, nullptr);
            _count++;
        }
        
            try {
                _pptr->setpollEventsFd(_fd, next);
            } catch (...) {
                // ignore
        void flush() {
            if (_count > 0) {
                kevent(_kqfd, _changes, _count, nullptr, 0, nullptr);
                _count = 0;
            }
        }
        
    private:
        int _kqfd;
        struct kevent _changes[MAX_CHANGES];
        int _count = 0;
    };

    // RAII Rearm guard - minimal overhead for edge-triggered
    class KqueueArmGuard {
    public:
        KqueueArmGuard(int fd, std::shared_ptr<con> c, KeventBatch* batch)
            : _fd(fd), _con(std::move(c)), _batch(batch) {}

        ~KqueueArmGuard() {
            if (!_armed || !_batch) return;
            // With edge-triggered, we don't re-arm unless needed for write
            // This saves significant syscall overhead
        }

        void disarm() { _armed = false; }
        
        void arm_write() {
            if (!_batch) return;
            _batch->add_change(_fd, EVFILT_WRITE, EV_ADD | EV_CLEAR);
        }

    private:
        bool _armed = true;
        int _fd;
        std::shared_ptr<con> _con;
        pollapi* _pptr;
        KeventBatch* _batch;
    };

    // ------------------------------------------------------------
@@ -153,7 +167,8 @@ namespace netplus {
              _kqfd(kqfd),
              _Events(new struct kevent[serversocket->getMaxconnections()]),
              _ServerSocket(serversocket),
              _EventCount(0)
              _EventCount(0),
              _batch(kqfd)
        {
            {
                std::lock_guard<std::mutex> lk(POLL_HANDLER_MUTEX);
@@ -200,46 +215,28 @@ namespace netplus {
        }

        void setpollEventsFd(int fd, int events) override {
            struct kevent changes[2];
            int nchanges = 0;
            // Edge-triggered with EV_CLEAR - no re-arming needed for data flow
            // Only add filters that are needed; delete others
            
            if (events == 0) {
                // Disable both read and write
                struct kevent delev[2];
                EV_SET(&delev[0], fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr);
                EV_SET(&delev[1], fd, EVFILT_WRITE, EV_DELETE, 0, 0, nullptr);
                kevent(_kqfd, delev, 2, nullptr, 0, nullptr);
                // Disable all events
                _batch.add_change(fd, EVFILT_READ, EV_DELETE);
                _batch.add_change(fd, EVFILT_WRITE, EV_DELETE);
                return;
            }

            // Set up read event (EV_ONESHOT)
            // Add/enable READ filter (edge-triggered)
            if (events & KQUEUE_EV_READ) {
                EV_SET(&changes[nchanges], fd, EVFILT_READ,
                       EV_ADD | EV_ONESHOT, 0, 0, nullptr);
                nchanges++;
                _batch.add_change(fd, EVFILT_READ, EV_ADD | EV_CLEAR);
            } else {
                struct kevent delev;
                EV_SET(&delev, fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr);
                kevent(_kqfd, &delev, 1, nullptr, 0, nullptr);
                _batch.add_change(fd, EVFILT_READ, EV_DELETE);
            }

            // Set up write event (EV_ONESHOT)
            // Add/enable WRITE filter (edge-triggered)
            if (events & KQUEUE_EV_WRITE) {
                EV_SET(&changes[nchanges], fd, EVFILT_WRITE,
                       EV_ADD | EV_ONESHOT, 0, 0, nullptr);
                nchanges++;
                _batch.add_change(fd, EVFILT_WRITE, EV_ADD | EV_CLEAR);
            } else {
                struct kevent delev;
                EV_SET(&delev, fd, EVFILT_WRITE, EV_DELETE, 0, 0, nullptr);
                kevent(_kqfd, &delev, 1, nullptr, 0, nullptr);
            }

            if (nchanges > 0) {
                if (kevent(_kqfd, changes, nchanges, nullptr, 0, nullptr) < 0) {
                    NetException except;
                    except[NetException::Error] << "setpollEventsFd: kevent failed: " << strerror(errno);
                    throw except;
                }
                _batch.add_change(fd, EVFILT_WRITE, EV_DELETE);
            }
        }

@@ -322,26 +319,16 @@ namespace netplus {
                    CONNECTIONS.emplace(fd, ccon);
                }

                // Add to kqueue (EV_ONESHOT)
                // Batching recv/send operations in user space amortizes re-arm cost
                struct kevent setevent;
                EV_SET(&setevent, fd, EVFILT_READ,
                       EV_ADD | EV_ONESHOT, 0, 0, nullptr);

                if (kevent(_kqfd, &setevent, 1, nullptr, 0, nullptr) < 0) {
                    std::lock_guard<std::mutex> lk(POLL_HANDLER_MUTEX);
                    CONNECTIONS.erase(fd);
                    NetException except;
                    except[NetException::Error] << "ConnectEventHandler: kevent ADD failed: " << strerror(errno);
                    throw except;
                }
                // Add to kqueue (edge-triggered with EV_CLEAR)
                // This avoids costly re-arm operations for bulk data
                _batch.add_change(fd, EVFILT_READ, EV_ADD | EV_CLEAR);

                evconnection->ConnectEvent(*ccon, tid, args);

                // If ConnectEvent queued data (e.g. HTTP/2 SETTINGS),
                // re-arm with WRITE so it gets flushed immediately.
                // enable WRITE to flush immediately
                if (!ccon->SendData.empty() || ccon->csock->hasPendingWrite()) {
                    setpollEventsFd(fd, KQUEUE_EV_READ | KQUEUE_EV_WRITE);
                    _batch.add_change(fd, EVFILT_WRITE, EV_ADD | EV_CLEAR);
                }

            } catch (NetException& e) {
@@ -360,7 +347,7 @@ namespace netplus {
                return;
            }

            KqueueArmGuard rearm(fd, c, this);
            KqueueArmGuard rearm(fd, c, &_batch);
            bool needClose = false;

            {
@@ -403,7 +390,7 @@ namespace netplus {
                                } catch (NetException& e) {
                                    if (e.getErrorType() == NetException::Note) {
                                        rearm.disarm();
                                        setpollEventsFd(fd, KQUEUE_EV_WRITE);
                                        _batch.add_change(fd, EVFILT_WRITE, EV_ADD | EV_CLEAR);
                                        return;
                                    }
                                    throw;
@@ -420,7 +407,7 @@ namespace netplus {
                            }
                        }

                        // Re-arm if handshake still in progress (EV_ONESHOT requires re-arm)
                        // Re-arm if handshake still in progress (edge-triggered)
                        if (!c->csock->getHandshakeDone()) {
                            int ev = KQUEUE_EV_READ;
                            if (c->csock->hasPendingWrite()) ev |= KQUEUE_EV_WRITE;
@@ -445,6 +432,7 @@ namespace netplus {
                        // Step 3: Application data (handshake done)
                        // Drain all available TLS records to avoid stalling
                        // when multiple records arrive in a single TCP segment.
                        // Edge-triggered: drain completely before returning
                        bool hasAppData = (events & KQUEUE_EV_READ) ||
                                          c->csock->hasBufferedData();
                        while (hasAppData && c->csock->getHandshakeDone() && !needClose) {
@@ -484,7 +472,7 @@ namespace netplus {
                                } catch (NetException& e) {
                                    if (e.getErrorType() == NetException::Note) {
                                        rearm.disarm();
                                        setpollEventsFd(fd, KQUEUE_EV_WRITE);
                                        _batch.add_change(fd, EVFILT_WRITE, EV_ADD | EV_CLEAR);
                                        return;
                                    }
                                    throw;
@@ -492,6 +480,9 @@ namespace netplus {
                            }

                            if (!c->SendData.empty()) {
                                // For large transfers (e.g., images), try to send all pending data
                                // Edge-triggered notification means we only get woken once per batch
                                while (!c->SendData.empty() && !needClose) {
                                    size_t sendlen = std::min((size_t)BLOCKSIZE, c->SendData.size());
                                    buffer out(c->SendData.data(), sendlen);

@@ -503,7 +494,7 @@ namespace netplus {
                                    } catch (NetException& e) {
                                        if (e.getErrorType() == NetException::Note) {
                                            rearm.disarm();
                                        setpollEventsFd(fd, KQUEUE_EV_WRITE);
                                            _batch.add_change(fd, EVFILT_WRITE, EV_ADD | EV_CLEAR);
                                            return;
                                        }
                                        throw;
@@ -511,6 +502,12 @@ namespace netplus {

                                    if (consumed > 0) {
                                        c->SendData.erase(c->SendData.begin(), c->SendData.begin() + consumed);
                                    } else {
                                        // Socket buffer full, wait for write-ready
                                        rearm.disarm();
                                        _batch.add_change(fd, EVFILT_WRITE, EV_ADD | EV_CLEAR);
                                        return;
                                    }
                                }
                            }

@@ -563,11 +560,9 @@ namespace netplus {
            {
                std::lock_guard<std::mutex> lk(ccon->event_mutex);

                // remove from kqueue
                struct kevent delev[2];
                EV_SET(&delev[0], fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr);
                EV_SET(&delev[1], fd, EVFILT_WRITE, EV_DELETE, 0, 0, nullptr);
                kevent(_kqfd, delev, 2, nullptr, 0, nullptr);
                // remove from kqueue (using batch for efficiency)
                _batch.add_change(fd, EVFILT_READ, EV_DELETE);
                _batch.add_change(fd, EVFILT_WRITE, EV_DELETE);

                // close socket
                safeCloseSocket(ccon);
@@ -585,6 +580,7 @@ namespace netplus {
        std::unique_ptr<struct kevent[]> _Events;
        socket* _ServerSocket;
        int _EventCount;
        KeventBatch _batch;
    };

    // ------------------------------------------------------------
@@ -754,7 +750,7 @@ namespace netplus {
            }

            struct kevent setevent;
            EV_SET(&setevent, ss->fd(), EVFILT_READ, EV_ADD, 0, 0, nullptr);
            EV_SET(&setevent, ss->fd(), EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, nullptr);

            if (kevent(_pollFD, &setevent, 1, nullptr, 0, nullptr) < 0) {
                NetException e;