Improve darwin tun performance

This commit is contained in:
世界 2025-07-02 19:16:14 +08:00
parent 8763c24e49
commit a0881ada32
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
16 changed files with 1894 additions and 159 deletions

View file

@ -170,10 +170,14 @@ func (s *System) tunLoop() {
s.txChecksumOffload = linuxTUN.TXChecksumOffload()
batchSize := linuxTUN.BatchSize()
if batchSize > 1 {
s.batchLoop(linuxTUN, batchSize)
s.batchLoopLinux(linuxTUN, batchSize)
return
}
}
if darwinTUN, isDarwinTUN := s.tun.(DarwinTUN); isDarwinTUN {
s.batchLoopDarwin(darwinTUN)
return
}
packetBuffer := make([]byte, s.mtu+PacketOffset)
for {
n, err := s.tun.Read(packetBuffer)
@ -217,7 +221,7 @@ func (s *System) wintunLoop(winTun WinTun) {
}
}
func (s *System) batchLoop(linuxTUN LinuxTUN, batchSize int) {
func (s *System) batchLoopLinux(linuxTUN LinuxTUN, batchSize int) {
packetBuffers := make([][]byte, batchSize)
writeBuffers := make([][]byte, batchSize)
packetSizes := make([]int, batchSize)
@ -256,6 +260,40 @@ func (s *System) batchLoop(linuxTUN LinuxTUN, batchSize int) {
}
}
func (s *System) batchLoopDarwin(darwinTUN DarwinTUN) {
var writeBuffers []*buf.Buffer
for {
buffers, err := darwinTUN.BatchRead()
if err != nil {
if E.IsClosed(err) {
return
}
s.logger.Error(E.Cause(err, "batch read packet"))
}
if len(buffers) == 0 {
continue
}
writeBuffers = writeBuffers[:0]
for _, buffer := range buffers {
packetSize := buffer.Len()
if packetSize < header.IPv4MinimumSize {
continue
}
if s.processPacket(buffer.Bytes()) {
writeBuffers = append(writeBuffers, buffer)
} else {
buffer.Release()
}
}
if len(writeBuffers) > 0 {
err = darwinTUN.BatchWrite(writeBuffers)
if err != nil {
s.logger.Trace(E.Cause(err, "batch write packet"))
}
}
}
}
func (s *System) processPacket(packet []byte) bool {
var (
writeBack bool