tcp_posix.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. /*
  2. *
  3. * Copyright 2015 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include "src/core/lib/iomgr/port.h"
  19. #ifdef GRPC_POSIX_SOCKET
  20. #include "src/core/lib/iomgr/network_status_tracker.h"
  21. #include "src/core/lib/iomgr/tcp_posix.h"
  22. #include <errno.h>
  23. #include <stdbool.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <sys/socket.h>
  27. #include <sys/types.h>
  28. #include <unistd.h>
  29. #include <grpc/slice.h>
  30. #include <grpc/support/alloc.h>
  31. #include <grpc/support/log.h>
  32. #include <grpc/support/string_util.h>
  33. #include <grpc/support/sync.h>
  34. #include <grpc/support/time.h>
  35. #include <grpc/support/useful.h>
  36. #include "src/core/lib/channel/channel_args.h"
  37. #include "src/core/lib/debug/trace.h"
  38. #include "src/core/lib/iomgr/ev_posix.h"
  39. #include "src/core/lib/iomgr/executor.h"
  40. #include "src/core/lib/profiling/timers.h"
  41. #include "src/core/lib/slice/slice_internal.h"
  42. #include "src/core/lib/slice/slice_string_helpers.h"
  43. #include "src/core/lib/support/string.h"
  44. #ifdef GRPC_HAVE_MSG_NOSIGNAL
  45. #define SENDMSG_FLAGS MSG_NOSIGNAL
  46. #else
  47. #define SENDMSG_FLAGS 0
  48. #endif
  49. #ifdef GRPC_MSG_IOVLEN_TYPE
  50. typedef GRPC_MSG_IOVLEN_TYPE msg_iovlen_type;
  51. #else
  52. typedef size_t msg_iovlen_type;
  53. #endif
  54. grpc_tracer_flag grpc_tcp_trace = GRPC_TRACER_INITIALIZER(false, "tcp");
  55. typedef struct {
  56. grpc_endpoint base;
  57. grpc_fd *em_fd;
  58. int fd;
  59. bool finished_edge;
  60. msg_iovlen_type iov_size; /* Number of slices to allocate per read attempt */
  61. double target_length;
  62. double bytes_read_this_round;
  63. gpr_refcount refcount;
  64. gpr_atm shutdown_count;
  65. int min_read_chunk_size;
  66. int max_read_chunk_size;
  67. /* garbage after the last read */
  68. grpc_slice_buffer last_read_buffer;
  69. grpc_slice_buffer *incoming_buffer;
  70. grpc_slice_buffer *outgoing_buffer;
  71. /** slice within outgoing_buffer to write next */
  72. size_t outgoing_slice_idx;
  73. /** byte within outgoing_buffer->slices[outgoing_slice_idx] to write next */
  74. size_t outgoing_byte_idx;
  75. grpc_closure *read_cb;
  76. grpc_closure *write_cb;
  77. grpc_closure *release_fd_cb;
  78. int *release_fd;
  79. grpc_closure read_done_closure;
  80. grpc_closure write_done_closure;
  81. char *peer_string;
  82. grpc_resource_user *resource_user;
  83. grpc_resource_user_slice_allocator slice_allocator;
  84. } grpc_tcp;
  85. typedef struct backup_poller {
  86. gpr_mu *pollset_mu;
  87. grpc_closure run_poller;
  88. } backup_poller;
  89. #define BACKUP_POLLER_POLLSET(b) ((grpc_pollset *)((b) + 1))
  90. static gpr_atm g_uncovered_notifications_pending;
  91. static gpr_atm g_backup_poller; /* backup_poller* */
  92. static void tcp_handle_read(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */,
  93. grpc_error *error);
  94. static void tcp_handle_write(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */,
  95. grpc_error *error);
  96. static void tcp_drop_uncovered_then_handle_write(grpc_exec_ctx *exec_ctx,
  97. void *arg /* grpc_tcp */,
  98. grpc_error *error);
  99. static void done_poller(grpc_exec_ctx *exec_ctx, void *bp,
  100. grpc_error *error_ignored) {
  101. backup_poller *p = (backup_poller *)bp;
  102. grpc_pollset_destroy(exec_ctx, BACKUP_POLLER_POLLSET(p));
  103. gpr_free(p);
  104. }
  105. static void run_poller(grpc_exec_ctx *exec_ctx, void *bp,
  106. grpc_error *error_ignored) {
  107. backup_poller *p = (backup_poller *)bp;
  108. gpr_mu_lock(p->pollset_mu);
  109. GRPC_LOG_IF_ERROR("backup_poller:pollset_work",
  110. grpc_pollset_work(exec_ctx, BACKUP_POLLER_POLLSET(p), NULL,
  111. gpr_now(GPR_CLOCK_MONOTONIC),
  112. gpr_inf_future(GPR_CLOCK_MONOTONIC)));
  113. gpr_mu_unlock(p->pollset_mu);
  114. if (gpr_atm_no_barrier_load(&g_backup_poller) == (gpr_atm)p) {
  115. GRPC_CLOSURE_SCHED(exec_ctx, &p->run_poller, GRPC_ERROR_NONE);
  116. } else {
  117. grpc_pollset_shutdown(exec_ctx, BACKUP_POLLER_POLLSET(p),
  118. GRPC_CLOSURE_INIT(&p->run_poller, done_poller, p,
  119. grpc_schedule_on_exec_ctx));
  120. }
  121. }
  122. static void cover_self(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) {
  123. backup_poller *p;
  124. gpr_atm old_count =
  125. gpr_atm_no_barrier_fetch_add(&g_uncovered_notifications_pending, 1);
  126. if (old_count == 0) {
  127. p = (backup_poller *)gpr_malloc(sizeof(*p) + grpc_pollset_size());
  128. grpc_pollset_init(BACKUP_POLLER_POLLSET(p), &p->pollset_mu);
  129. GRPC_CLOSURE_INIT(&p->run_poller, run_poller, p, grpc_executor_scheduler);
  130. gpr_atm_no_barrier_store(&g_backup_poller, (gpr_atm)p);
  131. GRPC_CLOSURE_SCHED(exec_ctx, &p->run_poller, GRPC_ERROR_NONE);
  132. } else {
  133. p = (backup_poller *)gpr_atm_no_barrier_load(&g_backup_poller);
  134. GPR_ASSERT(p != NULL);
  135. }
  136. grpc_pollset_add_fd(exec_ctx, BACKUP_POLLER_POLLSET(p), tcp->em_fd);
  137. }
  138. static void notify_on_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) {
  139. GRPC_CLOSURE_INIT(&tcp->read_done_closure, tcp_handle_read, tcp,
  140. grpc_schedule_on_exec_ctx);
  141. grpc_fd_notify_on_read(exec_ctx, tcp->em_fd, &tcp->read_done_closure);
  142. }
  143. static void notify_on_write(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) {
  144. cover_self(exec_ctx, tcp);
  145. GRPC_CLOSURE_INIT(&tcp->write_done_closure,
  146. tcp_drop_uncovered_then_handle_write, tcp,
  147. grpc_schedule_on_exec_ctx);
  148. grpc_fd_notify_on_write(exec_ctx, tcp->em_fd, &tcp->write_done_closure);
  149. }
  150. static void drop_uncovered(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) {
  151. backup_poller *p = (backup_poller *)gpr_atm_no_barrier_load(&g_backup_poller);
  152. if (gpr_atm_no_barrier_fetch_add(&g_uncovered_notifications_pending, -1) ==
  153. 1) {
  154. gpr_mu_lock(p->pollset_mu);
  155. gpr_atm_no_barrier_cas(&g_backup_poller, (gpr_atm)p, 0);
  156. GRPC_LOG_IF_ERROR("backup_poller:pollset_kick",
  157. grpc_pollset_kick(BACKUP_POLLER_POLLSET(p), NULL));
  158. gpr_mu_unlock(p->pollset_mu);
  159. }
  160. }
  161. static void tcp_drop_uncovered_then_handle_write(grpc_exec_ctx *exec_ctx,
  162. void *arg, grpc_error *error) {
  163. drop_uncovered(exec_ctx, (grpc_tcp *)arg);
  164. tcp_handle_write(exec_ctx, arg, error);
  165. }
  166. static void add_to_estimate(grpc_tcp *tcp, size_t bytes) {
  167. tcp->bytes_read_this_round += (double)bytes;
  168. }
  169. static void finish_estimate(grpc_tcp *tcp) {
  170. /* If we read >80% of the target buffer in one read loop, increase the size
  171. of the target buffer to either the amount read, or twice its previous
  172. value */
  173. if (tcp->bytes_read_this_round > tcp->target_length * 0.8) {
  174. tcp->target_length =
  175. GPR_MAX(2 * tcp->target_length, tcp->bytes_read_this_round);
  176. } else {
  177. tcp->target_length =
  178. 0.99 * tcp->target_length + 0.01 * tcp->bytes_read_this_round;
  179. }
  180. tcp->bytes_read_this_round = 0;
  181. }
  182. static size_t get_target_read_size(grpc_tcp *tcp) {
  183. grpc_resource_quota *rq = grpc_resource_user_quota(tcp->resource_user);
  184. double pressure = grpc_resource_quota_get_memory_pressure(rq);
  185. double target =
  186. tcp->target_length * (pressure > 0.8 ? (1.0 - pressure) / 0.2 : 1.0);
  187. size_t sz = (((size_t)GPR_CLAMP(target, tcp->min_read_chunk_size,
  188. tcp->max_read_chunk_size)) +
  189. 255) &
  190. ~(size_t)255;
  191. /* don't use more than 1/16th of the overall resource quota for a single read
  192. * alloc */
  193. size_t rqmax = grpc_resource_quota_peek_size(rq);
  194. if (sz > rqmax / 16 && rqmax > 1024) {
  195. sz = rqmax / 16;
  196. }
  197. return sz;
  198. }
  199. static grpc_error *tcp_annotate_error(grpc_error *src_error, grpc_tcp *tcp) {
  200. return grpc_error_set_str(
  201. grpc_error_set_int(src_error, GRPC_ERROR_INT_FD, tcp->fd),
  202. GRPC_ERROR_STR_TARGET_ADDRESS,
  203. grpc_slice_from_copied_string(tcp->peer_string));
  204. }
  205. static void tcp_handle_read(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */,
  206. grpc_error *error);
  207. static void tcp_handle_write(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */,
  208. grpc_error *error);
  209. static void tcp_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep,
  210. grpc_error *why) {
  211. grpc_tcp *tcp = (grpc_tcp *)ep;
  212. grpc_fd_shutdown(exec_ctx, tcp->em_fd, why);
  213. grpc_resource_user_shutdown(exec_ctx, tcp->resource_user);
  214. }
  215. static void tcp_free(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) {
  216. grpc_fd_orphan(exec_ctx, tcp->em_fd, tcp->release_fd_cb, tcp->release_fd,
  217. "tcp_unref_orphan");
  218. grpc_slice_buffer_destroy_internal(exec_ctx, &tcp->last_read_buffer);
  219. grpc_resource_user_unref(exec_ctx, tcp->resource_user);
  220. gpr_free(tcp->peer_string);
  221. gpr_free(tcp);
  222. }
  223. #ifndef NDEBUG
  224. #define TCP_UNREF(cl, tcp, reason) \
  225. tcp_unref((cl), (tcp), (reason), __FILE__, __LINE__)
  226. #define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), __FILE__, __LINE__)
  227. static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp,
  228. const char *reason, const char *file, int line) {
  229. if (GRPC_TRACER_ON(grpc_tcp_trace)) {
  230. gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
  231. gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
  232. "TCP unref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val,
  233. val - 1);
  234. }
  235. if (gpr_unref(&tcp->refcount)) {
  236. tcp_free(exec_ctx, tcp);
  237. }
  238. }
  239. static void tcp_ref(grpc_tcp *tcp, const char *reason, const char *file,
  240. int line) {
  241. if (GRPC_TRACER_ON(grpc_tcp_trace)) {
  242. gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
  243. gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
  244. "TCP ref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val,
  245. val + 1);
  246. }
  247. gpr_ref(&tcp->refcount);
  248. }
  249. #else
  250. #define TCP_UNREF(cl, tcp, reason) tcp_unref((cl), (tcp))
  251. #define TCP_REF(tcp, reason) tcp_ref((tcp))
  252. static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) {
  253. if (gpr_unref(&tcp->refcount)) {
  254. tcp_free(exec_ctx, tcp);
  255. }
  256. }
  257. static void tcp_ref(grpc_tcp *tcp) { gpr_ref(&tcp->refcount); }
  258. #endif
  259. static void tcp_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) {
  260. grpc_network_status_unregister_endpoint(ep);
  261. grpc_tcp *tcp = (grpc_tcp *)ep;
  262. grpc_slice_buffer_reset_and_unref_internal(exec_ctx, &tcp->last_read_buffer);
  263. TCP_UNREF(exec_ctx, tcp, "destroy");
  264. }
  265. static void call_read_cb(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp,
  266. grpc_error *error) {
  267. grpc_closure *cb = tcp->read_cb;
  268. if (GRPC_TRACER_ON(grpc_tcp_trace)) {
  269. size_t i;
  270. const char *str = grpc_error_string(error);
  271. gpr_log(GPR_DEBUG, "read: error=%s", str);
  272. for (i = 0; i < tcp->incoming_buffer->count; i++) {
  273. char *dump = grpc_dump_slice(tcp->incoming_buffer->slices[i],
  274. GPR_DUMP_HEX | GPR_DUMP_ASCII);
  275. gpr_log(GPR_DEBUG, "READ %p (peer=%s): %s", tcp, tcp->peer_string, dump);
  276. gpr_free(dump);
  277. }
  278. }
  279. tcp->read_cb = NULL;
  280. tcp->incoming_buffer = NULL;
  281. GRPC_CLOSURE_RUN(exec_ctx, cb, error);
  282. }
  283. #define MAX_READ_IOVEC 4
  284. static void tcp_do_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) {
  285. struct msghdr msg;
  286. struct iovec iov[MAX_READ_IOVEC];
  287. ssize_t read_bytes;
  288. size_t i;
  289. GPR_ASSERT(!tcp->finished_edge);
  290. GPR_ASSERT(tcp->iov_size <= MAX_READ_IOVEC);
  291. GPR_ASSERT(tcp->incoming_buffer->count <= MAX_READ_IOVEC);
  292. GPR_TIMER_BEGIN("tcp_continue_read", 0);
  293. for (i = 0; i < tcp->incoming_buffer->count; i++) {
  294. iov[i].iov_base = GRPC_SLICE_START_PTR(tcp->incoming_buffer->slices[i]);
  295. iov[i].iov_len = GRPC_SLICE_LENGTH(tcp->incoming_buffer->slices[i]);
  296. }
  297. msg.msg_name = NULL;
  298. msg.msg_namelen = 0;
  299. msg.msg_iov = iov;
  300. msg.msg_iovlen = tcp->iov_size;
  301. msg.msg_control = NULL;
  302. msg.msg_controllen = 0;
  303. msg.msg_flags = 0;
  304. GPR_TIMER_BEGIN("recvmsg", 0);
  305. do {
  306. read_bytes = recvmsg(tcp->fd, &msg, 0);
  307. } while (read_bytes < 0 && errno == EINTR);
  308. GPR_TIMER_END("recvmsg", read_bytes >= 0);
  309. if (read_bytes < 0) {
  310. /* NB: After calling call_read_cb a parallel call of the read handler may
  311. * be running. */
  312. if (errno == EAGAIN) {
  313. finish_estimate(tcp);
  314. /* We've consumed the edge, request a new one */
  315. notify_on_read(exec_ctx, tcp);
  316. } else {
  317. grpc_slice_buffer_reset_and_unref_internal(exec_ctx,
  318. tcp->incoming_buffer);
  319. call_read_cb(exec_ctx, tcp,
  320. tcp_annotate_error(GRPC_OS_ERROR(errno, "recvmsg"), tcp));
  321. TCP_UNREF(exec_ctx, tcp, "read");
  322. }
  323. } else if (read_bytes == 0) {
  324. /* 0 read size ==> end of stream */
  325. grpc_slice_buffer_reset_and_unref_internal(exec_ctx, tcp->incoming_buffer);
  326. call_read_cb(
  327. exec_ctx, tcp,
  328. tcp_annotate_error(
  329. GRPC_ERROR_CREATE_FROM_STATIC_STRING("Socket closed"), tcp));
  330. TCP_UNREF(exec_ctx, tcp, "read");
  331. } else {
  332. add_to_estimate(tcp, (size_t)read_bytes);
  333. GPR_ASSERT((size_t)read_bytes <= tcp->incoming_buffer->length);
  334. if ((size_t)read_bytes < tcp->incoming_buffer->length) {
  335. grpc_slice_buffer_trim_end(
  336. tcp->incoming_buffer,
  337. tcp->incoming_buffer->length - (size_t)read_bytes,
  338. &tcp->last_read_buffer);
  339. }
  340. GPR_ASSERT((size_t)read_bytes == tcp->incoming_buffer->length);
  341. call_read_cb(exec_ctx, tcp, GRPC_ERROR_NONE);
  342. TCP_UNREF(exec_ctx, tcp, "read");
  343. }
  344. GPR_TIMER_END("tcp_continue_read", 0);
  345. }
  346. static void tcp_read_allocation_done(grpc_exec_ctx *exec_ctx, void *tcpp,
  347. grpc_error *error) {
  348. grpc_tcp *tcp = (grpc_tcp *)tcpp;
  349. if (error != GRPC_ERROR_NONE) {
  350. grpc_slice_buffer_reset_and_unref_internal(exec_ctx, tcp->incoming_buffer);
  351. grpc_slice_buffer_reset_and_unref_internal(exec_ctx,
  352. &tcp->last_read_buffer);
  353. call_read_cb(exec_ctx, tcp, GRPC_ERROR_REF(error));
  354. TCP_UNREF(exec_ctx, tcp, "read");
  355. } else {
  356. tcp_do_read(exec_ctx, tcp);
  357. }
  358. }
  359. static void tcp_continue_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) {
  360. size_t target_read_size = get_target_read_size(tcp);
  361. if (tcp->incoming_buffer->length < target_read_size &&
  362. tcp->incoming_buffer->count < MAX_READ_IOVEC) {
  363. grpc_resource_user_alloc_slices(exec_ctx, &tcp->slice_allocator,
  364. target_read_size, 1, tcp->incoming_buffer);
  365. } else {
  366. tcp_do_read(exec_ctx, tcp);
  367. }
  368. }
  369. static void tcp_handle_read(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */,
  370. grpc_error *error) {
  371. grpc_tcp *tcp = (grpc_tcp *)arg;
  372. GPR_ASSERT(!tcp->finished_edge);
  373. if (error != GRPC_ERROR_NONE) {
  374. grpc_slice_buffer_reset_and_unref_internal(exec_ctx, tcp->incoming_buffer);
  375. grpc_slice_buffer_reset_and_unref_internal(exec_ctx,
  376. &tcp->last_read_buffer);
  377. call_read_cb(exec_ctx, tcp, GRPC_ERROR_REF(error));
  378. TCP_UNREF(exec_ctx, tcp, "read");
  379. } else {
  380. tcp_continue_read(exec_ctx, tcp);
  381. }
  382. }
  383. static void tcp_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep,
  384. grpc_slice_buffer *incoming_buffer, grpc_closure *cb) {
  385. grpc_tcp *tcp = (grpc_tcp *)ep;
  386. GPR_ASSERT(tcp->read_cb == NULL);
  387. tcp->read_cb = cb;
  388. tcp->incoming_buffer = incoming_buffer;
  389. grpc_slice_buffer_reset_and_unref_internal(exec_ctx, incoming_buffer);
  390. grpc_slice_buffer_swap(incoming_buffer, &tcp->last_read_buffer);
  391. TCP_REF(tcp, "read");
  392. if (tcp->finished_edge) {
  393. tcp->finished_edge = false;
  394. notify_on_read(exec_ctx, tcp);
  395. } else {
  396. GRPC_CLOSURE_SCHED(exec_ctx, &tcp->read_done_closure, GRPC_ERROR_NONE);
  397. }
  398. }
  399. /* returns true if done, false if pending; if returning true, *error is set */
  400. #define MAX_WRITE_IOVEC 1000
  401. static bool tcp_flush(grpc_tcp *tcp, grpc_error **error) {
  402. struct msghdr msg;
  403. struct iovec iov[MAX_WRITE_IOVEC];
  404. msg_iovlen_type iov_size;
  405. ssize_t sent_length;
  406. size_t sending_length;
  407. size_t trailing;
  408. size_t unwind_slice_idx;
  409. size_t unwind_byte_idx;
  410. for (;;) {
  411. sending_length = 0;
  412. unwind_slice_idx = tcp->outgoing_slice_idx;
  413. unwind_byte_idx = tcp->outgoing_byte_idx;
  414. for (iov_size = 0; tcp->outgoing_slice_idx != tcp->outgoing_buffer->count &&
  415. iov_size != MAX_WRITE_IOVEC;
  416. iov_size++) {
  417. iov[iov_size].iov_base =
  418. GRPC_SLICE_START_PTR(
  419. tcp->outgoing_buffer->slices[tcp->outgoing_slice_idx]) +
  420. tcp->outgoing_byte_idx;
  421. iov[iov_size].iov_len =
  422. GRPC_SLICE_LENGTH(
  423. tcp->outgoing_buffer->slices[tcp->outgoing_slice_idx]) -
  424. tcp->outgoing_byte_idx;
  425. sending_length += iov[iov_size].iov_len;
  426. tcp->outgoing_slice_idx++;
  427. tcp->outgoing_byte_idx = 0;
  428. }
  429. GPR_ASSERT(iov_size > 0);
  430. msg.msg_name = NULL;
  431. msg.msg_namelen = 0;
  432. msg.msg_iov = iov;
  433. msg.msg_iovlen = iov_size;
  434. msg.msg_control = NULL;
  435. msg.msg_controllen = 0;
  436. msg.msg_flags = 0;
  437. GPR_TIMER_BEGIN("sendmsg", 1);
  438. do {
  439. /* TODO(klempner): Cork if this is a partial write */
  440. sent_length = sendmsg(tcp->fd, &msg, SENDMSG_FLAGS);
  441. } while (sent_length < 0 && errno == EINTR);
  442. GPR_TIMER_END("sendmsg", 0);
  443. if (sent_length < 0) {
  444. if (errno == EAGAIN) {
  445. tcp->outgoing_slice_idx = unwind_slice_idx;
  446. tcp->outgoing_byte_idx = unwind_byte_idx;
  447. return false;
  448. } else if (errno == EPIPE) {
  449. *error = grpc_error_set_int(GRPC_OS_ERROR(errno, "sendmsg"),
  450. GRPC_ERROR_INT_GRPC_STATUS,
  451. GRPC_STATUS_UNAVAILABLE);
  452. return true;
  453. } else {
  454. *error = tcp_annotate_error(GRPC_OS_ERROR(errno, "sendmsg"), tcp);
  455. return true;
  456. }
  457. }
  458. GPR_ASSERT(tcp->outgoing_byte_idx == 0);
  459. trailing = sending_length - (size_t)sent_length;
  460. while (trailing > 0) {
  461. size_t slice_length;
  462. tcp->outgoing_slice_idx--;
  463. slice_length = GRPC_SLICE_LENGTH(
  464. tcp->outgoing_buffer->slices[tcp->outgoing_slice_idx]);
  465. if (slice_length > trailing) {
  466. tcp->outgoing_byte_idx = slice_length - trailing;
  467. break;
  468. } else {
  469. trailing -= slice_length;
  470. }
  471. }
  472. if (tcp->outgoing_slice_idx == tcp->outgoing_buffer->count) {
  473. *error = GRPC_ERROR_NONE;
  474. return true;
  475. }
  476. };
  477. }
  478. static void tcp_handle_write(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */,
  479. grpc_error *error) {
  480. grpc_tcp *tcp = (grpc_tcp *)arg;
  481. grpc_closure *cb;
  482. if (error != GRPC_ERROR_NONE) {
  483. cb = tcp->write_cb;
  484. tcp->write_cb = NULL;
  485. cb->cb(exec_ctx, cb->cb_arg, error);
  486. TCP_UNREF(exec_ctx, tcp, "write");
  487. return;
  488. }
  489. if (!tcp_flush(tcp, &error)) {
  490. if (GRPC_TRACER_ON(grpc_tcp_trace)) {
  491. gpr_log(GPR_DEBUG, "write: delayed");
  492. }
  493. notify_on_write(exec_ctx, tcp);
  494. } else {
  495. cb = tcp->write_cb;
  496. tcp->write_cb = NULL;
  497. if (GRPC_TRACER_ON(grpc_tcp_trace)) {
  498. const char *str = grpc_error_string(error);
  499. gpr_log(GPR_DEBUG, "write: %s", str);
  500. }
  501. GRPC_CLOSURE_RUN(exec_ctx, cb, error);
  502. TCP_UNREF(exec_ctx, tcp, "write");
  503. }
  504. }
  505. static void tcp_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep,
  506. grpc_slice_buffer *buf, grpc_closure *cb) {
  507. grpc_tcp *tcp = (grpc_tcp *)ep;
  508. grpc_error *error = GRPC_ERROR_NONE;
  509. if (GRPC_TRACER_ON(grpc_tcp_trace)) {
  510. size_t i;
  511. for (i = 0; i < buf->count; i++) {
  512. char *data =
  513. grpc_dump_slice(buf->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII);
  514. gpr_log(GPR_DEBUG, "WRITE %p (peer=%s): %s", tcp, tcp->peer_string, data);
  515. gpr_free(data);
  516. }
  517. }
  518. GPR_TIMER_BEGIN("tcp_write", 0);
  519. GPR_ASSERT(tcp->write_cb == NULL);
  520. if (buf->length == 0) {
  521. GPR_TIMER_END("tcp_write", 0);
  522. GRPC_CLOSURE_SCHED(
  523. exec_ctx, cb,
  524. grpc_fd_is_shutdown(tcp->em_fd)
  525. ? tcp_annotate_error(GRPC_ERROR_CREATE_FROM_STATIC_STRING("EOF"),
  526. tcp)
  527. : GRPC_ERROR_NONE);
  528. return;
  529. }
  530. tcp->outgoing_buffer = buf;
  531. tcp->outgoing_slice_idx = 0;
  532. tcp->outgoing_byte_idx = 0;
  533. if (!tcp_flush(tcp, &error)) {
  534. TCP_REF(tcp, "write");
  535. tcp->write_cb = cb;
  536. if (GRPC_TRACER_ON(grpc_tcp_trace)) {
  537. gpr_log(GPR_DEBUG, "write: delayed");
  538. }
  539. notify_on_write(exec_ctx, tcp);
  540. } else {
  541. if (GRPC_TRACER_ON(grpc_tcp_trace)) {
  542. const char *str = grpc_error_string(error);
  543. gpr_log(GPR_DEBUG, "write: %s", str);
  544. }
  545. GRPC_CLOSURE_SCHED(exec_ctx, cb, error);
  546. }
  547. GPR_TIMER_END("tcp_write", 0);
  548. }
  549. static void tcp_add_to_pollset(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep,
  550. grpc_pollset *pollset) {
  551. grpc_tcp *tcp = (grpc_tcp *)ep;
  552. grpc_pollset_add_fd(exec_ctx, pollset, tcp->em_fd);
  553. }
  554. static void tcp_add_to_pollset_set(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep,
  555. grpc_pollset_set *pollset_set) {
  556. grpc_tcp *tcp = (grpc_tcp *)ep;
  557. grpc_pollset_set_add_fd(exec_ctx, pollset_set, tcp->em_fd);
  558. }
  559. static char *tcp_get_peer(grpc_endpoint *ep) {
  560. grpc_tcp *tcp = (grpc_tcp *)ep;
  561. return gpr_strdup(tcp->peer_string);
  562. }
  563. static int tcp_get_fd(grpc_endpoint *ep) {
  564. grpc_tcp *tcp = (grpc_tcp *)ep;
  565. return tcp->fd;
  566. }
  567. static grpc_resource_user *tcp_get_resource_user(grpc_endpoint *ep) {
  568. grpc_tcp *tcp = (grpc_tcp *)ep;
  569. return tcp->resource_user;
  570. }
  571. static const grpc_endpoint_vtable vtable = {
  572. tcp_read, tcp_write, tcp_add_to_pollset, tcp_add_to_pollset_set,
  573. tcp_shutdown, tcp_destroy, tcp_get_resource_user, tcp_get_peer,
  574. tcp_get_fd};
  575. #define MAX_CHUNK_SIZE 32 * 1024 * 1024
  576. grpc_endpoint *grpc_tcp_create(grpc_exec_ctx *exec_ctx, grpc_fd *em_fd,
  577. const grpc_channel_args *channel_args,
  578. const char *peer_string) {
  579. int tcp_read_chunk_size = GRPC_TCP_DEFAULT_READ_SLICE_SIZE;
  580. int tcp_max_read_chunk_size = 4 * 1024 * 1024;
  581. int tcp_min_read_chunk_size = 256;
  582. grpc_resource_quota *resource_quota = grpc_resource_quota_create(NULL);
  583. if (channel_args != NULL) {
  584. for (size_t i = 0; i < channel_args->num_args; i++) {
  585. if (0 ==
  586. strcmp(channel_args->args[i].key, GRPC_ARG_TCP_READ_CHUNK_SIZE)) {
  587. grpc_integer_options options = {(int)tcp_read_chunk_size, 1,
  588. MAX_CHUNK_SIZE};
  589. tcp_read_chunk_size =
  590. grpc_channel_arg_get_integer(&channel_args->args[i], options);
  591. } else if (0 == strcmp(channel_args->args[i].key,
  592. GRPC_ARG_TCP_MIN_READ_CHUNK_SIZE)) {
  593. grpc_integer_options options = {(int)tcp_read_chunk_size, 1,
  594. MAX_CHUNK_SIZE};
  595. tcp_min_read_chunk_size =
  596. grpc_channel_arg_get_integer(&channel_args->args[i], options);
  597. } else if (0 == strcmp(channel_args->args[i].key,
  598. GRPC_ARG_TCP_MAX_READ_CHUNK_SIZE)) {
  599. grpc_integer_options options = {(int)tcp_read_chunk_size, 1,
  600. MAX_CHUNK_SIZE};
  601. tcp_max_read_chunk_size =
  602. grpc_channel_arg_get_integer(&channel_args->args[i], options);
  603. } else if (0 ==
  604. strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) {
  605. grpc_resource_quota_unref_internal(exec_ctx, resource_quota);
  606. resource_quota = grpc_resource_quota_ref_internal(
  607. (grpc_resource_quota *)channel_args->args[i].value.pointer.p);
  608. }
  609. }
  610. }
  611. if (tcp_min_read_chunk_size > tcp_max_read_chunk_size) {
  612. tcp_min_read_chunk_size = tcp_max_read_chunk_size;
  613. }
  614. tcp_read_chunk_size = GPR_CLAMP(tcp_read_chunk_size, tcp_min_read_chunk_size,
  615. tcp_max_read_chunk_size);
  616. grpc_tcp *tcp = (grpc_tcp *)gpr_malloc(sizeof(grpc_tcp));
  617. tcp->base.vtable = &vtable;
  618. tcp->peer_string = gpr_strdup(peer_string);
  619. tcp->fd = grpc_fd_wrapped_fd(em_fd);
  620. tcp->read_cb = NULL;
  621. tcp->write_cb = NULL;
  622. tcp->release_fd_cb = NULL;
  623. tcp->release_fd = NULL;
  624. tcp->incoming_buffer = NULL;
  625. tcp->target_length = (double)tcp_read_chunk_size;
  626. tcp->min_read_chunk_size = tcp_min_read_chunk_size;
  627. tcp->max_read_chunk_size = tcp_max_read_chunk_size;
  628. tcp->bytes_read_this_round = 0;
  629. tcp->iov_size = 1;
  630. tcp->finished_edge = true;
  631. /* paired with unref in grpc_tcp_destroy */
  632. gpr_ref_init(&tcp->refcount, 1);
  633. gpr_atm_no_barrier_store(&tcp->shutdown_count, 0);
  634. tcp->em_fd = em_fd;
  635. grpc_slice_buffer_init(&tcp->last_read_buffer);
  636. tcp->resource_user = grpc_resource_user_create(resource_quota, peer_string);
  637. grpc_resource_user_slice_allocator_init(
  638. &tcp->slice_allocator, tcp->resource_user, tcp_read_allocation_done, tcp);
  639. /* Tell network status tracker about new endpoint */
  640. grpc_network_status_register_endpoint(&tcp->base);
  641. grpc_resource_quota_unref_internal(exec_ctx, resource_quota);
  642. return &tcp->base;
  643. }
  644. int grpc_tcp_fd(grpc_endpoint *ep) {
  645. grpc_tcp *tcp = (grpc_tcp *)ep;
  646. GPR_ASSERT(ep->vtable == &vtable);
  647. return grpc_fd_wrapped_fd(tcp->em_fd);
  648. }
  649. void grpc_tcp_destroy_and_release_fd(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep,
  650. int *fd, grpc_closure *done) {
  651. grpc_network_status_unregister_endpoint(ep);
  652. grpc_tcp *tcp = (grpc_tcp *)ep;
  653. GPR_ASSERT(ep->vtable == &vtable);
  654. tcp->release_fd = fd;
  655. tcp->release_fd_cb = done;
  656. grpc_slice_buffer_reset_and_unref_internal(exec_ctx, &tcp->last_read_buffer);
  657. TCP_UNREF(exec_ctx, tcp, "destroy");
  658. }
  659. #endif