QBONE packet reader: fix UDP GRO

This was very broken in many ways:
 - the GRO slicing loop had an off by one error so it would skip the last segment
 - the slicing loop did not handle a GRO train with last packet smaller than the segment size
 - the unit test didn't actually test GRO slicing because it never sent coalesced writes
 - GRO mode did not change the buffer sizes in `ReadPacketResults`, so GRO trains that exceeded an expected single packet size would be truncated

cr/465087216 modified `QuicUdpSocketApi::ReadMultiplePackets` to read single packets at a time when GRO was requested, but that should not be necessary as `recvmmsg` can read GRO trains, provided that packet buffers are large enough.  This CL removes that special case, so that GRO and non-GRO paths both use `recvmmsg`.

Add a streamz distribution, `/gfe/gfe2/qbone/packet_reader_gro_segments`, of the number of packets coalesced into each GRO read.

Protected by `--qbone_enable_udp_gro`.

PiperOrigin-RevId: 1013877900
diff --git a/quiche/quic/core/quic_udp_socket.cc b/quiche/quic/core/quic_udp_socket.cc
index 2217337..145c24a 100644
--- a/quiche/quic/core/quic_udp_socket.cc
+++ b/quiche/quic/core/quic_udp_socket.cc
@@ -9,12 +9,15 @@
 
 #include "quiche/quic/core/quic_udp_socket.h"
 
+#include <algorithm>
 #include <string>
 
 #include "absl/base/optimization.h"
 #include "quiche/quic/core/io/socket.h"
 #include "quiche/quic/platform/api/quic_bug_tracker.h"
 #include "quiche/quic/platform/api/quic_flag_utils.h"
+#include "quiche/quic/platform/api/quic_logging.h"
+#include "quiche/common/quiche_callbacks.h"
 
 // Common cmsg-related functions are defined below.
 // Windows and POSIX cmsg formats are actually fairly similar, except the
@@ -205,4 +208,48 @@
 #endif
 }
 
+size_t QuicUdpSocketApi::ForEachGroSegment(
+    const ReadPacketResult& result,
+    quiche::UnretainedCallback<void(const ReadPacketResult&)> packet_sink) {
+  if (!result.ok) {
+    return 0;
+  }
+  if (!result.packet_info.HasValue(QuicUdpPacketInfoBit::IS_GRO)) {
+    QUIC_DVLOG(3) << "Dispatching non-coalesced packet with size: "
+                  << result.packet_buffer.buffer_len;
+    packet_sink(result);
+    return 1;
+  }
+
+  const size_t gso_total_size = result.packet_buffer.buffer_len;
+  const size_t gso_size = result.packet_info.gso_size();
+  QUIC_DVLOG(2) << "Read GRO train with total size: " << gso_total_size
+                << " and gso size: " << gso_size;
+  if (gso_size == 0) {
+    QUIC_BUG(quic_udp_socket_zero_gso_size) << "Invalid gso size of zero.";
+    return 0;
+  }
+
+  // Slice the coalesced UDP GRO train into individual segments. All segments
+  // are `gso_size` bytes, except the trailing segment which may be smaller.
+  ReadPacketResult gro_slice = result;
+  size_t num_segments = 0;
+  size_t bytes_processed = 0;
+  while (bytes_processed < gso_total_size) {
+    gro_slice.packet_buffer.buffer =
+        result.packet_buffer.buffer + bytes_processed;
+    gro_slice.packet_buffer.buffer_len =
+        std::min(gso_size, gso_total_size - bytes_processed);
+    QUIC_DVLOG(3) << "Dispatching GRO segment #" << num_segments
+                  << " with size: " << gro_slice.packet_buffer.buffer_len;
+    packet_sink(gro_slice);
+    bytes_processed += gro_slice.packet_buffer.buffer_len;
+    ++num_segments;
+  }
+
+  QUIC_DVLOG(2) << "Dispatched " << num_segments
+                << " GRO segments with total size: " << bytes_processed;
+  return num_segments;
+}
+
 }  // namespace quic
diff --git a/quiche/quic/core/quic_udp_socket.h b/quiche/quic/core/quic_udp_socket.h
index 6c237c0..750d9ca 100644
--- a/quiche/quic/core/quic_udp_socket.h
+++ b/quiche/quic/core/quic_udp_socket.h
@@ -16,6 +16,7 @@
 #include "quiche/quic/core/quic_utils.h"
 #include "quiche/quic/platform/api/quic_ip_address.h"
 #include "quiche/quic/platform/api/quic_socket_address.h"
+#include "quiche/common/quiche_callbacks.h"
 
 #ifndef UDP_GRO
 #define UDP_GRO 104
@@ -37,9 +38,15 @@
   TTL,                   // Read & Write
   ECN,                   // Read
   GOOGLE_PACKET_HEADER,  // Read
-  IS_GRO,                // Read
-  V6_FLOW_LABEL,         // Read & Write
-  TOS,                   // Read
+  // Note: When IS_GRO is set, each ReadPacketResult returned from ReadPacket /
+  // ReadMultiplePackets may contain a train of GRO coalesced packets. Consumers
+  // must check and possibly segment these trains into individual packets.
+  // ReadPacketResults must be large enough to accommodate a full GRO train, or
+  // risk data loss due to MSG_TRUNC.
+  // See ForEachGroSegment.
+  IS_GRO,         // Read
+  V6_FLOW_LABEL,  // Read & Write
+  TOS,            // Read
 
   // Must be the last value.
   NUM_BITS
@@ -88,7 +95,7 @@
     bitmask_.Set(QuicUdpPacketInfoBit::IS_GRO);
   }
 
-  size_t gso_size() { return gso_size_; }
+  size_t gso_size() const { return gso_size_; }
 
   const QuicIpAddress& self_v4_ip() const {
     QUICHE_DCHECK(HasValue(QuicUdpPacketInfoBit::V4_SELF_IP));
@@ -285,6 +292,21 @@
                              QuicUdpPacketInfoBitMask packet_info_interested,
                              ReadPacketResults* results);
 
+  // Slices a single datagram read result (which may be a coalesced UDP GRO
+  // train when `QuicUdpPacketInfoBit::IS_GRO` is set) into individual packet
+  // segments and invokes `packet_sink` on each segment in order.
+  //
+  // If `IS_GRO` is not set on `result.packet_info`, invokes `packet_sink` once
+  // on `result` directly. Returns the number of segments dispatched (0 if
+  // `!result.ok` or if `gso_size` is invalid).
+  //
+  // !!NOTE!! Dispatching GRO trains may result in unaligned packet buffers
+  // e.g., if gso_size is an odd value. `packet_sink` and any downstream code
+  // must be prepared for the ReadPacketResult buffer to be unaligned.
+  size_t ForEachGroSegment(
+      const ReadPacketResult& result,
+      quiche::UnretainedCallback<void(const ReadPacketResult&)> packet_sink);
+
   // Write a packet to |fd|.
   // packet_buffer, packet_buffer_len:  The packet buffer to write.
   // packet_info:                       The per packet information to set.
diff --git a/quiche/quic/core/quic_udp_socket_posix.inc b/quiche/quic/core/quic_udp_socket_posix.inc
index ae771f1..0635c3f 100644
--- a/quiche/quic/core/quic_udp_socket_posix.inc
+++ b/quiche/quic/core/quic_udp_socket_posix.inc
@@ -373,102 +373,88 @@
     QuicUdpSocketFd fd, QuicUdpPacketInfoBitMask packet_info_interested,
     ReadPacketResults* results) {
 #if defined(__linux__) && !defined(__ANDROID__)
-  if (packet_info_interested.IsSet(QuicUdpPacketInfoBit::IS_GRO)) {
-    size_t num_packets = 0;
-    for (ReadPacketResult& result : *results) {
-      result.ok = false;
-    }
-    for (ReadPacketResult& result : *results) {
-      ReadPacket(fd, packet_info_interested, &result);
-      if (!result.ok) {
-        break;
-      }
-      ++num_packets;
-    }
-    return num_packets;
-  } else {
-    // Use recvmmsg.
-    size_t hdrs_size = sizeof(mmsghdr) * results->size();
-    mmsghdr* hdrs = static_cast<mmsghdr*>(alloca(hdrs_size));
-    memset(hdrs, 0, hdrs_size);
+  // Use recvmmsg.
+  size_t hdrs_size = sizeof(mmsghdr) * results->size();
+  mmsghdr* hdrs = static_cast<mmsghdr*>(alloca(hdrs_size));
+  memset(hdrs, 0, hdrs_size);
 
-    struct TempPerPacketData {
-      iovec iov;
-      sockaddr_storage raw_peer_address;
-    };
-    TempPerPacketData* packet_data_array = static_cast<TempPerPacketData*>(
-        alloca(sizeof(TempPerPacketData) * results->size()));
+  struct TempPerPacketData {
+    iovec iov;
+    sockaddr_storage raw_peer_address;
+  };
+  TempPerPacketData* packet_data_array = static_cast<TempPerPacketData*>(
+      alloca(sizeof(TempPerPacketData) * results->size()));
 
-    for (size_t i = 0; i < results->size(); ++i) {
-      (*results)[i].ok = false;
+  for (size_t i = 0; i < results->size(); ++i) {
+    (*results)[i].ok = false;
 
-      msghdr* hdr = &hdrs[i].msg_hdr;
-      TempPerPacketData* packet_data = &packet_data_array[i];
-      packet_data->iov.iov_base = (*results)[i].packet_buffer.buffer;
-      packet_data->iov.iov_len = (*results)[i].packet_buffer.buffer_len;
+    msghdr* hdr = &hdrs[i].msg_hdr;
+    TempPerPacketData* packet_data = &packet_data_array[i];
+    packet_data->iov.iov_base = (*results)[i].packet_buffer.buffer;
+    packet_data->iov.iov_len = (*results)[i].packet_buffer.buffer_len;
 
-      hdr->msg_name = &packet_data->raw_peer_address;
-      hdr->msg_namelen = sizeof(sockaddr_storage);
-      hdr->msg_iov = &packet_data->iov;
-      hdr->msg_iovlen = 1;
-      hdr->msg_flags = 0;
-      hdr->msg_control = (*results)[i].control_buffer.buffer;
-      hdr->msg_controllen = (*results)[i].control_buffer.buffer_len;
+    hdr->msg_name = &packet_data->raw_peer_address;
+    hdr->msg_namelen = sizeof(sockaddr_storage);
+    hdr->msg_iov = &packet_data->iov;
+    hdr->msg_iovlen = 1;
+    hdr->msg_flags = 0;
+    hdr->msg_control = (*results)[i].control_buffer.buffer;
+    hdr->msg_controllen = (*results)[i].control_buffer.buffer_len;
 
-      QUICHE_DCHECK_GE(hdr->msg_controllen, kMinCmsgSpaceForRead);
-    }
-    // If MSG_TRUNC is set on Linux, recvmmsg will return the real packet size
-    // in |hdrs[i].msg_len| even if packet buffer is too small to receive it.
-    int packets_read = recvmmsg(fd, hdrs, results->size(), MSG_TRUNC, nullptr);
-    if (packets_read <= 0) {
-      const int error_num = errno;
-      if (error_num != EAGAIN) {
-        QUIC_LOG_FIRST_N(ERROR, 100)
-            << "Error reading packets: " << strerror(error_num);
-      }
-      return 0;
-    }
-
-    for (int i = 0; i < packets_read; ++i) {
-      if (hdrs[i].msg_len == 0) {
-        continue;
-      }
-
-      msghdr& hdr = hdrs[i].msg_hdr;
-      if (ABSL_PREDICT_FALSE(hdr.msg_flags & MSG_CTRUNC)) {
-        QUIC_BUG(quic_bug_10751_4) << "Control buffer too small. size:"
-                                   << (*results)[i].control_buffer.buffer_len
-                                   << ", need:" << hdr.msg_controllen;
-        continue;
-      }
-
-      if (ABSL_PREDICT_FALSE(hdr.msg_flags & MSG_TRUNC)) {
-        QUIC_LOG_FIRST_N(WARNING, 100)
-            << "Received truncated QUIC packet: buffer size:"
-            << (*results)[i].packet_buffer.buffer_len
-            << " packet size:" << hdrs[i].msg_len;
-        continue;
-      }
-
-      (*results)[i].ok = true;
-      (*results)[i].packet_buffer.buffer_len = hdrs[i].msg_len;
-
-      QuicUdpPacketInfo* packet_info = &(*results)[i].packet_info;
-      if (packet_info_interested.IsSet(QuicUdpPacketInfoBit::PEER_ADDRESS)) {
-        packet_info->SetPeerAddress(
-            QuicSocketAddress(packet_data_array[i].raw_peer_address));
-      }
-
-      if (hdr.msg_controllen > 0) {
-        for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr); cmsg != nullptr;
-             cmsg = CMSG_NXTHDR(&hdr, cmsg)) {
-          PopulatePacketInfoFromControlMessage(cmsg, packet_info,
-                                               packet_info_interested);
-        }
-      }
-    }
-    return packets_read;
+    QUICHE_DCHECK_GE(hdr->msg_controllen, kMinCmsgSpaceForRead);
   }
+  // If MSG_TRUNC is set on Linux, recvmmsg will return the real packet size
+  // in |hdrs[i].msg_len| even if packet buffer is too small to receive it.
+  int packets_read = recvmmsg(fd, hdrs, results->size(), MSG_TRUNC, nullptr);
+  if (packets_read <= 0) {
+    const int error_num = errno;
+    if (error_num != EAGAIN) {
+      QUIC_LOG_FIRST_N(ERROR, 100)
+          << "Error reading packets: " << strerror(error_num);
+    }
+    return 0;
+  }
+
+  for (int i = 0; i < packets_read; ++i) {
+    if (hdrs[i].msg_len == 0) {
+      continue;
+    }
+
+    msghdr& hdr = hdrs[i].msg_hdr;
+    if (ABSL_PREDICT_FALSE(hdr.msg_flags & MSG_CTRUNC)) {
+      QUIC_BUG(quic_bug_10751_4) << "Control buffer too small. size:"
+                                 << (*results)[i].control_buffer.buffer_len
+                                 << ", need:" << hdr.msg_controllen;
+      continue;
+    }
+
+    if (ABSL_PREDICT_FALSE(hdr.msg_flags & MSG_TRUNC)) {
+      QUIC_LOG_FIRST_N(WARNING, 100)
+          << "Received truncated QUIC packet: buffer size:"
+          << (*results)[i].packet_buffer.buffer_len
+          << " packet size:" << hdrs[i].msg_len;
+      continue;
+    }
+
+    (*results)[i].ok = true;
+    (*results)[i].packet_buffer.buffer_len = hdrs[i].msg_len;
+
+    QuicUdpPacketInfo* packet_info = &(*results)[i].packet_info;
+    if (packet_info_interested.IsSet(QuicUdpPacketInfoBit::PEER_ADDRESS)) {
+      packet_info->SetPeerAddress(
+          QuicSocketAddress(packet_data_array[i].raw_peer_address));
+    }
+
+    if (hdr.msg_controllen > 0) {
+      for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr); cmsg != nullptr;
+           cmsg = CMSG_NXTHDR(&hdr, cmsg)) {
+        PopulatePacketInfoFromControlMessage(cmsg, packet_info,
+                                             packet_info_interested);
+      }
+    }
+  }
+
+  return packets_read;
 #else
   size_t num_packets = 0;
   for (ReadPacketResult& result : *results) {
diff --git a/quiche/quic/core/quic_udp_socket_test.cc b/quiche/quic/core/quic_udp_socket_test.cc
index c2b6d4d..592c248 100644
--- a/quiche/quic/core/quic_udp_socket_test.cc
+++ b/quiche/quic/core/quic_udp_socket_test.cc
@@ -7,10 +7,14 @@
 #include <netinet/in.h>
 #include <stdint.h>
 
+#include <string>
+#include <vector>
+
 #include "absl/base/optimization.h"
 #include "absl/strings/string_view.h"
 #include "quiche/quic/core/io/socket.h"
 #include "quiche/quic/core/quic_types.h"
+#include "quiche/quic/platform/api/quic_expect_bug.h"
 #include "quiche/quic/platform/api/quic_socket_address.h"
 #include "quiche/quic/platform/api/quic_test.h"
 #include "quiche/common/quiche_ip_address.h"
@@ -156,6 +160,101 @@
 #endif
 }
 
+TEST_F(QuicUdpSocketTest, ForEachGroSegmentNonGroPacket) {
+  QuicUdpSocketApi socket_api;
+  std::string payload = "hello";
+  QuicUdpSocketApi::ReadPacketResult result;
+  result.ok = true;
+  result.packet_buffer = {payload.data(), payload.size()};
+
+  std::vector<std::string> segments;
+  size_t count = socket_api.ForEachGroSegment(
+      result, [&](const QuicUdpSocketApi::ReadPacketResult& slice) {
+        EXPECT_FALSE(slice.packet_info.HasValue(QuicUdpPacketInfoBit::IS_GRO));
+        segments.emplace_back(slice.packet_buffer.buffer,
+                              slice.packet_buffer.buffer_len);
+      });
+  EXPECT_EQ(count, 1u);
+  EXPECT_THAT(segments, ::testing::ElementsAre("hello"));
+}
+
+TEST_F(QuicUdpSocketTest, ForEachGroSegmentSlicesExactMultipleTrain) {
+  QuicUdpSocketApi socket_api;
+  std::string payload = "aaaaabbbbbccccc";
+  QuicUdpSocketApi::ReadPacketResult result;
+  result.ok = true;
+  result.packet_buffer = {payload.data(), payload.size()};
+  result.packet_info.set_gso_size(5);
+
+  std::vector<std::string> segments;
+  size_t count = socket_api.ForEachGroSegment(
+      result, [&](const QuicUdpSocketApi::ReadPacketResult& slice) {
+        EXPECT_TRUE(slice.packet_info.HasValue(QuicUdpPacketInfoBit::IS_GRO));
+        EXPECT_EQ(slice.packet_info.gso_size(), 5u);
+        segments.emplace_back(slice.packet_buffer.buffer,
+                              slice.packet_buffer.buffer_len);
+      });
+  EXPECT_EQ(count, 3u);
+  EXPECT_THAT(segments, ::testing::ElementsAre("aaaaa", "bbbbb", "ccccc"));
+}
+
+TEST_F(QuicUdpSocketTest, ForEachGroSegmentSlicesTrainWithTrailingSmallPacket) {
+  QuicUdpSocketApi socket_api;
+  std::string payload = "aaaaabbbbbcccccdd";
+  QuicUdpSocketApi::ReadPacketResult result;
+  result.ok = true;
+  result.packet_buffer = {payload.data(), payload.size()};
+  result.packet_info.set_gso_size(5);
+
+  std::vector<std::string> segments;
+  size_t count = socket_api.ForEachGroSegment(
+      result, [&](const QuicUdpSocketApi::ReadPacketResult& slice) {
+        EXPECT_TRUE(slice.packet_info.HasValue(QuicUdpPacketInfoBit::IS_GRO));
+        EXPECT_EQ(slice.packet_info.gso_size(), 5u);
+        segments.emplace_back(slice.packet_buffer.buffer,
+                              slice.packet_buffer.buffer_len);
+      });
+  EXPECT_EQ(count, 4u);
+  EXPECT_THAT(segments,
+              ::testing::ElementsAre("aaaaa", "bbbbb", "ccccc", "dd"));
+}
+
+TEST_F(QuicUdpSocketTest, ForEachGroSegmentZeroGsoSize) {
+  QuicUdpSocketApi socket_api;
+  std::string payload = "aaaaabbbbb";
+  QuicUdpSocketApi::ReadPacketResult result;
+  result.ok = true;
+  result.packet_buffer = {payload.data(), payload.size()};
+  result.packet_info.set_gso_size(0);
+
+  bool called = false;
+  size_t count = 0;
+  EXPECT_QUIC_BUG(count = socket_api.ForEachGroSegment(
+                      result,
+                      [&](const QuicUdpSocketApi::ReadPacketResult& /*slice*/) {
+                        called = true;
+                      }),
+                  "Invalid gso size of zero.");
+  EXPECT_EQ(count, 0u);
+  EXPECT_FALSE(called);
+}
+
+TEST_F(QuicUdpSocketTest, ForEachGroSegmentSkipsFailedResult) {
+  QuicUdpSocketApi socket_api;
+  std::string payload = "hello";
+  QuicUdpSocketApi::ReadPacketResult result;
+  result.ok = false;
+  result.packet_buffer = {payload.data(), payload.size()};
+
+  bool called = false;
+  size_t count = socket_api.ForEachGroSegment(
+      result, [&](const QuicUdpSocketApi::ReadPacketResult& /*slice*/) {
+        called = true;
+      });
+  EXPECT_EQ(count, 0u);
+  EXPECT_FALSE(called);
+}
+
 }  // namespace
 }  // namespace test
 }  // namespace quic