Skip to content

Commit c5d86a3

Browse files
committed
Improved sendfile by not setting the tcp_cork option when the file is smaller than 64k.
1 parent a2c639d commit c5d86a3

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

include/swoole_config.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
#define SW_SOCKET_DEFAULT_CONNECT_TIMEOUT 2
5454
#define SW_SOCKET_DEFAULT_READ_TIMEOUT 60
5555
#define SW_SOCKET_DEFAULT_WRITE_TIMEOUT 60
56+
#define SW_SOCKET_CORK_MIN_SIZE 65536
5657

5758
#define SW_SYSTEMD_FDS_START 3
5859

include/swoole_socket.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,13 +72,15 @@ struct SendfileTask {
7272

7373
struct SendfileRequest {
7474
File file;
75+
int8_t corked;
7576
off_t begin;
7677
off_t end;
7778

7879
public:
7980
SendfileRequest(const char *filename, off_t _offset) : file(filename, O_RDONLY) {
8081
begin = _offset;
8182
end = 0;
83+
corked = 0;
8284
}
8385
};
8486

src/network/socket.cc

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,11 @@ int Socket::sendfile_sync(const char *filename, off_t offset, size_t length, dou
131131
return SW_ERR;
132132
}
133133

134+
auto corked = false;
135+
if (end - offset > SW_SOCKET_CORK_MIN_SIZE) {
136+
corked = cork();
137+
}
138+
134139
ssize_t n, sent_bytes;
135140
while (offset < end) {
136141
sent_bytes = get_sendfile_chunk_size(offset, end);
@@ -149,6 +154,10 @@ int Socket::sendfile_sync(const char *filename, off_t offset, size_t length, dou
149154
}
150155
}
151156

157+
if (corked) {
158+
uncork();
159+
}
160+
152161
return SW_OK;
153162
}
154163

@@ -636,8 +645,12 @@ int Socket::handle_sendfile() {
636645
BufferChunk *chunk = buffer->front();
637646
SendfileRequest *task = (SendfileRequest *) chunk->value.ptr;
638647

639-
if (task->begin == 0) {
640-
cork();
648+
if (task->corked == 0) {
649+
if (task->end - task->begin > SW_SOCKET_CORK_MIN_SIZE) {
650+
task->corked = cork() ? 1 : -1;
651+
} else {
652+
task->corked = -1;
653+
}
641654
}
642655

643656
size_t sendn = get_sendfile_chunk_size(task->begin, task->end);
@@ -679,7 +692,10 @@ int Socket::handle_sendfile() {
679692
// sendfile completed
680693
if (task->begin == task->end) {
681694
buffer->pop();
682-
uncork();
695+
if (task->corked == 1) {
696+
uncork();
697+
task->corked = 0;
698+
}
683699
}
684700

685701
return SW_OK;

0 commit comments

Comments
 (0)