AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/09/15 00:56 flow patch-triage
2m Args:
null

Results:
{
  "EnableConfigs": [
    "HOMA",
    "IPV6"
  ],
  "FocusSymbols": [
    "homa_sendmsg",
    "homa_recvmsg",
    "homa_setsockopt",
    "homa_getsockopt",
    "homa_ioctl",
    "homa_ioc_info",
    "homa_bind",
    "homa_socket",
    "homa_softirq",
    "homa_dispatch_pkts",
    "homa_pool_set_region",
    "homa_rpc_reap",
    "homa_rpc_alloc_client",
    "homa_rpc_alloc_server",
    "homa_tx_copy_from_user"
  ],
  "KMSANReasoning": "The patch introduces the Homa transport protocol implementation, which includes a kernel-to-user memory information leak in `homa_recvmsg()`:\n\n1. In `homa_recvmsg()` (`net/homa/homa_plumbing.c`), when `msg-\u003emsg_name` is provided (which points to an uninitialized `struct sockaddr_storage addr` on the kernel stack in `____sys_recvmsg()` in `net/socket.c`):\n   - For `AF_INET` sockets, only `sin_family`, `sin_port`, and `sin_addr.s_addr` are populated in `struct sockaddr_in *in4`. The trailing 8-byte `sin_zero` padding array is left uninitialized, and `msg-\u003emsg_namelen` is set to `sizeof(*in4)` (16 bytes).\n   - For `AF_INET6` sockets, only `sin6_family`, `sin6_port`, and `sin6_addr` are set in `struct sockaddr_in6 *in6`. The `sin6_flowinfo` (4 bytes) and `sin6_scope_id` (4 bytes) fields are left uninitialized, and `msg-\u003emsg_namelen` is set to `sizeof(*in6)` (28 bytes).\n2. Upon return from `homa_recvmsg()`, `____sys_recvmsg()` invokes `move_addr_to_user(\u0026addr, msg_sys-\u003emsg_namelen, uaddr, uaddr_len)`, which copies the uninitialized kernel stack bytes from `addr` directly to userspace memory.\n\nKASAN, LOCKDEP, and UB sanitizers cannot detect this vulnerability because `addr` resides within the valid bounds of the caller's kernel stack frame and no out-of-bounds or use-after-free memory access occurs. KMSAN specifically tracks shadow initialization bits and detects kernel-to-user information leaks of uninitialized memory. Therefore, a dedicated KMSAN fuzzing session is justified.",
  "NeedsKMSAN": true,
  "Reasoning": "The patch series introduces the implementation of the Homa transport protocol (IPPROTO_HOMA) in the Linux kernel networking stack. It adds support for AF_INET and AF_INET6 Homa sockets, including sendmsg/recvmsg message passing, user buffer pools, setsockopt/getsockopt, HOMAIOCINFO ioctl, softirq packet dispatching, RPC state management, and custom memory pools. This new protocol is directly reachable from user space in standard virtualized environments and contains complex concurrency, locking, and packet processing logic that warrants thorough fuzzing.",
  "WorthFuzzing": true
}

1/1 2026/09/15 00:56 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 5dfb61235ce9a7847572ab2527dd1855871d9ab9\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Tue Sep 15 00:56:16 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst\nindex 2fc53093752d1..c6cb82ff627e2 100644\n--- a/Documentation/userspace-api/ioctl/ioctl-number.rst\n+++ b/Documentation/userspace-api/ioctl/ioctl-number.rst\n@@ -255,6 +255,7 @@ Code  Seq#    Include File                                             Comments\n                                                                        \u003cmailto:zapman@interlan.net\u003e\n 'h'   00-1F  linux/hpet.h                                              conflict!\n 'h'   80-8F  fs/hfsplus/ioctl.c\n+'h'   90-9F  uapi/linux/homa.h\n 'i'   00-3F  linux/i2o-dev.h                                           conflict!\n 'i'   0B-1F  linux/ipmi.h                                              conflict!\n 'i'   80-8F  linux/i8k.h\ndiff --git a/MAINTAINERS b/MAINTAINERS\nindex 0e04d92d1b098..56e7651d01716 100644\n--- a/MAINTAINERS\n+++ b/MAINTAINERS\n@@ -11938,6 +11938,13 @@ F:\tlib/test_hmm*\n F:\tmm/hmm*\n F:\ttools/testing/selftests/mm/*hmm*\n \n+HOMA TRANSPORT PROTOCOL\n+M:\tJohn Ousterhout \u003couster@cs.stanford.edu\u003e\n+S:\tMaintained\n+W:\thttps://homa-transport.atlassian.net/wiki/spaces/HOMA\n+F:\tinclude/uapi/linux/homa.h\n+F:\tnet/homa/\n+\n HONEYWELL ABP2030PA PRESSURE SENSOR SERIES IIO DRIVER\n M:\tPetre Rodan \u003cpetre.rodan@subdimension.ro\u003e\n L:\tlinux-iio@vger.kernel.org\ndiff --git a/include/uapi/linux/homa.h b/include/uapi/linux/homa.h\nnew file mode 100644\nindex 0000000000000..deeca70f944a1\n--- /dev/null\n+++ b/include/uapi/linux/homa.h\n@@ -0,0 +1,290 @@\n+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ WITH Linux-syscall-note */\n+\n+/* This file defines the kernel call interface for the Homa\n+ * transport protocol.\n+ */\n+\n+#ifndef _UAPI_LINUX_HOMA_H\n+#define _UAPI_LINUX_HOMA_H\n+\n+#include \u003clinux/in.h\u003e\n+#include \u003clinux/in6.h\u003e\n+#include \u003clinux/socket.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+/* IANA-assigned Internet Protocol number for Homa. */\n+#define IPPROTO_HOMA 146\n+\n+/**\n+ * define HOMA_MAX_MESSAGE_LENGTH - Maximum bytes of payload in a Homa\n+ * request or response message.\n+ */\n+#define HOMA_MAX_MESSAGE_LENGTH 1000000\n+\n+/**\n+ * define HOMA_BPAGE_SIZE - Number of bytes in pages used for receive\n+ * buffers. Must be power of two.\n+ */\n+#define HOMA_BPAGE_SIZE (1 \u003c\u003c HOMA_BPAGE_SHIFT)\n+#define HOMA_BPAGE_SHIFT 16\n+\n+/**\n+ * define HOMA_MAX_BPAGES - The largest number of bpages that will be required\n+ * to store an incoming message.\n+ */\n+#define HOMA_MAX_BPAGES ((HOMA_MAX_MESSAGE_LENGTH + HOMA_BPAGE_SIZE - 1) \u003e\u003e \\\n+\t\tHOMA_BPAGE_SHIFT)\n+\n+/**\n+ * define HOMA_MIN_DEFAULT_PORT - The 16 bit port space is divided into\n+ * two nonoverlapping regions. Ports 1-32767 are reserved exclusively\n+ * for well-defined server ports. The remaining ports are used for client\n+ * ports; these are allocated automatically by Homa. Port 0 is reserved.\n+ */\n+#define HOMA_MIN_DEFAULT_PORT 0x8000\n+\n+/**\n+ * struct homa_sendmsg_args - Provides information needed by Homa's\n+ * sendmsg; passed to sendmsg using the msg_control field.\n+ */\n+struct homa_sendmsg_args {\n+\t/**\n+\t * @id: (in/out) An initial value of 0 means a new request is\n+\t * being sent; nonzero means the message is a reply to the given\n+\t * id. If the message is a request, then the value is modified to\n+\t * hold the id of the new RPC.\n+\t */\n+\t__u64 id;\n+\n+\t/**\n+\t * @completion_cookie: (in) Used only for request messages; will be\n+\t * returned by recvmsg when the RPC completes. Typically used to\n+\t * locate app-specific info about the RPC.\n+\t */\n+\t__u64 completion_cookie;\n+\n+\t/**\n+\t * @flags: (in) OR-ed combination of bits that control the operation.\n+\t * See below for values.\n+\t */\n+\t__u32 flags;\n+\n+\t/** @reserved: Not currently used, must be 0. */\n+\t__u32 reserved;\n+};\n+\n+/* Flag bits for homa_sendmsg_args.flags (see man page for documentation):\n+ */\n+#define HOMA_SENDMSG_PRIVATE       0x01\n+#define HOMA_SENDMSG_VALID_FLAGS   0x01\n+\n+/**\n+ * struct homa_recvmsg_args - Provides information needed by Homa's\n+ * recvmsg; passed to recvmsg using the msg_control field.\n+ */\n+struct homa_recvmsg_args {\n+\t/**\n+\t * @id: (in/out) Initial value is 0 to wait for any shared RPC;\n+\t * nonzero means wait for that specific (private) RPC. Returns\n+\t * the id of the RPC received.\n+\t */\n+\t__u64 id;\n+\n+\t/**\n+\t * @completion_cookie: (out) If the incoming message is a response,\n+\t * this will return the completion cookie specified when the\n+\t * request was sent. For requests this will always be zero.\n+\t */\n+\t__u64 completion_cookie;\n+\n+\t/**\n+\t * @num_bpages: (in/out) Number of valid entries in @bpage_offsets.\n+\t * Passes in bpages from previous messages that can now be\n+\t * recycled; returns bpages from the new message.\n+\t */\n+\t__u32 num_bpages;\n+\n+\t/** @reserved: Not currently used, must be 0. */\n+\t__u32 reserved;\n+\n+\t/**\n+\t * @bpage_offsets: (in/out) Each entry is an offset into the buffer\n+\t * region for the socket pool. When returned from recvmsg, the\n+\t * offsets indicate where fragments of the new message are stored. All\n+\t * entries but the last refer to full buffer pages (HOMA_BPAGE_SIZE\n+\t * bytes) and are bpage-aligned. The last entry may refer to a bpage\n+\t * fragment and is not necessarily aligned. The application now owns\n+\t * these bpages and must eventually return them to Homa, using\n+\t * bpage_offsets in a future recvmsg invocation.\n+\t */\n+\t__u32 bpage_offsets[HOMA_MAX_BPAGES];\n+};\n+\n+/** define SO_HOMA_RCVBUF: setsockopt option for specifying buffer region. */\n+#define SO_HOMA_RCVBUF 10\n+\n+/**\n+ * define SO_HOMA_SERVER: setsockopt option for specifying whether a\n+ * socket will act as server.\n+ */\n+#define SO_HOMA_SERVER 11\n+\n+/** struct homa_rcvbuf_args - setsockopt argument for SO_HOMA_RCVBUF. */\n+struct homa_rcvbuf_args {\n+\t/** @start: Address of first byte of buffer region in user space. */\n+\t__u64 start;\n+\n+\t/** @length: Total number of bytes available at @start. */\n+\t__u64 length;\n+};\n+\n+/**\n+ * struct homa_rpc_info - Used by HOMAIOCINFO to return information about\n+ * a specific RPC.\n+ */\n+struct homa_rpc_info {\n+\t/**\n+\t * @id: Identifier for the RPC, unique among all RPCs sent by the\n+\t * client node. If the low-order bit is 1, this node is the server\n+\t * for the RPC; 0 means we are the client.\n+\t */\n+\t__u64 id;\n+\n+\t/** @peer: Address of the peer socket for this RPC. */\n+\tunion {\n+\t\tstruct __kernel_sockaddr_storage storage;\n+\t\tstruct sockaddr_in in4;\n+\t\tstruct sockaddr_in6 in6;\n+\t} peer;\n+\n+\t/**\n+\t * @completion_cookie: For client-side RPCs this gives the completion\n+\t * cookie specified when the RPC was initiated. For server-side RPCs\n+\t * this is zero.\n+\t */\n+\t__u64 completion_cookie;\n+\n+\t/**\n+\t * @tx_length: Length of the outgoing message in bytes, or -1 if\n+\t * the sendmsg hasn't yet been called.\n+\t */\n+\t__s32 tx_length;\n+\n+\t/**\n+\t * @tx_sent: Number of bytes of the outgoing message that have been\n+\t * transmitted at least once.\n+\t */\n+\t__u32 tx_sent;\n+\n+\t/**\n+\t * @tx_granted: Number of bytes of the outgoing message that the\n+\t * receiver has authorized us to transmit (includes unscheduled\n+\t * bytes).\n+\t */\n+\t__u32 tx_granted;\n+\n+\t/** @reserved: Reserved for future use. */\n+\t__u32 reserved;\n+\n+\t/**\n+\t * @rx_length: Length of the incoming message, in bytes. -1 means\n+\t * the length is not yet known (this is a client-side RPC and\n+\t * no packets have been received).\n+\t */\n+\t__s32 rx_length;\n+\n+\t/**\n+\t * @rx_remaining: Number of bytes in the incoming message that have\n+\t * not yet been received.\n+\t */\n+\t__u32 rx_remaining;\n+\n+\t/**\n+\t * @rx_gaps: The number of gaps in the incoming message. A gap is\n+\t * a range of bytes that have not been received yet, but bytes after\n+\t * the gap have been received.\n+\t */\n+\t__u32 rx_gaps;\n+\n+\t/**\n+\t * @rx_gap_bytes: The total number of bytes in gaps in the incoming\n+\t * message.\n+\t */\n+\t__u32 rx_gap_bytes;\n+\n+\t/**\n+\t * @rx_granted: The number of bytes in the message that the sender\n+\t * is authorized to transmit (includes unscheduled bytes).\n+\t */\n+\t__u32 rx_granted;\n+\n+\t/**\n+\t * @flags: Various single-bit values associated with the RPC:\n+\t * HOMA_RPC_BUF_STALL:  The incoming message is currently stalled\n+\t *                      because there is insufficient receiver buffer\n+\t *                      space.\n+\t * HOMA_RPC_PRIVATE:    The RPC has been created as \"private\"; set\n+\t *                      only on the client side.\n+\t * HOMA_RPC_RX_READY:   The incoming message is complete and has\n+\t *                      been queued waiting for a thread to call\n+\t *                      recvmsg.\n+\t * HOMA_RPC_RX_COPY:    There are packets that have been received,\n+\t *                      whose data has not yet been copied from\n+\t *                      packet buffers to user space.\n+\t */\n+\t__u16 flags;\n+#define HOMA_RPC_BUF_STALL    1\n+#define HOMA_RPC_PRIVATE      2\n+#define HOMA_RPC_RX_READY     4\n+#define HOMA_RPC_RX_COPY      8\n+};\n+\n+/**\n+ * struct homa_info - In/out argument passed to HOMAIOCINFO. Fields labeled\n+ * as \"in\" must be set by the application; other fields are returned to the\n+ * application from the kernel.\n+ */\n+struct homa_info {\n+\t/**\n+\t * @rpc_info: (in) Address of memory region in which to store\n+\t * information about individual RPCs. Actual type is\n+\t * \"struct homa_rpc_info *\".\n+\t */\n+\t__u64 rpc_info;\n+\n+\t/**\n+\t * @rpc_info_length: (in) Number of bytes of storage available at\n+\t * rpc_info.\n+\t */\n+\t__u64 rpc_info_length;\n+\n+\t/**\n+\t * @bpool_avail_bytes: Number of bytes in the buffer pool for incoming\n+\t * messages that is currently available for new messages.\n+\t */\n+\t__u64 bpool_avail_bytes;\n+\n+\t/** @port: Port number handled by this socket. */\n+\t__u32 port;\n+\n+\t/**\n+\t * @num_rpcs: Total number of active RPCs (both server and client) for\n+\t * this socket. The number stored at @rpc_info will be less than this\n+\t * if @rpc_info_length is too small.\n+\t */\n+\t__u32 num_rpcs;\n+\n+\t/**\n+\t * @error_msg: Provides additional information about the last error\n+\t * returned by a Homa-related kernel call such as sendmsg, recvmsg,\n+\t * or ioctl. Not updated for some obvious return values such as EINTR\n+\t * or EWOULDBLOCK.\n+\t */\n+#define HOMA_ERROR_MSG_SIZE 104\n+\tchar error_msg[HOMA_ERROR_MSG_SIZE];\n+};\n+\n+/* I/O control calls on Homa sockets.*/\n+#define HOMAIOCINFO  _IOWR('h', 0x90, struct homa_info)\n+\n+#endif /* _UAPI_LINUX_HOMA_H */\ndiff --git a/net/Kconfig b/net/Kconfig\nindex e384773935515..6780fee341a08 100644\n--- a/net/Kconfig\n+++ b/net/Kconfig\n@@ -252,6 +252,7 @@ source \"net/bridge/netfilter/Kconfig\"\n endif # if NETFILTER\n \n source \"net/sctp/Kconfig\"\n+source \"net/homa/Kconfig\"\n source \"net/rds/Kconfig\"\n source \"net/tipc/Kconfig\"\n source \"net/atm/Kconfig\"\ndiff --git a/net/Makefile b/net/Makefile\nindex 5b2dd7f07a85e..f9a3c966a83b2 100644\n--- a/net/Makefile\n+++ b/net/Makefile\n@@ -40,6 +40,7 @@ ifneq ($(CONFIG_VLAN_8021Q),)\n obj-y\t\t\t\t+= 8021q/\n endif\n obj-$(CONFIG_IP_SCTP)\t\t+= sctp/\n+obj-$(CONFIG_HOMA)\t\t+= homa/\n obj-$(CONFIG_RDS)\t\t+= rds/\n obj-$(CONFIG_WIRELESS)\t\t+= wireless/\n obj-$(CONFIG_MAC80211)\t\t+= mac80211/\ndiff --git a/net/homa/Kconfig b/net/homa/Kconfig\nnew file mode 100644\nindex 0000000000000..a420ea18b6c19\n--- /dev/null\n+++ b/net/homa/Kconfig\n@@ -0,0 +1,20 @@\n+# SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+#\n+# Homa transport protocol\n+#\n+\n+config HOMA\n+\ttristate \"The Homa transport protocol\"\n+\tdepends on IPV6\n+\n+\thelp\n+\t  Homa is a network transport protocol for communication within\n+\t  a datacenter. It provides significantly lower latency than TCP,\n+\t  particularly for workloads containing a mixture of large and small\n+\t  messages operating at high network utilization. At present, Homa\n+\t  has been only partially upstreamed; this version provides bare-bones\n+\t  functionality but is not performant. For more information see the\n+\t  homa(7) man page or checkout the Homa Wiki at\n+\t  https://homa-transport.atlassian.net/wiki/spaces/HOMA/overview.\n+\n+\t  If unsure, say N.\ndiff --git a/net/homa/Makefile b/net/homa/Makefile\nnew file mode 100644\nindex 0000000000000..b36e7fca19b59\n--- /dev/null\n+++ b/net/homa/Makefile\n@@ -0,0 +1,16 @@\n+# SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+#\n+# Makefile for the Linux implementation of the Homa transport protocol.\n+\n+obj-$(CONFIG_HOMA) += homa.o\n+homa-y:=        homa_incoming.o \\\n+\t\thoma_interest.o \\\n+\t\thoma_outgoing.o \\\n+\t\thoma_peer.o \\\n+\t\thoma_plumbing.o \\\n+\t\thoma_pool.o \\\n+\t\thoma_rpc.o \\\n+\t\thoma_sock.o \\\n+\t\thoma_timer.o \\\n+\t\thoma_tx_pool.o \\\n+\t\thoma_utils.o\ndiff --git a/net/homa/homa_impl.h b/net/homa/homa_impl.h\nnew file mode 100644\nindex 0000000000000..6172902e5d8c5\n--- /dev/null\n+++ b/net/homa/homa_impl.h\n@@ -0,0 +1,593 @@\n+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */\n+\n+/* This file contains definitions that are shared across the files\n+ * that implement Homa for Linux.\n+ */\n+\n+#ifndef _HOMA_IMPL_H\n+#define _HOMA_IMPL_H\n+\n+#include \u003clinux/bug.h\u003e\n+\n+#include \u003clinux/audit.h\u003e\n+#include \u003clinux/icmp.h\u003e\n+#include \u003clinux/init.h\u003e\n+#include \u003clinux/list.h\u003e\n+#include \u003clinux/module.h\u003e\n+#include \u003clinux/kernel.h\u003e\n+#include \u003clinux/kthread.h\u003e\n+#include \u003clinux/completion.h\u003e\n+#include \u003clinux/proc_fs.h\u003e\n+#include \u003clinux/sched/signal.h\u003e\n+#include \u003clinux/skbuff.h\u003e\n+#include \u003clinux/socket.h\u003e\n+#include \u003clinux/vmalloc.h\u003e\n+#include \u003cnet/icmp.h\u003e\n+#include \u003cnet/ip.h\u003e\n+#include \u003cnet/netns/generic.h\u003e\n+#include \u003cnet/protocol.h\u003e\n+#include \u003cnet/inet_common.h\u003e\n+#include \u003cnet/gro.h\u003e\n+#include \u003cnet/rps.h\u003e\n+\n+#include \u003clinux/homa.h\u003e\n+#include \"homa_wire.h\"\n+\n+/* Forward declarations. */\n+struct homa;\n+struct homa_peer;\n+struct homa_rpc;\n+struct homa_route;\n+struct homa_sock;\n+\n+/**\n+ * union sockaddr_in_union - Holds either an IPv4 or IPv6 address (smaller\n+ * and easier to use than sockaddr_storage).\n+ */\n+union sockaddr_in_union {\n+\t/** @sa: Used to access as a generic sockaddr. */\n+\tstruct sockaddr sa;\n+\n+\t/** @in4: Used to access as IPv4 socket. */\n+\tstruct sockaddr_in in4;\n+\n+\t/** @in6: Used to access as IPv6 socket.  */\n+\tstruct sockaddr_in6 in6;\n+};\n+\n+/**\n+ * struct homa - Stores overall information about the Homa transport, which\n+ * is shared across all Homa sockets and all network namespaces.\n+ */\n+struct homa {\n+\t/**\n+\t * @next_outgoing_id: Id to use for next outgoing RPC request.\n+\t * This is always even: it's used only to generate client-side ids.\n+\t * Accessed without locks. Note: RPC ids are unique within a\n+\t * single client machine.\n+\t */\n+\tatomic64_t next_outgoing_id;\n+\n+\t/**\n+\t * @peertab: Info about all the other hosts we have communicated with;\n+\t * includes peers from all network namespaces.\n+\t */\n+\tstruct homa_peertab *peertab;\n+\n+\t/**\n+\t * @socktab: Information about all open sockets. Dynamically\n+\t * allocated; must be kfreed.\n+\t */\n+\tstruct homa_socktab *socktab;\n+\n+\t/**\n+\t * @tx_pools: One tx_page_pool for each NUMA node on the machine.\n+\t * If there are no cores for a node, then its value is NULL.\n+\t */\n+\tstruct homa_tx_pool *tx_pools[MAX_NUMNODES];\n+\n+\t/** @max_numa: Highest NUMA node id in use by any core. */\n+\tint max_numa;\n+\n+\t/**\n+\t * @tx_page_frees_per_sec: Rate at which to return pages from\n+\t * homa_tx_page_pools back to Linux. This is the total rate across\n+\t * all pools. Set externally via sysctl.\n+\t */\n+\tint tx_page_frees_per_sec;\n+\n+\t/**\n+\t * @tx_pages_to_free: Space in which to collect pages that are\n+\t * about to be released. Dynamically allocated.\n+\t */\n+\tstruct page **tx_pages_to_free;\n+\n+\t/**\n+\t * @tx_pages_to_free_slots: Maximum number of pages that can be\n+\t * stored in tx_pages_to_free;\n+\t */\n+\tint tx_pages_to_free_slots;\n+\n+\t/**\n+\t * @tx_page_free_time: homa_clock() time when the next tx\n+\t * page should be freed. Could be in the past.\n+\t */\n+\tu64 tx_page_free_time;\n+\n+\t/**\n+\t * @tx_page_pool_min_kb: A floor on the amount of space for Homa to\n+\t * retain in a pool, specified in Kbytes. Set externally via\n+\t * sysctl.\n+\t */\n+\tint tx_page_pool_min_kb;\n+\n+\t/**\n+\t * @link_mbps: The raw bandwidth of the network uplink, in\n+\t * units of 1e06 bits per second.  Set externally via sysctl.\n+\t */\n+\tint link_mbps;\n+\n+\t/**\n+\t * @resend_ticks: When an RPC's @silent_ticks reaches this value,\n+\t * start sending RESEND requests.\n+\t */\n+\tint resend_ticks;\n+\n+\t/**\n+\t * @resend_interval: minimum number of homa timer ticks between\n+\t * RESENDs for the same RPC.\n+\t */\n+\tint resend_interval;\n+\n+\t/**\n+\t * @timeout_ticks: abort an RPC if its silent_ticks reaches this value.\n+\t */\n+\tint timeout_ticks;\n+\n+\t/**\n+\t * @timeout_resends: Assume that a server is dead if it has not\n+\t * responded after this many RESENDs have been sent to it.\n+\t */\n+\tint timeout_resends;\n+\n+\t/**\n+\t * @request_ack_ticks: How many timer ticks we'll wait for the\n+\t * client to ack an RPC before explicitly requesting an ack.\n+\t * Set externally via sysctl.\n+\t */\n+\tint request_ack_ticks;\n+\n+\t/**\n+\t * @dead_frags_limit: If hsk-\u003edead_frags is less than this number\n+\t * for a socket, then Homa reaps RPCs in a way that minimizes impact\n+\t * on performance but may permit dead RPCs to accumulate. If\n+\t * dead_frags exceeds this value, then Homa switches to a more\n+\t * aggressive approach to reaping RPCs. Set externally via sysctl.\n+\t */\n+\tint dead_frags_limit;\n+\n+\t/**\n+\t * @max_dead_frags: The largest value of hsk-\u003edead_frags that has\n+\t * existed so far for any socket.  Readable via sysctl, and may be\n+\t * reset via sysctl to begin recalculating.\n+\t */\n+\tint max_dead_frags;\n+\n+\t/**\n+\t * @max_gso_size: Maximum number of bytes that will be included\n+\t * in a single output packet that Homa passes to Linux. Can be set\n+\t * externally via sysctl to lower the limit already enforced by Linux.\n+\t */\n+\tint max_gso_size;\n+\n+\t/**\n+\t * @wmem_max: Limit on the value of sk_sndbuf for any socket. Set\n+\t * externally via sysctl.\n+\t */\n+\tint wmem_max;\n+\n+\t/**\n+\t * @timer_ticks: number of times that homa_timer has been invoked\n+\t * (may wraparound, which is safe).\n+\t */\n+\tu32 timer_ticks;\n+\n+\t/**\n+\t * @bpage_lease_usecs: how long a core can own a bpage (microseconds)\n+\t * before its ownership can be revoked to reclaim the page.\n+\t */\n+\tint bpage_lease_usecs;\n+\n+\t/**\n+\t * @bpage_lease_cycles: same as bpage_lease_usecs except in\n+\t * homa_clock() units.\n+\t */\n+\tint bpage_lease_cycles;\n+\n+\t/**\n+\t * @next_id: Set via sysctl; causes next_outgoing_id to be set to\n+\t * this value; always reads as zero. Typically used while debugging to\n+\t * ensure that different nodes use different ranges of ids.\n+\t */\n+\tint next_id;\n+\n+\t/**\n+\t * @destroyed: True means that this structure is being destroyed\n+\t * so everyone should clean up.\n+\t */\n+\tbool destroyed;\n+\n+};\n+\n+/**\n+ * struct homa_net - Contains Homa information that is specific to a\n+ * particular network namespace.\n+ */\n+struct homa_net {\n+\t/** @homa: Global Homa information. */\n+\tstruct homa *homa;\n+\n+\t/**\n+\t * @prev_default_port: The most recent port number assigned from\n+\t * the range of default ports.\n+\t */\n+\tu16 prev_default_port;\n+\n+\t/**\n+\t * @num_routes: The total number of struct homa_peers that exist\n+\t * for this namespace. Managed by homa_peer.c under the peertab lock.\n+\t */\n+\tint num_routes;\n+};\n+\n+/**\n+ * struct homa_skb_info - Additional information needed by Homa for each\n+ * outbound DATA packet. Space is allocated for this at the very end of the\n+ * linear part of the skb.\n+ */\n+struct homa_skb_info {\n+\t/**\n+\t * @data_bytes: total bytes of message data across all of the\n+\t * segments in this packet.\n+\t */\n+\tint data_bytes;\n+\n+\t/**\n+\t * @dont_defer: True means that homa_qdisc_enqueue should pass this\n+\t * packet along without considering NIC congestion. This flag is set\n+\t * by the pacer when it retransmits packets after deferral.\n+\t */\n+\tbool dont_defer;\n+};\n+\n+/**\n+ * homa_get_skb_info() - Return the address of Homa's private information\n+ * for an sk_buff.\n+ * @skb:     Socket buffer whose info is needed.\n+ * Return: address of Homa's private information for @skb.\n+ */\n+static inline struct homa_skb_info *homa_get_skb_info(struct sk_buff *skb)\n+{\n+\treturn (struct homa_skb_info *)(skb_end_pointer(skb)) - 1;\n+}\n+\n+/**\n+ * homa_set_doff() - Fills in the doff TCP header field for a packet.\n+ * @skb:   Packet whose doff field is to be set.\n+ * @size:  Size of the \"header\" in bytes (must be a multiple of 4). This is\n+ *         needed for two reasons. First, for TSO to work it must indicate\n+ *         the number of bytes that should be replicated in each segment.\n+ *         The bytes after this will be distributed among segments. Second,\n+ *         for TCP hijacking to work it must have a valid value (20 is a\n+ *         good choice if the packet isn't a TSO frame).\n+ */\n+static inline void homa_set_doff(struct sk_buff *skb, int size)\n+{\n+\ttcp_hdr(skb)-\u003edoff = size \u003e\u003e 2;\n+}\n+\n+/** skb_is_ipv6() - Return true if the packet is encapsulated with IPv6,\n+ *  false otherwise (presumably it's IPv4).\n+ */\n+static inline bool skb_is_ipv6(const struct sk_buff *skb)\n+{\n+\treturn ipv6_hdr(skb)-\u003eversion == 6;\n+}\n+\n+/**\n+ * ipv6_to_ipv4() - Given an IPv6 address produced by ipv4_to_ipv6, return\n+ * the original IPv4 address (in network byte order).\n+ * @ip6:  IPv6 address; assumed to be a mapped IPv4 address.\n+ * Return: IPv4 address stored in @ip6.\n+ */\n+static inline __be32 ipv6_to_ipv4(const struct in6_addr ip6)\n+{\n+\treturn ip6.in6_u.u6_addr32[3];\n+}\n+\n+/**\n+ * canonical_ipv6_addr() - Convert a socket address to the \"standard\"\n+ * form used in Homa, which is always an IPv6 address; if the original address\n+ * was IPv4, convert it to an IPv4-mapped IPv6 address.\n+ * @addr:   Address to canonicalize (if NULL, \"any\" is returned).\n+ * Return: IPv6 address corresponding to @addr.\n+ */\n+static inline struct in6_addr canonical_ipv6_addr(const union sockaddr_in_union\n+\t\t\t\t\t\t  *addr)\n+{\n+\tstruct in6_addr mapped;\n+\n+\tif (addr) {\n+\t\tif (addr-\u003esa.sa_family == AF_INET6)\n+\t\t\treturn addr-\u003ein6.sin6_addr;\n+\t\tipv6_addr_set_v4mapped(addr-\u003ein4.sin_addr.s_addr, \u0026mapped);\n+\t\treturn mapped;\n+\t}\n+\treturn in6addr_any;\n+}\n+\n+/**\n+ * skb_canonical_ipv6_saddr() - Given a packet buffer, return its source\n+ * address in the \"standard\" form used in Homa, which is always an IPv6\n+ * address; if the original address was IPv4, convert it to an IPv4-mapped\n+ * IPv6 address.\n+ * @skb:   The source address will be extracted from this packet buffer.\n+ * Return: IPv6 address for @skb's source machine.\n+ */\n+static inline struct in6_addr skb_canonical_ipv6_saddr(struct sk_buff *skb)\n+{\n+\tstruct in6_addr mapped;\n+\n+\tif (skb_is_ipv6(skb))\n+\t\treturn ipv6_hdr(skb)-\u003esaddr;\n+\tipv6_addr_set_v4mapped(ip_hdr(skb)-\u003esaddr, \u0026mapped);\n+\treturn mapped;\n+}\n+\n+/**\n+ * homa_make_header_avl() - Invokes pskb_may_pull to make sure that all the\n+ * Homa header information for a packet is in the linear part of the skb\n+ * where it can be addressed using skb_transport_header.\n+ * @skb:     Packet for which header is needed.\n+ * Return:   The result of pskb_may_pull (true for success)\n+ */\n+static inline bool homa_make_header_avl(struct sk_buff *skb)\n+{\n+\tint pull_length;\n+\n+\tpull_length = skb_transport_header(skb) - skb-\u003edata + HOMA_MAX_HEADER;\n+\tif (pull_length \u003e skb-\u003elen)\n+\t\tpull_length = skb-\u003elen;\n+\treturn pskb_may_pull(skb, pull_length);\n+}\n+\n+extern unsigned int homa_net_id;\n+\n+void     homa_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,\n+\t\t      struct homa_rpc *rpc);\n+enum skb_drop_reason homa_add_packet(struct homa_rpc *rpc, struct sk_buff *skb);\n+int      homa_bind(struct socket *sk, struct sockaddr_unsized *addr,\n+\t\t   int addr_len);\n+void     homa_close(struct sock *sock, long timeout);\n+int      homa_copy_to_user(struct homa_rpc *rpc);\n+void     homa_data_pkt(struct sk_buff *skb, struct homa_rpc *rpc);\n+void     homa_destroy(struct homa *homa);\n+void     homa_dispatch_pkts(struct sk_buff *skb);\n+int      homa_err_handler_v4(struct sk_buff *skb, u32 info);\n+int      homa_err_handler_v6(struct sk_buff *skb,\n+\t\t\t     struct inet6_skb_parm *opt, u8 type,  u8 code,\n+\t\t\t     int offset, __be32 info);\n+struct homa_gap *homa_gap_alloc(struct list_head *next, int start, int end);\n+int      homa_getsockopt(struct sock *sk, int level, int optname,\n+\t\t\t char __user *optval, int __user *optlen);\n+int      homa_hash(struct sock *sk);\n+enum hrtimer_restart homa_hrtimer(struct hrtimer *timer);\n+int      homa_init(struct homa *homa);\n+int      homa_ioc_info(struct socket *sock, unsigned long arg);\n+int      homa_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg);\n+int      homa_load(void);\n+void     homa_message_out_init(struct homa_rpc *rpc, int length);\n+void     homa_need_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,\n+\t\t\t   struct homa_rpc *rpc);\n+void     homa_net_destroy(struct homa_net *hnet);\n+void     homa_net_exit(struct net *net);\n+int      homa_net_init(struct homa_net *hnet, struct homa *homa);\n+int      homa_net_start(struct net *net);\n+__poll_t homa_poll(struct file *file, struct socket *sock,\n+\t\t   struct poll_table_struct *wait);\n+int      homa_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,\n+\t\t      int flags);\n+void     homa_request_retrans(struct homa_rpc *rpc);\n+int      homa_resend_data(struct homa_rpc *rpc, int start, int end);\n+void     homa_resend_pkt(struct sk_buff *skb, struct homa_rpc *rpc,\n+\t\t\t struct homa_sock *hsk);\n+void     homa_rpc_handoff(struct homa_rpc *rpc);\n+int      homa_rpc_tx_end(struct homa_rpc *rpc);\n+int      homa_sendmsg(struct sock *sk, struct msghdr *msg, size_t len);\n+int      homa_setsockopt(struct sock *sk, int level, int optname,\n+\t\t\t sockptr_t optval, unsigned int optlen);\n+int      homa_shutdown(struct socket *sock, int how);\n+struct sk_buff *__homa_skb_alloc(int length);\n+int      homa_socket(struct sock *sk);\n+int      homa_softirq(struct sk_buff *skb);\n+void     homa_spin(int ns);\n+void     homa_timer(struct homa *homa);\n+void     homa_timer_check_rpc(struct homa_rpc *rpc);\n+int      homa_timer_main(void *transport);\n+int      homa_tx_copy_from_user(struct homa_rpc *rpc, struct iov_iter *iter,\n+\t\t\t\tbool xmit);\n+struct sk_buff *homa_tx_skb_alloc(struct homa_rpc *rpc, u32 offset, u32 *end);\n+int      homa_tx_skb_send(struct homa_rpc *rpc, u32 offset, u32 *end);\n+void     homa_unhash(struct sock *sk);\n+void     homa_rpc_unknown_pkt(struct sk_buff *skb, struct homa_rpc *rpc);\n+void     homa_unload(void);\n+int      homa_wait_private(struct homa_rpc *rpc, int nonblocking);\n+struct homa_rpc *homa_wait_shared(struct homa_sock *hsk, int nonblocking);\n+int      homa_xmit_control(enum homa_packet_type type, void *contents,\n+\t\t\t   size_t length, struct homa_rpc *rpc);\n+int      __homa_xmit_control(void *contents, size_t length,\n+\t\t\t     struct homa_route *route, struct homa_sock *hsk);\n+void     homa_xmit_data(struct homa_rpc *rpc);\n+void     homa_xmit_unknown(struct sk_buff *skb, struct homa_sock *hsk);\n+\n+int      homa_message_in_init(struct homa_rpc *rpc, int length);\n+\n+/**\n+ * homa_net() - Return the struct homa_net associated with a particular\n+ * struct net.\n+ * @net:     Get the Homa data for this net namespace.\n+ * Return:   see above.\n+ */\n+static inline struct homa_net *homa_net(struct net *net)\n+{\n+\treturn (struct homa_net *)net_generic(net, homa_net_id);\n+}\n+\n+/**\n+ * homa_clock() - Return a fine-grain clock value that is monotonic and\n+ * consistent across cores.\n+ * Return: see above.\n+ */\n+static inline u64 homa_clock(void)\n+{\n+\t/* This function exists to make it easy to switch time sources\n+\t * if/when new or better sources become available.\n+\t */\n+\treturn ktime_get_ns();\n+}\n+\n+/**\n+ * homa_clock_khz() - Return the frequency of the values returned by\n+ * homa_clock, in units of KHz.\n+ * Return: see above.\n+ */\n+static inline u64 homa_clock_khz(void)\n+{\n+\treturn 1000000;\n+}\n+\n+/**\n+ * homa_ns_to_cycles() - Convert from units of nanoseconds to units of\n+ * homa_clock().\n+ * @ns:      A time measurement in nanoseconds\n+ * Return:   The time in homa_clock() units corresponding to @ns.\n+ */\n+static inline u64 homa_ns_to_cycles(u64 ns)\n+{\n+\tu64 tmp;\n+\n+\ttmp = ns * homa_clock_khz();\n+\tdo_div(tmp, 1000000);\n+\treturn tmp;\n+}\n+\n+/* Homa Locking Strategy:\n+ *\n+ * (Note: this documentation is referenced in several other places in the\n+ * Homa code)\n+ *\n+ * In the Linux TCP/IP stack the primary locking mechanism is a sleep-lock\n+ * per socket. However, per-socket locks aren't adequate for Homa, because\n+ * sockets are \"larger\" in Homa. In TCP, a socket corresponds to a single\n+ * connection between two peers; an application can have hundreds or\n+ * thousands of sockets open at once, so per-socket locks leave lots of\n+ * opportunities for concurrency. With Homa, a single socket can be used for\n+ * communicating with any number of peers, so there will typically be just\n+ * one socket per thread. As a result, a single Homa socket must support many\n+ * concurrent RPCs efficiently, and a per-socket lock would create a bottleneck\n+ * (Homa tried this approach initially).\n+ *\n+ * Thus, the primary locks used in Homa spinlocks at RPC granularity. This\n+ * allows operations on different RPCs for the same socket to proceed\n+ * concurrently. Homa also has socket locks (which are spinlocks different\n+ * from the official socket sleep-locks) but these are used much less\n+ * frequently than RPC locks.\n+ *\n+ * Lock Ordering:\n+ *\n+ * There are several other locks in Homa besides RPC locks, all of which\n+ * are spinlocks. When multiple locks are held, they must be acquired in a\n+ * consistent order in order to prevent deadlock. Here are the rules for Homa:\n+ * 1. Except for RPC locks, socket locks, and the grant lock, all locks\n+ *    should be considered \"leaf\" locks: don't acquire other locks while\n+ *    holding them.\n+ * 2. The lock order is:\n+ *    * Grant lock\n+ *    * RPC lock\n+ *    * Socket lock\n+ *    * Other lock\n+ *\n+ * It may seem surprising that RPC locks are acquired *before* socket locks,\n+ * but this is essential for high performance. Homa has been designed so that\n+ * many common operations (such as processing input packets) can be performed\n+ * while holding only an RPC lock; this allows operations on different RPCs\n+ * to proceed in parallel. Only a few operations, such as handing off an\n+ * incoming message to a waiting thread, require the socket lock. If socket\n+ * locks had to be acquired first, any operation that might eventually need\n+ * the socket lock would have to acquire it before the RPC lock, which would\n+ * severely restrict concurrency.\n+ *\n+ * Socket Shutdown:\n+ *\n+ * It is possible for socket shutdown to begin while operations are underway\n+ * that hold RPC locks but not the socket lock. For example, a new RPC\n+ * creation might be underway when a socket is shut down. The RPC creation\n+ * will eventually acquire the socket lock and add the new RPC to those\n+ * for the socket; it would be very bad if this were to happen after\n+ * homa_sock_shutdown thinks it has deleted all RPCs for the socket.\n+ * In general, any operation that acquires a socket lock must check\n+ * hsk-\u003eshutdown after acquiring the lock and abort if hsk-\u003eshutdown is set.\n+ *\n+ * Spinlock Implications:\n+ *\n+ * Homa uses spinlocks exclusively; this is needed because locks typically\n+ * need to be acquired at atomic level, such as in SoftIRQ code.\n+ *\n+ * Operations that can block, such as memory allocation and copying data\n+ * to/from user space, are not permitted while holding spinlocks (spinlocks\n+ * disable interrupts, so the holder must not block. This results in awkward\n+ * code in several places to move restricted operations outside locked\n+ * regions. Such code typically looks like this:\n+ *   - Acquire a reference on an object such as an RPC, in order to prevent\n+ *     the object from being deleted.\n+ *   - Release the object's lock.\n+ *   - Perform the restricted operation.\n+ *   - Re-acquire the lock.\n+ *   - Release the reference.\n+ * It is possible that the object may have been modified by some other party\n+ * while it was unlocked, so additional checks may be needed after reacquiring\n+ * the lock. As one example, an RPC may have been terminated, in which case\n+ * any operation in progress on that RPC should be aborted after reacquiring\n+ * the lock.\n+ *\n+ * Lists of RPCs:\n+ *\n+ * There are a few places where Homa needs to process all of the RPCs\n+ * associated with a socket, such as the timer. Such code must first lock\n+ * the socket (to protect access to the link pointers) then lock\n+ * individual RPCs on the list. However, this violates the rules for locking\n+ * order. It isn't safe to unlock the socket before locking the individual RPCs,\n+ * because RPCs could be deleted and their memory recycled between the unlock\n+ * of the socket lock and the lock of the RPC; this could result in corruption.\n+ * Homa uses two different approaches to handle this situation:\n+ * 1. Use ``homa_protect_rpcs`` to prevent RPC reaping for a socket. RPCs can\n+ *    still be terminated, but their memory won't go away until\n+ *    homa_unprotect_rpcs is invoked. This allows the socket lock to be\n+ *    released before acquiring RPC locks; after acquiring each RPC lock,\n+ *    the RPC must be checked to see if it has been terminated; if so, skip it.\n+ * 2. Use ``spin_trylock_bh`` to acquire the RPC lock while still holding the\n+ *    socket lock. If this fails, then release the socket lock and retry\n+ *    both the socket lock and the RPC lock. Of course, the state of both\n+ *    socket and RPC could change before the locks are finally acquired.\n+ *\n+ * Locks and Packet Transmission:\n+ *\n+ * Homa must not hold locks while transmitting packets (e.g. by calling\n+ * ip_queue_xmit or ip6_xmit). This is because homa_qdisc could be invoked\n+ * during the transmission process, and it may need to acquire locks under\n+ * some conditions (such as an RPC lock). Homa_qdisc is invoked with the\n+ * qdisc lock held, so invoking ip*xmit with a lock held can result in\n+ * AB-BA deadlocks.\n+ */\n+\n+#endif /* _HOMA_IMPL_H */\ndiff --git a/net/homa/homa_incoming.c b/net/homa/homa_incoming.c\nnew file mode 100644\nindex 0000000000000..d85dd325de4d1\n--- /dev/null\n+++ b/net/homa/homa_incoming.c\n@@ -0,0 +1,886 @@\n+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+\n+/* This file contains functions that handle incoming Homa messages. */\n+\n+#include \"homa_impl.h\"\n+#include \"homa_interest.h\"\n+#include \"homa_peer.h\"\n+#include \"homa_pool.h\"\n+\n+/**\n+ * homa_message_in_init() - Constructor for homa_message_in.\n+ * @rpc:          RPC whose msgin structure should be initialized. The\n+ *                msgin struct is assumed to be zeroes.\n+ * @length:       Total number of bytes in message.\n+ * Return:        Zero for successful initialization, or a negative errno\n+ *                if rpc-\u003emsgin could not be initialized.\n+ */\n+int homa_message_in_init(struct homa_rpc *rpc, int length)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tint err;\n+\n+\tif (((unsigned int)length) \u003e HOMA_MAX_MESSAGE_LENGTH)\n+\t\treturn -EINVAL;\n+\n+\trpc-\u003emsgin.length = length;\n+\t__skb_queue_head_init(\u0026rpc-\u003emsgin.packets);\n+\tINIT_LIST_HEAD(\u0026rpc-\u003emsgin.gaps);\n+\trpc-\u003emsgin.bytes_remaining = length;\n+\terr = homa_pool_alloc_msg(rpc);\n+\tif (err != 0) {\n+\t\trpc-\u003emsgin.length = -1;\n+\t\treturn err;\n+\t}\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_gap_alloc() - Allocate a new gap and add it to a gap list.\n+ * @next:   Add the new gap just before this list element.\n+ * @start:  Offset of first byte covered by the gap.\n+ * @end:    Offset of byte just after the last one covered by the gap.\n+ * Return:  Pointer to the new gap, or NULL if memory couldn't be allocated\n+ *          for the gap object.\n+ */\n+struct homa_gap *homa_gap_alloc(struct list_head *next, int start, int end)\n+{\n+\tstruct homa_gap *gap;\n+\n+\tgap = kmalloc_obj(*gap, GFP_ATOMIC);\n+\tif (!gap)\n+\t\treturn NULL;\n+\tgap-\u003estart = start;\n+\tgap-\u003eend = end;\n+\tgap-\u003etime = homa_clock();\n+\tlist_add_tail(\u0026gap-\u003elinks, next);\n+\treturn gap;\n+}\n+\n+/**\n+ * homa_request_retrans() - The function is invoked when it appears that\n+ * data packets for a message have been lost. It issues RESEND requests\n+ * as appropriate and may modify the state of the RPC.\n+ * @rpc:     RPC for which incoming data is delinquent; must be locked by\n+ *           caller.\n+ */\n+void homa_request_retrans(struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_resend_hdr *resends;\n+\tstruct homa_resend_hdr resend;\n+\tstruct homa_gap *gap;\n+\tint offset, length;\n+\tint num_gaps, i;\n+\n+\tif (rpc-\u003emsgin.length \u003e= 0) {\n+\t\t/* Issue RESENDS for any gaps in incoming data.  Must\n+\t\t * pre-allocate space for all of the packet headers because\n+\t\t * so we don't have to release the RPC lock while iterating\n+\t\t * the gap list.\n+\t\t */\n+\t\tnum_gaps = list_count_nodes(\u0026rpc-\u003emsgin.gaps);\n+\t\tresends = kzalloc_objs(*resends, num_gaps, GFP_ATOMIC);\n+\t\tif (!resends)\n+\t\t\treturn;\n+\t\ti = 0;\n+\t\tlist_for_each_entry(gap, \u0026rpc-\u003emsgin.gaps, links) {\n+\t\t\tresends[i].offset = htonl(gap-\u003estart);\n+\t\t\tresends[i].length = htonl(gap-\u003eend - gap-\u003estart);\n+\t\t\ti++;\n+\t\t}\n+\t\tfor (i = 0; i \u003c num_gaps; i++)\n+\t\t\thoma_xmit_control(RESEND, \u0026resends[i],\n+\t\t\t\t\t  sizeof(resends[i]), rpc);\n+\t\tkfree(resends);\n+\n+\t\t/* Issue a RESEND for any granted data after the last gap. */\n+\t\toffset = rpc-\u003emsgin.recv_end;\n+\t\tlength = rpc-\u003emsgin.length - rpc-\u003emsgin.recv_end;\n+\t\tif (length \u003c= 0)\n+\t\t\treturn;\n+\t} else {\n+\t\t/* No data has been received for the RPC. Ask the sender to\n+\t\t * resend everything it has sent so far.\n+\t\t */\n+\t\toffset = 0;\n+\t\tlength = -1;\n+\t}\n+\n+\tmemset(\u0026resend, 0, sizeof(resend));\n+\tresend.offset = htonl(offset);\n+\tresend.length = htonl(length);\n+\thoma_xmit_control(RESEND, \u0026resend, sizeof(resend), rpc);\n+}\n+\n+/**\n+ * homa_add_packet() - Add an incoming packet to the contents of a\n+ * partially received message.\n+ * @rpc:   Add the packet to the msgin for this RPC.\n+ * @skb:   The new packet. If the packet is linked into rpc then an additional\n+ *         reference will be taken on it.\n+ * Return: 0 if the packet was successfully linked into rpc, otherwise the\n+ *         reason why the packet was not linked in.\n+ */\n+enum skb_drop_reason homa_add_packet(struct homa_rpc *rpc, struct sk_buff *skb)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_data_hdr *h = (struct homa_data_hdr *)skb-\u003edata;\n+\tstruct homa_gap *gap, *dummy, *gap2;\n+\tu32 start = ntohl(h-\u003eseg.offset);\n+\tu32 length = homa_data_len(skb);\n+\tenum skb_drop_reason reason = 0;\n+\tu32 end = start + length;\n+\n+\tif (start \u003e= rpc-\u003emsgin.length ||\n+\t    length \u003e (rpc-\u003emsgin.length - start)) {\n+\t\treason = SKB_DROP_REASON_PKT_TOO_BIG;\n+\t\tgoto ignore;\n+\t}\n+\n+\tif (start == rpc-\u003emsgin.recv_end) {\n+\t\t/* Common case: packet is sequential. */\n+\t\trpc-\u003emsgin.recv_end += length;\n+\t\tgoto keep;\n+\t}\n+\n+\tif (start \u003e rpc-\u003emsgin.recv_end) {\n+\t\t/* Packet creates a new gap. */\n+\t\tif (!homa_gap_alloc(\u0026rpc-\u003emsgin.gaps,\n+\t\t\t\t    rpc-\u003emsgin.recv_end, start)) {\n+\t\t\treason = SKB_DROP_REASON_NOMEM;\n+\t\t\tgoto ignore;\n+\t\t}\n+\t\trpc-\u003emsgin.recv_end = end;\n+\t\tgoto keep;\n+\t}\n+\n+\t/* Must now check to see if the packet fills in part or all of\n+\t * an existing gap.\n+\t */\n+\tlist_for_each_entry_safe(gap, dummy, \u0026rpc-\u003emsgin.gaps, links) {\n+\t\t/* Is packet at the start of this gap? */\n+\t\tif (start \u003c= gap-\u003estart) {\n+\t\t\tif (end \u003c= gap-\u003estart)\n+\t\t\t\tcontinue;\n+\t\t\tif (start \u003c gap-\u003estart) {\n+\t\t\t\treason = SKB_DROP_REASON_DUP_FRAG;\n+\t\t\t\tgoto ignore;\n+\t\t\t}\n+\t\t\tif (end \u003e gap-\u003eend) {\n+\t\t\t\treason = SKB_DROP_REASON_DUP_FRAG;\n+\t\t\t\tgoto ignore;\n+\t\t\t}\n+\t\t\tgap-\u003estart = end;\n+\t\t\tif (gap-\u003estart \u003e= gap-\u003eend) {\n+\t\t\t\tlist_del(\u0026gap-\u003elinks);\n+\t\t\t\tkfree(gap);\n+\t\t\t}\n+\t\t\tgoto keep;\n+\t\t}\n+\n+\t\t/* Is packet at the end of this gap? BTW, at this point we know\n+\t\t * the packet can't cover the entire gap.\n+\t\t */\n+\t\tif (end \u003e= gap-\u003eend) {\n+\t\t\tif (start \u003e= gap-\u003eend)\n+\t\t\t\tcontinue;\n+\t\t\tif (end \u003e gap-\u003eend) {\n+\t\t\t\treason = SKB_DROP_REASON_DUP_FRAG;\n+\t\t\t\tgoto ignore;\n+\t\t\t}\n+\t\t\tgap-\u003eend = start;\n+\t\t\tgoto keep;\n+\t\t}\n+\n+\t\t/* Packet is in the middle of the gap; must split the gap. */\n+\t\tgap2 = homa_gap_alloc(\u0026gap-\u003elinks, gap-\u003estart, start);\n+\t\tif (!gap2) {\n+\t\t\treason = SKB_DROP_REASON_NOMEM;\n+\t\t\tgoto ignore;\n+\t\t}\n+\t\tgap2-\u003etime = gap-\u003etime;\n+\t\tgap-\u003estart = end;\n+\t\tgoto keep;\n+\t}\n+\t/* Packet doesn't overlap any gap, so it is a duplicate. */\n+\treason = SKB_DROP_REASON_DUP_FRAG;\n+\n+ignore:\n+\treturn reason;\n+\n+keep:\n+\t__skb_queue_tail(\u0026rpc-\u003emsgin.packets, skb);\n+\tskb_get(skb);\n+\trpc-\u003emsgin.bytes_remaining -= length;\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_copy_to_user() - Copy as much data as possible from incoming\n+ * packet buffers to buffers in user space.\n+ * @rpc:     RPC for which data should be copied. Must be locked by caller.\n+ * Return:   Zero for success or a negative errno if there is an error.\n+ *           It is possible for the RPC to be freed while this function\n+ *           executes (it releases and reacquires the RPC lock). If that\n+ *           happens, -EINVAL will be returned and the state of @rpc\n+ *           will be RPC_DEAD. Clears the RPC_PKTS_READY bit in @rpc-\u003eflags\n+ *           if all available packets have been copied out.\n+ */\n+int homa_copy_to_user(struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+#define MAX_SKBS 20\n+\tstruct sk_buff *skbs[MAX_SKBS];\n+\tint error = 0;\n+\tint n = 0;             /* Number of filled entries in skbs. */\n+\tint i;\n+\n+\t/* Tricky note: we can't hold the RPC lock while we're actually\n+\t * copying to user space, because (a) it's illegal to hold a spinlock\n+\t * while copying to user space and (b) we'd like for homa_softirq\n+\t * to add more packets to the RPC while we're copying these out.\n+\t * So, collect a bunch of packets to copy, then release the lock,\n+\t * copy them, and reacquire the lock.\n+\t */\n+\twhile (true) {\n+\t\tstruct sk_buff *skb;\n+\n+\t\tif (rpc-\u003estate == RPC_DEAD) {\n+\t\t\terror = -EINVAL;\n+\t\t\tbreak;\n+\t\t}\n+\n+\t\tskb = __skb_dequeue(\u0026rpc-\u003emsgin.packets);\n+\t\tif (skb) {\n+\t\t\tskbs[n] = skb;\n+\t\t\tn++;\n+\t\t\tif (n \u003c MAX_SKBS)\n+\t\t\t\tcontinue;\n+\t\t}\n+\t\tif (n == 0) {\n+\t\t\tclear_bit(RPC_PKTS_READY, \u0026rpc-\u003eflags);\n+\t\t\tbreak;\n+\t\t}\n+\n+\t\t/* At this point we've collected a batch of packets (or\n+\t\t * run out of packets); copy any available packets out to\n+\t\t * user space.\n+\t\t */\n+\t\thoma_rpc_unlock(rpc);\n+\n+\t\t/* Each iteration of this loop copies out one skb. */\n+\t\tfor (i = 0; i \u003c n; i++) {\n+\t\t\tstruct homa_data_hdr *h = (struct homa_data_hdr *)\n+\t\t\t\t\tskbs[i]-\u003edata;\n+\t\t\tint pkt_length = homa_data_len(skbs[i]);\n+\t\t\tint offset = ntohl(h-\u003eseg.offset);\n+\t\t\tint buf_bytes, chunk_size;\n+\t\t\tstruct iov_iter iter;\n+\t\t\tint copied = 0;\n+\t\t\tchar __user *dst;\n+\n+\t\t\t/* Each iteration of this loop copies to one\n+\t\t\t * user buffer.\n+\t\t\t */\n+\t\t\twhile (copied \u003c pkt_length) {\n+\t\t\t\tchunk_size = pkt_length - copied;\n+\t\t\t\tdst = homa_pool_get_buffer(rpc, offset + copied,\n+\t\t\t\t\t\t\t   \u0026buf_bytes);\n+\t\t\t\tif (buf_bytes \u003c chunk_size) {\n+\t\t\t\t\tif (buf_bytes == 0) {\n+\t\t\t\t\t\t/* skb has data beyond message\n+\t\t\t\t\t\t * end?\n+\t\t\t\t\t\t */\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tchunk_size = buf_bytes;\n+\t\t\t\t}\n+\t\t\t\terror = import_ubuf(READ, dst, chunk_size,\n+\t\t\t\t\t\t    \u0026iter);\n+\t\t\t\tif (error)\n+\t\t\t\t\tgoto free_skbs;\n+\t\t\t\terror = skb_copy_datagram_iter(skbs[i],\n+\t\t\t\t\t\t\t       sizeof(*h) +\n+\t\t\t\t\t\t\t       copied,  \u0026iter,\n+\t\t\t\t\t\t\t       chunk_size);\n+\t\t\t\tif (error)\n+\t\t\t\t\tgoto free_skbs;\n+\t\t\t\tcopied += chunk_size;\n+\t\t\t}\n+\t\t}\n+\n+free_skbs:\n+\t\tfor (i = 0; i \u003c n; i++)\n+\t\t\tconsume_skb(skbs[i]);\n+\t\tn = 0;\n+\t\thoma_rpc_lock_preempt(rpc);\n+\t\tif (error)\n+\t\t\tbreak;\n+\t}\n+\treturn error;\n+}\n+\n+/**\n+ * homa_dispatch_pkts() - Top-level function that processes a batch of packets,\n+ * all related to the same RPC.\n+ * @skb:       First packet in the batch, linked through skb-\u003enext.\n+ */\n+void homa_dispatch_pkts(struct sk_buff *skb)\n+{\n+\tconst struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);\n+\tstruct homa_data_hdr *h = (struct homa_data_hdr *)skb-\u003edata;\n+\tu64 id = homa_local_id(h-\u003ecommon.sender_id);\n+\tint dport = ntohs(h-\u003ecommon.dport);\n+\tstruct homa_rpc *rpc = NULL;\n+\tstruct homa_sock *hsk;\n+\tstruct homa_net *hnet;\n+\tstruct sk_buff *next;\n+\n+\t/* Find the appropriate socket.*/\n+\thnet = homa_net(dev_net(skb-\u003edev));\n+\thsk = homa_sock_find(hnet, dport);\n+\tif (!hsk || (!homa_is_client(id) \u0026\u0026 !hsk-\u003eis_server)) {\n+\t\tif (skb_is_ipv6(skb))\n+\t\t\ticmp6_send(skb, ICMPV6_DEST_UNREACH,\n+\t\t\t\t   ICMPV6_PORT_UNREACH, 0, NULL, IP6CB(skb));\n+\t\telse\n+\t\t\ticmp_send(skb, ICMP_DEST_UNREACH,\n+\t\t\t\t  ICMP_PORT_UNREACH, 0);\n+\t\twhile (skb) {\n+\t\t\tnext = skb-\u003enext;\n+\t\t\tkfree_skb(skb);\n+\t\t\tskb = next;\n+\t\t}\n+\t\tif (hsk)\n+\t\t\tsock_put(\u0026hsk-\u003esock);\n+\t\treturn;\n+\t}\n+\n+\t/* Each iteration through the following loop processes one packet. */\n+\tfor (; skb; skb = next) {\n+\t\th = (struct homa_data_hdr *)skb-\u003edata;\n+\t\tnext = skb-\u003enext;\n+\n+\t\t/* Relinquish the RPC lock temporarily if it's needed\n+\t\t * elsewhere.\n+\t\t */\n+\t\tif (rpc) {\n+\t\t\tif (test_bit(APP_NEEDS_LOCK, \u0026rpc-\u003eflags)) {\n+\t\t\t\thoma_rpc_unlock(rpc);\n+\n+\t\t\t\t/* This short spin is needed to ensure that the\n+\t\t\t\t * other thread gets the lock before this thread\n+\t\t\t\t * grabs it again below (the need for this\n+\t\t\t\t * was confirmed experimentally in 2/2025;\n+\t\t\t\t * without it, the handoff fails 20-25% of the\n+\t\t\t\t * time). Furthermore, the call to homa_spin\n+\t\t\t\t * seems to allow the other thread to acquire\n+\t\t\t\t * the lock more quickly.\n+\t\t\t\t */\n+\t\t\t\thoma_spin(100);\n+\t\t\t\thoma_rpc_lock(rpc);\n+\t\t\t}\n+\t\t}\n+\n+\t\t/* If we don't already have an RPC, find it, lock it,\n+\t\t * and create a reference on it.\n+\t\t */\n+\t\tif (!rpc) {\n+\t\t\tif (!homa_is_client(id)) {\n+\t\t\t\t/* We are the server for this RPC. */\n+\t\t\t\tif (h-\u003ecommon.type == DATA) {\n+\t\t\t\t\t/* Create a new RPC if one doesn't\n+\t\t\t\t\t * already exist.\n+\t\t\t\t\t */\n+\t\t\t\t\trpc = homa_rpc_alloc_server(hsk, \u0026saddr,\n+\t\t\t\t\t\t\t\t    h);\n+\t\t\t\t\tif (IS_ERR(rpc)) {\n+\t\t\t\t\t\trpc = NULL;\n+\t\t\t\t\t\tgoto discard;\n+\t\t\t\t\t}\n+\t\t\t\t} else {\n+\t\t\t\t\trpc = homa_rpc_find_server(hsk, \u0026saddr,\n+\t\t\t\t\t\t\t\t   id);\n+\t\t\t\t}\n+\t\t\t} else {\n+\t\t\t\trpc = homa_rpc_find_client(hsk, id);\n+\t\t\t}\n+\t\t\tif (rpc)\n+\t\t\t\thoma_rpc_hold(rpc);\n+\t\t}\n+\t\tif (unlikely(!rpc)) {\n+\t\t\tif (h-\u003ecommon.type != NEED_ACK \u0026\u0026\n+\t\t\t    h-\u003ecommon.type != ACK \u0026\u0026\n+\t\t\t    h-\u003ecommon.type != RESEND)\n+\t\t\t\tgoto discard;\n+\t\t} else {\n+\t\t\tif (h-\u003ecommon.type == DATA ||\n+\t\t\t    h-\u003ecommon.type == BUSY)\n+\t\t\t\trpc-\u003esilent_ticks = 0;\n+\t\t}\n+\n+\t\tswitch (h-\u003ecommon.type) {\n+\t\tcase DATA:\n+\t\t\thoma_data_pkt(skb, rpc);\n+\t\t\tbreak;\n+\t\tcase RESEND:\n+\t\t\thoma_resend_pkt(skb, rpc, hsk);\n+\t\t\tbreak;\n+\t\tcase RPC_UNKNOWN:\n+\t\t\thoma_rpc_unknown_pkt(skb, rpc);\n+\t\t\tbreak;\n+\t\tcase BUSY:\n+\t\t\t/* Nothing to do for these packets except reset\n+\t\t\t * silent_ticks, which happened above.\n+\t\t\t */\n+\t\t\tgoto discard;\n+\t\tcase NEED_ACK:\n+\t\t\thoma_need_ack_pkt(skb, hsk, rpc);\n+\t\t\tbreak;\n+\t\tcase ACK:\n+\t\t\thoma_ack_pkt(skb, hsk, rpc);\n+\t\t\tbreak;\n+\t\tdefault:\n+\t\t\tgoto discard;\n+\t\t}\n+\t\tcontinue;\n+\n+discard:\n+\t\tkfree_skb(skb);\n+\t}\n+\tif (rpc) {\n+\t\thoma_rpc_put(rpc);\n+\t\thoma_rpc_unlock(rpc);\n+\t}\n+\n+\t/* We need to reap dead RPCs here under two conditions:\n+\t * 1. The socket has hit its limit on tx buffer space and threads are\n+\t *    blocked waiting for skbs to be released.\n+\t * 2. A large number of dead RPCs have accumulated, and it seems\n+\t *    that the reaper isn't keeping up when invoked only at\n+\t *    \"convenient\" times (see \"RPC Reaping Strategy\" in homa_rpc_reap\n+\t *    code for details).\n+\t */\n+\tif (hsk-\u003edead_frags \u003e 0) {\n+\t\twhile (test_bit(HOMA_SOCK_NOSPACE, \u0026hsk-\u003eflags) ||\n+\t\t       hsk-\u003edead_frags \u003e= 2 * hsk-\u003ehoma-\u003edead_frags_limit) {\n+\t\t\tint more;\n+\n+\t\t\tmore = homa_rpc_reap(hsk);\n+\t\t\tif (!more)\n+\t\t\t\tbreak;\n+\t\t}\n+\t}\n+\tsock_put(\u0026hsk-\u003esock);\n+}\n+\n+/**\n+ * homa_data_pkt() - Handler for incoming DATA packets\n+ * @skb:     Incoming packet; size known to be large enough for the header.\n+ *           This function now owns the packet.\n+ * @rpc:     Information about the RPC corresponding to this packet.\n+ *           Must be locked by the caller.\n+ */\n+void homa_data_pkt(struct sk_buff *skb, struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tenum skb_drop_reason drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;\n+\tstruct homa_data_hdr *h = (struct homa_data_hdr *)skb-\u003edata;\n+\n+\tif (rpc-\u003estate != RPC_INCOMING \u0026\u0026 homa_is_client(rpc-\u003eid)) {\n+\t\tif (unlikely(rpc-\u003estate != RPC_OUTGOING))\n+\t\t\tgoto handle_ack;\n+\t\trpc-\u003estate = RPC_INCOMING;\n+\t\tif (homa_message_in_init(rpc, ntohl(h-\u003emessage_length)) != 0) {\n+\t\t\tdrop_reason = SKB_DROP_REASON_NOMEM;\n+\t\t\tgoto handle_ack;\n+\t\t}\n+\t} else if (rpc-\u003estate != RPC_INCOMING) {\n+\t\t/* Must be server; note that homa_rpc_alloc_server already\n+\t\t * initialized msgin and allocated buffers.\n+\t\t */\n+\t\tif (unlikely(rpc-\u003emsgin.length \u003e= 0))\n+\t\t\tgoto handle_ack;\n+\t}\n+\n+\tif (rpc-\u003emsgin.num_bpages == 0) {\n+\t\t/* Drop packets that arrive when we can't allocate buffer\n+\t\t * space. If we keep them around, packet buffer usage can\n+\t\t * exceed available cache space, resulting in poor\n+\t\t * performance.\n+\t\t */\n+\t\tdrop_reason = SKB_DROP_REASON_NOMEM;\n+\t\tgoto handle_ack;\n+\t}\n+\n+\tdrop_reason = homa_add_packet(rpc, skb);\n+\n+\tif (skb_queue_len(\u0026rpc-\u003emsgin.packets) != 0 \u0026\u0026\n+\t    !test_bit(RPC_PKTS_READY, \u0026rpc-\u003eflags)) {\n+\t\tset_bit(RPC_PKTS_READY, \u0026rpc-\u003eflags);\n+\t\thoma_rpc_handoff(rpc);\n+\t}\n+\n+handle_ack:\n+\t/* It's important to handle acks *after* calling homa_add_packet.\n+\t * Otherwise we can end up with extraneous handoffs: we have to release\n+\t * the RPC lock to handle acks, but that could allow some other thread\n+\t * to receive a previous handoff made by homa_rpc_alloc_server, even\n+\t * though the packet hasn't been added to the RPC. If this happens\n+\t * the call to homa_rpc_handoff above will have to make an additional\n+\t * handoff.\n+\t */\n+\tif (h-\u003eack.client_id) {\n+\t\tconst struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);\n+\n+\t\thoma_rpc_ack(rpc-\u003ehsk, rpc, \u0026saddr, 1, \u0026h-\u003eack);\n+\t}\n+\tkfree_skb_reason(skb, drop_reason);\n+}\n+\n+/**\n+ * homa_resend_pkt() - Handler for incoming RESEND packets\n+ * @skb:     Incoming packet; size already verified large enough for header.\n+ *           This function now owns the packet.\n+ * @rpc:     Information about the RPC corresponding to this packet; must\n+ *           be locked by caller, but may be NULL if there is no RPC matching\n+ *           this packet\n+ * @hsk:     Socket on which the packet was received.\n+ */\n+void homa_resend_pkt(struct sk_buff *skb, struct homa_rpc *rpc,\n+\t\t     struct homa_sock *hsk)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_resend_hdr *h = (struct homa_resend_hdr *)skb-\u003edata;\n+\tint offset = ntohl(h-\u003eoffset);\n+\tint length = ntohl(h-\u003elength);\n+\tint end = offset + length;\n+\tstruct homa_busy_hdr busy;\n+\tint tx_end;\n+\n+\tif (!rpc) {\n+\t\thoma_xmit_unknown(skb, hsk);\n+\t\tgoto done;\n+\t}\n+\n+\ttx_end = homa_rpc_tx_end(rpc);\n+\tif (!homa_is_client(rpc-\u003eid) \u0026\u0026 rpc-\u003estate != RPC_OUTGOING) {\n+\t\t/* We are the server for this RPC and don't yet have a\n+\t\t * response message, so send BUSY to keep the client\n+\t\t * waiting.\n+\t\t */\n+\t\thoma_xmit_control(BUSY, \u0026busy, sizeof(busy), rpc);\n+\t\tgoto done;\n+\t}\n+\n+\tif (length == -1)\n+\t\tend = tx_end;\n+\n+\t/* Don't retransmit data that we haven't transmitted for the first\n+\t * time: we're not ready to send that data yet (we'll send a BUSY\n+\t * packet below if needed).\n+\t */\n+\thoma_resend_data(rpc, offset, (end \u003e tx_end) ? tx_end : end);\n+\tif (rpc-\u003estate == RPC_DEAD)\n+\t\tgoto done;\n+\n+\tif (offset \u003e= tx_end) {\n+\t\t/* We have chosen not to transmit any of the requested data;\n+\t\t * send BUSY so the receiver knows we are alive.\n+\t\t */\n+\t\thoma_xmit_control(BUSY, \u0026busy, sizeof(busy), rpc);\n+\t\tgoto done;\n+\t}\n+\n+done:\n+\tconsume_skb(skb);\n+}\n+\n+/**\n+ * homa_rpc_unknown_pkt() - Handler for incoming RPC_UNKNOWN packets.\n+ * @skb:     Incoming packet; size known to be large enough for the header.\n+ *           This function now owns the packet.\n+ * @rpc:     Information about the RPC corresponding to this packet. Must\n+ *           be locked by caller.\n+ */\n+void homa_rpc_unknown_pkt(struct sk_buff *skb, struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tif (homa_is_client(rpc-\u003eid)) {\n+\t\tif (rpc-\u003estate == RPC_OUTGOING) {\n+\t\t\tint tx_end = homa_rpc_tx_end(rpc);\n+\n+\t\t\t/* It appears that everything we've already transmitted\n+\t\t\t * has been lost; retransmit it.\n+\t\t\t */\n+\t\t\thoma_resend_data(rpc, 0, tx_end);\n+\t\t\tgoto done;\n+\t\t}\n+\t} else {\n+\t\thoma_rpc_end(rpc);\n+\t}\n+done:\n+\tconsume_skb(skb);\n+}\n+\n+/**\n+ * homa_need_ack_pkt() - Handler for incoming NEED_ACK packets\n+ * @skb:     Incoming packet; size already verified large enough for header.\n+ *           This function now owns the packet.\n+ * @hsk:     Socket on which the packet was received.\n+ * @rpc:     The RPC named in the packet header, or NULL if no such\n+ *           RPC exists. The RPC must have been locked by the caller.\n+ */\n+void homa_need_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,\n+\t\t       struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_common_hdr *h = (struct homa_common_hdr *)skb-\u003edata;\n+\tconst struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);\n+\tu64 id = homa_local_id(h-\u003esender_id);\n+\tstruct homa_route *route;\n+\tstruct homa_ack_hdr ack;\n+\n+\t/* Don't ack if it's not safe for the peer to purge its state\n+\t * for this RPC (the RPC still exists and we haven't received\n+\t * the entire response), or if we can't find peer info.\n+\t */\n+\tif (rpc \u0026\u0026 (rpc-\u003estate != RPC_INCOMING ||\n+\t\t    rpc-\u003emsgin.bytes_remaining)) {\n+\t\thoma_request_retrans(rpc);\n+\t\tgoto done;\n+\t}\n+\troute = homa_route_get(hsk, \u0026saddr);\n+\tif (IS_ERR(route))\n+\t\tgoto done;\n+\n+\t/* Send an ACK for this RPC. At the same time, include all of the\n+\t * other acks available for the peer. Note: can't use rpc below,\n+\t * since it may be NULL.\n+\t */\n+\tmemset(\u0026ack, 0, sizeof(ack));\n+\tack.common.type = ACK;\n+\tack.common.sport = h-\u003edport;\n+\tack.common.dport = h-\u003esport;\n+\tack.common.sender_id = cpu_to_be64(id);\n+\tack.num_acks = htons(homa_peer_get_acks(route-\u003epeer,\n+\t\t\t\t\t\tHOMA_MAX_ACKS_PER_PKT,\n+\t\t\t\t\t\tack.acks));\n+\tif (rpc)\n+\t\thoma_rpc_unlock(rpc);\n+\t__homa_xmit_control(\u0026ack, sizeof(ack), route, hsk);\n+\tif (rpc)\n+\t\thoma_rpc_lock(rpc);\n+\thoma_route_release(route);\n+\n+done:\n+\tconsume_skb(skb);\n+}\n+\n+/**\n+ * homa_ack_pkt() - Handler for incoming ACK packets\n+ * @skb:     Incoming packet; size already verified large enough for header.\n+ *           This function now owns the packet.\n+ * @hsk:     Socket on which the packet was received.\n+ * @rpc:     The RPC named in the packet header, or NULL if no such\n+ *           RPC exists. The RPC must be locked by the caller.\n+ */\n+void homa_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,\n+\t\t  struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tconst struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);\n+\tstruct homa_ack_hdr *h = (struct homa_ack_hdr *)skb-\u003edata;\n+\tint count;\n+\n+\tif (rpc)\n+\t\thoma_rpc_end(rpc);\n+\n+\tcount = ntohs(h-\u003enum_acks);\n+\tif (count \u003e HOMA_MAX_ACKS_PER_PKT)\n+\t\tcount = HOMA_MAX_ACKS_PER_PKT;\n+\tif (count \u003e 0)\n+\t\thoma_rpc_ack(hsk, rpc, \u0026saddr, count, h-\u003eacks);\n+\tconsume_skb(skb);\n+}\n+\n+/**\n+ * homa_wait_private() - Waits until the response has been received for\n+ * a specific RPC or the RPC has failed with an error.\n+ * @rpc:          RPC to wait for; an error will be returned if the RPC is\n+ *                not a client RPC or not private. Must be locked by caller.\n+ * @nonblocking:  Nonzero means return immediately if @rpc not ready.\n+ * Return:        0 means that @rpc is ready for attention: either its response\n+ *                has been received or it has an unrecoverable error such as\n+ *                ETIMEDOUT (in rpc-\u003eerror). Nonzero means some other error\n+ *                (such as EINTR or EINVAL) occurred before @rpc became ready\n+ *                for attention; in this case the return value is a negative\n+ *                errno.\n+ */\n+int homa_wait_private(struct homa_rpc *rpc, int nonblocking)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_interest interest;\n+\tint result;\n+\n+\tif (!test_bit(RPC_PRIVATE, \u0026rpc-\u003eflags))\n+\t\treturn -EINVAL;\n+\n+\t/* Each iteration through this loop waits until rpc needs attention\n+\t * in some way (e.g. packets have arrived), then deals with that need\n+\t * (e.g. copy to user space). It may take many iterations until the\n+\t * RPC is ready for the application.\n+\t */\n+\twhile (1) {\n+\t\tresult = 0;\n+\t\tif (!rpc-\u003eerror)\n+\t\t\trpc-\u003eerror = homa_copy_to_user(rpc);\n+\t\tif (rpc-\u003eerror)\n+\t\t\tbreak;\n+\t\tif (rpc-\u003emsgin.length \u003e= 0 \u0026\u0026\n+\t\t    rpc-\u003emsgin.bytes_remaining == 0 \u0026\u0026\n+\t\t    skb_queue_len(\u0026rpc-\u003emsgin.packets) == 0)\n+\t\t\tbreak;\n+\n+\t\tif (nonblocking) {\n+\t\t\tresult = -EAGAIN;\n+\t\t\tbreak;\n+\t\t}\n+\n+\t\tresult = homa_interest_init_private(\u0026interest, rpc);\n+\t\tif (result != 0)\n+\t\t\tbreak;\n+\n+\t\thoma_rpc_unlock(rpc);\n+\t\tresult = homa_interest_wait(\u0026interest);\n+\n+\t\thoma_rpc_lock_preempt(rpc);\n+\t\thoma_interest_unlink_private(\u0026interest);\n+\t\tif (result != 0)\n+\t\t\tbreak;\n+\t}\n+\n+\treturn result;\n+}\n+\n+/**\n+ * homa_wait_shared() - Wait for the completion of any non-private\n+ * incoming message on a socket.\n+ * @hsk:          Socket on which to wait. Must not be locked.\n+ * @nonblocking:  Nonzero means return immediately if no RPC is ready.\n+ *\n+ * Return:    Pointer to an RPC with a complete incoming message or nonzero\n+ *            error field, or a negative errno (usually -EINTR). If an RPC\n+ *            is returned it will be locked and referenced; the caller\n+ *            must release the lock and the reference.\n+ */\n+struct homa_rpc *homa_wait_shared(struct homa_sock *hsk, int nonblocking)\n+\t__cond_acquires(nonnull, rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_interest interest;\n+\tstruct homa_rpc *rpc;\n+\tint result;\n+\n+\t/* Each iteration through this loop waits until an RPC needs attention\n+\t * in some way (e.g. packets have arrived), then deals with that need\n+\t * (e.g. copy to user space). It may take many iterations until an\n+\t * RPC is ready for the application.\n+\t */\n+\twhile (1) {\n+\t\thoma_sock_lock(hsk);\n+\t\tif (hsk-\u003eshutdown) {\n+\t\t\trpc = ERR_PTR(-ESHUTDOWN);\n+\t\t\thoma_sock_unlock(hsk);\n+\t\t\tgoto done;\n+\t\t}\n+\t\tif (!list_empty(\u0026hsk-\u003eready_rpcs)) {\n+\t\t\trpc = list_first_entry(\u0026hsk-\u003eready_rpcs,\n+\t\t\t\t\t       struct homa_rpc,\n+\t\t\t\t\t       ready_links);\n+\t\t\thoma_rpc_hold(rpc);\n+\t\t\tlist_del_init(\u0026rpc-\u003eready_links);\n+\t\t\tif (!list_empty(\u0026hsk-\u003eready_rpcs)) {\n+\t\t\t\t/* There are still more RPCs available, so\n+\t\t\t\t * let Linux know.\n+\t\t\t\t */\n+\t\t\t\thsk-\u003esock.sk_data_ready(\u0026hsk-\u003esock);\n+\t\t\t}\n+\t\t\thoma_sock_unlock(hsk);\n+\t\t} else if (nonblocking) {\n+\t\t\trpc = ERR_PTR(-EAGAIN);\n+\t\t\thoma_sock_unlock(hsk);\n+\n+\t\t\t/* This is a good time to cleanup dead RPCS. */\n+\t\t\thoma_rpc_reap(hsk);\n+\t\t\tgoto done;\n+\t\t} else {\n+\t\t\thoma_interest_init_shared(\u0026interest, hsk);\n+\t\t\thoma_sock_unlock(hsk);\n+\t\t\tresult = homa_interest_wait(\u0026interest);\n+\n+\t\t\tif (result != 0) {\n+\t\t\t\trpc = ERR_PTR(result);\n+\t\t\t\tgoto done;\n+\t\t\t}\n+\n+\t\t\trpc = interest.rpc;\n+\t\t\tif (!rpc) {\n+\t\t\t\trpc = ERR_PTR(-ESHUTDOWN);\n+\t\t\t\tgoto done;\n+\t\t\t}\n+\t\t}\n+\n+\t\thoma_rpc_lock_preempt(rpc);\n+\t\tif (!rpc-\u003eerror)\n+\t\t\trpc-\u003eerror = homa_copy_to_user(rpc);\n+\t\tif (rpc-\u003eerror) {\n+\t\t\tif (rpc-\u003estate != RPC_DEAD)\n+\t\t\t\tbreak;\n+\t\t} else if (rpc-\u003emsgin.bytes_remaining == 0 \u0026\u0026\n+\t\t    skb_queue_len(\u0026rpc-\u003emsgin.packets) == 0)\n+\t\t\tbreak;\n+\t\thoma_rpc_put(rpc);\n+\t\thoma_rpc_unlock(rpc);\n+\t}\n+\n+done:\n+\treturn rpc;\n+}\n+\n+/**\n+ * homa_rpc_handoff() - This function is called when the input message for\n+ * an RPC is ready for attention from a user thread. It notifies a waiting\n+ * reader and/or queues the RPC, as appropriate.\n+ * @rpc:                RPC to handoff; must be locked.\n+ */\n+void homa_rpc_handoff(struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_sock *hsk = rpc-\u003ehsk;\n+\n+\tif (rpc-\u003estate == RPC_DEAD)\n+\t\treturn;\n+\n+\tif (test_bit(RPC_PRIVATE, \u0026rpc-\u003eflags)) {\n+\t\thoma_interest_notify_private(rpc);\n+\t\treturn;\n+\t}\n+\n+\t/* Shared RPC; if there is a waiting thread, hand off the RPC;\n+\t * otherwise enqueue it.\n+\t */\n+\thoma_sock_lock(hsk);\n+\tif (hsk-\u003eshutdown) {\n+\t\thoma_sock_unlock(hsk);\n+\t\treturn;\n+\t}\n+\tif (!list_empty(\u0026hsk-\u003einterests)) {\n+\t\thoma_rpc_hold(rpc);\n+\t\thoma_interest_notify_shared(hsk, rpc);\n+\t} else if (list_empty(\u0026rpc-\u003eready_links)) {\n+\t\tlist_add_tail(\u0026rpc-\u003eready_links, \u0026hsk-\u003eready_rpcs);\n+\t\thsk-\u003esock.sk_data_ready(\u0026hsk-\u003esock);\n+\t}\n+\thoma_sock_unlock(hsk);\n+}\ndiff --git a/net/homa/homa_interest.c b/net/homa/homa_interest.c\nnew file mode 100644\nindex 0000000000000..66ea429aac274\n--- /dev/null\n+++ b/net/homa/homa_interest.c\n@@ -0,0 +1,192 @@\n+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+\n+/* This file contains functions for managing homa_interest structs. */\n+\n+#include \"homa_impl.h\"\n+#include \"homa_interest.h\"\n+#include \"homa_rpc.h\"\n+#include \"homa_sock.h\"\n+\n+/* DESIGN NOTES:\n+ * The key idea behind the design of the interest mechanism is to reduce usage\n+ * of socket locks while handing off ready RPCs to application threads. Private\n+ * handoffs do not require the socket lock to be acquired at all. Shared\n+ * handoffs must acquire the socket lock to select one thread from a pool of\n+ * waiting threads. But in the normal case the thread receiving the ready RPC\n+ * does not need to acquire the socket lock again after the RPC has been\n+ * handed off to it. The HOMA_INTEREST_HANDOFF_ACTIVE mechanism eliminates\n+ * races that would otherwise be present in the absence of locking.\n+ */\n+\n+/**\n+ * homa_interest_init_shared() - Initialize an interest and queue it up on\n+ * a socket.\n+ * @interest:  Interest to initialize\n+ * @hsk:       Socket on which the interests should be queued. Must be locked\n+ *             by caller.\n+ */\n+void homa_interest_init_shared(struct homa_interest *interest,\n+\t\t\t       struct homa_sock *hsk)\n+\t__must_hold(hsk-\u003elock)\n+{\n+\tinterest-\u003erpc = NULL;\n+\tatomic_set(\u0026interest-\u003estate, 0);\n+\tinterest-\u003eblocked = 0;\n+\tinit_waitqueue_head(\u0026interest-\u003ewait_queue);\n+\tinterest-\u003ehsk = hsk;\n+\tlist_add(\u0026interest-\u003elinks, \u0026hsk-\u003einterests);\n+}\n+\n+/**\n+ * homa_interest_init_private() - Initialize an interest that will wait\n+ * on a particular (private) RPC, and link it to that RPC.\n+ * @interest:   Interest to initialize.\n+ * @rpc:        RPC to associate with the interest. Must be private, and\n+ *              caller must have locked it.\n+ *\n+ * Return:      0 for success, otherwise a negative errno.\n+ */\n+int homa_interest_init_private(struct homa_interest *interest,\n+\t\t\t       struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tif (rpc-\u003eprivate_interest)\n+\t\treturn -EINVAL;\n+\n+\tinterest-\u003erpc = rpc;\n+\tatomic_set(\u0026interest-\u003estate, 0);\n+\tinterest-\u003eblocked = 0;\n+\tinit_waitqueue_head(\u0026interest-\u003ewait_queue);\n+\tinterest-\u003ehsk = rpc-\u003ehsk;\n+\tINIT_LIST_HEAD(\u0026interest-\u003elinks);\n+\trpc-\u003eprivate_interest = interest;\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_interest_wait() - Wait for an interest to have an actionable RPC,\n+ * or for an error to occur.\n+ * @interest:     Interest to wait for; must previously have been initialized\n+ *                and linked to a socket or RPC. On return, the interest\n+ *                will have been unlinked if it is shared and its ready flag\n+ *                is set; otherwise it may still be linked.\n+ *\n+ * Return: 0 for success (the ready flag is set in the interest), or -EINTR\n+ * if the thread received an interrupt. When this function returns, the\n+ * interest will no longer be linked to a socket (if it ever was).\n+ */\n+int homa_interest_wait(struct homa_interest *interest)\n+{\n+\tstruct homa_sock *hsk = interest-\u003ehsk;\n+\tint result = 0;\n+\tint iteration;\n+\tint wait_err;\n+\n+\tinterest-\u003eblocked = 0;\n+\n+\t/* This loop iterates in order to poll and/or reap dead RPCS. */\n+\tfor (iteration = 0; ; iteration++) {\n+\t\tif (iteration != 0)\n+\t\t\t/* Give NAPI/SoftIRQ tasks a chance to run. */\n+\t\t\tschedule();\n+\n+\t\tif (atomic_read_acquire(\u0026interest-\u003estate) \u0026 HOMA_INTEREST_READY)\n+\t\t\tgoto done;\n+\n+\t\tif (signal_pending(current)) {\n+\t\t\twait_err = -ERESTARTSYS;\n+\t\t\tgoto check_err;\n+\t\t}\n+\n+\t\t/* See if we can cleanup dead RPCs while waiting. */\n+\t\tif (homa_rpc_reap(hsk) != 0)\n+\t\t\tcontinue;\n+\n+\t\tbreak;\n+\t}\n+\n+\tinterest-\u003eblocked = 1;\n+\twait_err = wait_event_interruptible_exclusive(interest-\u003ewait_queue,\n+\t\t\t\t\t\t      atomic_read_acquire(\u0026interest-\u003estate) \u0026\n+\t\t\t\t\t\t      HOMA_INTEREST_READY);\n+\n+check_err:\n+\tif (wait_err == -ERESTARTSYS) {\n+\t\tint ready;\n+\n+\t\t/* An interrupt occurred. We have to do two things.  First,\n+\t\t * unlink the interest from the socket (if it was linked).\n+\t\t * Second, check to see if in the meantime the interest\n+\t\t * received a handoff. If so, ignore the interrupt. Must hold\n+\t\t * the socket lock while checking, in order to eliminate races\n+\t\t * with homa_rpc_handoff. Technically these are only needed\n+\t\t * for shared interests, but it's harmless to do them for\n+\t\t * private interests as well.\n+\t\t */\n+\t\thoma_sock_lock(hsk);\n+\t\tlist_del_init(\u0026interest-\u003elinks);\n+\t\tready = atomic_read_acquire(\u0026interest-\u003estate) \u0026\n+\t\t\tHOMA_INTEREST_READY;\n+\t\thoma_sock_unlock(hsk);\n+\t\tif (ready == 0)\n+\t\t\tresult = -EINTR;\n+\t}\n+\n+done:\n+\t/* Make sure that the handing off thread has completely finished\n+\t * accessing the interest, so that it's safe for our caller to\n+\t * reuse the interest's memory.\n+\t */\n+\twhile (atomic_read(\u0026interest-\u003estate) \u0026 HOMA_INTEREST_HANDOFF_ACTIVE)\n+\t\tcpu_relax();\n+\treturn result;\n+}\n+\n+/**\n+ * homa_interest_notify_private() - If a thread is waiting on the private\n+ * interest for an RPC, wake it up.\n+ * @rpc:      RPC that may (potentially) have a private interest. Must be\n+ *            locked by the caller.\n+ */\n+void homa_interest_notify_private(struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tif (rpc-\u003eprivate_interest) {\n+\t\t/* See comment in homa_interest_notify_shared. */\n+\t\tatomic_set_release(\u0026rpc-\u003eprivate_interest-\u003estate,\n+\t\t\t\t   HOMA_INTEREST_READY |\n+\t\t\t\t   HOMA_INTEREST_HANDOFF_ACTIVE);\n+\t\twake_up(\u0026rpc-\u003eprivate_interest-\u003ewait_queue);\n+\t\tatomic_set_release(\u0026rpc-\u003eprivate_interest-\u003estate,\n+\t\t\t\t   HOMA_INTEREST_READY);\n+\t}\n+}\n+\n+/**\n+ * homa_interest_notify_shared() - Hand an RPC off to one of the interests\n+ * available for a socket.\n+ * @hsk:      Socket for the handoff; must have at least one interest.\n+ *            Must be locked by caller.\n+ * @rpc:      RPC to handoff; can be NULL to indicate that the socket\n+ *            has been shutdown. Caller must have taken a reference.\n+ */\n+void homa_interest_notify_shared(struct homa_sock *hsk, struct homa_rpc *rpc)\n+\t__must_hold(hsk-\u003elock)\n+{\n+\tstruct homa_interest *interest;\n+\n+\tinterest = list_first_entry(\u0026hsk-\u003einterests,\n+\t\t\t\t    struct homa_interest, links);\n+\tlist_del_init(\u0026interest-\u003elinks);\n+\tinterest-\u003erpc = rpc;\n+\n+\t/* The dance below eliminates two race conditions: (a) a waking up\n+\t * thread doesn't see the change to state and (b) a waking up thread\n+\t * recycles the memory of the interest before we have finished\n+\t * accessing it in wake_up.\n+\t */\n+\tatomic_set_release(\u0026interest-\u003estate,\n+\t\t\t   HOMA_INTEREST_READY | HOMA_INTEREST_HANDOFF_ACTIVE);\n+\twake_up(\u0026interest-\u003ewait_queue);\n+\tatomic_set_release(\u0026interest-\u003estate, HOMA_INTEREST_READY);\n+}\ndiff --git a/net/homa/homa_interest.h b/net/homa/homa_interest.h\nnew file mode 100644\nindex 0000000000000..cb0b3f0d4f183\n--- /dev/null\n+++ b/net/homa/homa_interest.h\n@@ -0,0 +1,92 @@\n+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */\n+\n+/* This file defines struct homa_interest and related functions.  */\n+\n+#ifndef _HOMA_INTEREST_H\n+#define _HOMA_INTEREST_H\n+\n+#include \"homa_rpc.h\"\n+#include \"homa_sock.h\"\n+\n+/**\n+ * struct homa_interest - Holds info that allows applications to wait for\n+ * incoming RPC messages. An interest can be either private, in which case\n+ * the application is waiting for a single specific RPC response and the\n+ * interest is referenced by an rpc-\u003eprivate_interest, or shared, in which\n+ * case the application is waiting for any incoming message that isn't\n+ * private and the interest is present on hsk-\u003einterests.\n+ */\n+struct homa_interest {\n+\t/**\n+\t * @rpc: If ready is set, then this holds an RPC that needs\n+\t * attention, or NULL if this is a shared interest and hsk has\n+\t * been shutdown. If ready is not set, this will be NULL if the\n+\t * interest is shared; if it's private, it holds the RPC the\n+\t * interest is associated with. If non-NULL, a reference has been\n+\t * taken on the RPC.\n+\t */\n+\tstruct homa_rpc *rpc;\n+\n+\t/**\n+\t * @state: Used to manage the process of handing off an RPC.  Consists\n+\t * of the following bits:\n+\t * HOMA_INTEREST_READY:\n+\t *     Nonzero means the interest is ready for attention: either there\n+\t *     is an RPC that needs attention or @hsk has been shutdown.\n+\t * HOMA_INTEREST_HANDOFF_ACTIVE:\n+\t *     Nonzero means a handing-off thread is still accessing the\n+\t *     interest. Used to ensure that the handing-off thread is\n+\t *     completely finished before homa_interest_wait returns (so\n+\t *     that the interest can safely be deleted).\n+\t */\n+#define HOMA_INTEREST_READY           1\n+#define HOMA_INTEREST_HANDOFF_ACTIVE  2\n+\tatomic_t state;\n+\n+\t/**\n+\t * @blocked: Zero means a handoff was received without the thread\n+\t * needing to block; nonzero means the thread blocked.\n+\t */\n+\tint blocked;\n+\n+\t/**\n+\t * @wait_queue: Used to block the thread while waiting (will never\n+\t * have more than one queued thread).\n+\t */\n+\tstruct wait_queue_head wait_queue;\n+\n+\t/** @hsk: Socket that the interest is associated with. */\n+\tstruct homa_sock *hsk;\n+\n+\t/**\n+\t * @links: If the interest is shared, used to link this object into\n+\t * @hsk-\u003einterests.\n+\t */\n+\tstruct list_head links;\n+};\n+\n+/**\n+ * homa_interest_unlink_private() - Detach a private interest from its\n+ * RPC. Note: this can race with homa_rpc_handoff, so on return it's\n+ * possible that the interest is ready.\n+ * @interest:    Interest to remove. Must have been initialized with\n+ *               homa_interest_init_private. Its RPC must be locked by\n+ *               the caller.\n+ */\n+static inline void homa_interest_unlink_private(struct homa_interest *interest)\n+\t__must_hold(interest-\u003erpc-\u003ebucket-\u003elock)\n+{\n+\tif (interest == interest-\u003erpc-\u003eprivate_interest)\n+\t\tinterest-\u003erpc-\u003eprivate_interest = NULL;\n+}\n+\n+void     homa_interest_init_shared(struct homa_interest *interest,\n+\t\t\t\t   struct homa_sock *hsk);\n+int      homa_interest_init_private(struct homa_interest *interest,\n+\t\t\t\t    struct homa_rpc *rpc);\n+void     homa_interest_notify_private(struct homa_rpc *rpc);\n+void     homa_interest_notify_shared(struct homa_sock *hsk,\n+\t\t\t\t     struct homa_rpc *rpc);\n+int      homa_interest_wait(struct homa_interest *interest);\n+\n+#endif /* _HOMA_INTEREST_H */\ndiff --git a/net/homa/homa_outgoing.c b/net/homa/homa_outgoing.c\nnew file mode 100644\nindex 0000000000000..afc7c034d1453\n--- /dev/null\n+++ b/net/homa/homa_outgoing.c\n@@ -0,0 +1,537 @@\n+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+\n+/* This file contains functions related to the sender side of message\n+ * transmission. It also contains utility functions for sending packets.\n+ */\n+\n+#include \"homa_impl.h\"\n+#include \"homa_peer.h\"\n+#include \"homa_rpc.h\"\n+#include \"homa_tx_pool.h\"\n+#include \"homa_wire.h\"\n+\n+/**\n+ * homa_message_out_init() - Initialize rpc-\u003emsgout. This function doesn't\n+ * read data from user space or create sk_buffs, but it sets up information\n+ * such as the message geometry.\n+ * @rpc:       RPC whose output message should be initialized. Must be\n+ *             locked by caller. Fields in rpc-\u003emsgout should have been\n+ *             zeroed by the caller.\n+ * @length:    Number of bytes that will eventually be in rpc-\u003emsgout.\n+ */\n+void homa_message_out_init(struct homa_rpc *rpc, int length)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct dst_entry *dst;\n+\tu64 max_segs;\n+\tint mtu;\n+\n+\tmemset(\u0026rpc-\u003emsgout, 0, sizeof(rpc-\u003emsgout));\n+\trpc-\u003emsgout.length = length;\n+\trpc-\u003emsgout.init_time = homa_clock();\n+\n+\t/* Compute the geometry of packets. */\n+\trcu_read_lock();\n+\tdst = rcu_dereference(rpc-\u003eroute-\u003edst);\n+\tmtu = dst_mtu(dst);\n+\trpc-\u003emsgout.max_seg_data = mtu - rpc-\u003ehsk-\u003eip_header_length -\n+\t\t\t\t   sizeof(struct homa_data_hdr);\n+\tmax_segs = min_t(u32, rpc-\u003ehsk-\u003ehoma-\u003emax_gso_size,\n+\t\t\t dst-\u003edev-\u003egso_max_size) -\n+\t\t   (sizeof(struct homa_data_hdr) + HOMA_SKB_EXTRA);\n+\tdo_div(max_segs, rpc-\u003emsgout.max_seg_data +\n+\t\t\t sizeof(struct homa_seg_hdr));\n+\tif (max_segs \u003e dst-\u003edev-\u003egso_max_segs)\n+\t\tmax_segs = dst-\u003edev-\u003egso_max_segs;\n+\tif (max_segs \u003c 1)\n+\t\tmax_segs = 1;\n+\trpc-\u003emsgout.max_gso_segs = max_segs;\n+\trpc-\u003emsgout.max_gso_data = max_segs * rpc-\u003emsgout.max_seg_data;\n+\trcu_read_unlock();\n+}\n+\n+/**\n+ * homa_tx_copy_from_user() - Copy outbound message data for an RPC from\n+ * user space into kernel memory and (possibly) start transmitting packets.\n+ * @rpc:      RPC whose tx message is to be copied.\n+ * @iter:     Describes the location in user space of the message\n+ *            data.\n+ * @xmit:     True means this function should also start transmitting packets.\n+ *            False means only copy data; don't transmit packets.\n+ * Return:    Zero for success, otherwise a negative errno.\n+ */\n+int homa_tx_copy_from_user(struct homa_rpc *rpc, struct iov_iter *iter,\n+\t\t\t   bool xmit)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_frag_filler filler;\n+\tint err, hdr_space;\n+\tu64 num_segs;\n+\tint offset;\n+\n+\thoma_message_out_init(rpc, iter-\u003ecount);\n+\n+\t/* Allocate kernel memory to hold the message data (note that we\n+\t * need to allocate extra space for homa_seg_hdrs).\n+\t */\n+\tnum_segs = rpc-\u003emsgout.length + rpc-\u003emsgout.max_seg_data - 1;\n+\tdo_div(num_segs, rpc-\u003emsgout.max_seg_data);\n+\thdr_space = num_segs * sizeof(struct homa_seg_hdr);\n+\trpc-\u003emsgout.frags = \u0026rpc-\u003emsgout.frag;\n+\trpc-\u003emsgout.num_frags = 1;\n+\terr = homa_tx_pool_alloc(rpc-\u003ehsk-\u003ehoma, rpc-\u003emsgout.length + hdr_space,\n+\t\t\t\t \u0026rpc-\u003emsgout.num_frags, \u0026rpc-\u003emsgout.frags);\n+\tif (err != 0)\n+\t\treturn err;\n+\trpc-\u003emsgout.frag_bytes = rpc-\u003emsgout.length + hdr_space;\n+\trefcount_add(rpc-\u003emsgout.frag_bytes, \u0026rpc-\u003ehsk-\u003esock.sk_wmem_alloc);\n+\n+\t/* Copy the data in from user space, preceding each segment of data\n+\t * with its homa_seg_hdr.\n+\t */\n+\thoma_rpc_unlock(rpc);\n+\thoma_frag_filler_init(\u0026filler, rpc-\u003emsgout.num_frags,\n+\t\t\t      rpc-\u003emsgout.frags);\n+\toffset = 0;\n+\twhile (offset \u003c rpc-\u003emsgout.length) {\n+\t\tint seg_size = min(rpc-\u003emsgout.length - offset,\n+\t\t\t\t   rpc-\u003emsgout.max_seg_data);\n+\t\tstruct homa_seg_hdr seg_hdr;\n+\n+\t\tseg_hdr.offset = htonl(offset);\n+\t\terr = homa_copy_to_frags(\u0026filler, \u0026seg_hdr, sizeof(seg_hdr));\n+\t\tif (unlikely(err != 0))\n+\t\t\tgoto done;\n+\t\terr = homa_copy_iter_to_frags(\u0026filler, iter, seg_size);\n+\t\tif (unlikely(err != 0))\n+\t\t\tgoto done;\n+\t\toffset += seg_size;\n+\n+\t\t/* Make sure that anyone seeing a change in copied_from_user\n+\t\t * also sees related changes to rpc-\u003emsgout.\n+\t\t */\n+\t\tsmp_store_release(\u0026rpc-\u003emsgout.copied_from_user, offset);\n+\t}\n+\n+done:\n+\thoma_rpc_lock(rpc);\n+\tif (xmit \u0026\u0026 err == 0)\n+\t\thoma_xmit_data(rpc);\n+\treturn err;\n+}\n+\n+/**\n+ * __homa_skb_alloc() - Allocate a new (empty) sk_buff for use in transmitting\n+ * data or control info.\n+ * @length:       Number of bytes of data that the caller would like to\n+ *                have available in the linear part of the sk_buff for\n+ *                the Homa header and additional data beyond that. This\n+ *                function will allocate additional space for IP and\n+ *                Ethernet headers, as well as for the homa_skb_info.\n+ * Return:        New sk_buff, or NULL if there was insufficient memory.\n+ *                The sk_buff will be configured so that the next\n+ *                skb_put will be for the transport (Homa) header. The\n+ *                homa_skb_info is not initialized.\n+ */\n+struct sk_buff *__homa_skb_alloc(int length)\n+{\n+\tstruct sk_buff *skb;\n+\n+\tskb = alloc_skb(HOMA_SKB_EXTRA + sizeof(struct homa_skb_info) + length,\n+\t\t\tGFP_ATOMIC);\n+\tif (likely(skb)) {\n+\t\tskb_reserve(skb, HOMA_SKB_EXTRA);\n+\t\tskb_reset_transport_header(skb);\n+\t}\n+\treturn skb;\n+}\n+\n+/**\n+ * homa_tx_skb_alloc() - Create an outgoing data packet for a Homa message.\n+ * @rpc:      RPC for the message. Its @msgout must have been initialized\n+ *            (e.g. the packet geometry will be determined by information\n+ *            in @rpc-\u003emsgout).\n+ * @offset:   Offset within the message of the first byte of data for\n+ *            this packet.\n+ * @end:      Offset within the message of the byte just after the last\n+ *            one to include in this packet. The skb may actually end either\n+ *            before or after this offset; this value is modified to hold\n+ *            the actual end.\n+ * Return:    A pointer to the sk_buff, or a negative errno for error.\n+ */\n+struct sk_buff *homa_tx_skb_alloc(struct homa_rpc *rpc, u32 offset, u32 *end)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tint msg_frags_left, bytes_left, bytes_to_skip, rem;\n+\tstruct homa_sock *hsk = rpc-\u003ehsk;\n+\tstruct homa_skb_info *homa_info;\n+\tskb_frag_t *msg_frag, *skb_frag;\n+\tstruct skb_shared_info *shinfo;\n+\tu64 seg_index, num_segs;\n+\tstruct homa_data_hdr *h;\n+\tstruct sk_buff *skb;\n+\tint err;\n+\n+\tif (offset \u003e= rpc-\u003emsgout.length)\n+\t\treturn ERR_PTR(-EINVAL);\n+\tif (*end \u003e rpc-\u003emsgout.length)\n+\t\t*end = rpc-\u003emsgout.length;\n+\n+\t/* Find the location within rpc-\u003emsgin.frags of the data for the\n+\t * first segment to output (skipping its homa_seg_hdr, since that\n+\t * will be in the linear part of the skb). Also, round offset down\n+\t * to the start of its segment.\n+\t */\n+\tseg_index = offset;\n+\trem = do_div(seg_index, rpc-\u003emsgout.max_seg_data);\n+\toffset -= rem;\n+\tbytes_to_skip = seg_index * (rpc-\u003emsgout.max_seg_data +\n+\t\t\t\t     sizeof(struct homa_seg_hdr)) +\n+\t\t\tsizeof(struct homa_seg_hdr);\n+\tfor (msg_frags_left = rpc-\u003emsgout.num_frags,\n+\t     msg_frag = rpc-\u003emsgout.frags; ; msg_frags_left--, msg_frag++) {\n+\t\tif (bytes_to_skip \u003c skb_frag_size(msg_frag))\n+\t\t\tbreak;\n+\t\tbytes_to_skip -= skb_frag_size(msg_frag);\n+\t}\n+\n+\t/* Compute how much data from rpc-\u003emsgout.frags to include in the\n+\t * packet.\n+\t */\n+\tnum_segs = *end - offset + rpc-\u003emsgout.max_seg_data - 1;\n+\tdo_div(num_segs, rpc-\u003emsgout.max_seg_data);\n+\tif (num_segs \u003e rpc-\u003emsgout.max_gso_segs)\n+\t\tnum_segs = rpc-\u003emsgout.max_gso_segs;\n+\tbytes_left = num_segs * (rpc-\u003emsgout.max_seg_data +\n+\t\t\t\t sizeof(struct homa_seg_hdr)) -\n+\t\t     sizeof(struct homa_seg_hdr);\n+\n+\tskb = __homa_skb_alloc(sizeof(struct homa_data_hdr));\n+\tif (unlikely(!skb))\n+\t\treturn ERR_PTR(-ENOMEM);\n+\tskb-\u003eooo_okay = 1;\n+\tshinfo = skb_shinfo(skb);\n+\n+\t/* Fill in the Homa header (which will be replicated in every\n+\t * segment by GSO). The header in the linear portion contains the\n+\t * homa_seg_hdr for the first fragment.\n+\t */\n+\th = (struct homa_data_hdr *)skb_put(skb, sizeof(struct homa_data_hdr));\n+\tmemset(h, 0, sizeof(*h));\n+\th-\u003ecommon.sport = htons(hsk-\u003eport);\n+\th-\u003ecommon.dport = htons(rpc-\u003edport);\n+\th-\u003ecommon.type = DATA;\n+\thoma_set_doff(skb, sizeof(struct homa_data_hdr) -\n+\t\t\t   sizeof(struct homa_seg_hdr));\n+\th-\u003ecommon.sender_id = cpu_to_be64(rpc-\u003eid);\n+\th-\u003emessage_length = htonl(rpc-\u003emsgout.length);\n+\thoma_peer_get_acks(rpc-\u003eroute-\u003epeer, 1, \u0026h-\u003eack);\n+\tif (offset \u003c rpc-\u003emsgout.next_xmit_offset)\n+\t\th-\u003eretransmit = 1;\n+\th-\u003eseg.offset = htonl(offset);\n+\n+\t/* Virtually copy data from rpc-\u003emsgout.frags to the skb; each\n+\t * iteration of the following loop copies one frag.\n+\t */\n+\twhile (bytes_left \u003e 0 \u0026\u0026 shinfo-\u003enr_frags \u003c MAX_SKB_FRAGS \u0026\u0026\n+\t       msg_frags_left \u003e 0) {\n+\t\tskb_frag_t *skb_frag = \u0026shinfo-\u003efrags[shinfo-\u003enr_frags];\n+\t\tstruct page *page;\n+\t\tint frag_bytes;\n+\n+\t\tfrag_bytes = min(skb_frag_size(msg_frag) - bytes_to_skip,\n+\t\t\t\t bytes_left);\n+\t\tpage = skb_frag_page(msg_frag);\n+\t\tget_page(page);\n+\t\tskb_frag-\u003enetmem = page_to_netmem(page);\n+\t\tskb_frag-\u003eoffset = msg_frag-\u003eoffset + bytes_to_skip;\n+\t\tskb_frag_size_set(skb_frag, frag_bytes);\n+\t\tskb_len_add(skb, frag_bytes);\n+\n+\t\tbytes_left -= frag_bytes;\n+\t\tbytes_to_skip = 0;\n+\t\tmsg_frag++;\n+\t\tmsg_frags_left--;\n+\t\tshinfo-\u003enr_frags++;\n+\t}\n+\n+\tif (bytes_left \u003e 0 \u0026\u0026 msg_frags_left \u003e 0 \u0026\u0026\n+\t    shinfo-\u003enr_frags \u003e= MAX_SKB_FRAGS) {\n+\t\t/* There wasn't enough fragment space in skb to store all the\n+\t\t * desired segments. Round the skb back to the nearest segment\n+\t\t * boundary.\n+\t\t */\n+\t\twhile (bytes_left \u003e 0) {\n+\t\t\tbytes_left -= rpc-\u003emsgout.max_seg_data +\n+\t\t\t\t      sizeof(struct homa_seg_hdr);\n+\t\t\tnum_segs--;\n+\t\t}\n+\t\tif (num_segs == 0) {\n+\t\t\terr = -EINVAL;\n+\t\t\tgoto error;\n+\t\t}\n+\t\twhile (bytes_left \u003c 0) {\n+\t\t\tskb_frag = \u0026shinfo-\u003efrags[shinfo-\u003enr_frags - 1];\n+\t\t\tif (-bytes_left \u003c skb_frag_size(skb_frag)) {\n+\t\t\t\tskb_frag_size_sub(skb_frag, -bytes_left);\n+\t\t\t\tskb_len_add(skb, bytes_left);\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tbytes_left += skb_frag_size(skb_frag);\n+\t\t\tskb_len_add(skb, -skb_frag_size(skb_frag));\n+\t\t\tput_page(skb_frag_page(skb_frag));\n+\t\t\tshinfo-\u003enr_frags--;\n+\t\t}\n+\t}\n+\t*end = min_t(u32, offset + num_segs * rpc-\u003emsgout.max_seg_data,\n+\t\t     rpc-\u003emsgout.length);\n+\n+\t/* Fill in fields in shinfo. */\n+\tif (num_segs \u003e 1) {\n+\t\tshinfo-\u003egso_segs = num_segs;\n+\t\tshinfo-\u003egso_size = rpc-\u003emsgout.max_seg_data +\n+\t\t\t\t   sizeof(struct homa_seg_hdr);\n+\t\tshinfo-\u003egso_type = (hsk-\u003einet.sk.sk_family ==\n+\t\t\t\t    AF_INET6) ? SKB_GSO_TCPV6 :\n+\t\t\t\t    SKB_GSO_TCPV4;\n+\t}\n+\n+\t/* Initialize homa_skb_info for the packet. */\n+\thoma_info = homa_get_skb_info(skb);\n+\tmemset(homa_info, 0, sizeof(*homa_info));\n+\thoma_info-\u003edata_bytes = *end - offset;\n+\thoma_info-\u003edont_defer = false;\n+\treturn skb;\n+\n+error:\n+\tkfree_skb_reason(skb, SKB_DROP_REASON_NOT_SPECIFIED);\n+\treturn ERR_PTR(err);\n+}\n+\n+/**\n+ * homa_tx_skb_send() - Create and send one (GSO) data packet for an RPC. The\n+ * dimensions of the packet transmitted may change from those specified\n+ * in the argument depending on factors such as availability of GSO,\n+ * MTU, etc.\n+ * @rpc:         RPC for which to send the packet. This function releases\n+ *               and then re-requires rpc's lock, so the RPC could be\n+ *               dead when this function returns.\n+ * @offset:      The packet must contain this offset.\n+ * @end:         Offset of the message byte just after the last one\n+ *               the caller would like included in the packet. Modified\n+ *               to hold the offset just after the last byte actually\n+ *               included in the packet.\n+ * Return:       0 for success, otherwise a negative errno.\n+ */\n+int homa_tx_skb_send(struct homa_rpc *rpc, u32 offset, u32 *end)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_route *route;\n+\tstruct sk_buff *skb;\n+\tint err;\n+\n+\tskb = homa_tx_skb_alloc(rpc, offset, end);\n+\tif (IS_ERR(skb))\n+\t\treturn PTR_ERR(skb);\n+\n+\t/* Note: must update next_xmit_offset here, before releasing the\n+\t * RPC lock below; otherwise some other thread might decide to\n+\t * transmit the same bytes.\n+\t */\n+\tif (*end \u003e rpc-\u003emsgout.next_xmit_offset)\n+\t\trpc-\u003emsgout.next_xmit_offset = *end;\n+\n+\terr = homa_route_validate(rpc);\n+\tif (err != 0) {\n+\t\tkfree_skb_reason(skb, SKB_DROP_REASON_IP_OUTNOROUTES);\n+\t\treturn err;\n+\t}\n+\troute = rpc-\u003eroute;\n+\n+\t/* Take a reference on the route so we can safely use it even after\n+\t * the RPC lock has been released (rpc-\u003eroute may change, but not\n+\t * route).\n+\t */\n+\thoma_route_hold(route);\n+\thoma_rpc_unlock(rpc);\n+\terr = homa_route_xmit(skb, rpc-\u003ehsk, route, 0);\n+\thoma_route_release(route);\n+\thoma_rpc_lock(rpc);\n+\treturn err;\n+}\n+\n+/**\n+ * homa_xmit_control() - Send a control packet to the other end of an RPC.\n+ * @type:      Packet type, such as DATA.\n+ * @contents:  Address of buffer containing the contents of the packet.\n+ *             Only information after the common header must be valid;\n+ *             the common header will be filled in by this function.\n+ * @length:    Length of @contents (including the common header).\n+ * @rpc:       The packet will go to the socket that handles the other end\n+ *             of this RPC. Addressing info for the packet, including all of\n+ *             the fields of homa_common_hdr except type, will be set from this.\n+ *\n+ * Return:     Either zero (for success), or a negative errno value if there\n+ *             was a problem.\n+ */\n+int homa_xmit_control(enum homa_packet_type type, void *contents,\n+\t\t      size_t length, struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_common_hdr *h = contents;\n+\tstruct homa_route *route;\n+\tint err;\n+\n+\tmemset(h, 0, sizeof(*h));\n+\th-\u003etype = type;\n+\th-\u003esport = htons(rpc-\u003ehsk-\u003eport);\n+\th-\u003edport = htons(rpc-\u003edport);\n+\th-\u003esender_id = cpu_to_be64(rpc-\u003eid);\n+\terr = homa_route_validate(rpc);\n+\tif (err != 0)\n+\t\treturn err;\n+\troute = rpc-\u003eroute;\n+\n+\t/* Must take a reference on route to ensure it persists through\n+\t * packet transmission (rpc-\u003eroute could get replaced once we\n+\t * release the RPC lock).\n+\t */\n+\thoma_route_hold(route);\n+\thoma_rpc_unlock(rpc);\n+\terr = __homa_xmit_control(contents, length, route, rpc-\u003ehsk);\n+\thoma_route_release(route);\n+\thoma_rpc_lock(rpc);\n+\treturn err;\n+}\n+\n+/**\n+ * __homa_xmit_control() - Lower-level version of homa_xmit_control: sends\n+ * a control packet.\n+ * @contents:  Address of buffer containing the contents of the packet.\n+ *             The caller must have filled in all of the information,\n+ *             including the common header.\n+ * @length:    Length of @contents.\n+ * @route:     Route via which to send packet (includes destination).\n+ * @hsk:       Socket via which the packet will be sent.\n+ *\n+ * Return:     Either zero (for success), or a negative errno value if there\n+ *             was a problem.\n+ */\n+int __homa_xmit_control(void *contents, size_t length, struct homa_route *route,\n+\t\t\tstruct homa_sock *hsk)\n+{\n+\tstruct homa_common_hdr *h;\n+\tstruct sk_buff *skb;\n+\tint extra_bytes;\n+\tint err;\n+\n+\tskb = __homa_skb_alloc(HOMA_MAX_HEADER);\n+\tif (unlikely(!skb))\n+\t\treturn -ENOBUFS;\n+\n+\th = skb_put(skb, length);\n+\tmemcpy(h, contents, length);\n+\textra_bytes = HOMA_MIN_PKT_LENGTH - length;\n+\tif (extra_bytes \u003e 0)\n+\t\tmemset(skb_put(skb, extra_bytes), 0, extra_bytes);\n+\tskb-\u003eooo_okay = 1;\n+\thoma_set_doff(skb, 20);\n+\terr = homa_route_xmit(skb, hsk, route, 0);\n+\treturn err;\n+}\n+\n+/**\n+ * homa_xmit_unknown() - Send an RPC_UNKNOWN packet to a peer.\n+ * @skb:         Buffer containing an incoming packet; identifies the peer to\n+ *               which the RPC_UNKNOWN packet should be sent.\n+ * @hsk:         Socket that should be used to send the RPC_UNKNOWN packet.\n+ */\n+void homa_xmit_unknown(struct sk_buff *skb, struct homa_sock *hsk)\n+{\n+\tstruct homa_common_hdr *h = (struct homa_common_hdr *)skb-\u003edata;\n+\tstruct in6_addr saddr = skb_canonical_ipv6_saddr(skb);\n+\tstruct homa_rpc_unknown_hdr unknown;\n+\tstruct homa_route *route;\n+\n+\tmemset(\u0026unknown, 0, sizeof(unknown));\n+\tunknown.common.sport = h-\u003edport;\n+\tunknown.common.dport = h-\u003esport;\n+\tunknown.common.type = RPC_UNKNOWN;\n+\tunknown.common.sender_id = cpu_to_be64(homa_local_id(h-\u003esender_id));\n+\troute = homa_route_get(hsk, \u0026saddr);\n+\tif (!IS_ERR(route)) {\n+\t\t__homa_xmit_control(\u0026unknown, sizeof(unknown), route, hsk);\n+\t\thoma_route_release(route);\n+\t}\n+}\n+\n+/**\n+ * homa_xmit_data() - If an RPC has outbound data packets that are permitted\n+ * to be transmitted according to the scheduling mechanism, arrange for\n+ * them to be sent.\n+ * @rpc:       RPC to check for transmittable packets. Must be locked by\n+ *             caller.\n+ */\n+void homa_xmit_data(struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tu32 xmit_offset, end;\n+\n+\twhile (rpc-\u003estate != RPC_DEAD) {\n+\t\txmit_offset = rpc-\u003emsgout.next_xmit_offset;\n+\n+\t\t/* Don't transmit unless enough data has been copied from user\n+\t\t * space for a maximum-size packet.\n+\t\t */\n+\t\tif (xmit_offset + rpc-\u003emsgout.max_gso_data \u003e\n+\t\t    rpc-\u003emsgout.copied_from_user \u0026\u0026\n+\t\t    rpc-\u003emsgout.copied_from_user \u003c rpc-\u003emsgout.length)\n+\t\t\tbreak;\n+\n+\t\tif (xmit_offset \u003e= rpc-\u003emsgout.length)\n+\t\t\tbreak;\n+\t\tend = rpc-\u003emsgout.length;\n+\t\thoma_tx_skb_send(rpc, xmit_offset, \u0026end);\n+\t}\n+}\n+\n+/**\n+ * homa_resend_data() - This function is invoked as part of handling RESEND\n+ * requests. It retransmits the packet(s) containing a given range of bytes\n+ * from a message.\n+ * @rpc:      RPC for which data should be resent. Must be locked by caller.\n+ * @start:    Offset within @rpc-\u003emsgout of the first byte to retransmit.\n+ * @end:      Offset within @rpc-\u003emsgout of the byte just after the last one\n+ *            to retransmit.\n+ * Return:    0 for success, otherwise a negative errno.\n+ */\n+int homa_resend_data(struct homa_rpc *rpc, int start, int end)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tu32 offset, pkt_end;\n+\tint err = 0;\n+\n+\tfor (offset = start; offset \u003c end; offset = pkt_end) {\n+\t\tpkt_end = end;\n+\t\terr = homa_tx_skb_send(rpc, offset, \u0026pkt_end);\n+\t\tif (err != 0)\n+\t\t\tbreak;\n+\t\tif (rpc-\u003estate == RPC_DEAD)\n+\t\t\tbreak;\n+\t}\n+\treturn err;\n+}\n+\n+/**\n+ * homa_rpc_tx_end() - Return the offset of the first byte in an\n+ * RPC's outgoing message that has not (with high probability) been\n+ * passed to the NIC (i.e. offsets beyond this point have not been\n+ * passed to ip*xmit or are deferred in homa_qdisc).\n+ * @rpc:    RPC to check\n+ * Return:  See above. If the message has been fully transmitted then\n+ *          rpc-\u003emsgout.length is returned.\n+ */\n+int homa_rpc_tx_end(struct homa_rpc *rpc)\n+{\n+\treturn rpc-\u003emsgout.next_xmit_offset;\n+}\ndiff --git a/net/homa/homa_peer.c b/net/homa/homa_peer.c\nnew file mode 100644\nindex 0000000000000..e387a399299bd\n--- /dev/null\n+++ b/net/homa/homa_peer.c\n@@ -0,0 +1,669 @@\n+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+\n+/* This file provides functions related to homa_peer, homa_route, and\n+ * homa_peertab objects.\n+ */\n+\n+#include \"homa_impl.h\"\n+#include \"homa_peer.h\"\n+#include \"homa_rpc.h\"\n+\n+#include \u003clinux/xxhash.h\u003e\n+\n+/* Wrapper to allow xxhash to be used as rhashtable hash function. */\n+static u32 xxh32_hash(const void *data, u32 len, u32 seed)\n+{\n+\treturn xxh32(data, len, seed);\n+}\n+\n+const struct rhashtable_params peer_ht_params = {\n+\t.key_len     = sizeof(struct homa_peer_key),\n+\t.key_offset  = offsetof(struct homa_peer, ht_key),\n+\t.head_offset = offsetof(struct homa_peer, ht_linkage),\n+\t.nelem_hint = 10000,\n+\t.hashfn = xxh32_hash,\n+\t.obj_cmpfn = homa_peer_compare\n+};\n+\n+const struct rhashtable_params route_ht_params = {\n+\t.key_len     = sizeof(struct homa_route_key),\n+\t.key_offset  = offsetof(struct homa_route, key),\n+\t.head_offset = offsetof(struct homa_route, ht_linkage),\n+\t.nelem_hint = 10000,\n+\t.hashfn = xxh32_hash\n+};\n+\n+/**\n+ * homa_peer_alloc_peertab() - Allocate and initialize a homa_peertab.\n+ *\n+ * Return:    A pointer to the new homa_peertab, or ERR_PTR(-errno) if there\n+ *            was a problem.\n+ */\n+struct homa_peertab *homa_peer_alloc_peertab(void)\n+{\n+\tstruct homa_peertab *peertab;\n+\tint err;\n+\n+\tpeertab = kzalloc_obj(*peertab, GFP_KERNEL);\n+\tif (!peertab)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\n+\tspin_lock_init(\u0026peertab-\u003elock);\n+\terr = rhashtable_init(\u0026peertab-\u003epeer_ht, \u0026peer_ht_params);\n+\tif (err)\n+\t\tgoto error;\n+\terr = rhashtable_init(\u0026peertab-\u003eroute_ht, \u0026route_ht_params);\n+\tif (err) {\n+\t\trhashtable_destroy(\u0026peertab-\u003epeer_ht);\n+\t\tgoto error;\n+\t}\n+\tpeertab-\u003eroute_ht_valid = true;\n+\trhashtable_walk_enter(\u0026peertab-\u003eroute_ht, \u0026peertab-\u003eroute_ht_iter);\n+\tpeertab-\u003egc_threshold = 5000;\n+\tpeertab-\u003enet_max = 10000;\n+\tpeertab-\u003eidle_secs_min = 10;\n+\tpeertab-\u003eidle_secs_max = 120;\n+\n+\thoma_peer_update_sysctl_deps(peertab);\n+\treturn peertab;\n+\n+error:\n+\thoma_peer_free_peertab(peertab);\n+\treturn ERR_PTR(err);\n+}\n+\n+/**\n+ * homa_peer_free_net() - Garbage collect all of the peer information\n+ * associated with a particular network namespace.\n+ * @hnet:    Network namespace whose peers should be freed. There must not\n+ *           be any active sockets or RPCs for this namespace.\n+ */\n+void homa_peer_free_net(struct homa_net *hnet)\n+{\n+\tstruct homa_peertab *peertab = hnet-\u003ehoma-\u003epeertab;\n+\tstruct rhashtable_iter iter;\n+\tstruct homa_route *route;\n+\n+\tspin_lock_bh(\u0026peertab-\u003elock);\n+\trhashtable_walk_enter(\u0026peertab-\u003eroute_ht, \u0026iter);\n+\trhashtable_walk_start(\u0026iter);\n+\twhile (1) {\n+\t\troute = rhashtable_walk_next(\u0026iter);\n+\t\tif (!route)\n+\t\t\tbreak;\n+\t\tif (IS_ERR(route))\n+\t\t\tcontinue;\n+\t\tif (route-\u003ekey.hnet != hnet)\n+\t\t\tcontinue;\n+\t\tif (rhashtable_remove_fast(\u0026peertab-\u003eroute_ht,\n+\t\t\t\t\t   \u0026route-\u003eht_linkage,\n+\t\t\t\t\t   route_ht_params) == 0) {\n+\t\t\thoma_route_release(route);\n+\t\t\thnet-\u003enum_routes--;\n+\t\t\tpeertab-\u003enum_routes--;\n+\t\t}\n+\t}\n+\trhashtable_walk_stop(\u0026iter);\n+\trhashtable_walk_exit(\u0026iter);\n+\tWARN(hnet-\u003enum_routes != 0, \"%s ended up with hnet-\u003enum_routes %d\",\n+\t     __func__, hnet-\u003enum_routes);\n+\tspin_unlock_bh(\u0026peertab-\u003elock);\n+}\n+\n+/**\n+ * homa_route_delete_fn() - This function is invoked for each entry in\n+ * the route_ht hash table by the rhashtable code when the table is being\n+ * deleted. It frees its argument.\n+ * @object:     homa_peer to free.\n+ * @dummy:      Not used.\n+ */\n+void homa_route_delete_fn(void *object, void *dummy)\n+\t__must_hold(((struct homa_route *)object)-\u003ekey.hnet-\u003ehoma-\u003epeertab-\u003elock)\n+{\n+\tstruct homa_route *route = object;\n+\n+\t/* Must unlink from the peer here (peertab is going away so\n+\t * it won't be safe to do it later, if the reference count doesn't\n+\t * drop to zero here).\n+\t */\n+\thoma_peer_unlink(route);\n+\thoma_route_release(route);\n+}\n+\n+/**\n+ * homa_peer_free_peertab() - Destructor for homa_peertabs.\n+ * @peertab:  The table to destroy. Caller must ensure that it will never\n+ *            be accessed again.\n+ */\n+void homa_peer_free_peertab(struct homa_peertab *peertab)\n+{\n+\tif (peertab-\u003eroute_ht_valid) {\n+\t\trhashtable_walk_exit(\u0026peertab-\u003eroute_ht_iter);\n+\t\trhashtable_free_and_destroy(\u0026peertab-\u003eroute_ht,\n+\t\t\t\t\t    homa_route_delete_fn,\n+\t\t\t\t\t    NULL);\n+\t\trcu_barrier();\n+\t\trhashtable_destroy(\u0026peertab-\u003epeer_ht);\n+\t\tpeertab-\u003eroute_ht_valid = false;\n+\t}\n+\tkfree(peertab);\n+}\n+\n+/**\n+ * homa_peer_alloc() - Allocate and initialize a new homa_peer object.\n+ * @hsk:        Socket for which the peer will be used.\n+ * @addr:       Address of the desired host: IPv4 addresses are represented\n+ *              as IPv4-mapped IPv6 addresses.\n+ * Return:      The peer associated with @addr, or a negative errno if an\n+ *              error occurred. On a successful return the reference count\n+ *              will be incremented for the returned peer. Sets hsk-\u003eerror_msg\n+ *              on errors.\n+ */\n+struct homa_peer *homa_peer_alloc(struct homa_sock *hsk,\n+\t\t\t\t  const struct in6_addr *addr)\n+{\n+\tstruct homa_peer *peer;\n+\n+\tpeer = kzalloc_obj(*peer, GFP_ATOMIC);\n+\tif (!peer) {\n+\t\thsk-\u003eerror_msg = \"couldn't allocate memory for homa_peer\";\n+\t\treturn (struct homa_peer *)ERR_PTR(-ENOMEM);\n+\t}\n+\tpeer-\u003eht_key.addr = *addr;\n+\tpeer-\u003eht_key.hnet = hsk-\u003ehnet;\n+\trefcount_set(\u0026peer-\u003erefs, 1);\n+\tspin_lock_init(\u0026peer-\u003elock);\n+\n+\treturn peer;\n+}\n+\n+/**\n+ * homa_peer_free() - Release any resources in a peer and free the homa_peer\n+ * struct.\n+ * @peer:   Peer to free. The @refs field must be zero (this also implies\n+ *          for example, that the peer is not on any lists and\n+ *          peer-\u003egrantable_rpcs is empty).\n+ */\n+void homa_peer_free(struct homa_peer *peer)\n+{\n+\tkfree(peer);\n+}\n+\n+/**\n+ * homa_peer_get() - Returns the peer associated with a given host; creates\n+ * a new homa_peer if one doesn't already exist.\n+ * @hsk:        Socket where the peer will be used.\n+ * @addr:       Address of the desired host: IPv4 addresses are represented\n+ *              as IPv4-mapped IPv6 addresses.\n+ *\n+ * Return:      The peer associated with @addr, or a negative errno if an\n+ *              error occurred. On a successful return the reference count\n+ *              will be incremented for the returned peer. The caller must\n+ *              eventually call homa_peer_release to release the reference.\n+ */\n+struct homa_peer *homa_peer_get(struct homa_sock *hsk,\n+\t\t\t\tconst struct in6_addr *addr)\n+\t__must_hold(hsk-\u003ehoma-\u003epeertab-\u003elock)\n+{\n+\tstruct homa_peertab *peertab = hsk-\u003ehoma-\u003epeertab;\n+\tstruct homa_peer_key key;\n+\tstruct homa_peer *peer;\n+\tint status;\n+\n+\tkey.addr = *addr;\n+\tkey.hnet = hsk-\u003ehnet;\n+\n+\t/* Fast path: use existing entry if it exists. */\n+\tpeer = rhashtable_lookup(\u0026peertab-\u003epeer_ht, \u0026key, peer_ht_params);\n+\tif (peer) {\n+\t\trefcount_inc(\u0026peer-\u003erefs);\n+\t\treturn peer;\n+\t}\n+\n+\t/* No existing entry, so we have to create a new one. */\n+\tpeer = homa_peer_alloc(hsk, addr);\n+\tif (IS_ERR(peer))\n+\t\treturn peer;\n+\tstatus = rhashtable_lookup_insert_fast(\u0026peertab-\u003epeer_ht,\n+\t\t\t\t\t       \u0026peer-\u003eht_linkage,\n+\t\t\t\t\t       peer_ht_params);\n+\tif (status != 0) {\n+\t\tpr_err(\"homa_peer_get received unexpected error return from rhashtable_lookup_insert_fast\");\n+\t\thsk-\u003eerror_msg = \"unexpected error return from rhashtable_lookup_insert_fast\";\n+\t\thoma_peer_free(peer);\n+\t\treturn ERR_PTR(status);\n+\t}\n+\treturn peer;\n+}\n+\n+/**\n+ * homa_route_alloc() - Allocate and initialize a new homa_route.\n+ * object.\n+ * @hsk:       Socket for which the homa_route will be used.\n+ * @key:       Key that will be used for this entry in peertab-\u003eroute_ht.\n+ *             Contains the destination address and other information needed\n+ *             to create a flowi and a dst_entry.\n+ * Return:     A new homa_route corresdponding to @hsk and @key, or a\n+ *             negative errno if an error occurred. Sets hsk-\u003eerror_msg on\n+ *             errors. On success, all fields have been initialized except\n+ *             @peer; the route has not been inserted in route_ht and its\n+ *             reference count will be one.\n+ */\n+struct homa_route *homa_route_alloc(struct homa_sock *hsk,\n+\t\t\t\t    const struct homa_route_key *key)\n+{\n+\tstruct homa_route *route;\n+\tstruct dst_entry *dst;\n+\tint err;\n+\n+\troute = kzalloc_obj(*route, GFP_ATOMIC);\n+\tif (!route) {\n+\t\thsk-\u003eerror_msg = \"couldn't allocate memory for homa_route\";\n+\t\treturn ERR_PTR(-ENOMEM);\n+\t}\n+\tspin_lock_init(\u0026route-\u003elock);\n+\trefcount_set(\u0026route-\u003erefs, 1);\n+\troute-\u003eaccess_jiffies = jiffies;\n+\troute-\u003ekey = *key;\n+\n+\t/* Find a dst_entry to use for this route. */\n+\troute-\u003eflow.flowi_secid = key-\u003esecid;\n+\tif (ipv6_addr_v4mapped(\u0026route-\u003ekey.daddr)) {\n+\t\tstruct rtable *rt;\n+\n+\t\tflowi4_init_output(\u0026route-\u003eflow.u.ip4, key-\u003ebound_dev_if,\n+\t\t\t\t   key-\u003emark, 0, RT_SCOPE_UNIVERSE,\n+\t\t\t\t   IPPROTO_HOMA, 0,\n+\t\t\t\t   ipv6_to_ipv4(route-\u003ekey.daddr),\n+\t\t\t\t   ipv6_to_ipv4(route-\u003ekey.saddr), 0, 0,\n+\t\t\t\t   key-\u003euid);\n+\t\trt = ip_route_output_flow(sock_net(\u0026hsk-\u003esock),\n+\t\t\t\t\t  \u0026route-\u003eflow.u.ip4, \u0026hsk-\u003esock);\n+\t\tif (IS_ERR(rt)) {\n+\t\t\terr = PTR_ERR(rt);\n+\t\t\tgoto error;\n+\t\t}\n+\t\trcu_assign_pointer(route-\u003edst, \u0026rt-\u003edst);\n+\t} else {\n+\t\t/* This code is derived from code in tcp_v6_connect. */\n+\t\troute-\u003eflow.u.ip6.flowi6_proto = IPPROTO_HOMA;\n+\t\troute-\u003eflow.u.ip6.daddr = route-\u003ekey.daddr;\n+\t\troute-\u003eflow.u.ip6.saddr = route-\u003ekey.saddr;\n+\t\troute-\u003eflow.u.ip6.flowlabel = ip6_make_flowinfo(0, 0);\n+\t\troute-\u003eflow.u.ip6.flowi6_oif = key-\u003ebound_dev_if;\n+\t\troute-\u003eflow.u.ip6.flowi6_mark = key-\u003emark;\n+\t\troute-\u003eflow.u.ip6.fl6_dport = 0;\n+\t\troute-\u003eflow.u.ip6.fl6_sport = 0;\n+\t\troute-\u003eflow.u.ip6.flowi6_uid = key-\u003euid;\n+\t\tdst = ip6_dst_lookup_flow(sock_net(\u0026hsk-\u003esock), \u0026hsk-\u003esock,\n+\t\t\t\t\t\t   \u0026route-\u003eflow.u.ip6, NULL);\n+\t\trcu_assign_pointer(route-\u003edst, dst);\n+\n+\t\tif (IS_ERR(route-\u003edst)) {\n+\t\t\terr = PTR_ERR(route-\u003edst);\n+\t\t\tgoto error;\n+\t\t}\n+\t\troute-\u003edst_cookie = rt6_get_cookie(dst_rt6_info(dst));\n+\t}\n+\treturn route;\n+error:\n+\thsk-\u003eerror_msg = \"couldn't find route for peer\";\n+\tkfree(route);\n+\treturn ERR_PTR(err);\n+}\n+\n+/**\n+ * homa_route_free() - Release any resources in a homa_route and\n+ * free the object's memory. May be invoked either as an RCU callback\n+ * or directly (if invoked directly, caller must ensure exclusive\n+ * access to the object, e.g. it was never actually published in\n+ * route_ht).\n+ * @head:     @rcu_head field  in the route to free.\n+ */\n+void homa_route_free(struct rcu_head *head)\n+{\n+\tstruct homa_route *route;\n+\n+\troute = container_of(head, struct homa_route, rcu_head);\n+\tdst_release(rcu_dereference_protected(route-\u003edst, 1));\n+\tspin_lock_bh(\u0026route-\u003ekey.hnet-\u003ehoma-\u003epeertab-\u003elock);\n+\thoma_peer_unlink(route);\n+\tspin_unlock_bh(\u0026route-\u003ekey.hnet-\u003ehoma-\u003epeertab-\u003elock);\n+\tkfree(route);\n+}\n+\n+/**\n+ * homa_route_get() - Returns a homa_route object that can be\n+ * used to communicate with a given host over a given socket. Indirectly\n+ * provides access to a homa_peer object for @addr.\n+ * @hsk:        Socket where the peer will be used.\n+ * @addr:       Address of the desired host: IPv4 addresses are represented\n+ *              as IPv4-mapped IPv6 addresses.\n+ *\n+ * Return:      The homa_route associated with @addr, or a negative\n+ *              errno if an error occurred. On a successful return the\n+ *              reference count will be incremented for the returned object.\n+ *              The caller must eventually call homa_peer_route_release to\n+ *              release the reference.\n+ */\n+struct homa_route *homa_route_get(struct homa_sock *hsk,\n+\t\t\t\t  const struct in6_addr *addr)\n+{\n+\tstruct homa_peertab *peertab = hsk-\u003ehoma-\u003epeertab;\n+\tstruct homa_route *route, *other;\n+\tstruct homa_route_key route_key;\n+\tstruct homa_peer *peer;\n+\n+\t/* See if we already have a suitable route cached. */\n+\trcu_read_lock();\n+\thoma_route_key_init(\u0026route_key, hsk, addr);\n+\troute = rhashtable_lookup(\u0026peertab-\u003eroute_ht, \u0026route_key,\n+\t\t\t\t  route_ht_params);\n+\tif (route \u0026\u0026 refcount_inc_not_zero(\u0026route-\u003erefs)) {\n+\t\troute-\u003eaccess_jiffies = jiffies;\n+\t\trcu_read_unlock();\n+\t\treturn route;\n+\t}\n+\n+\t/* No existing entry, so we have to create a new one. Switch from\n+\t * RCU to real locking for this.\n+\t */\n+\trcu_read_unlock();\n+\troute = homa_route_alloc(hsk, \u0026route_key);\n+\tif (IS_ERR(route))\n+\t\treturn route;\n+\n+\tspin_lock_bh(\u0026peertab-\u003elock);\n+\tpeer = homa_peer_get(hsk, addr);\n+\tif (IS_ERR(peer)) {\n+\t\tspin_unlock_bh(\u0026peertab-\u003elock);\n+\t\thoma_route_free(\u0026route-\u003ercu_head);\n+\t\troute = ERR_PTR(PTR_ERR(peer));\n+\t\treturn route;\n+\t}\n+\troute-\u003epeer = peer;\n+\n+\t/* Insert the new entry in the flow table. It's possible that\n+\t * someone else already created the entry concurrently.\n+\t */\n+\tother = rhashtable_lookup_get_insert_fast(\u0026peertab-\u003eroute_ht,\n+\t\t\t\t\t\t  \u0026route-\u003eht_linkage,\n+\t\t\t\t\t\t  route_ht_params);\n+\tif (IS_ERR(other)) {\n+\t\t/* Couldn't insert; return the error info. */\n+\t\thsk-\u003eerror_msg = \"rhashtable_lookup_get_insert_key failed in homa_route_get\";\n+\t\tspin_unlock_bh(\u0026peertab-\u003elock);\n+\t\thoma_route_free(\u0026route-\u003ercu_head);\n+\t\troute = other;\n+\t} else if (other) {\n+\t\t/* Someone else already created the desired object; use that\n+\t\t * one instead of ours.\n+\t\t */\n+\t\trefcount_inc(\u0026other-\u003erefs);\n+\t\tspin_unlock_bh(\u0026peertab-\u003elock);\n+\t\thoma_route_free(\u0026route-\u003ercu_head);\n+\t\troute = other;\n+\t\troute-\u003eaccess_jiffies = jiffies;\n+\t} else {\n+\t\t/* The new object was inserted in the hash table. */\n+\t\trefcount_inc(\u0026route-\u003erefs);\n+\t\tpeertab-\u003enum_routes++;\n+\t\troute_key.hnet-\u003enum_routes++;\n+\t\tspin_unlock_bh(\u0026peertab-\u003elock);\n+\t}\n+\treturn route;\n+}\n+\n+/**\n+ * homa_route_validate() - Check to be sure that the information in the\n+ * route for an RPC is still valid; if not, try to allocate a new route\n+ * for the RPC.\n+ * @rpc:    RPC whose routing information should be checked.\n+ * Return:  Zero for success, or a negative errno if the route was invalid\n+ *          and no new route could be created.\n+ */\n+int homa_route_validate(struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_route *route, *old;\n+\tstruct dst_entry *dst;\n+\n+\told = rpc-\u003eroute;\n+\trcu_read_lock();\n+\tdst = rcu_dereference_protected(old-\u003edst, 1);\n+\trcu_read_unlock();\n+\tif (!dst_check(dst, rpc-\u003eroute-\u003edst_cookie)) {\n+\t\tstruct homa_peertab *peertab = rpc-\u003ehsk-\u003ehoma-\u003epeertab;\n+\n+\t\t/* Existing route is no longer valid; remove it from\n+\t\t * the hash table and try to create a new one.\n+\t\t */\n+\t\tspin_lock_bh(\u0026peertab-\u003elock);\n+\t\tif (rhashtable_remove_fast(\u0026peertab-\u003eroute_ht, \u0026old-\u003eht_linkage,\n+\t\t\t\t\t   route_ht_params) == 0) {\n+\t\t\thoma_route_release(old);\n+\t\t\tpeertab-\u003enum_routes--;\n+\t\t\told-\u003ekey.hnet-\u003enum_routes--;\n+\t\t}\n+\t\tspin_unlock_bh(\u0026peertab-\u003elock);\n+\t\troute = homa_route_get(rpc-\u003ehsk, \u0026rpc-\u003eroute-\u003epeer-\u003eaddr);\n+\t\tif (IS_ERR(route))\n+\t\t\treturn PTR_ERR(route);\n+\t\told = xchg(\u0026rpc-\u003eroute, route);\n+\t\thoma_route_release(old);\n+\t}\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_route_gc() - This function is invoked by Homa at regular intervals;\n+ * its job is to ensure that the number of routes stays within limits. If\n+ * the number grows too large, it selectively deletes routes (and peers)\n+ * to get back under the limit.\n+ * @peertab:   Structure to garbage-collect.\n+ */\n+void homa_route_gc(struct homa_peertab *peertab)\n+{\n+#define EVICT_BATCH_SIZE 5\n+\tstruct homa_route *victims[EVICT_BATCH_SIZE];\n+\tint num_victims;\n+\tint i;\n+\n+\tspin_lock_bh(\u0026peertab-\u003elock);\n+\tif (peertab-\u003enum_routes \u003c peertab-\u003egc_threshold)\n+\t\tgoto done;\n+\tnum_victims = homa_route_pick_victims(peertab, victims,\n+\t\t\t\t\t      EVICT_BATCH_SIZE);\n+\tif (num_victims == 0)\n+\t\tgoto done;\n+\n+\tfor (i = 0; i \u003c num_victims; i++) {\n+\t\tstruct homa_route *route = victims[i];\n+\n+\t\tif (rhashtable_remove_fast(\u0026peertab-\u003eroute_ht,\n+\t\t\t\t\t   \u0026route-\u003eht_linkage,\n+\t\t\t\t\t   route_ht_params) == 0) {\n+\t\t\tpeertab-\u003enum_routes--;\n+\t\t\troute-\u003ekey.hnet-\u003enum_routes--;\n+\t\t\thoma_route_release(route);\n+\t\t}\n+\t}\n+done:\n+\tspin_unlock_bh(\u0026peertab-\u003elock);\n+}\n+\n+/**\n+ * homa_route_pick_victims() - Select a few routes that can be freed.\n+ * @peertab:      Choose routes that are stored here.\n+ * @victims:      Return addresses of victims here.\n+ * @max_victims:  Limit on how many victims to choose (and size of @victims\n+ *                array).\n+ * Return:        The number of routes stored in @victims; may be zero.\n+ */\n+int homa_route_pick_victims(struct homa_peertab *peertab,\n+\t\t\t    struct homa_route *victims[], int max_victims)\n+{\n+\tstruct homa_route *route;\n+\tint num_victims = 0;\n+\tint to_scan;\n+\tint i, idle;\n+\n+\t/* Scan 2 routes for every potential victim and keep the \"best\"\n+\t * routes for removal.\n+\t */\n+\trhashtable_walk_start(\u0026peertab-\u003eroute_ht_iter);\n+\tfor (to_scan = 2 * max_victims; to_scan \u003e 0; to_scan--) {\n+\t\troute = rhashtable_walk_next(\u0026peertab-\u003eroute_ht_iter);\n+\t\tif (!route) {\n+\t\t\t/* Reached the end of the table; restart at\n+\t\t\t * the beginning.\n+\t\t\t */\n+\t\t\trhashtable_walk_stop(\u0026peertab-\u003eroute_ht_iter);\n+\t\t\trhashtable_walk_exit(\u0026peertab-\u003eroute_ht_iter);\n+\t\t\trhashtable_walk_enter(\u0026peertab-\u003epeer_ht,\n+\t\t\t\t\t      \u0026peertab-\u003eroute_ht_iter);\n+\t\t\trhashtable_walk_start(\u0026peertab-\u003eroute_ht_iter);\n+\t\t\troute = rhashtable_walk_next(\u0026peertab-\u003eroute_ht_iter);\n+\t\t\tif (!route)\n+\t\t\t\tbreak;\n+\t\t}\n+\t\tif (IS_ERR(route)) {\n+\t\t\t/* rhashtable decided to restart the search at the\n+\t\t\t * beginning.\n+\t\t\t */\n+\t\t\troute = rhashtable_walk_next(\u0026peertab-\u003eroute_ht_iter);\n+\t\t\tif (!route || IS_ERR(route))\n+\t\t\t\tbreak;\n+\t\t}\n+\n+\t\t/* Has this route been idle long enough to be candidate for\n+\t\t * eviction?\n+\t\t */\n+\t\tidle = jiffies - route-\u003eaccess_jiffies;\n+\t\tif (idle \u003c peertab-\u003eidle_jiffies_min)\n+\t\t\tcontinue;\n+\t\tif (idle \u003c peertab-\u003eidle_jiffies_max \u0026\u0026\n+\t\t    route-\u003ekey.hnet-\u003enum_routes \u003c= peertab-\u003enet_max)\n+\t\t\tcontinue;\n+\n+\t\t/* Sort the candidate into the existing list of victims. */\n+\t\tfor (i = 0; i \u003c num_victims; i++) {\n+\t\t\tif (route == victims[i]) {\n+\t\t\t\t/* This can happen if there aren't very many\n+\t\t\t\t * routes and we wrapped around in the hash\n+\t\t\t\t * table.\n+\t\t\t\t */\n+\t\t\t\troute = NULL;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tif (homa_route_prefer_evict(peertab, route, victims[i]))\n+\t\t\t\tswap(route, victims[i]);\n+\t\t}\n+\n+\t\tif (num_victims \u003c max_victims \u0026\u0026 route) {\n+\t\t\tvictims[num_victims] = route;\n+\t\t\tnum_victims++;\n+\t\t}\n+\t}\n+\trhashtable_walk_stop(\u0026peertab-\u003eroute_ht_iter);\n+\treturn num_victims;\n+}\n+\n+/**\n+ * homa_route_prefer_evict() - Given two routes, determine which one is\n+ * a better candidate for eviction.\n+ * @peertab:    Overall information used to manage routes.\n+ * @route1:     First route.\n+ * @route2:     Second route.\n+ * Return:      True if @route1 is a better candidate for eviction than @route2.\n+ */\n+int homa_route_prefer_evict(struct homa_peertab *peertab,\n+\t\t\t    struct homa_route *route1,\n+\t\t\t    struct homa_route *route2)\n+{\n+\t/* Prefer a route whose homa_net is over its limit; if both are either\n+\t * over or under, then prefer the route with the longest idle time.\n+\t */\n+\tif (route1-\u003ekey.hnet-\u003enum_routes \u003e peertab-\u003enet_max) {\n+\t\tif (route2-\u003ekey.hnet-\u003enum_routes \u003c= peertab-\u003enet_max)\n+\t\t\treturn true;\n+\t\telse\n+\t\t\treturn time_before(route1-\u003eaccess_jiffies,\n+\t\t\t\t\t   route2-\u003eaccess_jiffies);\n+\t}\n+\tif (route2-\u003ekey.hnet-\u003enum_routes \u003e peertab-\u003enet_max)\n+\t\treturn false;\n+\telse\n+\t\treturn time_before(route1-\u003eaccess_jiffies,\n+\t\t\t\t   route2-\u003eaccess_jiffies);\n+}\n+\n+/**\n+ * homa_peer_add_ack() - Add a given RPC to the list of unacked\n+ * RPCs for its server. Once this method has been invoked, it's safe\n+ * to delete the RPC, since it will eventually be acked to the server.\n+ * @rpc:    Client RPC that has now completed. Must be locked by caller.\n+ */\n+void homa_peer_add_ack(struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_peer *peer = rpc-\u003eroute-\u003epeer;\n+\tstruct homa_ack_hdr ack;\n+\n+\thoma_peer_lock(peer);\n+\tif (peer-\u003enum_acks \u003c HOMA_MAX_ACKS_PER_PKT) {\n+\t\tpeer-\u003eacks[peer-\u003enum_acks].client_id = cpu_to_be64(rpc-\u003eid);\n+\t\tpeer-\u003eacks[peer-\u003enum_acks].server_port = htons(rpc-\u003edport);\n+\t\tpeer-\u003enum_acks++;\n+\t\thoma_peer_unlock(peer);\n+\t\treturn;\n+\t}\n+\n+\t/* The peer has filled up; send an ACK message to empty it. The\n+\t * RPC in the message header will also be considered ACKed.\n+\t */\n+\tmemcpy(ack.acks, peer-\u003eacks, sizeof(peer-\u003eacks));\n+\tack.num_acks = htons(peer-\u003enum_acks);\n+\tpeer-\u003enum_acks = 0;\n+\thoma_peer_unlock(peer);\n+\thoma_xmit_control(ACK, \u0026ack, sizeof(ack), rpc);\n+}\n+\n+/**\n+ * homa_peer_get_acks() - Copy acks out of a peer, and remove them from the\n+ * peer.\n+ * @peer:    Peer to check for possible unacked RPCs.\n+ * @count:   Maximum number of acks to return.\n+ * @dst:     The acks are copied to this location.\n+ *\n+ * Return:   The number of acks extracted from the peer (\u003c= count).\n+ */\n+int homa_peer_get_acks(struct homa_peer *peer, int count, struct homa_ack *dst)\n+{\n+\t/* Don't waste time acquiring the lock if there are no ids available. */\n+\tif (peer-\u003enum_acks == 0)\n+\t\treturn 0;\n+\n+\thoma_peer_lock(peer);\n+\n+\tif (count \u003e peer-\u003enum_acks)\n+\t\tcount = peer-\u003enum_acks;\n+\tmemcpy(dst, \u0026peer-\u003eacks[peer-\u003enum_acks - count],\n+\t       count * sizeof(peer-\u003eacks[0]));\n+\tpeer-\u003enum_acks -= count;\n+\n+\thoma_peer_unlock(peer);\n+\treturn count;\n+}\n+\n+/**\n+ * homa_peer_update_sysctl_deps() - Update any peertab fields that depend\n+ * on values set by sysctl. This function is invoked anytime a peer sysctl\n+ * value is updated.\n+ * @peertab:   Struct to update.\n+ */\n+void homa_peer_update_sysctl_deps(struct homa_peertab *peertab)\n+{\n+\tpeertab-\u003eidle_jiffies_min = peertab-\u003eidle_secs_min * HZ;\n+\tpeertab-\u003eidle_jiffies_max = peertab-\u003eidle_secs_max * HZ;\n+}\ndiff --git a/net/homa/homa_peer.h b/net/homa/homa_peer.h\nnew file mode 100644\nindex 0000000000000..a0c80997ce199\n--- /dev/null\n+++ b/net/homa/homa_peer.h\n@@ -0,0 +1,457 @@\n+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */\n+\n+/* This file contains definitions related to managing peers and routes\n+ * (homa_peer, homa_route, homa_peertab).\n+ */\n+\n+#ifndef _HOMA_PEER_H\n+#define _HOMA_PEER_H\n+\n+#include \"homa_wire.h\"\n+#include \"homa_sock.h\"\n+\n+#include \u003clinux/rhashtable.h\u003e\n+\n+struct homa_rpc;\n+\n+/**\n+ * struct homa_peertab - Stores homa_peer and homa_route objects. There is\n+ * one of these per struct homa.\n+ */\n+struct homa_peertab {\n+\t/**\n+\t * @lock: Used to synchronize updates to @peer_ht, @route_ht, as well\n+\t * as other operations on this object.\n+\t */\n+\tspinlock_t lock;\n+\n+\t/** @peer_ht: Hash table that stores struct peers. */\n+\tstruct rhashtable peer_ht;\n+\n+\t/**\n+\t * @route_ht:  Hash table that stores homa_peer_flow objects.\n+\t * There can be multiple entries in this table for each peer.\n+\t */\n+\tstruct rhashtable route_ht;\n+\n+\t/**\n+\t * @route_ht_iter: Used to scan route_ht to find routes to garbage\n+\t * collect.\n+\t */\n+\tstruct rhashtable_iter route_ht_iter;\n+\n+\t/** @num_routes: Total number of objects currently in @route_ht. */\n+\tint num_routes;\n+\n+\t/**\n+\t * @route_ht_valid: True means route_ht has been initialized and must\n+\t * eventually be destroyed (it also means peer_ht has been initialized).\n+\t */\n+\tbool route_ht_valid;\n+\n+\t/**\n+\t * @gc_stop_count: Nonzero means that route garbage collection\n+\t * should not be performed (conflicting state changes are underway).\n+\t */\n+\tint gc_stop_count;\n+\n+\t/**\n+\t * @gc_threshold: If @num_routes is less than this, don't bother\n+\t * doing any peer garbage collection. Set externally via sysctl.\n+\t */\n+\tint gc_threshold;\n+\n+\t/**\n+\t * @net_max: If the number of peers for a homa_net exceeds this number,\n+\t * work aggressively to reclaim peers for that homa_net. Set\n+\t * externally via sysctl.\n+\t */\n+\tint net_max;\n+\n+\t/**\n+\t * @idle_secs_min: A peer will not be considered for garbage collection\n+\t * under any circumstances if it has been idle less than this many\n+\t * seconds. Set externally via sysctl.\n+\t */\n+\tint idle_secs_min;\n+\n+\t/**\n+\t * @idle_jiffies_min: Same as idle_secs_min except in units\n+\t * of jiffies.\n+\t */\n+\tint idle_jiffies_min;\n+\n+\t/**\n+\t * @idle_secs_max: A peer that has been idle for less than\n+\t * this many seconds will not be considered for garbage collection\n+\t * unless its homa_net has more than @net_threshold peers. Set\n+\t * externally via sysctl.\n+\t */\n+\tint idle_secs_max;\n+\n+\t/**\n+\t * @idle_jiffies_max: Same as idle_secs_max except in units\n+\t * of jiffies.\n+\t */\n+\tint idle_jiffies_max;\n+\n+\t/** @rcu_head: Holds state of a pending call_rcu invocation. */\n+\tstruct rcu_head rcu_head;\n+};\n+\n+/**\n+ * struct homa_peer_key - Used to look up homa_peer structs in homa_peertab-\u003epeer_ht.\n+ */\n+struct homa_peer_key {\n+\t/**\n+\t * @addr: Address of the desired host. IPv4 addresses are represented\n+\t * with IPv4-mapped IPv6 addresses. Must be the first variable in\n+\t * the struct, because of union in homa_peer.\n+\t */\n+\tstruct in6_addr addr;\n+\n+\t/** @hnet: The network namespace in which this peer is valid. */\n+\tstruct homa_net *hnet;\n+};\n+\n+/**\n+ * struct homa_peer - One of these objects exists for each machine that we\n+ * have communicated with (either as client or server). This struct contains\n+ * information that is common to all uses of the peer.\n+ */\n+struct homa_peer {\n+\tunion {\n+\t\t/**\n+\t\t * @addr: IPv6 address for the machine (IPv4 addresses are\n+\t\t * stored as IPv4-mapped IPv6 addresses).\n+\t\t */\n+\t\tstruct in6_addr addr;\n+\n+\t\t/** @ht_key: The hash table key for this peer in peertab-\u003epeer_ht. */\n+\t\tstruct homa_peer_key ht_key;\n+\t};\n+\n+\t/**\n+\t * @refs: Number of outstanding references to this peer. Does *not*\n+\t * include a reference for the entry in peertab-\u003epeer_ht. The peer\n+\t * can be freed when this value becomes zero.\n+\t */\n+\trefcount_t refs;\n+\n+\t/**\n+\t * @ht_linkage: Used by rashtable implement to link this peer into\n+\t * peertab-\u003epeer_ht.\n+\t */\n+\tstruct rhash_head ht_linkage;\n+\n+\t/**\n+\t * @lock: used to synchronize access to fields in this struct, such\n+\t * as @num_acks, @acks, @dst, and @dst_cookie.\n+\t */\n+\tspinlock_t lock ____cacheline_aligned_in_smp;\n+\n+\t/**\n+\t * @num_acks: the number of (initial) entries in @acks that\n+\t * currently hold valid information.\n+\t */\n+\tint num_acks;\n+\n+\t/**\n+\t * @acks: info about client RPCs whose results have been completely\n+\t * received.\n+\t */\n+\tstruct homa_ack acks[HOMA_MAX_ACKS_PER_PKT];\n+\n+};\n+\n+/**\n+ * struct homa_route_key - Used to look up homa_route structs in\n+ * homa_peertab_route_ht. These fields represent all of the information\n+ * that could impact the choice of a particular struct dst_entry.\n+ */\n+struct homa_route_key {\n+\t/**\n+\t * @saddr: Source network address. IPv4 addresses are represented\n+\t * with IPv4-mapped IPv6 addresses.\n+\t */\n+\tstruct in6_addr saddr;\n+\t/**\n+\t * @daddr: Destination network address. IPv4 addresses are represented\n+\t * with IPv4-mapped IPv6 addresses.\n+\t */\n+\tstruct in6_addr daddr;\n+\n+\t/**\n+\t * @hnet: The network namespace in which this route is valid. This\n+\t * needs to be a homa_hnet pointer, not just struct net, in order\n+\t * to access homa_hnet-\u003enum_routes.\n+\t */\n+\tstruct homa_net *hnet;\n+\n+\t/**\n+\t * @sk_policy_out: sk-\u003esk_policy[XFRM_POLICY_OUT]: uniquely\n+\t * determines IPsec policy, if any.\n+\t */\n+\tstruct xfrm_policy *sk_policy_out;\n+\n+\t/** @uid: sock-\u003esk_sk_uid */\n+\tkuid_t uid;\n+\n+\t/** @mark: sock-\u003esk_mark */\n+\tu32 mark;\n+\n+\t/** @secid: flowic.secid produced by security_sk_classify_flow. */\n+\tu32 secid;\n+\n+\t/** @bound_dev_if: sock-\u003esk_bound_dev_if */\n+\tint bound_dev_if;\n+};\n+\n+/**\n+ * struct homa_route - Holds a dst_entry for communicating with a\n+ * particular peer, as well as information needed to cache the dst_entry\n+ * and share it for multiple RPCs. There can be more than one of these\n+ * objects per peer, which have different homa_route_keys.\n+ */\n+struct homa_route {\n+\t/**\n+\t * @lock: used to synchronize uypdates to this struct.\n+\t */\n+\tspinlock_t lock;\n+\n+\t/**\n+\t * @refs: Number of outstanding references to this object. Includes\n+\t * one reference for the entry in peertab-\u003eroute_ht, plus one for each\n+\t * call to homa_route_get that has not been canceled by a call to\n+\t * homa_peer_route_release; the object will be freed (via RCU) when\n+\t * this count becomes zero.\n+\t */\n+\trefcount_t refs;\n+\n+\t/**\n+\t * @access_jiffies: Time in jiffies of most recent access to this\n+\t * object; used for garbage collection.\n+\t */\n+\tunsigned long access_jiffies;\n+\n+\t/** @key: Identifies this entry in peertab-\u003eroute_ht. */\n+\tstruct homa_route_key key;\n+\n+\t/**\n+\t * @peer: Peer with which this route is associated. This object holds a\n+\t * reference on the peer.\n+\t */\n+\tstruct homa_peer *peer;\n+\n+\t/**\n+\t * @dst: Used to route packets to this peer; this object owns a\n+\t * reference that must eventually be released.\n+\t */\n+\tstruct dst_entry __rcu *dst;\n+\n+\t/**\n+\t * @dst_cookie: Used to check whether dst is still valid. This is\n+\t * accessed without synchronization, which is racy, but the worst\n+\t * that can happen is using an obsolete dst.\n+\t */\n+\tu32 dst_cookie;\n+\n+\t/**\n+\t * @flow: Contains parameters used to generate @dst; must be\n+\t * retained and passed to ip*xmit.\n+\t */\n+\tstruct flowi flow;\n+\n+\t/**\n+\t * @ht_linkage: Used by rashtable to link this object into\n+\t * peertab-\u003eroute_ht.\n+\t */\n+\tstruct rhash_head ht_linkage;\n+\n+\t/** @rcu_head: Holds state of a pending call_rcu invocation. */\n+\tstruct rcu_head rcu_head;\n+};\n+\n+void     homa_dst_refresh(struct homa_peertab *peertab,\n+\t\t\t  struct homa_peer *peer, struct homa_sock *hsk);\n+void     homa_peer_add_ack(struct homa_rpc *rpc);\n+struct homa_peer\n+\t*homa_peer_alloc(struct homa_sock *hsk, const struct in6_addr *addr);\n+struct homa_peertab\n+\t*homa_peer_alloc_peertab(void);\n+int      homa_peer_dointvec(const struct ctl_table *table, int write,\n+\t\t\t    void *buffer, size_t *lenp, loff_t *ppos);\n+void     homa_peer_free(struct homa_peer *peer);\n+void     homa_peer_free_net(struct homa_net *hnet);\n+void     homa_peer_free_peertab(struct homa_peertab *peertab);\n+struct homa_peer\n+\t*homa_peer_get(struct homa_sock *hsk, const struct in6_addr *addr);\n+int      homa_peer_get_acks(struct homa_peer *peer, int count,\n+\t\t\t    struct homa_ack *dst);\n+void     homa_peer_lock_slow(struct homa_peer *peer);\n+void     homa_peer_release_fn(void *object, void *dummy);\n+void     homa_peer_update_sysctl_deps(struct homa_peertab *peertab);\n+void     homa_peer_set_cutoffs(struct homa_peer *peer, int c0, int c1,\n+\t\t\t       int c2, int c3, int c4, int c5, int c6, int c7);\n+struct homa_route\n+\t*homa_route_alloc(struct homa_sock *hsk,\n+\t\t\t  const struct homa_route_key *key);\n+void     homa_route_delete_fn(void *object, void *dummy);\n+void     homa_route_free(struct rcu_head *head);\n+void     homa_route_gc(struct homa_peertab *peertab);\n+struct homa_route\n+\t*homa_route_get(struct homa_sock *hsk,\n+\t\t\t\t    const struct in6_addr *addr);\n+u32      homa_route_hash(const void *data, u32 len, u32 seed);\n+int      homa_route_pick_victims(struct homa_peertab *peertab,\n+\t\t\t\t struct homa_route *victims[], int max_victims);\n+int      homa_route_prefer_evict(struct homa_peertab *peertab,\n+\t\t\t\t struct homa_route *route1,\n+\t\t\t\t struct homa_route *route2);\n+int      homa_route_validate(struct homa_rpc *rpc);\n+\n+extern const struct rhashtable_params peer_ht_params;\n+extern const struct rhashtable_params route_ht_params;\n+\n+/**\n+ * homa_peer_lock() - Acquire the lock for a peer.\n+ * @peer:    Peer to lock.\n+ */\n+static inline void homa_peer_lock(struct homa_peer *peer)\n+\t__acquires(peer-\u003elock)\n+{\n+\tspin_lock_bh(\u0026peer-\u003elock);\n+}\n+\n+/**\n+ * homa_peer_unlock() - Release the lock for a peer.\n+ * @peer:   Peer to lock.\n+ */\n+static inline void homa_peer_unlock(struct homa_peer *peer)\n+\t__releases(peer-\u003elock)\n+{\n+\tspin_unlock_bh(\u0026peer-\u003elock);\n+}\n+\n+/**\n+ * homa_route_hold() - Increment the reference count on a route.\n+ * Caller must eventually invoke homa_route_release to decrement the\n+ * reference count again.\n+ * @route:   Route whose reference count should be incremented. Caller must\n+ *           already hold a reference to this.\n+ */\n+static inline void homa_route_hold(struct homa_route *route)\n+{\n+\trefcount_inc(\u0026route-\u003erefs);\n+}\n+\n+/**\n+ * homa_route_release() - Release a reference on a route (cancels the effect of\n+ * a previous call to homa_route_hold). If the reference count becomes zero\n+ * then the route may be deleted at any time.\n+ * @route:      Object to release.\n+ */\n+static inline void homa_route_release(struct homa_route *route)\n+{\n+\tif (refcount_dec_and_test(\u0026route-\u003erefs))\n+\t\tcall_rcu(\u0026route-\u003ercu_head, homa_route_free);\n+}\n+\n+/**\n+ * homa_peer_compare() - Comparison function for entries in @peertab-\u003epeer_ht.\n+ * @arg:   Contains one of the keys to compare.\n+ * @obj:   homa_peer object containing the other key to compare.\n+ * Return: 0 means the keys match, 1 means mismatch.\n+ */\n+static inline int homa_peer_compare(struct rhashtable_compare_arg *arg,\n+\t\t\t\t    const void *obj)\n+{\n+\tconst struct homa_peer_key *key = arg-\u003ekey;\n+\tconst struct homa_peer *peer = obj;\n+\n+\treturn !(ipv6_addr_equal(\u0026key-\u003eaddr, \u0026peer-\u003eht_key.addr) \u0026\u0026\n+\t\t peer-\u003eht_key.hnet == key-\u003ehnet);\n+}\n+\n+/**\n+ * homa_route_xmit() - Transmit a packet according to a given route.\n+ * @skb:      Packet to transmit.\n+ * @hsk:      Socket on which to transmit packet.\n+ * @route:    Route to use to transmit packet.\n+ * @priority: Priority for packet.\n+ * Return:    0 for success, otherwise a negative errno.\n+ */\n+static inline int homa_route_xmit(struct sk_buff *skb, struct homa_sock *hsk,\n+\t\t\t\t  struct homa_route *route, int priority)\n+{\n+\trcu_read_lock();\n+\tdst_hold(rcu_dereference(route-\u003edst));\n+\tskb_dst_set(skb, rcu_dereference(route-\u003edst));\n+\trcu_read_unlock();\n+\tif (ipv6_addr_v4mapped(\u0026route-\u003epeer-\u003eaddr)) {\n+\t\thsk-\u003einet.tos = priority \u003c\u003c 5;\n+\t\treturn ip_queue_xmit(\u0026hsk-\u003einet.sk, skb, \u0026route-\u003eflow);\n+\t}\n+\treturn ip6_xmit(\u0026hsk-\u003einet.sk, skb, \u0026route-\u003eflow.u.ip6, 0,\n+\t\t\tNULL, priority \u003c\u003c 5, 0);\n+}\n+\n+/**\n+ * homa_peer_unlink() - Remove the connection between a route and its peer,\n+ * potentially freeing the peer in the process.\n+ * @route:    Route to disconnect.\n+ */\n+static inline void homa_peer_unlink(struct homa_route *route)\n+\t__must_hold(route-\u003ehnet-\u003ehoma-\u003epeertab-\u003elock)\n+{\n+\tstruct homa_peertab *peertab;\n+\n+\tif (!route-\u003epeer)\n+\t\treturn;\n+\n+\t/* Note: we don't need to use RCU for freeing peers because we have\n+\t * already used RCU for freeing routes, so we know there are no\n+\t * outstanding uses. By holding the peertab lock we have locked\n+\t * out calls to homa_peer_get.\n+\t */\n+\tpeertab = route-\u003ekey.hnet-\u003ehoma-\u003epeertab;\n+\tif (refcount_dec_and_test(\u0026route-\u003epeer-\u003erefs)) {\n+\t\trhashtable_remove_fast(\u0026peertab-\u003epeer_ht,\n+\t\t\t\t       \u0026route-\u003epeer-\u003eht_linkage,\n+\t\t\t\t       peer_ht_params);\n+\t\thoma_peer_free(route-\u003epeer);\n+\t}\n+\troute-\u003epeer = NULL;\n+}\n+\n+/**\n+ * homa_route_key_init() - Initialize the fields of a key for\n+ * peertab-\u003eroute_ht. Note: caller must hold an RCU read lock.\n+ * @key:      Key to initialize\n+ * @hsk:      Socket from which to pull fields for the key other than\n+ *            daddr.\n+ * @daddr:    Destination address for the key.\n+ */\n+static inline void homa_route_key_init(struct homa_route_key *key,\n+\t\t\t\t       const struct homa_sock *hsk,\n+\t\t\t\t       const struct in6_addr *daddr)\n+{\n+\tstruct flowi_common flowic;\n+\n+\tmemset(key, 0, sizeof(*key));\n+\tif (hsk-\u003esock.sk_family == AF_INET)\n+\t\tipv6_addr_set_v4mapped(hsk-\u003einet.inet_saddr, \u0026key-\u003esaddr);\n+\telse\n+\t\tkey-\u003esaddr = hsk-\u003einet.pinet6-\u003esaddr;\n+\tkey-\u003edaddr = *daddr;\n+\tkey-\u003ehnet = hsk-\u003ehnet;\n+\tkey-\u003esk_policy_out = rcu_dereference(hsk-\u003esock.sk_policy[XFRM_POLICY_OUT]);\n+\tkey-\u003euid = hsk-\u003esock.sk_uid;\n+\tkey-\u003emark = hsk-\u003esock.sk_mark;\n+\tflowic.flowic_secid = 0;\n+\tsecurity_sk_classify_flow(\u0026hsk-\u003esock, \u0026flowic);\n+\tkey-\u003esecid = flowic.flowic_secid;\n+\tkey-\u003ebound_dev_if = hsk-\u003esock.sk_bound_dev_if;\n+}\n+\n+#endif /* _HOMA_PEER_H */\ndiff --git a/net/homa/homa_plumbing.c b/net/homa/homa_plumbing.c\nnew file mode 100644\nindex 0000000000000..de3483b21d489\n--- /dev/null\n+++ b/net/homa/homa_plumbing.c\n@@ -0,0 +1,1302 @@\n+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+\n+/* This file consists mostly of \"glue\" that hooks Homa into the rest of\n+ * the Linux kernel. The guts of the protocol are in other files.\n+ */\n+\n+#include \"homa_impl.h\"\n+#include \"homa_peer.h\"\n+#include \"homa_pool.h\"\n+\n+/* Identifier for retrieving Homa-specific data for a struct net. */\n+unsigned int homa_net_id;\n+\n+/* This structure defines functions that allow Homa to be used as a\n+ * pernet subsystem.\n+ */\n+static struct pernet_operations homa_net_ops = {\n+\t.init = homa_net_start,\n+\t.exit = homa_net_exit,\n+\t.id = \u0026homa_net_id,\n+\t.size = sizeof(struct homa_net)\n+};\n+\n+/* Global data for Homa. Avoid referencing directly except when there is\n+ * no alternative (instead, use a homa pointer stored in a struct or\n+ * passed via a parameter). This allows overriding during unit tests.\n+ */\n+static struct homa homa_data;\n+\n+/* This structure defines functions that handle various operations on\n+ * Homa sockets. These functions are relatively generic: they are called\n+ * to implement top-level system calls. Many of these operations can\n+ * be implemented by PF_INET6 functions that are independent of the\n+ * Homa protocol.\n+ */\n+static const struct proto_ops homa_proto_ops = {\n+\t.family\t\t   = PF_INET,\n+\t.owner\t\t   = THIS_MODULE,\n+\t.release\t   = inet_release,\n+\t.bind\t\t   = homa_bind,\n+\t.connect\t   = inet_dgram_connect,\n+\t.socketpair\t   = sock_no_socketpair,\n+\t.accept\t\t   = sock_no_accept,\n+\t.getname\t   = inet_getname,\n+\t.poll\t\t   = homa_poll,\n+\t.ioctl\t\t   = homa_ioctl,\n+\t.listen\t\t   = sock_no_listen,\n+\t.shutdown\t   = homa_shutdown,\n+\t.setsockopt\t   = sock_common_setsockopt,\n+\t.getsockopt\t   = sock_common_getsockopt,\n+\t.sendmsg\t   = inet_sendmsg,\n+\t.recvmsg\t   = inet_recvmsg,\n+\t.mmap\t\t   = sock_no_mmap,\n+\t.set_peek_off\t   = sk_set_peek_off,\n+};\n+\n+static const struct proto_ops homav6_proto_ops = {\n+\t.family\t\t   = PF_INET6,\n+\t.owner\t\t   = THIS_MODULE,\n+\t.release\t   = inet6_release,\n+\t.bind\t\t   = homa_bind,\n+\t.connect\t   = inet_dgram_connect,\n+\t.socketpair\t   = sock_no_socketpair,\n+\t.accept\t\t   = sock_no_accept,\n+\t.getname\t   = inet6_getname,\n+\t.poll\t\t   = homa_poll,\n+\t.ioctl\t\t   = homa_ioctl,\n+\t.listen\t\t   = sock_no_listen,\n+\t.shutdown\t   = homa_shutdown,\n+\t.setsockopt\t   = sock_common_setsockopt,\n+\t.getsockopt\t   = sock_common_getsockopt,\n+\t.sendmsg\t   = inet_sendmsg,\n+\t.recvmsg\t   = inet_recvmsg,\n+\t.mmap\t\t   = sock_no_mmap,\n+\t.set_peek_off\t   = sk_set_peek_off,\n+};\n+\n+/* This structure also defines functions that handle various operations\n+ * on Homa sockets. However, these functions are lower-level than those\n+ * in homa_proto_ops: they are specific to the PF_INET or PF_INET6\n+ * protocol family, and in many cases they are invoked by functions in\n+ * homa_proto_ops. Most of these functions have Homa-specific implementations.\n+ */\n+static struct proto homa_prot = {\n+\t.name\t\t   = \"HOMA\",\n+\t.owner\t\t   = THIS_MODULE,\n+\t.close\t\t   = homa_close,\n+\t.connect\t   = ip4_datagram_connect,\n+\t.init\t\t   = homa_socket,\n+\t.destroy\t   = homa_sock_destroy,\n+\t.setsockopt\t   = homa_setsockopt,\n+\t.getsockopt\t   = homa_getsockopt,\n+\t.sendmsg\t   = homa_sendmsg,\n+\t.recvmsg\t   = homa_recvmsg,\n+\t.hash\t\t   = homa_hash,\n+\t.unhash\t\t   = homa_unhash,\n+\t.obj_size\t   = sizeof(struct homa_sock),\n+\t.no_autobind       = 1,\n+};\n+\n+static struct proto homav6_prot = {\n+\t.name\t\t   = \"HOMAv6\",\n+\t.owner\t\t   = THIS_MODULE,\n+\t.close\t\t   = homa_close,\n+\t.connect\t   = ip6_datagram_connect,\n+\t.init\t\t   = homa_socket,\n+\t.destroy\t   = homa_sock_destroy,\n+\t.setsockopt\t   = homa_setsockopt,\n+\t.getsockopt\t   = homa_getsockopt,\n+\t.sendmsg\t   = homa_sendmsg,\n+\t.recvmsg\t   = homa_recvmsg,\n+\t.hash\t\t   = homa_hash,\n+\t.unhash\t\t   = homa_unhash,\n+\t.obj_size\t   = sizeof(struct homa_v6_sock),\n+\t.ipv6_pinfo_offset = offsetof(struct homa_v6_sock, inet6),\n+\t.no_autobind       = 1,\n+};\n+\n+/* Top-level structure describing the Homa protocol. */\n+static struct inet_protosw homa_protosw = {\n+\t.type              = SOCK_DGRAM,\n+\t.protocol          = IPPROTO_HOMA,\n+\t.prot              = \u0026homa_prot,\n+\t.ops               = \u0026homa_proto_ops,\n+\t.flags             = INET_PROTOSW_REUSE,\n+};\n+\n+static struct inet_protosw homav6_protosw = {\n+\t.type              = SOCK_DGRAM,\n+\t.protocol          = IPPROTO_HOMA,\n+\t.prot              = \u0026homav6_prot,\n+\t.ops               = \u0026homav6_proto_ops,\n+\t.flags             = INET_PROTOSW_REUSE,\n+};\n+\n+/* This structure is used by IP to deliver incoming Homa packets to us. */\n+static struct net_protocol homa_protocol = {\n+\t.handler =\thoma_softirq,\n+\t.err_handler =\thoma_err_handler_v4,\n+\t.no_policy =     1,\n+};\n+\n+static struct inet6_protocol homav6_protocol = {\n+\t.handler =\thoma_softirq,\n+\t.err_handler =\thoma_err_handler_v6,\n+\t.flags =        INET6_PROTO_NOPOLICY | INET6_PROTO_FINAL,\n+};\n+\n+/* Sizes of the headers for each Homa packet type, in bytes. */\n+static u16 header_lengths[] = {\n+\tsizeof(struct homa_data_hdr),\n+\t0,\n+\tsizeof(struct homa_resend_hdr),\n+\tsizeof(struct homa_rpc_unknown_hdr),\n+\tsizeof(struct homa_busy_hdr),\n+\t0,\n+\t0,\n+\tsizeof(struct homa_need_ack_hdr),\n+\tsizeof(struct homa_ack_hdr)\n+};\n+\n+/* Thread that runs timer code to detect lost packets and crashed peers. */\n+static struct task_struct *timer_kthread;\n+\n+/* Used to wakeup timer_kthread at regular intervals. */\n+static struct hrtimer hrtimer;\n+\n+/**\n+ * homa_load() - invoked when this module is loaded into the Linux kernel\n+ * Return: 0 on success, otherwise a negative errno.\n+ */\n+int __init homa_load(void)\n+{\n+\tstruct homa *homa = \u0026homa_data;\n+\tbool init_protocol6 = false;\n+\tbool init_protosw6 = false;\n+\tbool init_protocol = false;\n+\tbool init_protosw = false;\n+\tbool init_net_ops = false;\n+\tbool init_proto6 = false;\n+\tbool init_proto = false;\n+\tbool init_homa = false;\n+\tint status;\n+\n+\t/* Compile-time validations that no packet header is longer\n+\t * than HOMA_MAX_HEADER.\n+\t */\n+\tBUILD_BUG_ON(sizeof(struct homa_data_hdr) \u003e HOMA_MAX_HEADER);\n+\tBUILD_BUG_ON(sizeof(struct homa_resend_hdr) \u003e HOMA_MAX_HEADER);\n+\tBUILD_BUG_ON(sizeof(struct homa_rpc_unknown_hdr) \u003e HOMA_MAX_HEADER);\n+\tBUILD_BUG_ON(sizeof(struct homa_busy_hdr) \u003e HOMA_MAX_HEADER);\n+\tBUILD_BUG_ON(sizeof(struct homa_need_ack_hdr) \u003e HOMA_MAX_HEADER);\n+\tBUILD_BUG_ON(sizeof(struct homa_ack_hdr) \u003e HOMA_MAX_HEADER);\n+\n+\t/* Extra constraints on data packets:\n+\t * - Ensure minimum header length so Homa doesn't have to worry about\n+\t *   padding data packets.\n+\t * - Make sure data packet headers are a multiple of 4 bytes (needed\n+\t *   for TCP/TSO compatibility).\n+\t */\n+\tBUILD_BUG_ON(sizeof(struct homa_data_hdr) \u003c HOMA_MIN_PKT_LENGTH);\n+\tBUILD_BUG_ON((sizeof(struct homa_data_hdr) -\n+\t\t      sizeof(struct homa_seg_hdr)) \u0026 0x3);\n+\n+\t/* Detect size changes in uAPI structs. */\n+\tBUILD_BUG_ON(sizeof(struct homa_sendmsg_args) != 24);\n+\tBUILD_BUG_ON(sizeof(struct homa_recvmsg_args) != 88);\n+\n+\tstatus = homa_init(homa);\n+\tif (status)\n+\t\tgoto error;\n+\tinit_homa = true;\n+\n+\tstatus = register_pernet_subsys(\u0026homa_net_ops);\n+\tif (status != 0) {\n+\t\tpr_err(\"Homa got error from register_pernet_subsys: %d\\n\",\n+\t\t       status);\n+\t\tgoto error;\n+\t}\n+\tinit_net_ops = true;\n+\n+\tstatus = proto_register(\u0026homa_prot, 1);\n+\tif (status != 0) {\n+\t\tpr_err(\"proto_register failed for homa_prot: %d\\n\", status);\n+\t\tgoto error;\n+\t}\n+\tinit_proto = true;\n+\n+\tstatus = proto_register(\u0026homav6_prot, 1);\n+\tif (status != 0) {\n+\t\tpr_err(\"proto_register failed for homav6_prot: %d\\n\", status);\n+\t\tgoto error;\n+\t}\n+\tinit_proto6 = true;\n+\n+\tinet_register_protosw(\u0026homa_protosw);\n+\tinit_protosw = true;\n+\n+\tstatus = inet6_register_protosw(\u0026homav6_protosw);\n+\tif (status != 0) {\n+\t\tpr_err(\"inet6_register_protosw failed in %s: %d\\n\", __func__,\n+\t\t       status);\n+\t\tgoto error;\n+\t}\n+\tinit_protosw6 = true;\n+\n+\tstatus = inet_add_protocol(\u0026homa_protocol, IPPROTO_HOMA);\n+\tif (status != 0) {\n+\t\tpr_err(\"inet_add_protocol failed in %s: %d\\n\", __func__,\n+\t\t       status);\n+\t\tgoto error;\n+\t}\n+\tinit_protocol = true;\n+\n+\tstatus = inet6_add_protocol(\u0026homav6_protocol, IPPROTO_HOMA);\n+\tif (status != 0) {\n+\t\tpr_err(\"inet6_add_protocol failed in %s: %d\\n\",  __func__,\n+\t\t       status);\n+\t\tgoto error;\n+\t}\n+\tinit_protocol6 = true;\n+\n+\ttimer_kthread = kthread_run(homa_timer_main, homa, \"homa_timer\");\n+\tif (IS_ERR(timer_kthread)) {\n+\t\tstatus = PTR_ERR(timer_kthread);\n+\t\tpr_err(\"couldn't create Homa timer thread: error %d\\n\",\n+\t\t       status);\n+\t\ttimer_kthread = NULL;\n+\t\tgoto error;\n+\t}\n+\n+\treturn 0;\n+\n+error:\n+\tif (timer_kthread)\n+\t\tkthread_stop(timer_kthread);\n+\tif (init_homa)\n+\t\thoma_destroy(homa);\n+\tif (init_protocol)\n+\t\tinet_del_protocol(\u0026homa_protocol, IPPROTO_HOMA);\n+\tif (init_protocol6)\n+\t\tinet6_del_protocol(\u0026homav6_protocol, IPPROTO_HOMA);\n+\tif (init_protosw)\n+\t\tinet_unregister_protosw(\u0026homa_protosw);\n+\tif (init_protosw6)\n+\t\tinet6_unregister_protosw(\u0026homav6_protosw);\n+\tif (init_proto)\n+\t\tproto_unregister(\u0026homa_prot);\n+\tif (init_proto6)\n+\t\tproto_unregister(\u0026homav6_prot);\n+\tif (init_net_ops)\n+\t\tunregister_pernet_subsys(\u0026homa_net_ops);\n+\treturn status;\n+}\n+\n+/**\n+ * homa_unload() - invoked when this module is unloaded from the Linux kernel.\n+ */\n+void __exit homa_unload(void)\n+{\n+\tstruct homa *homa = \u0026homa_data;\n+\n+\tpr_notice(\"Homa module unloading\\n\");\n+\n+\tif (timer_kthread)\n+\t\tkthread_stop(timer_kthread);\n+\tinet_del_protocol(\u0026homa_protocol, IPPROTO_HOMA);\n+\tinet_unregister_protosw(\u0026homa_protosw);\n+\tinet6_del_protocol(\u0026homav6_protocol, IPPROTO_HOMA);\n+\tinet6_unregister_protosw(\u0026homav6_protosw);\n+\tproto_unregister(\u0026homa_prot);\n+\tproto_unregister(\u0026homav6_prot);\n+\tunregister_pernet_subsys(\u0026homa_net_ops);\n+\thoma_destroy(homa);\n+}\n+\n+module_init(homa_load);\n+module_exit(homa_unload);\n+\n+/**\n+ * homa_net_start() - Initialize Homa for a new network namespace.\n+ * @net:    The net that Homa will be associated with.\n+ * Return:  0 on success, otherwise a negative errno.\n+ */\n+int homa_net_start(struct net *net)\n+{\n+\tpr_notice(\"Homa attaching to net namespace\\n\");\n+\treturn homa_net_init(homa_net(net), \u0026homa_data);\n+}\n+\n+/**\n+ * homa_net_exit() - Perform Homa cleanup needed when a network namespace\n+ * is destroyed.\n+ * @net:    The net from which Homa should be removed.\n+ */\n+void homa_net_exit(struct net *net)\n+{\n+\tpr_notice(\"Homa detaching from net namespace\\n\");\n+\thoma_net_destroy(homa_net(net));\n+}\n+\n+/**\n+ * homa_bind() - Implements the bind system call for Homa sockets: associates\n+ * a well-known service port with a socket. Unlike other AF_INET6 protocols,\n+ * there is no need to invoke this system call for sockets that are only\n+ * used as clients.\n+ * @sock:     Socket on which the system call was invoked.\n+ * @addr:     Contains the desired port number.\n+ * @addr_len: Number of bytes in uaddr.\n+ * Return:    0 on success, otherwise a negative errno. Sets hsk-\u003eerror_msg\n+ *            on errors.\n+ */\n+int homa_bind(struct socket *sock, struct sockaddr_unsized *addr, int addr_len)\n+{\n+\tunion sockaddr_in_union *addr_in = (union sockaddr_in_union *)addr;\n+\tstruct homa_sock *hsk = homa_sk(sock-\u003esk);\n+\tint port = 0;\n+\n+\tif (unlikely(addr-\u003esa_family != sock-\u003esk-\u003esk_family)) {\n+\t\thsk-\u003eerror_msg = \"address family in bind address didn't match socket\";\n+\t\treturn -EAFNOSUPPORT;\n+\t}\n+\tif (addr_in-\u003ein6.sin6_family == AF_INET6) {\n+\t\tif (addr_len \u003c sizeof(struct sockaddr_in6)) {\n+\t\t\thsk-\u003eerror_msg = \"ipv6 address too short\";\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\t\tport = ntohs(addr_in-\u003ein6.sin6_port);\n+\t} else if (addr_in-\u003ein4.sin_family == AF_INET) {\n+\t\tif (addr_len \u003c sizeof(struct sockaddr_in)) {\n+\t\t\thsk-\u003eerror_msg = \"ipv4 address too short\";\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\t\tport = ntohs(addr_in-\u003ein4.sin_port);\n+\t}\n+\treturn homa_sock_bind(hsk-\u003ehnet, hsk, port);\n+}\n+\n+/**\n+ * homa_close() - Invoked when close system call is invoked on a Homa socket.\n+ * @sk:      Socket being closed\n+ * @timeout: ??\n+ */\n+void homa_close(struct sock *sk, long timeout)\n+{\n+\tstruct homa_sock *hsk = homa_sk(sk);\n+\n+\thoma_sock_shutdown(hsk);\n+\tsk_common_release(sk);\n+}\n+\n+/**\n+ * homa_shutdown() - Implements the shutdown system call for Homa sockets.\n+ * @sock:    Socket to shut down.\n+ * @how:     Ignored: for other sockets, can independently shut down\n+ *           sending and receiving, but for Homa any shutdown will\n+ *           shut down everything.\n+ *\n+ * Return: 0 on success, otherwise a negative errno.\n+ */\n+int homa_shutdown(struct socket *sock, int how)\n+{\n+\thoma_sock_shutdown(homa_sk(sock-\u003esk));\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_ioc_info() - The top-level function that implements the\n+ * HOMAIOCINFO ioctl for Homa sockets.\n+ * @sock:  Socket for this request\n+ * @arg:   The address in user space of the argument to ioctl, which\n+ *          is a homa_info struct.\n+ *\n+ * Return:  0 on success, otherwise a negative errno. Sets hsk-\u003eerror_msg\n+ *          on errors.\n+ */\n+int homa_ioc_info(struct socket *sock, unsigned long arg)\n+{\n+\tstruct homa_sock *hsk = homa_sk(sock-\u003esk);\n+\tstruct homa_rpc **rpcs = NULL;\n+\tstruct homa_rpc_info rinfo;\n+\tstruct homa_info hinfo;\n+\tstruct homa_rpc *rpc;\n+\tint result = 0;\n+\tint bytes_avl;\n+\tint num_rpcs;\n+\tchar *dst;\n+\tint i;\n+\n+\tif (unlikely(copy_from_user(\u0026hinfo, (void __user *)arg,\n+\t\t\t\t    sizeof(hinfo)))) {\n+\t\thsk-\u003eerror_msg = \"invalid address for homa_info\";\n+\t\treturn -EFAULT;\n+\t}\n+\n+\tif (!homa_protect_rpcs(hsk)) {\n+\t\thsk-\u003eerror_msg = \"socket has been shut down\";\n+\t\treturn -ESHUTDOWN;\n+\t}\n+\thinfo.bpool_avail_bytes = homa_pool_avail_bytes(hsk-\u003ebuffer_pool);\n+\thinfo.port = hsk-\u003eport;\n+\tdst = (char *)hinfo.rpc_info;\n+\tbytes_avl = hinfo.rpc_info_length;\n+\thinfo.num_rpcs = 0;\n+\n+\t/* This function is tricky because we need to hold an RCU lock\n+\t * while scanning the RPCs of the socket, but we can't hold the\n+\t * RCU lock while copying status information out to user space.\n+\t * Thus, we first collect pointers to all the RPCs in a separate\n+\t * array (while holding an RCU lock), acquire a reference on each\n+\t * RPC, then release the RCU lock and copy out to user space.\n+\t */\n+\tnum_rpcs = 0;\n+\trcu_read_lock();\n+\tlist_for_each_entry_rcu(rpc, \u0026hsk-\u003eactive_rpcs, active_links)\n+\t\tnum_rpcs++;\n+\n+\tif (num_rpcs \u003e 0) {\n+\t\t/* Allocate an array and populate it with homa_rpc pointers.\n+\t\t * Must release the RCU lock temporarily while allocating.\n+\t\t */\n+\t\trcu_read_unlock();\n+\t\trpcs = kmalloc_objs(*rpcs, num_rpcs, GFP_KERNEL_ACCOUNT);\n+\t\tif (!rpcs) {\n+\t\t\thoma_unprotect_rpcs(hsk);\n+\t\t\treturn -ENOMEM;\n+\t\t}\n+\t\trcu_read_lock();\n+\t\ti = 0;\n+\t\tlist_for_each_entry_rcu(rpc, \u0026hsk-\u003eactive_rpcs, active_links) {\n+\t\t\thoma_rpc_lock(rpc);\n+\t\t\tif (rpc-\u003estate != RPC_DEAD) {\n+\t\t\t\trpcs[i] = rpc;\n+\t\t\t\thoma_rpc_hold(rpc);\n+\t\t\t\ti++;\n+\t\t\t}\n+\t\t\thoma_rpc_unlock(rpc);\n+\t\t\tif (i == num_rpcs)\n+\t\t\t\tbreak;\n+\t\t}\n+\t\t/* The number of RPCs could have changed between the first\n+\t\t * pass and the second pass.\n+\t\t */\n+\t\tnum_rpcs = i;\n+\t}\n+\trcu_read_unlock();\n+\thoma_unprotect_rpcs(hsk);\n+\n+\t/* Now scan the array and copy information out to user space.  Note\n+\t * that RPCs could have ended since we added them to the array.\n+\t */\n+\tfor (i = 0; i \u003c num_rpcs; i++) {\n+\t\trpc = rpcs[i];\n+\t\thoma_rpc_lock(rpc);\n+\t\thoma_rpc_put(rpc);\n+\t\tif (rpc-\u003estate == RPC_DEAD) {\n+\t\t\thoma_rpc_unlock(rpc);\n+\t\t\tcontinue;\n+\t\t}\n+\t\thoma_rpc_get_info(rpc, \u0026rinfo);\n+\t\thoma_rpc_unlock(rpc);\n+\t\tif (dst \u0026\u0026 bytes_avl \u003e= sizeof(rinfo) \u0026\u0026 result == 0) {\n+\t\t\tif (copy_to_user((void __user *)dst, \u0026rinfo,\n+\t\t\t\t\t sizeof(rinfo))) {\n+\t\t\t\thsk-\u003eerror_msg = \"couldn't copy homa_rpc_info to user space: invalid or read-only address?\";\n+\t\t\t\tresult = -EFAULT;\n+\t\t\t}\n+\t\t\tdst += sizeof(rinfo);\n+\t\t\tbytes_avl -= sizeof(rinfo);\n+\t\t}\n+\t\thinfo.num_rpcs++;\n+\t}\n+\tkfree(rpcs);\n+\n+\tsnprintf(hinfo.error_msg, HOMA_ERROR_MSG_SIZE, \"%s\", hsk-\u003eerror_msg);\n+\n+\tif (copy_to_user((void __user *)arg, \u0026hinfo, sizeof(hinfo))) {\n+\t\thsk-\u003eerror_msg = \"couldn't copy homa_info to user space: read-only address?\";\n+\t\treturn -EFAULT;\n+\t}\n+\treturn result;\n+}\n+\n+/**\n+ * homa_ioctl() - Implements the ioctl system call for Homa sockets.\n+ * @sock:  Socket on which the system call was invoked.\n+ * @cmd:   Identifier for a particular ioctl operation.\n+ * @arg:   Operation-specific argument; typically the address of a block\n+ *         of data in user address space.\n+ *\n+ * Return: 0 on success, otherwise a negative errno. Sets hsk-\u003eerror_msg\n+ *         on errors.\n+ */\n+int homa_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)\n+{\n+\tif (cmd == HOMAIOCINFO)\n+\t\treturn homa_ioc_info(sock, arg);\n+\thoma_sk(sock-\u003esk)-\u003eerror_msg = \"ioctl opcode isn't supported by Homa\";\n+\treturn -EINVAL;\n+}\n+\n+/**\n+ * homa_socket() - Implements the socket(2) system call for sockets.\n+ * @sk:    Socket on which the system call was invoked. The non-Homa\n+ *         parts have already been initialized.\n+ *\n+ * Return: always 0 (success).\n+ */\n+int homa_socket(struct sock *sk)\n+{\n+\treturn homa_sock_init(homa_sk(sk));\n+}\n+\n+/**\n+ * homa_setsockopt() - Implements the setsockopt system call for Homa sockets.\n+ * @sk:      Socket on which the system call was invoked.\n+ * @level:   Level at which the operation should be handled; will always\n+ *           be IPPROTO_HOMA.\n+ * @optname: Identifies a particular setsockopt operation.\n+ * @optval:  Address in user space of information about the option.\n+ * @optlen:  Number of bytes of data at @optval.\n+ * Return:   0 on success, otherwise a negative errno. Sets hsk-\u003eerror_msg\n+ *           on errors.\n+ */\n+int homa_setsockopt(struct sock *sk, int level, int optname,\n+\t\t    sockptr_t optval, unsigned int optlen)\n+{\n+\tstruct homa_sock *hsk = homa_sk(sk);\n+\tint ret;\n+\n+\tif (level != IPPROTO_HOMA) {\n+\t\thsk-\u003eerror_msg = \"homa_setsockopt invoked with level not IPPROTO_HOMA\";\n+\t\treturn -ENOPROTOOPT;\n+\t}\n+\n+\tif (optname == SO_HOMA_RCVBUF) {\n+\t\tstruct homa_rcvbuf_args args;\n+\n+\t\tif (optlen != sizeof(struct homa_rcvbuf_args)) {\n+\t\t\thsk-\u003eerror_msg = \"invalid optlen argument: must be sizeof(struct homa_rcvbuf_args)\";\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\n+\t\tif (copy_from_sockptr(\u0026args, optval, optlen)) {\n+\t\t\thsk-\u003eerror_msg = \"invalid address for homa_rcvbuf_args\";\n+\t\t\treturn -EFAULT;\n+\t\t}\n+\n+\t\t/* Do a trivial test to make sure we can at least write the\n+\t\t * first page of the region.\n+\t\t */\n+\t\tif (copy_to_user(u64_to_user_ptr(args.start), \u0026args,\n+\t\t\t\t sizeof(args))) {\n+\t\t\thsk-\u003eerror_msg = \"receive buffer region is not writable\";\n+\t\t\treturn -EFAULT;\n+\t\t}\n+\n+\t\tret = homa_pool_set_region(hsk, u64_to_user_ptr(args.start),\n+\t\t\t\t\t   args.length);\n+\t} else if (optname == SO_HOMA_SERVER) {\n+\t\tint arg;\n+\n+\t\tif (optlen != sizeof(arg)) {\n+\t\t\thsk-\u003eerror_msg = \"invalid optlen argument: must be sizeof(int)\";\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\n+\t\tif (copy_from_sockptr(\u0026arg, optval, optlen)) {\n+\t\t\thsk-\u003eerror_msg = \"invalid address for SO_HOMA_SERVER value\";\n+\t\t\treturn -EFAULT;\n+\t\t}\n+\n+\t\tif (arg)\n+\t\t\thsk-\u003eis_server = true;\n+\t\telse\n+\t\t\thsk-\u003eis_server = false;\n+\t\tret = 0;\n+\t} else {\n+\t\thsk-\u003eerror_msg = \"setsockopt option not supported by Homa\";\n+\t\tret = -ENOPROTOOPT;\n+\t}\n+\treturn ret;\n+}\n+\n+/**\n+ * homa_getsockopt() - Implements the getsockopt system call for Homa sockets.\n+ * @sk:      Socket on which the system call was invoked.\n+ * @level:   Selects level in the network stack to handle the request;\n+ *           must be IPPROTO_HOMA.\n+ * @optname: Identifies a particular setsockopt operation.\n+ * @optval:  Address in user space where the option's value should be stored.\n+ * @optlen:  Number of bytes available at optval; will be overwritten with\n+ *           actual number of bytes stored.\n+ * Return:   0 on success, otherwise a negative errno. Sets hsk-\u003eerror_msg\n+ *           on errors.\n+ */\n+int homa_getsockopt(struct sock *sk, int level, int optname,\n+\t\t    char __user *optval, int __user *optlen)\n+{\n+\tstruct homa_sock *hsk = homa_sk(sk);\n+\tstruct homa_rcvbuf_args rcvbuf_args;\n+\tint is_server;\n+\tvoid *result;\n+\tint len;\n+\n+\tif (copy_from_sockptr(\u0026len, USER_SOCKPTR(optlen), sizeof(int))) {\n+\t\thsk-\u003eerror_msg = \"invalid address for optlen argument to getsockopt\";\n+\t\treturn -EFAULT;\n+\t}\n+\n+\tif (level != IPPROTO_HOMA) {\n+\t\thsk-\u003eerror_msg = \"homa_getsockopt invoked with level not IPPROTO_HOMA\";\n+\t\treturn -ENOPROTOOPT;\n+\t}\n+\tif (optname == SO_HOMA_RCVBUF) {\n+\t\tif (len \u003c sizeof(rcvbuf_args)) {\n+\t\t\thsk-\u003eerror_msg = \"invalid optlen argument: must be sizeof(struct homa_rcvbuf_args)\";\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\n+\t\thoma_sock_lock(hsk);\n+\t\thoma_pool_get_rcvbuf(hsk-\u003ebuffer_pool, \u0026rcvbuf_args);\n+\t\thoma_sock_unlock(hsk);\n+\t\tlen = sizeof(rcvbuf_args);\n+\t\tresult = \u0026rcvbuf_args;\n+\t} else if (optname == SO_HOMA_SERVER) {\n+\t\tif (len \u003c sizeof(is_server)) {\n+\t\t\thsk-\u003eerror_msg = \"invalid optlen argument: must be sizeof(int)\";\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\n+\t\tis_server = hsk-\u003eis_server;\n+\t\tlen = sizeof(is_server);\n+\t\tresult = \u0026is_server;\n+\t} else {\n+\t\thsk-\u003eerror_msg = \"getsockopt option not supported by Homa\";\n+\t\treturn -ENOPROTOOPT;\n+\t}\n+\n+\tif (copy_to_sockptr(USER_SOCKPTR(optlen), \u0026len, sizeof(int))) {\n+\t\thsk-\u003eerror_msg = \"couldn't update optlen argument to getsockopt: read-only?\";\n+\t\treturn -EFAULT;\n+\t}\n+\n+\tif (copy_to_sockptr(USER_SOCKPTR(optval), result, len)) {\n+\t\thsk-\u003eerror_msg = \"couldn't update optval argument to getsockopt: read-only?\";\n+\t\treturn -EFAULT;\n+\t}\n+\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_sendmsg() - Send a request or response message on a Homa socket.\n+ * @sk:     Socket on which the system call was invoked.\n+ * @msg:    Structure describing the message to send; the msg_control\n+ *          field points to additional information.\n+ * @length: Number of bytes of the message.\n+ * Return:  0 on success, otherwise a negative errno. Sets hsk-\u003eerror_msg\n+ *          on errors.\n+ */\n+int homa_sendmsg(struct sock *sk, struct msghdr *msg, size_t length)\n+{\n+\tDECLARE_SOCKADDR(union sockaddr_in_union *, addr, msg-\u003emsg_name);\n+\tstruct homa_sock *hsk = homa_sk(sk);\n+\tstruct homa_sendmsg_args args;\n+\tstruct homa_rpc *rpc = NULL;\n+\tint result = 0;\n+\n+\tif (!addr) {\n+\t\thsk-\u003eerror_msg = \"no msg_name passed to sendmsg\";\n+\t\tresult = -EINVAL;\n+\t\tgoto error;\n+\t}\n+\n+\tif (unlikely(!msg-\u003emsg_control_is_user)) {\n+\t\thsk-\u003eerror_msg = \"msg_control argument for sendmsg isn't in user space\";\n+\t\tresult = -EINVAL;\n+\t\tgoto error;\n+\t}\n+\tif (unlikely(copy_from_user(\u0026args, (void __user *)msg-\u003emsg_control,\n+\t\t\t\t    sizeof(args)))) {\n+\t\thsk-\u003eerror_msg = \"invalid address for msg_control argument to sendmsg\";\n+\t\tresult = -EFAULT;\n+\t\tgoto error;\n+\t}\n+\tif (args.flags \u0026 ~HOMA_SENDMSG_VALID_FLAGS ||\n+\t    args.reserved != 0) {\n+\t\thsk-\u003eerror_msg = \"reserved fields in homa_sendmsg_args must be zero\";\n+\t\tresult = -EINVAL;\n+\t\tgoto error;\n+\t}\n+\n+\tif (!homa_sock_wmem_avl(hsk)) {\n+\t\tresult = homa_sock_wait_wmem(hsk,\n+\t\t\t\t\t     msg-\u003emsg_flags \u0026 MSG_DONTWAIT);\n+\t\tif (result != 0)\n+\t\t\tgoto error;\n+\t}\n+\n+\tif (addr-\u003esa.sa_family != sk-\u003esk_family) {\n+\t\thsk-\u003eerror_msg = \"address family in sendmsg address must match the socket\";\n+\t\tresult = -EAFNOSUPPORT;\n+\t\tgoto error;\n+\t}\n+\tif (msg-\u003emsg_namelen \u003c sizeof(struct sockaddr_in) ||\n+\t    (msg-\u003emsg_namelen \u003c sizeof(struct sockaddr_in6) \u0026\u0026\n+\t     addr-\u003ein6.sin6_family == AF_INET6)) {\n+\t\thsk-\u003eerror_msg = \"msg_namelen too short\";\n+\t\tresult = -EINVAL;\n+\t\tgoto error;\n+\t}\n+\n+\tif (unlikely(msg-\u003emsg_iter.count == 0)) {\n+\t\thsk-\u003eerror_msg = \"message has length zero\";\n+\t\tresult = -EINVAL;\n+\t\tgoto error;\n+\t}\n+\tif (unlikely(msg-\u003emsg_iter.count \u003e HOMA_MAX_MESSAGE_LENGTH)) {\n+\t\thsk-\u003eerror_msg = \"message length exceeded HOMA_MAX_MESSAGE_LENGTH\";\n+\t\tresult = -EINVAL;\n+\t\tgoto error;\n+\t}\n+\n+\tif (!args.id) {\n+\t\t/* This is a request message. */\n+\t\trpc = homa_rpc_alloc_client(hsk, addr);\n+\t\tif (IS_ERR(rpc)) {\n+\t\t\tresult = PTR_ERR(rpc);\n+\t\t\trpc = NULL;\n+\t\t\tgoto error;\n+\t\t}\n+\t\thoma_rpc_hold(rpc);\n+\t\tif (args.flags \u0026 HOMA_SENDMSG_PRIVATE)\n+\t\t\tset_bit(RPC_PRIVATE, \u0026rpc-\u003eflags);\n+\t\trpc-\u003ecompletion_cookie = args.completion_cookie;\n+\t\tresult = homa_tx_copy_from_user(rpc, \u0026msg-\u003emsg_iter, true);\n+\t\tif (result)\n+\t\t\tgoto error;\n+\t\targs.id = rpc-\u003eid;\n+\t\thoma_rpc_unlock(rpc); /* Locked by homa_rpc_alloc_client. */\n+\n+\t\tif (unlikely(copy_to_user((void __user *)msg-\u003emsg_control,\n+\t\t\t\t\t  \u0026args, sizeof(args)))) {\n+\t\t\thoma_rpc_lock(rpc);\n+\t\t\thsk-\u003eerror_msg = \"couldn't update homa_sendmsg_args argument to sendmsg: read-only?\";\n+\t\t\tresult = -EFAULT;\n+\t\t\tgoto error;\n+\t\t}\n+\t\thoma_rpc_put(rpc);\n+\t} else {\n+\t\t/* This is a response message. */\n+\t\tstruct in6_addr canonical_dest;\n+\n+\t\tif (args.completion_cookie != 0) {\n+\t\t\thsk-\u003eerror_msg = \"completion_cookie must be zero when sending responses\";\n+\t\t\tresult = -EINVAL;\n+\t\t\tgoto error;\n+\t\t}\n+\t\tcanonical_dest = canonical_ipv6_addr(addr);\n+\n+\t\trpc = homa_rpc_find_server(hsk, \u0026canonical_dest, args.id);\n+\t\tif (!rpc) {\n+\t\t\t/* Return without an error if the RPC doesn't exist;\n+\t\t\t * this could be totally valid (e.g. client is\n+\t\t\t * no longer interested in it).\n+\t\t\t */\n+\t\t\treturn 0;\n+\t\t}\n+\t\thoma_rpc_hold(rpc);\n+\t\tif (rpc-\u003eerror) {\n+\t\t\thsk-\u003eerror_msg = \"RPC has failed, so can't send response\";\n+\t\t\tresult = rpc-\u003eerror;\n+\t\t\tgoto error;\n+\t\t}\n+\t\tif (rpc-\u003estate != RPC_IN_SERVICE) {\n+\t\t\thsk-\u003eerror_msg = \"RPC is not in a state where a response can be sent\";\n+\t\t\tresult = -EINVAL;\n+\t\t\tgoto error_dont_end_rpc;\n+\t\t}\n+\t\trpc-\u003estate = RPC_OUTGOING;\n+\n+\t\tresult = homa_tx_copy_from_user(rpc, \u0026msg-\u003emsg_iter, true);\n+\t\tif (result \u0026\u0026 rpc-\u003estate != RPC_DEAD) {\n+\t\t\thsk-\u003eerror_msg = \"error copying response message data from user space\";\n+\t\t\tgoto error;\n+\t\t}\n+\t\thoma_rpc_put(rpc);\n+\t\thoma_rpc_unlock(rpc); /* Locked by homa_rpc_find_server. */\n+\t}\n+\treturn 0;\n+\n+error:\n+\tif (rpc)\n+\t\thoma_rpc_end(rpc);\n+\n+error_dont_end_rpc:\n+\tif (rpc) {\n+\t\thoma_rpc_put(rpc);\n+\n+\t\t/* Locked by homa_rpc_find_server or homa_rpc_alloc_client. */\n+\t\thoma_rpc_unlock(rpc);\n+\t}\n+\treturn result;\n+}\n+\n+/**\n+ * homa_recvmsg() - Receive a message from a Homa socket.\n+ * @sk:          Socket on which the system call was invoked.\n+ * @msg:         Controlling information for the receive.\n+ * @len:         Total bytes of space available in msg-\u003emsg_iov; not used.\n+ * @flags:       Flags from system call; only MSG_DONTWAIT is used.\n+ * Return:       The length of the message on success, otherwise a negative\n+ *               errno. Sets hsk-\u003eerror_msg on errors.\n+ */\n+int homa_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags)\n+{\n+\tstruct homa_sock *hsk = homa_sk(sk);\n+\tstruct homa_recvmsg_args control;\n+\tstruct homa_rpc *rpc = NULL;\n+\tint nonblocking;\n+\tint result;\n+\n+\tif (unlikely(!msg-\u003emsg_control)) {\n+\t\t/* This test isn't strictly necessary, but it provides a\n+\t\t * hook for testing kernel call times.\n+\t\t */\n+\t\thsk-\u003eerror_msg = \"no msg_control passed to recvmsg\";\n+\t\treturn -EINVAL;\n+\t}\n+\tif (msg-\u003emsg_controllen != sizeof(control)) {\n+\t\thsk-\u003eerror_msg = \"invalid msg_controllen in recvmsg\";\n+\t\treturn -EINVAL;\n+\t}\n+\tif (unlikely(copy_from_user(\u0026control, (void __user *)msg-\u003emsg_control,\n+\t\t\t\t    sizeof(control)))) {\n+\t\thsk-\u003eerror_msg = \"invalid address for msg_control argument to recvmsg\";\n+\t\treturn -EFAULT;\n+\t}\n+\tcontrol.completion_cookie = 0;\n+\n+\tif (control.num_bpages \u003e HOMA_MAX_BPAGES) {\n+\t\thsk-\u003eerror_msg = \"num_pages exceeds HOMA_MAX_BPAGES\";\n+\t\tresult = -EINVAL;\n+\t\tgoto done;\n+\t}\n+\tif (control.reserved != 0) {\n+\t\thsk-\u003eerror_msg = \"reserved fields in homa_recvmsg_args must be zero\";\n+\t\tresult = -EINVAL;\n+\t\tgoto done;\n+\t}\n+\tif (!hsk-\u003ebuffer_pool) {\n+\t\thsk-\u003eerror_msg = \"SO_HOMA_RECVBUF socket option has not been set\";\n+\t\tresult = -EINVAL;\n+\t\tgoto done;\n+\t}\n+\tresult = homa_pool_free_bufs(hsk-\u003ebuffer_pool, control.num_bpages,\n+\t\t\t\t     control.bpage_offsets);\n+\tcontrol.num_bpages = 0;\n+\tif (result != 0) {\n+\t\thsk-\u003eerror_msg = \"error while releasing buffer pages\";\n+\t\tgoto done;\n+\t}\n+\n+\tnonblocking = flags \u0026 MSG_DONTWAIT;\n+\tif (control.id != 0) {\n+\t\trpc = homa_rpc_find_client(hsk, control.id); /* Locks RPC. */\n+\t\tif (!rpc) {\n+\t\t\thsk-\u003eerror_msg = \"invalid RPC id passed to recvmsg\";\n+\t\t\tresult = -EINVAL;\n+\t\t\tgoto done;\n+\t\t}\n+\t\thoma_rpc_hold(rpc);\n+\t\tresult = homa_wait_private(rpc, nonblocking);\n+\t\tif (result != 0) {\n+\t\t\thsk-\u003eerror_msg = \"error while waiting for private RPC to complete\";\n+\t\t\tcontrol.id = 0;\n+\t\t\tgoto done;\n+\t\t}\n+\t} else {\n+\t\trpc = homa_wait_shared(hsk, nonblocking);\n+\t\tif (IS_ERR(rpc)) {\n+\t\t\t/* If we get here, it means there was an error that\n+\t\t\t * prevented us from finding an RPC to return. Errors\n+\t\t\t * in the RPC itself are handled below.\n+\t\t\t */\n+\t\t\thsk-\u003eerror_msg = \"error while waiting for shared RPC to complete\";\n+\t\t\tresult = PTR_ERR(rpc);\n+\t\t\trpc = NULL;\n+\t\t\tgoto done;\n+\t\t}\n+\t}\n+\tif (rpc-\u003eerror) {\n+\t\thsk-\u003eerror_msg = \"RPC failed\";\n+\t\tresult = rpc-\u003eerror;\n+\t} else {\n+\t\tresult = rpc-\u003emsgin.length;\n+\t}\n+\n+\t/* Collect result information. */\n+\tcontrol.id = rpc-\u003eid;\n+\tcontrol.completion_cookie = rpc-\u003ecompletion_cookie;\n+\tif (likely(result \u003e 0)) {\n+\t\tcontrol.num_bpages = rpc-\u003emsgin.num_bpages;\n+\t\tmemcpy(control.bpage_offsets, rpc-\u003emsgin.bpage_offsets,\n+\t\t       sizeof(rpc-\u003emsgin.bpage_offsets));\n+\t}\n+\tif (msg-\u003emsg_name) {\n+\t\tif (sk-\u003esk_family == AF_INET6) {\n+\t\t\tDECLARE_SOCKADDR(struct sockaddr_in6 *, in6,\n+\t\t\t\t\t msg-\u003emsg_name);\n+\n+\t\t\tin6-\u003esin6_family = AF_INET6;\n+\t\t\tin6-\u003esin6_port = htons(rpc-\u003edport);\n+\t\t\tin6-\u003esin6_addr = rpc-\u003eroute-\u003epeer-\u003eaddr;\n+\t\t\tmsg-\u003emsg_namelen = sizeof(*in6);\n+\t\t} else {\n+\t\t\tDECLARE_SOCKADDR(struct sockaddr_in *, in4,\n+\t\t\t\t\t msg-\u003emsg_name);\n+\n+\t\t\tin4-\u003esin_family = AF_INET;\n+\t\t\tin4-\u003esin_port = htons(rpc-\u003edport);\n+\t\t\tin4-\u003esin_addr.s_addr = ipv6_to_ipv4(rpc-\u003eroute-\u003epeer-\u003eaddr);\n+\t\t\tmsg-\u003emsg_namelen = sizeof(*in4);\n+\t\t}\n+\t}\n+\n+\tif (result \u003c 0) {\n+\t\thoma_rpc_end(rpc);\n+\t} else {\n+\t\t/* This indicates that the application now owns the buffers, so\n+\t\t * they won't be freed in homa_rpc_end.\n+\t\t */\n+\t\trpc-\u003emsgin.num_bpages = 0;\n+\t\tif (homa_is_client(rpc-\u003eid)) {\n+\t\t\thoma_peer_add_ack(rpc);\n+\t\t\thoma_rpc_end(rpc);\n+\t\t} else {\n+\t\t\trpc-\u003estate = RPC_IN_SERVICE;\n+\t\t}\n+\t}\n+\n+done:\n+\t/* Note: must release the RPC lock before calling homa_rpc_reap\n+\t * or copying results to user space.\n+\t */\n+\tif (rpc) {\n+\t\thoma_rpc_put(rpc);\n+\n+\t\t/* Locked by homa_rpc_find_client or homa_wait_shared. */\n+\t\thoma_rpc_unlock(rpc);\n+\t}\n+\n+\twhile (test_bit(HOMA_SOCK_NOSPACE, \u0026hsk-\u003eflags)) {\n+\t\t/* There are tasks waiting for tx memory, so reap\n+\t\t * immediately.\n+\t\t */\n+\t\tif (!homa_rpc_reap(hsk))\n+\t\t\tbreak;\n+\t}\n+\n+\tif (unlikely(copy_to_user((__force void __user *)msg-\u003emsg_control,\n+\t\t\t\t  \u0026control, sizeof(control)))) {\n+\t\thsk-\u003eerror_msg = \"couldn't update homa_recvmsg_args argument to recvmsg: read-only?\";\n+\t\tresult = -EFAULT;\n+\t}\n+\n+\treturn result;\n+}\n+\n+/**\n+ * homa_hash() - Not needed for Homa.\n+ * @sk:    Socket for the operation\n+ * Return: ??\n+ */\n+int homa_hash(struct sock *sk)\n+{\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_unhash() - Not needed for Homa.\n+ * @sk:    Socket for the operation\n+ */\n+void homa_unhash(struct sock *sk)\n+{\n+}\n+\n+/**\n+ * homa_softirq() - This function is invoked at SoftIRQ level to handle\n+ * incoming packets.\n+ * @skb:   The incoming packet.\n+ * Return: Always 0\n+ */\n+int homa_softirq(struct sk_buff *skb)\n+{\n+\tstruct sk_buff *packets, *other_pkts, *next;\n+\tstruct sk_buff **prev_link, **other_link;\n+\tenum skb_drop_reason reason;\n+\tstruct homa_common_hdr *h;\n+\tint header_offset;\n+\n+\t/* skb may actually contain many distinct packets, linked through\n+\t * skb_shinfo(skb)-\u003efrag_list by the Homa GRO mechanism. Make a\n+\t * pass through the list to process all of the short packets,\n+\t * leaving the longer packets in the list. Also, perform various\n+\t * prep/cleanup/error checking functions.\n+\t */\n+\tskb-\u003enext = skb_shinfo(skb)-\u003efrag_list;\n+\tskb_shinfo(skb)-\u003efrag_list = NULL;\n+\tpackets = skb;\n+\tprev_link = \u0026packets;\n+\tfor (skb = packets; skb; skb = next) {\n+\t\tnext = skb-\u003enext;\n+\n+\t\t/* Make the header available at skb-\u003edata, even if the packet\n+\t\t * is fragmented. One complication: it's possible that the IP\n+\t\t * header hasn't yet been removed (this happens for GRO packets\n+\t\t * on the frag_list, since they aren't handled explicitly by IP.\n+\t\t */\n+\t\tif (!homa_make_header_avl(skb)) {\n+\t\t\treason = SKB_DROP_REASON_HDR_TRUNC;\n+\t\t\tgoto discard;\n+\t\t}\n+\t\theader_offset = skb_transport_header(skb) - skb-\u003edata;\n+\t\tif (header_offset)\n+\t\t\t__skb_pull(skb, header_offset);\n+\n+\t\t/* Reject packets that are too short or have bogus types. */\n+\t\th = (struct homa_common_hdr *)skb-\u003edata;\n+\t\tif (unlikely(skb-\u003elen \u003c sizeof(struct homa_common_hdr) ||\n+\t\t\t     h-\u003etype \u003c DATA || h-\u003etype \u003e MAX_OP ||\n+\t\t\t     skb-\u003elen \u003c header_lengths[h-\u003etype - DATA])) {\n+\t\t\treason = SKB_DROP_REASON_PKT_TOO_SMALL;\n+\t\t\tgoto discard;\n+\t\t}\n+\n+\t\t/* Process the packet now if it is a control packet or\n+\t\t * if it contains an entire short message.\n+\t\t */\n+\t\tif (h-\u003etype != DATA || ntohl(((struct homa_data_hdr *)h)\n+\t\t\t\t-\u003emessage_length) \u003c 1400) {\n+\t\t\t*prev_link = skb-\u003enext;\n+\t\t\tskb-\u003enext = NULL;\n+\t\t\thoma_dispatch_pkts(skb);\n+\t\t} else {\n+\t\t\tprev_link = \u0026skb-\u003enext;\n+\t\t}\n+\t\tcontinue;\n+\n+discard:\n+\t\t*prev_link = skb-\u003enext;\n+\t\tkfree_skb_reason(skb, reason);\n+\t}\n+\n+\t/* Now process the longer packets. Each iteration of this loop\n+\t * collects all of the packets for a particular RPC and dispatches\n+\t * them (batching the packets for an RPC allows more efficient\n+\t * generation of grants).\n+\t */\n+\twhile (packets) {\n+\t\tstruct in6_addr saddr, saddr2;\n+\t\tstruct homa_common_hdr *h2;\n+\t\tstruct sk_buff *skb2;\n+\n+\t\tskb = packets;\n+\t\tprev_link = \u0026skb-\u003enext;\n+\t\tsaddr = skb_canonical_ipv6_saddr(skb);\n+\t\tother_pkts = NULL;\n+\t\tother_link = \u0026other_pkts;\n+\t\th = (struct homa_common_hdr *)skb-\u003edata;\n+\t\tfor (skb2 = skb-\u003enext; skb2; skb2 = next) {\n+\t\t\tnext = skb2-\u003enext;\n+\t\t\th2 = (struct homa_common_hdr *)skb2-\u003edata;\n+\t\t\tif (h2-\u003esender_id == h-\u003esender_id) {\n+\t\t\t\tsaddr2 = skb_canonical_ipv6_saddr(skb2);\n+\t\t\t\tif (ipv6_addr_equal(\u0026saddr, \u0026saddr2)) {\n+\t\t\t\t\t*prev_link = skb2;\n+\t\t\t\t\tprev_link = \u0026skb2-\u003enext;\n+\t\t\t\t\tcontinue;\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\t*other_link = skb2;\n+\t\t\tother_link = \u0026skb2-\u003enext;\n+\t\t}\n+\t\t*prev_link = NULL;\n+\t\t*other_link = NULL;\n+\t\thoma_dispatch_pkts(packets);\n+\t\tpackets = other_pkts;\n+\t}\n+\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_err_handler_v4() - Invoked by IP to handle an incoming error\n+ * packet, such as ICMP UNREACHABLE.\n+ * @skb:    The incoming packet; skb-\u003edata points to the byte just after\n+ *          the ICMP header (the first byte of the embedded packet IP header).\n+ * @skb:   The incoming packet.\n+ * @info:  Information about the error that occurred?\n+ *\n+ * Return: zero, or a negative errno if the error couldn't be handled here.\n+ */\n+int homa_err_handler_v4(struct sk_buff *skb, u32 info)\n+{\n+\tstruct homa *homa = homa_net(dev_net(skb-\u003edev))-\u003ehoma;\n+\tconst struct icmphdr *icmp = icmp_hdr(skb);\n+\tstruct in6_addr daddr;\n+\tint type = icmp-\u003etype;\n+\tint code = icmp-\u003ecode;\n+\tstruct iphdr *iph;\n+\tint error = 0;\n+\tint port = 0;\n+\n+\tiph = (struct iphdr *)(skb-\u003edata);\n+\tipv6_addr_set_v4mapped(iph-\u003edaddr, \u0026daddr);\n+\tif (type == ICMP_DEST_UNREACH \u0026\u0026 code == ICMP_PORT_UNREACH) {\n+\t\tstruct homa_common_hdr *h = (struct homa_common_hdr *)(skb-\u003edata\n+\t\t\t\t+ iph-\u003eihl * 4);\n+\n+\t\tport = ntohs(h-\u003edport);\n+\t\terror = -ENOTCONN;\n+\t} else if (type == ICMP_DEST_UNREACH) {\n+\t\tif (code == ICMP_PROT_UNREACH)\n+\t\t\terror = -EPROTONOSUPPORT;\n+\t\telse\n+\t\t\terror = -EHOSTUNREACH;\n+\t} else {\n+\t\tpr_notice(\"%s invoked with info %x, ICMP type %d, ICMP code %d\\n\",\n+\t\t\t  __func__, info, type, code);\n+\t}\n+\tif (error != 0)\n+\t\thoma_abort_rpcs(homa, \u0026daddr, port, error);\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_err_handler_v6() - Invoked by IP to handle an incoming error\n+ * packet, such as ICMP UNREACHABLE.\n+ * @skb:    The incoming packet; skb-\u003edata points to the byte just after\n+ *          the ICMP header (the first byte of the embedded packet IP header).\n+ * @opt:    Not used.\n+ * @type:   Type of ICMP packet.\n+ * @code:   Additional information about the error.\n+ * @offset: Total length of IPv6 header, including any extension headers.\n+ * @info:   Information about the error that occurred?\n+ *\n+ * Return: zero, or a negative errno if the error couldn't be handled here.\n+ */\n+int homa_err_handler_v6(struct sk_buff *skb, struct inet6_skb_parm *opt,\n+\t\t\tu8 type,  u8 code,  int offset,  __be32 info)\n+{\n+\tconst struct ipv6hdr *iph = (const struct ipv6hdr *)skb-\u003edata;\n+\tstruct homa *homa = homa_net(dev_net(skb-\u003edev))-\u003ehoma;\n+\tint error = 0;\n+\tint port = 0;\n+\n+\tif (type == ICMPV6_DEST_UNREACH \u0026\u0026 code == ICMPV6_PORT_UNREACH) {\n+\t\tconst struct homa_common_hdr *h;\n+\n+\t\th = (struct homa_common_hdr *)(skb-\u003edata + offset);\n+\t\tport = ntohs(h-\u003edport);\n+\t\terror = -ENOTCONN;\n+\t} else if (type == ICMPV6_DEST_UNREACH \u0026\u0026 code == ICMPV6_ADDR_UNREACH) {\n+\t\terror = -EHOSTUNREACH;\n+\t} else if (type == ICMPV6_PARAMPROB \u0026\u0026 code == ICMPV6_UNK_NEXTHDR) {\n+\t\terror = -EPROTONOSUPPORT;\n+\t}\n+\tif (error != 0)\n+\t\thoma_abort_rpcs(homa, \u0026iph-\u003edaddr, port, error);\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_poll() - Invoked by Linux as part of implementing select, poll,\n+ * epoll, etc.\n+ * @file:  Open file that is participating in a poll, select, etc.\n+ * @sock:  A Homa socket, associated with @file.\n+ * @wait:  This table will be registered with the socket, so that it\n+ *         is notified when the socket's ready state changes.\n+ *\n+ * Return: A mask of bits such as EPOLLIN, which indicate the current\n+ *         state of the socket.\n+ */\n+__poll_t homa_poll(struct file *file, struct socket *sock,\n+\t\t   struct poll_table_struct *wait)\n+{\n+\tstruct homa_sock *hsk = homa_sk(sock-\u003esk);\n+\t__poll_t mask;\n+\n+\tmask = 0;\n+\tsock_poll_wait(file, sock, wait);\n+\tif (homa_sock_wmem_avl(hsk))\n+\t\tmask |= EPOLLOUT | EPOLLWRNORM;\n+\telse\n+\t\tset_bit(HOMA_SOCK_NOSPACE, \u0026hsk-\u003eflags);\n+\n+\tif (hsk-\u003eshutdown)\n+\t\tmask |= EPOLLIN;\n+\n+\tif (!list_empty(\u0026hsk-\u003eready_rpcs))\n+\t\tmask |= EPOLLIN | EPOLLRDNORM;\n+\treturn mask;\n+}\n+\n+/**\n+ * homa_hrtimer() - This function is invoked by the hrtimer mechanism to\n+ * wake up the timer thread. Runs at IRQ level.\n+ * @timer:   The timer that triggered; not used.\n+ *\n+ * Return:   Always HRTIMER_NORESTART.\n+ */\n+enum hrtimer_restart homa_hrtimer(struct hrtimer *timer)\n+{\n+\twake_up_process(timer_kthread);\n+\treturn HRTIMER_NORESTART;\n+}\n+\n+/**\n+ * homa_timer_main() - Top-level function for the timer thread.\n+ * @transport:  Pointer to struct homa.\n+ *\n+ * Return:         Always 0.\n+ */\n+int homa_timer_main(void *transport)\n+{\n+\tstruct homa *homa = (struct homa *)transport;\n+\tktime_t tick_interval;\n+\tu64 nsec;\n+\n+\thrtimer_setup(\u0026hrtimer, homa_hrtimer, CLOCK_MONOTONIC,\n+\t\t      HRTIMER_MODE_REL);\n+\tnsec = 1000000;                   /* 1 ms */\n+\ttick_interval = ns_to_ktime(nsec);\n+\twhile (1) {\n+\t\tset_current_state(TASK_UNINTERRUPTIBLE);\n+\t\tif (!kthread_should_stop()) {\n+\t\t\thrtimer_start(\u0026hrtimer, tick_interval,\n+\t\t\t\t      HRTIMER_MODE_REL);\n+\t\t\tschedule();\n+\t\t}\n+\t\t__set_current_state(TASK_RUNNING);\n+\t\tif (kthread_should_stop())\n+\t\t\tbreak;\n+\t\thoma_timer(homa);\n+\t}\n+\thrtimer_cancel(\u0026hrtimer);\n+\treturn 0;\n+}\n+\n+MODULE_LICENSE(\"Dual BSD/GPL\");\n+MODULE_AUTHOR(\"John Ousterhout \u003couster@cs.stanford.edu\u003e\");\n+MODULE_DESCRIPTION(\"Homa transport protocol\");\n+MODULE_VERSION(\"1.0\");\n+\n+/* Arrange for this module to be loaded automatically when a Homa socket is\n+ * opened. Apparently symbols don't work in the macros below, so must use\n+ * numeric values for IPPROTO_HOMA (146) and SOCK_DGRAM(2).\n+ */\n+MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET, 146, 2);\n+MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET6, 146, 2);\ndiff --git a/net/homa/homa_pool.c b/net/homa/homa_pool.c\nnew file mode 100644\nindex 0000000000000..0aadfbc53ef1b\n--- /dev/null\n+++ b/net/homa/homa_pool.c\n@@ -0,0 +1,553 @@\n+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+\n+#include \"homa_impl.h\"\n+#include \"homa_pool.h\"\n+\n+/* This file contains functions that manage user-space buffer pools. */\n+\n+/* Used when determining how many bpages to consider for allocation. */\n+#define MIN_EXTRA 4\n+\n+/**\n+ * set_bpages_needed() - Set the bpages_needed field of @pool based\n+ * on the length of the first RPC that's waiting for buffer space.\n+ * The caller must own the lock for @pool-\u003ehsk.\n+ * @pool: Pool to update.\n+ */\n+static void set_bpages_needed(struct homa_pool *pool)\n+{\n+\tstruct homa_rpc *rpc = list_first_entry(\u0026pool-\u003ehsk-\u003ewaiting_for_bufs,\n+\t\t\t\t\t\tstruct homa_rpc, buf_links);\n+\n+\tpool-\u003ebpages_needed = (rpc-\u003emsgin.length + HOMA_BPAGE_SIZE - 1) \u003e\u003e\n+\t\t\t      HOMA_BPAGE_SHIFT;\n+}\n+\n+/**\n+ * homa_pool_alloc() - Allocate and initialize a new homa_pool (it will have\n+ * no region associated with it until homa_pool_set_region is invoked).\n+ * @hsk:          Socket the pool will be associated with.\n+ * Return: A pointer to the new pool or a negative errno.\n+ */\n+struct homa_pool *homa_pool_alloc(struct homa_sock *hsk)\n+{\n+\tstruct homa_pool *pool;\n+\n+\tpool = kzalloc_obj(*pool, GFP_KERNEL_ACCOUNT);\n+\tif (!pool)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\tpool-\u003ehsk = hsk;\n+\treturn pool;\n+}\n+\n+/**\n+ * homa_pool_set_region() - Associate a region of memory with a pool.\n+ * @hsk:          Socket whose pool the region will be associated with.\n+ *                Must not be locked, and the pool must not currently\n+ *                have a region associated with it.\n+ * @region:       First byte of the memory region for the pool, allocated\n+ *                by the application; must be page-aligned.\n+ * @region_size:  Total number of bytes available at @buf_region.\n+ * Return: Either zero (for success) or a negative errno for failure.\n+ */\n+int homa_pool_set_region(struct homa_sock *hsk, void __user *region,\n+\t\t\t u64 region_size)\n+{\n+\tstruct homa_pool_core __percpu *cores;\n+\tstruct homa_bpage *descriptors;\n+\tint i, result, num_bpages;\n+\tstruct homa_pool *pool;\n+\tu64 min_size;\n+\n+\tif (((uintptr_t)region) \u0026 ~PAGE_MASK) {\n+\t\thsk-\u003eerror_msg = \"buffer pool is not page aligned\";\n+\t\treturn -EINVAL;\n+\t}\n+\n+\t/* The region must be large enough to hold a private bpage for\n+\t * each core, plus enough additional space for a couple of\n+\t * full-size messages. Otherwise we could deadlock over allocation\n+\t * (no free pages available, so no attempt is made to steal back\n+\t * private pages).\n+\t */\n+\tmin_size = nr_cpu_ids;\n+\tmin_size = min_size * HOMA_BPAGE_SIZE + 2 * HOMA_MAX_MESSAGE_LENGTH;\n+\tif (region_size \u003c min_size) {\n+\t\thsk-\u003eerror_msg = \"buffer pool is not large enough\";\n+\t\treturn -EINVAL;\n+\t}\n+\n+\t/* The region must not be so large that offsets into the region\n+\t * overflow the 32-bit values used in bpage_offsets in\n+\t * homa_recvmsg_args.\n+\t */\n+\tif (region_size \u003e 0x100000000ULL) {\n+\t\thsk-\u003eerror_msg = \"buffer pool cannot be larger than 4 GB\";\n+\t\treturn -EINVAL;\n+\t}\n+\n+\t/* Allocate memory before locking the socket, so we can allocate\n+\t * without GFP_ATOMIC.\n+\t */\n+\tnum_bpages = region_size \u003e\u003e HOMA_BPAGE_SHIFT;\n+\tdescriptors = kmalloc_array(num_bpages, sizeof(struct homa_bpage),\n+\t\t\t\t    GFP_KERNEL | __GFP_ZERO | __GFP_ACCOUNT);\n+\tif (!descriptors)\n+\t\treturn -ENOMEM;\n+\tcores = alloc_percpu_gfp(struct homa_pool_core, __GFP_ZERO);\n+\tif (!cores) {\n+\t\tresult = -ENOMEM;\n+\t\tgoto error;\n+\t}\n+\n+\thoma_sock_lock(hsk);\n+\tpool = hsk-\u003ebuffer_pool;\n+\tif (pool-\u003eregion) {\n+\t\tresult = -EINVAL;\n+\t\thoma_sock_unlock(hsk);\n+\t\tgoto error;\n+\t}\n+\n+\tpool-\u003enum_bpages = num_bpages;\n+\tpool-\u003edescriptors = descriptors;\n+\tatomic_set(\u0026pool-\u003efree_bpages, pool-\u003enum_bpages);\n+\tpool-\u003ebpages_needed = INT_MAX;\n+\tpool-\u003ecores = cores;\n+\tpool-\u003echeck_waiting_invoked = 0;\n+\n+\tfor (i = 0; i \u003c pool-\u003enum_bpages; i++) {\n+\t\tstruct homa_bpage *bp = \u0026pool-\u003edescriptors[i];\n+\n+\t\tspin_lock_init(\u0026bp-\u003elock);\n+\t\tbp-\u003eowner = -1;\n+\t}\n+\n+\t/* Barrier ensures that concurrent cores trying to access\n+\t * newly-created region will see all the region's data.\n+\t */\n+\tsmp_store_release(\u0026pool-\u003eregion, (char __user *)region);\n+\thoma_sock_unlock(hsk);\n+\treturn 0;\n+\n+error:\n+\tkfree(descriptors);\n+\tfree_percpu(cores);\n+\treturn result;\n+}\n+\n+/**\n+ * homa_pool_free() - Destructor for homa_pool. After this method\n+ * returns, the object should not be used (it will be freed here).\n+ * @pool: Pool to destroy.\n+ */\n+void homa_pool_free(struct homa_pool *pool)\n+{\n+\tif (homa_pool_exists(pool)) {\n+\t\tkfree(pool-\u003edescriptors);\n+\t\tfree_percpu(pool-\u003ecores);\n+\t\tpool-\u003eregion = NULL;\n+\t}\n+\tkfree(pool);\n+}\n+\n+/**\n+ * homa_pool_get_rcvbuf() - Return information needed to handle getsockopt\n+ * for HOMA_SO_RCVBUF.\n+ * @pool:         Pool for which information is needed.\n+ * @args:         Store info here.\n+ */\n+void homa_pool_get_rcvbuf(struct homa_pool *pool,\n+\t\t\t  struct homa_rcvbuf_args *args)\n+{\n+\targs-\u003estart = (uintptr_t)pool-\u003eregion;\n+\targs-\u003elength = (u64)pool-\u003enum_bpages \u003c\u003c HOMA_BPAGE_SHIFT;\n+}\n+\n+/**\n+ * homa_bpage_available() - Check whether a bpage is available for use.\n+ * @bpage:      Bpage to check\n+ * @now:        Current time (homa_clock() units)\n+ * Return:      True if the bpage is free or if it can be stolen, otherwise\n+ *              false.\n+ */\n+bool homa_bpage_available(struct homa_bpage *bpage, u64 now)\n+{\n+\treturn bpage-\u003erefs == 0 || (bpage-\u003erefs == 1 \u0026\u0026 bpage-\u003eowner \u003e= 0 \u0026\u0026\n+\t\t\t\t    bpage-\u003eexpiration \u003c= now);\n+}\n+\n+/**\n+ * homa_pool_get_pages() - Allocate one or more full pages from the pool.\n+ * @pool:         Pool from which to allocate pages\n+ * @num_pages:    Number of pages needed\n+ * @pages:        The indices of the allocated pages are stored here; caller\n+ *                must ensure this array is big enough. Reference counts have\n+ *                been set to 1 on all of these pages (or 2 if set_owner\n+ *                was specified).\n+ * @set_owner:    If nonzero, the current core is marked as owner of all\n+ *                of the allocated pages (and the expiration time is also\n+ *                set). Otherwise the pages are left unowned.\n+ * Return: 0 for success, -1 if there wasn't enough free space in the pool.\n+ */\n+int homa_pool_get_pages(struct homa_pool *pool, int num_pages, u32 *pages,\n+\t\t\tint set_owner)\n+{\n+\tint core_num = smp_processor_id();\n+\tstruct homa_pool_core *core;\n+\tu64 now = homa_clock();\n+\tint alloced = 0;\n+\tint limit = 0;\n+\tint free;\n+\n+\tcore = this_cpu_ptr(pool-\u003ecores);\n+\n+\t/* Atomically check for available space and decrement the\n+\t * free page counter.\n+\t */\n+\tfree = atomic_read_acquire(\u0026pool-\u003efree_bpages);\n+\twhile (1) {\n+\t\tif (free \u003c num_pages)\n+\t\t\treturn -1;\n+\t\tif (atomic_try_cmpxchg(\u0026pool-\u003efree_bpages, \u0026free,\n+\t\t\t\t       free - num_pages))\n+\t\t\tbreak;\n+\t}\n+\n+\t/* Once we get to this point we know we will be able to find\n+\t * enough free pages; now we just have to find them.\n+\t */\n+\twhile (alloced != num_pages) {\n+\t\tstruct homa_bpage *bpage;\n+\t\tint cur;\n+\n+\t\t/* If we don't need to use all of the bpages in the pool,\n+\t\t * then try to use only the ones with low indexes. This\n+\t\t * will reduce the cache footprint for the pool by reusing\n+\t\t * a few bpages over and over. Specifically this code will\n+\t\t * not consider any candidate page whose index is \u003e= limit.\n+\t\t * Limit is chosen to make sure there are a reasonable\n+\t\t * number of free pages in the range, so we won't have to\n+\t\t * check a huge number of pages.\n+\t\t */\n+\t\tif (limit == 0) {\n+\t\t\tint extra;\n+\n+\t\t\tlimit = pool-\u003enum_bpages -\n+\t\t\t\tatomic_read(\u0026pool-\u003efree_bpages);\n+\t\t\textra = limit \u003e\u003e 2;\n+\t\t\tlimit += (extra \u003c MIN_EXTRA) ? MIN_EXTRA : extra;\n+\t\t\tif (limit \u003e pool-\u003enum_bpages)\n+\t\t\t\tlimit = pool-\u003enum_bpages;\n+\t\t}\n+\n+\t\tcur = core-\u003enext_candidate;\n+\t\tcore-\u003enext_candidate++;\n+\t\tif (cur \u003e= limit) {\n+\t\t\tcore-\u003enext_candidate = 0;\n+\n+\t\t\t/* Must recompute the limit for each new loop through\n+\t\t\t * the bpage array: we may need to consider a larger\n+\t\t\t * range of pages because of concurrent allocations.\n+\t\t\t */\n+\t\t\tlimit = 0;\n+\t\t\tcontinue;\n+\t\t}\n+\t\tbpage = \u0026pool-\u003edescriptors[cur];\n+\n+\t\t/* Figure out whether this candidate is free (or can be\n+\t\t * stolen). Do a quick check without locking the page, and\n+\t\t * if the page looks promising, then lock it and check again\n+\t\t * (must check again in case someone else snuck in and\n+\t\t * grabbed the page).\n+\t\t */\n+\t\tif (!homa_bpage_available(bpage, now))\n+\t\t\tcontinue;\n+\t\tif (!spin_trylock_bh(\u0026bpage-\u003elock))\n+\t\t\t/* Rather than wait for a locked page to become free,\n+\t\t\t * just go on to the next page. If the page is locked,\n+\t\t\t * it probably won't turn out to be available anyway.\n+\t\t\t */\n+\t\t\tcontinue;\n+\t\tif (!homa_bpage_available(bpage, now)) {\n+\t\t\tspin_unlock_bh(\u0026bpage-\u003elock);\n+\t\t\tcontinue;\n+\t\t}\n+\t\tif (bpage-\u003eowner \u003e= 0)\n+\t\t\tatomic_fetch_inc_release(\u0026pool-\u003efree_bpages);\n+\t\tif (set_owner) {\n+\t\t\tbpage-\u003erefs = 2;\n+\t\t\tbpage-\u003eowner = core_num;\n+\t\t\tbpage-\u003eexpiration = now +\n+\t\t\t\t\t    pool-\u003ehsk-\u003ehoma-\u003ebpage_lease_cycles;\n+\t\t} else {\n+\t\t\tbpage-\u003erefs = 1;\n+\t\t\tbpage-\u003eowner = -1;\n+\t\t}\n+\t\tspin_unlock_bh(\u0026bpage-\u003elock);\n+\t\tpages[alloced] = cur;\n+\t\talloced++;\n+\t}\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_pool_alloc_msg() - Allocate buffer space for an incoming message.\n+ * @rpc:  RPC that needs space allocated for its incoming message (space must\n+ *        not already have been allocated). The fields @msgin-\u003enum_buffers\n+ *        and @msgin-\u003ebuffers are filled in. Must be locked by caller.\n+ * Return: The return value is normally 0, which means either buffer space\n+ * was allocated or the @rpc was queued on @hsk-\u003ewaiting. If a fatal error\n+ * occurred, such as no buffer pool present, then a negative errno is\n+ * returned.\n+ */\n+int homa_pool_alloc_msg(struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_pool *pool = rpc-\u003ehsk-\u003ebuffer_pool;\n+\tint full_pages, partial, i, core_id;\n+\tstruct homa_pool_core *core;\n+\tu32 pages[HOMA_MAX_BPAGES];\n+\tstruct homa_bpage *bpage;\n+\tstruct homa_rpc *other;\n+\n+\tif (!homa_pool_exists(pool))\n+\t\treturn -ENOMEM;\n+\tif (rpc-\u003estate == RPC_DEAD)\n+\t\treturn 0;\n+\n+\t/* First allocate any full bpages that are needed. */\n+\tfull_pages = rpc-\u003emsgin.length \u003e\u003e HOMA_BPAGE_SHIFT;\n+\tif (unlikely(full_pages)) {\n+\t\tif (homa_pool_get_pages(pool, full_pages, pages, 0) != 0)\n+\t\t\tgoto out_of_space;\n+\t\tfor (i = 0; i \u003c full_pages; i++)\n+\t\t\trpc-\u003emsgin.bpage_offsets[i] = pages[i] \u003c\u003c\n+\t\t\t\t\tHOMA_BPAGE_SHIFT;\n+\t}\n+\trpc-\u003emsgin.num_bpages = full_pages;\n+\n+\t/* The last chunk may be less than a full bpage; for this we use\n+\t * the bpage that we own (and reuse it for multiple messages).\n+\t */\n+\tpartial = rpc-\u003emsgin.length \u0026 (HOMA_BPAGE_SIZE - 1);\n+\tif (unlikely(partial == 0))\n+\t\tgoto success;\n+\tcore_id = smp_processor_id();\n+\tcore = this_cpu_ptr(pool-\u003ecores);\n+\tbpage = \u0026pool-\u003edescriptors[core-\u003epage_hint];\n+\tspin_lock_bh(\u0026bpage-\u003elock);\n+\tif (bpage-\u003eowner != core_id) {\n+\t\tspin_unlock_bh(\u0026bpage-\u003elock);\n+\t\tgoto new_page;\n+\t}\n+\tif ((core-\u003eallocated + partial) \u003e HOMA_BPAGE_SIZE) {\n+\t\tif (bpage-\u003erefs == 1) {\n+\t\t\t/* Bpage is totally free, so we can reuse it. */\n+\t\t\tcore-\u003eallocated = 0;\n+\t\t} else {\n+\t\t\tbpage-\u003eowner = -1;\n+\n+\t\t\t/* We know the reference count can't reach zero here\n+\t\t\t * because of check above, so we won't have to decrement\n+\t\t\t * pool-\u003efree_bpages.\n+\t\t\t */\n+\t\t\tbpage-\u003erefs--;\n+\t\t\tspin_unlock_bh(\u0026bpage-\u003elock);\n+\t\t\tgoto new_page;\n+\t\t}\n+\t}\n+\tbpage-\u003eexpiration = homa_clock() +\n+\t\t\t    pool-\u003ehsk-\u003ehoma-\u003ebpage_lease_cycles;\n+\tbpage-\u003erefs++;\n+\tspin_unlock_bh(\u0026bpage-\u003elock);\n+\tgoto allocate_partial;\n+\n+\t/* Can't use the current page; get another one. */\n+new_page:\n+\tif (homa_pool_get_pages(pool, 1, pages, 1) != 0) {\n+\t\thoma_pool_free_bufs(pool, rpc-\u003emsgin.num_bpages,\n+\t\t\t\t    rpc-\u003emsgin.bpage_offsets);\n+\t\trpc-\u003emsgin.num_bpages = 0;\n+\t\tgoto out_of_space;\n+\t}\n+\tcore-\u003epage_hint = pages[0];\n+\tcore-\u003eallocated = 0;\n+\n+allocate_partial:\n+\trpc-\u003emsgin.bpage_offsets[rpc-\u003emsgin.num_bpages] = core-\u003eallocated\n+\t\t\t+ (core-\u003epage_hint \u003c\u003c HOMA_BPAGE_SHIFT);\n+\trpc-\u003emsgin.num_bpages++;\n+\tcore-\u003eallocated += partial;\n+\n+success:\n+\treturn 0;\n+\n+\t/* We get here if there wasn't enough buffer space for this\n+\t * message; add the RPC to hsk-\u003ewaiting_for_bufs. The list is sorted\n+\t * by RPC length in order to implement SRPT.\n+\t */\n+out_of_space:\n+\thoma_sock_lock(pool-\u003ehsk);\n+\tlist_for_each_entry(other, \u0026pool-\u003ehsk-\u003ewaiting_for_bufs, buf_links) {\n+\t\tif (other-\u003emsgin.length \u003e rpc-\u003emsgin.length) {\n+\t\t\tlist_add_tail(\u0026rpc-\u003ebuf_links, \u0026other-\u003ebuf_links);\n+\t\t\tgoto queued;\n+\t\t}\n+\t}\n+\tlist_add_tail(\u0026rpc-\u003ebuf_links, \u0026pool-\u003ehsk-\u003ewaiting_for_bufs);\n+\n+queued:\n+\tset_bpages_needed(pool);\n+\thoma_sock_unlock(pool-\u003ehsk);\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_pool_get_buffer() - Given an RPC, figure out where to store incoming\n+ * message data.\n+ * @rpc:        RPC for which incoming message data is being processed; its\n+ *              msgin must be properly initialized and buffer space must have\n+ *              been allocated for the message.\n+ * @offset:     Offset within @rpc's incoming message.\n+ * @available:  Will be filled in with the number of bytes of space available\n+ *              at the returned address (could be zero if offset is\n+ *              (erroneously) past the end of the message).\n+ * Return:      The application's virtual address for buffer space corresponding\n+ *              to @offset in the incoming message for @rpc.\n+ */\n+void __user *homa_pool_get_buffer(struct homa_rpc *rpc, int offset,\n+\t\t\t\t  int *available)\n+{\n+\tint bpage_index, bpage_offset;\n+\n+\tbpage_index = offset \u003e\u003e HOMA_BPAGE_SHIFT;\n+\tif (offset \u003e= rpc-\u003emsgin.length) {\n+\t\tWARN_ONCE(true, \"%s got offset %d \u003e= message length %d\\n\",\n+\t\t\t  __func__, offset, rpc-\u003emsgin.length);\n+\t\t*available = 0;\n+\t\treturn NULL;\n+\t}\n+\tbpage_offset = offset \u0026 (HOMA_BPAGE_SIZE - 1);\n+\t*available = (bpage_index \u003c (rpc-\u003emsgin.num_bpages - 1))\n+\t\t\t? HOMA_BPAGE_SIZE - bpage_offset\n+\t\t\t: rpc-\u003emsgin.length - offset;\n+\treturn rpc-\u003ehsk-\u003ebuffer_pool-\u003eregion +\n+\t\t\trpc-\u003emsgin.bpage_offsets[bpage_index] + bpage_offset;\n+}\n+\n+/**\n+ * homa_pool_free_bufs() - Release buffer space so that it can be\n+ * reused.\n+ * @pool:         Pool that the buffer space belongs to. Doesn't need to\n+ *                be locked.\n+ * @num_buffers:  How many buffers to release.\n+ * @buffers:      Points to @num_buffers values, each of which is an offset\n+ *                from the start of the pool to the buffer to be released.\n+ * Return:        0 for success, otherwise a negative errno.\n+ */\n+int homa_pool_free_bufs(struct homa_pool *pool, int num_buffers, u32 *buffers)\n+{\n+\tint i;\n+\n+\tif (!homa_pool_exists(pool))\n+\t\treturn -EINVAL;\n+\tfor (i = 0; i \u003c num_buffers; i++) {\n+\t\tu32 bpage_index = buffers[i] \u003e\u003e HOMA_BPAGE_SHIFT;\n+\t\tstruct homa_bpage *bpage;\n+\n+\t\tif (bpage_index \u003e= pool-\u003enum_bpages)\n+\t\t\treturn -EINVAL;\n+\t\tbpage = \u0026pool-\u003edescriptors[bpage_index];\n+\n+\t\tspin_lock_bh(\u0026bpage-\u003elock);\n+\t\tif (bpage-\u003erefs == 0 || (bpage-\u003erefs == 1 \u0026\u0026\n+\t\t\t\t\t bpage-\u003eowner \u003e= 0)) {\n+\t\t\t/* This bpage is already free; looks like the app\n+\t\t\t * has misbehaved and freed an offset multiple times.\n+\t\t\t */\n+\t\t\tspin_unlock_bh(\u0026bpage-\u003elock);\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\t\tbpage-\u003erefs--;\n+\t\tif (bpage-\u003erefs == 0)\n+\t\t\tatomic_fetch_inc(\u0026pool-\u003efree_bpages);\n+\t\tspin_unlock_bh(\u0026bpage-\u003elock);\n+\t}\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_pool_check_waiting() - Checks to see if there are enough free\n+ * bpages to wake up any RPCs that were blocked. Whenever\n+ * homa_pool_free_bufs is invoked, this function must be invoked later,\n+ * at a point when the caller holds no locks (homa_pool_free_bufs may\n+ * be invoked with locks held, so it can't safely invoke this function).\n+ * This is regrettably tricky, but I can't think of a better solution.\n+ * @pool:         Information about the buffer pool.\n+ */\n+void homa_pool_check_waiting(struct homa_pool *pool)\n+{\n+\tif (!homa_pool_exists(pool))\n+\t\treturn;\n+\twhile (atomic_read_acquire(\u0026pool-\u003efree_bpages) \u003e= pool-\u003ebpages_needed) {\n+\t\tstruct homa_rpc *rpc;\n+\n+\t\thoma_sock_lock(pool-\u003ehsk);\n+\t\tif (list_empty(\u0026pool-\u003ehsk-\u003ewaiting_for_bufs)) {\n+\t\t\tpool-\u003ebpages_needed = INT_MAX;\n+\t\t\thoma_sock_unlock(pool-\u003ehsk);\n+\t\t\tbreak;\n+\t\t}\n+\t\trpc = list_first_entry(\u0026pool-\u003ehsk-\u003ewaiting_for_bufs,\n+\t\t\t\t       struct homa_rpc, buf_links);\n+\t\tif (!homa_rpc_try_lock(rpc)) {\n+\t\t\t/* Can't just spin on the RPC lock because we're\n+\t\t\t * holding the socket lock and the lock order is\n+\t\t\t * rpc-then-socket (see \"Homa Locking Strategy\" in\n+\t\t\t * homa_impl.h). Instead, release the socket lock\n+\t\t\t * and try the entire operation again.\n+\t\t\t */\n+\t\t\thoma_sock_unlock(pool-\u003ehsk);\n+\t\t\tcpu_relax();\n+\t\t\tcontinue;\n+\t\t}\n+\t\tlist_del_init(\u0026rpc-\u003ebuf_links);\n+\t\tif (list_empty(\u0026pool-\u003ehsk-\u003ewaiting_for_bufs))\n+\t\t\tpool-\u003ebpages_needed = INT_MAX;\n+\t\telse\n+\t\t\tset_bpages_needed(pool);\n+\t\thoma_sock_unlock(pool-\u003ehsk);\n+\t\thoma_pool_alloc_msg(rpc);\n+\t\thoma_rpc_unlock(rpc);\n+\t}\n+}\n+\n+/**\n+ * homa_pool_avail_bytes() - Return a count of the number of bytes currently\n+ * unused and available for allocation in a pool.\n+ * @pool:    Pool of interest.\n+ * Return:    See above.\n+ */\n+u64 homa_pool_avail_bytes(struct homa_pool *pool)\n+{\n+\tstruct homa_pool_core *core;\n+\tstruct homa_bpage *bpage;\n+\tu64 avail;\n+\tint cpu;\n+\n+\tif (!homa_pool_exists(pool))\n+\t\treturn 0;\n+\tavail = atomic_read(\u0026pool-\u003efree_bpages);\n+\tavail *= HOMA_BPAGE_SIZE;\n+\tfor (cpu = 0; cpu \u003c nr_cpu_ids; cpu++) {\n+\t\tcore = per_cpu_ptr(pool-\u003ecores, cpu);\n+\t\tbpage = \u0026pool-\u003edescriptors[core-\u003epage_hint];\n+\t\tif (bpage-\u003eowner == cpu) {\n+\t\t\tif (bpage-\u003erefs \u003e 1)\n+\t\t\t\tavail += HOMA_BPAGE_SIZE - core-\u003eallocated;\n+\t\t\telse\n+\t\t\t\tavail += HOMA_BPAGE_SIZE;\n+\t\t}\n+\t}\n+\treturn avail;\n+}\ndiff --git a/net/homa/homa_pool.h b/net/homa/homa_pool.h\nnew file mode 100644\nindex 0000000000000..80b14475d0be2\n--- /dev/null\n+++ b/net/homa/homa_pool.h\n@@ -0,0 +1,184 @@\n+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */\n+\n+/* This file contains definitions used to manage user-space buffer pools.\n+ */\n+\n+#ifndef _HOMA_POOL_H\n+#define _HOMA_POOL_H\n+\n+#include \u003clinux/percpu.h\u003e\n+\n+#include \"homa_rpc.h\"\n+\n+/**\n+ * struct homa_bpage - Contains information about a single page in\n+ * a buffer pool.\n+ */\n+struct homa_bpage {\n+\t/** @lock: to synchronize shared access. */\n+\tspinlock_t lock;\n+\n+\t/**\n+\t * @refs: Counts number of distinct uses of this\n+\t * bpage (1 tick for each message that is using\n+\t * this page, plus an additional tick if the @owner\n+\t * field is set).\n+\t */\n+\tint refs;\n+\n+\t/**\n+\t * @owner: kernel core that currently owns this page\n+\t * (\u003c 0 if none).\n+\t */\n+\tint owner;\n+\n+\t/**\n+\t * @expiration: homa_clock() time after which it's OK to steal this\n+\t * page from its current owner (if @refs is 1).\n+\t */\n+\tu64 expiration;\n+} ____cacheline_aligned_in_smp;\n+\n+/**\n+ * struct homa_pool_core - Holds core-specific data for a homa_pool (a bpage\n+ * out of which that core is allocating small chunks).\n+ */\n+struct homa_pool_core {\n+\t/**\n+\t * @page_hint: Index of bpage in pool-\u003edescriptors,\n+\t * which may be owned by this core. If so, we'll use it\n+\t * for allocating partial pages.\n+\t */\n+\tint page_hint;\n+\n+\t/**\n+\t * @allocated: if the page given by @page_hint is\n+\t * owned by this core, this variable gives the number of\n+\t * (initial) bytes that have already been allocated\n+\t * from the page.\n+\t */\n+\tint allocated;\n+\n+\t/**\n+\t * @next_candidate: when searching for free bpages,\n+\t * check this index next.\n+\t */\n+\tint next_candidate;\n+};\n+\n+/**\n+ * struct homa_pool - Describes a pool of buffer space for incoming\n+ * messages for a particular socket; managed by homa_pool.c. The pool is\n+ * divided up into \"bpages\", which are a multiple of the hardware page size.\n+ * A bpage may be owned by a particular core so that it can more efficiently\n+ * allocate space for small messages.\n+ */\n+struct homa_pool {\n+\t/**\n+\t * @hsk: the socket that this pool belongs to.\n+\t */\n+\tstruct homa_sock *hsk;\n+\n+\t/**\n+\t * @region: beginning of the pool's region (in the app's virtual\n+\t * memory). Divided into bpages. 0 means the pool hasn't yet been\n+\t * initialized. This pointer is used for lock-free synchronization\n+\t * between a core creating the region and other cores attempting\n+\t * to use it.\n+\t */\n+\tchar __user *region;\n+\n+\t/** @num_bpages: total number of bpages in the pool. */\n+\tint num_bpages;\n+\n+\t/** @descriptors: kmalloced area containing one entry for each bpage. */\n+\tstruct homa_bpage *descriptors;\n+\n+\t/**\n+\t * @free_bpages: the number of pages still available for allocation\n+\t * by homa_pool_get_pages. This equals the number of pages with zero\n+\t * reference counts, minus the number of pages that have been claimed\n+\t * by homa_pool_get_pages but not yet allocated.\n+\t */\n+\tatomic_t free_bpages;\n+\n+\t/**\n+\t * @bpages_needed: the number of free bpages required to satisfy the\n+\t * needs of the first RPC on @hsk-\u003ewaiting_for_bufs, or INT_MAX if\n+\t * that queue is empty.\n+\t */\n+\tint bpages_needed;\n+\n+\t/** @cores: core-specific info; dynamically allocated. */\n+\tstruct homa_pool_core __percpu *cores;\n+\n+\t/**\n+\t * @check_waiting_invoked: incremented during unit tests when\n+\t * homa_pool_check_waiting is invoked.\n+\t */\n+\tint check_waiting_invoked;\n+};\n+\n+bool     homa_bpage_available(struct homa_bpage *bpage, u64 now);\n+struct   homa_pool *homa_pool_alloc(struct homa_sock *hsk);\n+int      homa_pool_alloc_msg(struct homa_rpc *rpc);\n+u64      homa_pool_avail_bytes(struct homa_pool *pool);\n+void     homa_pool_check_waiting(struct homa_pool *pool);\n+void     homa_pool_free(struct homa_pool *pool);\n+void __user *homa_pool_get_buffer(struct homa_rpc *rpc, int offset,\n+\t\t\t\t  int *available);\n+int      homa_pool_get_pages(struct homa_pool *pool, int num_pages,\n+\t\t\t     u32 *pages, int leave_locked);\n+void     homa_pool_get_rcvbuf(struct homa_pool *pool,\n+\t\t\t      struct homa_rcvbuf_args *args);\n+int      homa_pool_free_bufs(struct homa_pool *pool, int num_buffers,\n+\t\t\t     u32 *buffers);\n+int      homa_pool_set_region(struct homa_sock *hsk, void __user *region,\n+\t\t\t      u64 region_size);\n+\n+/**\n+ * homa_pool_unlink() - Remove an RPC from any lists related to buffer\n+ * pool memory, so the RPC will not be accessed by this module again.\n+ * @rpc:     RPC to unlink. Must be locked, and the rpc's socket must\n+ *           also be locked.\n+ */\n+static inline void homa_pool_unlink(struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+\t__must_hold(rpc-\u003ehsk-\u003elock)\n+{\n+\tlist_del_init(\u0026rpc-\u003ebuf_links);\n+}\n+\n+/**\n+ * homa_pool_release() - Invoked when RPCs are being reaped: releases\n+ * pool space owned by the RPC.\n+ * @rpc:        RPC to clean up. Caller must ensure that no-one else can\n+ *              access the RPC concurrently (e.g., it is being reaped).\n+ */\n+static inline void homa_pool_release(struct homa_rpc *rpc)\n+{\n+\tif (rpc-\u003emsgin.num_bpages \u003e 0) {\n+\t\thoma_pool_free_bufs(rpc-\u003ehsk-\u003ebuffer_pool,\n+\t\t\t\t    rpc-\u003emsgin.num_bpages,\n+\t\t\t\t    rpc-\u003emsgin.bpage_offsets);\n+\t\trpc-\u003emsgin.num_bpages = 0;\n+\t}\n+}\n+\n+/**\n+ * homa_pool_exists() - Determine whether a pool has been fully initialized\n+ * with a memory region.\n+ * @pool:     Pool to check.\n+ * Return:    True if there is a memory region associated with the pool,\n+ *            false if SO_HOMA_RCVBUF hasn't been invoked for the socket.\n+ */\n+static inline bool homa_pool_exists(struct homa_pool *pool)\n+{\n+\t/* This barrier allows lockless concurrent allocation of the pool:\n+\t * it ensures that if the pool exists we'll see all of the initialized\n+\t * values related to the pool.\n+\t */\n+\treturn smp_load_acquire(\u0026pool-\u003eregion) != NULL;\n+}\n+\n+#endif /* _HOMA_POOL_H */\ndiff --git a/net/homa/homa_rpc.c b/net/homa/homa_rpc.c\nnew file mode 100644\nindex 0000000000000..3c94489641c21\n--- /dev/null\n+++ b/net/homa/homa_rpc.c\n@@ -0,0 +1,735 @@\n+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+\n+/* This file contains functions for managing homa_rpc structs. */\n+\n+#include \"homa_impl.h\"\n+#include \"homa_interest.h\"\n+#include \"homa_peer.h\"\n+#include \"homa_pool.h\"\n+#include \"homa_tx_pool.h\"\n+\n+/**\n+ * homa_rpc_alloc_client() - Allocate and initialize a client RPC (one that\n+ * is used to issue an outgoing request). Doesn't send any packets. Invoked\n+ * with no locks held.\n+ * @hsk:      Socket to which the RPC belongs.\n+ * @dest:     Address of host (ip and port) to which the RPC will be sent.\n+ *\n+ * Return:    A pointer to the newly allocated object, or a negative\n+ *            errno if an error occurred. The RPC will be locked; the\n+ *            caller must eventually unlock it. Sets hsk-\u003eerror_msg on errors.\n+ */\n+struct homa_rpc *homa_rpc_alloc_client(struct homa_sock *hsk,\n+\t\t\t\t       const union sockaddr_in_union *dest)\n+\t__cond_acquires(nonnull, crpc-\u003ebucket-\u003elock)\n+{\n+\tstruct in6_addr dest_addr_as_ipv6 = canonical_ipv6_addr(dest);\n+\tstruct homa_rpc_bucket *bucket;\n+\tstruct homa_rpc *crpc;\n+\tint err;\n+\n+\tcrpc = kzalloc_obj(*crpc, GFP_KERNEL_ACCOUNT);\n+\tif (unlikely(!crpc)) {\n+\t\thsk-\u003eerror_msg = \"couldn't allocate memory for client RPC\";\n+\t\treturn ERR_PTR(-ENOMEM);\n+\t}\n+\n+\t/* Initialize fields that don't require the socket lock. */\n+\tcrpc-\u003ehsk = hsk;\n+\tcrpc-\u003eid = atomic64_fetch_add(2, \u0026hsk-\u003ehoma-\u003enext_outgoing_id);\n+\tbucket = homa_client_rpc_bucket(hsk, crpc-\u003eid);\n+\tcrpc-\u003ebucket = bucket;\n+\tcrpc-\u003estate = RPC_OUTGOING;\n+\trefcount_set(\u0026crpc-\u003erefs, 1);\n+\tcrpc-\u003eroute = homa_route_get(hsk, \u0026dest_addr_as_ipv6);\n+\tif (IS_ERR(crpc-\u003eroute)) {\n+\t\terr = PTR_ERR(crpc-\u003eroute);\n+\t\tcrpc-\u003eroute = NULL;\n+\t\tgoto error;\n+\t}\n+\tcrpc-\u003edport = ntohs(dest-\u003ein6.sin6_port);\n+\tcrpc-\u003emsgin.length = -1;\n+\tcrpc-\u003emsgout.length = -1;\n+\tINIT_LIST_HEAD(\u0026crpc-\u003eready_links);\n+\tINIT_LIST_HEAD(\u0026crpc-\u003ebuf_links);\n+\tINIT_LIST_HEAD(\u0026crpc-\u003edead_links);\n+\tcrpc-\u003eresend_timer_ticks = hsk-\u003ehoma-\u003etimer_ticks;\n+\tcrpc-\u003emagic = HOMA_RPC_MAGIC;\n+\tcrpc-\u003estart_time = homa_clock();\n+\n+\t/* Initialize fields that require locking. This allows the most\n+\t * expensive work, such as copying in the message from user space,\n+\t * to be performed without holding locks. Also, can't hold spin\n+\t * locks while doing things that could block, such as memory allocation.\n+\t */\n+\thoma_bucket_lock(bucket, crpc-\u003eid);\n+\thoma_sock_lock(hsk);\n+\tif (hsk-\u003eshutdown) {\n+\t\thoma_sock_unlock(hsk);\n+\t\thoma_rpc_unlock(crpc);\n+\t\thsk-\u003eerror_msg = \"socket has been shut down\";\n+\t\terr = -ESHUTDOWN;\n+\t\tgoto error;\n+\t}\n+\thlist_add_head(\u0026crpc-\u003ehash_links, \u0026bucket-\u003erpcs);\n+\trcu_read_lock();\n+\tlist_add_tail_rcu(\u0026crpc-\u003eactive_links, \u0026hsk-\u003eactive_rpcs);\n+\trcu_read_unlock();\n+\thoma_sock_unlock(hsk);\n+\n+\treturn crpc;\n+\n+error:\n+\tif (crpc-\u003eroute)\n+\t\thoma_route_release(crpc-\u003eroute);\n+\tkfree(crpc);\n+\treturn ERR_PTR(err);\n+}\n+\n+/**\n+ * homa_rpc_alloc_server() - Allocate and initialize a server RPC (one that is\n+ * used to manage an incoming request). If appropriate, the RPC will also\n+ * be handed off (we do it here, while we have the socket locked, to avoid\n+ * acquiring the socket lock a second time later for the handoff).\n+ * @hsk:      Socket that owns this RPC.\n+ * @source:   IP address (network byte order) of the RPC's client.\n+ * @h:        Header for the first data packet received for this RPC; used\n+ *            to initialize the RPC.\n+ *\n+ * Return:  A pointer to a new RPC, which is locked, or a negative errno\n+ *          if an error occurred. If there is already an RPC corresponding\n+ *          to h, then it is returned instead of creating a new RPC.\n+ */\n+struct homa_rpc *homa_rpc_alloc_server(struct homa_sock *hsk,\n+\t\t\t\t       const struct in6_addr *source,\n+\t\t\t\t       struct homa_data_hdr *h)\n+\t__cond_acquires(nonnull, srpc-\u003ebucket-\u003elock)\n+{\n+\tu64 id = homa_local_id(h-\u003ecommon.sender_id);\n+\tstruct homa_rpc_bucket *bucket;\n+\tstruct homa_rpc *srpc = NULL;\n+\tint err;\n+\n+\tif (!hsk-\u003ebuffer_pool)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\n+\t/* Lock the bucket, and make sure no-one else has already created\n+\t * the desired RPC.\n+\t */\n+\tbucket = homa_server_rpc_bucket(hsk, id);\n+\thoma_bucket_lock(bucket, id);\n+\thlist_for_each_entry(srpc, \u0026bucket-\u003erpcs, hash_links) {\n+\t\tif (srpc-\u003eid == id \u0026\u0026\n+\t\t    srpc-\u003edport == ntohs(h-\u003ecommon.sport) \u0026\u0026\n+\t\t    ipv6_addr_equal(\u0026srpc-\u003eroute-\u003epeer-\u003eaddr, source)) {\n+\t\t\t/* RPC already exists; just return it instead\n+\t\t\t * of creating a new RPC.\n+\t\t\t */\n+\t\t\treturn srpc;\n+\t\t}\n+\t}\n+\n+\t/* Initialize fields that don't require the socket lock. */\n+\tif (hsk-\u003esock.sk_memcg) {\n+\t\tstruct mem_cgroup *old = set_active_memcg(hsk-\u003esock.sk_memcg);\n+\n+\t\tsrpc = kzalloc_obj(*srpc, GFP_ATOMIC | __GFP_ACCOUNT);\n+\t\tset_active_memcg(old);\n+\t} else {\n+\t\tsrpc = kzalloc_obj(*srpc, GFP_ATOMIC);\n+\t}\n+\tif (!srpc) {\n+\t\terr = -ENOMEM;\n+\t\tgoto error;\n+\t}\n+\n+\t/* Must be initialized before any errors can occur in this function. */\n+\tINIT_LIST_HEAD(\u0026srpc-\u003ebuf_links);\n+\n+\tsrpc-\u003ehsk = hsk;\n+\tsrpc-\u003ebucket = bucket;\n+\tsrpc-\u003estate = RPC_INCOMING;\n+\trefcount_set(\u0026srpc-\u003erefs, 1);\n+\tsrpc-\u003eroute = homa_route_get(hsk, source);\n+\tif (IS_ERR(srpc-\u003eroute)) {\n+\t\terr = PTR_ERR(srpc-\u003eroute);\n+\t\tsrpc-\u003eroute = NULL;\n+\t\tgoto error;\n+\t}\n+\tsrpc-\u003edport = ntohs(h-\u003ecommon.sport);\n+\tsrpc-\u003eid = id;\n+\tsrpc-\u003emsgin.length = -1;\n+\tsrpc-\u003emsgout.length = -1;\n+\tINIT_LIST_HEAD(\u0026srpc-\u003eready_links);\n+\tINIT_LIST_HEAD(\u0026srpc-\u003edead_links);\n+\tsrpc-\u003eresend_timer_ticks = hsk-\u003ehoma-\u003etimer_ticks;\n+\tsrpc-\u003emagic = HOMA_RPC_MAGIC;\n+\tsrpc-\u003estart_time = homa_clock();\n+\terr = homa_message_in_init(srpc, ntohl(h-\u003emessage_length));\n+\tif (err != 0)\n+\t\tgoto error;\n+\n+\t/* Initialize fields that require socket to be locked. */\n+\thoma_sock_lock(hsk);\n+\tif (hsk-\u003eshutdown) {\n+\t\thoma_sock_unlock(hsk);\n+\t\terr = -ESHUTDOWN;\n+\t\tgoto error;\n+\t}\n+\thlist_add_head(\u0026srpc-\u003ehash_links, \u0026bucket-\u003erpcs);\n+\tlist_add_tail_rcu(\u0026srpc-\u003eactive_links, \u0026hsk-\u003eactive_rpcs);\n+\thoma_sock_unlock(hsk);\n+\tif (ntohl(h-\u003eseg.offset) == 0 \u0026\u0026 srpc-\u003emsgin.num_bpages \u003e 0) {\n+\t\tset_bit(RPC_PKTS_READY, \u0026srpc-\u003eflags);\n+\t\thoma_rpc_handoff(srpc);\n+\t}\n+\treturn srpc;\n+\n+error:\n+\tif (srpc) {\n+\t\thoma_pool_release(srpc);\n+\t\tif (srpc-\u003eroute)\n+\t\t\thoma_route_release(srpc-\u003eroute);\n+\t}\n+\thoma_bucket_unlock(bucket, id);\n+\tkfree(srpc);\n+\treturn ERR_PTR(err);\n+}\n+\n+/**\n+ * homa_rpc_ack() - Handle one or more acknowledgments for RPCs.\n+ * @hsk:      Socket on which the ack(s) were received. Can sometimes be used\n+ *            to avoid a socket lookup.\n+ * @rpc:      RPC for which caller holds lock (NULL if none).\n+ * @saddr:    Source address from which the ack was received (the client\n+ *            node for the RPC)\n+ * @num_acks: Number of acknowledgments in @acks\n+ * @acks:     Information about one or more RPCs from @saddr that may now be\n+ *            deleted safely.\n+ */\n+void homa_rpc_ack(struct homa_sock *hsk, struct homa_rpc *rpc,\n+\t\t  const struct in6_addr *saddr, int num_acks,\n+\t\t  struct homa_ack *acks)\n+{\n+\tstruct homa_sock *hsk2;\n+\tstruct homa_rpc *rpc2;\n+\tu16 server_port;\n+\tu64 id;\n+\tint i;\n+\n+\tif (rpc)\n+\t\thoma_rpc_unlock(rpc);\n+\tfor (i = 0; i \u003c num_acks; i++) {\n+\t\tstruct homa_ack *ack = \u0026acks[i];\n+\n+\t\tserver_port = ntohs(ack-\u003eserver_port);\n+\t\tid = homa_local_id(ack-\u003eclient_id);\n+\t\tif (hsk-\u003eport != server_port) {\n+\t\t\t/* Without RCU, sockets other than hsk can be deleted\n+\t\t\t * out from under us.\n+\t\t\t */\n+\t\t\thsk2 = homa_sock_find(hsk-\u003ehnet, server_port);\n+\t\t\tif (!hsk2)\n+\t\t\t\tcontinue;\n+\t\t} else {\n+\t\t\thsk2 = hsk;\n+\t\t}\n+\t\trpc2 = homa_rpc_find_server(hsk2, saddr, id);\n+\t\tif (rpc2) {\n+\t\t\thoma_rpc_end(rpc2);\n+\t\t\thoma_rpc_unlock(rpc2); /* Locked by homa_rpc_find_server. */\n+\t\t}\n+\t\tif (hsk2 != hsk)\n+\t\t\tsock_put(\u0026hsk2-\u003esock);\n+\t}\n+\tif (rpc)\n+\t\thoma_rpc_lock(rpc);\n+}\n+\n+/**\n+ * homa_rpc_end() - Stop all activity on an RPC and begin the process of\n+ * releasing its resources; this process will continue in the background\n+ * until homa_rpc_reap eventually completes it.\n+ * @rpc:  Structure to clean up, or NULL. Must be locked. Its socket must\n+ *        not be locked. The RPC may still be used after this function returns\n+ *        (there are many places where the RPC lock is temporarily released,\n+ *        and it would add too much complexity to put checks for death\n+ *        every time the lock is reacquired). However, any code that could\n+ *        make the RPC visible again must check rpc-\u003estate; if the RPC is\n+ *        dead then that code must no-op itself.\n+ */\n+void homa_rpc_end(struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\t/* The goal for this function is to make the RPC inaccessible,\n+\t * so that no other code will ever access it again. However, don't\n+\t * actually release resources or tear down the internal structure\n+\t * of the RPC; leave that to homa_rpc_reap, which runs later. There\n+\t * are two reasons for this. First, releasing resources may be\n+\t * expensive, so we don't want to keep the caller waiting; homa_rpc_reap\n+\t * will run in situations where there is time to spare. Second, there\n+\t * may be other code that currently has pointers to this RPC but\n+\t * temporarily released the lock (e.g. to copy data to/from user space).\n+\t * It isn't safe to clean up until that code has finished its work and\n+\t * released any pointers to the RPC (homa_rpc_reap will ensure that\n+\t * this has happened). So, this function should only make changes\n+\t * needed to make the RPC inaccessible.\n+\t */\n+\tif (!rpc || rpc-\u003estate == RPC_DEAD)\n+\t\treturn;\n+\trpc-\u003estate = RPC_DEAD;\n+\trpc-\u003eerror = -EINVAL;\n+\n+\t/* Unlink from all lists, so no-one will ever find this RPC again. */\n+\thoma_sock_lock(rpc-\u003ehsk);\n+\t__hlist_del(\u0026rpc-\u003ehash_links);\n+\tlist_del_rcu(\u0026rpc-\u003eactive_links);\n+\tlist_add_tail(\u0026rpc-\u003edead_links, \u0026rpc-\u003ehsk-\u003edead_rpcs);\n+\t__list_del_entry(\u0026rpc-\u003eready_links);\n+\thoma_pool_unlink(rpc);\n+\thoma_interest_notify_private(rpc);\n+\n+\trpc-\u003ehsk-\u003edead_frags += rpc-\u003emsgout.num_frags + 1;\n+\tif (rpc-\u003ehsk-\u003edead_frags \u003e rpc-\u003ehsk-\u003ehoma-\u003emax_dead_frags)\n+\t\t/* This update isn't thread-safe; it's just a\n+\t\t * statistic so it's OK if updates occasionally get\n+\t\t * missed.\n+\t\t */\n+\t\trpc-\u003ehsk-\u003ehoma-\u003emax_dead_frags = rpc-\u003ehsk-\u003edead_frags;\n+\n+\thoma_sock_unlock(rpc-\u003ehsk);\n+}\n+\n+/**\n+ * homa_rpc_abort() - Terminate an RPC.\n+ * @rpc:     RPC to be terminated.  Must be locked by caller.\n+ * @error:   A negative errno value indicating the error that caused the abort.\n+ *           If this is a client RPC, the error will be returned to the\n+ *           application; if it's a server RPC, the error is ignored and\n+ *           we just free the RPC.\n+ */\n+void homa_rpc_abort(struct homa_rpc *rpc, int error)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tif (!homa_is_client(rpc-\u003eid)) {\n+\t\thoma_rpc_end(rpc);\n+\t\treturn;\n+\t}\n+\trpc-\u003eerror = error;\n+\thoma_rpc_handoff(rpc);\n+}\n+\n+/**\n+ * homa_abort_rpcs() - Abort all RPCs to/from a particular peer.\n+ * @homa:    Overall data about the Homa protocol implementation.\n+ * @addr:    Address (network order) of the destination whose RPCs are\n+ *           to be aborted.\n+ * @port:    If nonzero, then RPCs will only be aborted if they were\n+ *\t     targeted at this server port.\n+ * @error:   Negative errno value indicating the reason for the abort.\n+ */\n+void homa_abort_rpcs(struct homa *homa, const struct in6_addr *addr,\n+\t\t     int port, int error)\n+{\n+\tstruct homa_socktab_scan scan;\n+\tstruct homa_sock *hsk;\n+\tstruct homa_rpc *rpc;\n+\n+\tfor (hsk = homa_socktab_start_scan(homa-\u003esocktab, \u0026scan); hsk;\n+\t     hsk = homa_socktab_next(\u0026scan)) {\n+\t\t/* Skip the (expensive) lock acquisition if there's no\n+\t\t * work to do.\n+\t\t */\n+\t\tif (list_empty(\u0026hsk-\u003eactive_rpcs))\n+\t\t\tcontinue;\n+\t\tif (!homa_protect_rpcs(hsk))\n+\t\t\tcontinue;\n+\t\trcu_read_lock();\n+\t\tlist_for_each_entry_rcu(rpc, \u0026hsk-\u003eactive_rpcs, active_links) {\n+\t\t\tif (!ipv6_addr_equal(\u0026rpc-\u003eroute-\u003epeer-\u003eaddr, addr))\n+\t\t\t\tcontinue;\n+\t\t\tif (port \u0026\u0026 rpc-\u003edport != port)\n+\t\t\t\tcontinue;\n+\t\t\thoma_rpc_lock(rpc);\n+\t\t\tif (rpc-\u003estate != RPC_DEAD)\n+\t\t\t\thoma_rpc_abort(rpc, error);\n+\t\t\thoma_rpc_unlock(rpc);\n+\t\t}\n+\t\trcu_read_unlock();\n+\t\thoma_unprotect_rpcs(hsk);\n+\t}\n+\thoma_socktab_end_scan(\u0026scan);\n+}\n+\n+/**\n+ * homa_rpc_reap() - Invoked to release resources associated with dead\n+ * RPCs for a given socket. Each call will do a small amount of work; there\n+ * may still be unreaped RPCs on return.\n+ * @hsk:      Homa socket that may contain dead RPCs. Must not be locked by the\n+ *            caller; this function will lock and release.\n+ *\n+ * Return: A return value of 0 means that we ran out of work to do; calling\n+ *         again may not do any work (there could be unreaped RPCs, but if so,\n+ *         they cannot currently be reaped).  A value greater than zero means\n+ *         there is still more reaping work to be done.\n+ */\n+int homa_rpc_reap(struct homa_sock *hsk)\n+{\n+\t/* RPC Reaping Strategy:\n+\t *\n+\t * (Note: there are references to this comment elsewhere in the\n+\t * Homa code)\n+\t *\n+\t * This function is separate from homa_rpc_end for two reasons.\n+\t * First, there may be outstanding references to an RPC when\n+\t * homa_rpc_end is invoked; the storage for the RPC cannot be\n+\t * freed until all of those references have been released.\n+\t * Second, reaping an RPC is potentially expensive (if it owns a\n+\t * lot of buffer memory) and homa_rpc_end could be invoked in\n+\t * homa_softirq when there are short messages waiting to be processed.\n+\t * Taking time to reap a long RPC could result in delays for\n+\t * subsequent short RPCs. This second reason is less important\n+\t * now than it used to be (in earlier versions of Homa skbs for both\n+\t * inbound and outbound messages were retained until the RPC was\n+\t * reaped, and freeing the skbs was relatively expensive; now no\n+\t * skbs are retained; there are only pages of tx message memory to\n+\t * return to homa_tx_pool).\n+\t *\n+\t * Thus Homa doesn't reap immediately in homa_rpc_end. Instead, dead\n+\t * RPCs are queued up and reaping occurs in this function, which is\n+\t * invoked later. The challenge is to do this so that (a) we don't allow\n+\t * large numbers of dead RPCs to accumulate and (b) we minimize the\n+\t * impact of reaping on latency of unrelated messages.\n+\t *\n+\t * The primary place where homa_rpc_reap is invoked is when threads\n+\t * are waiting for incoming messages. The thread has nothing else to\n+\t * do (it may even be polling for input), so reaping can be performed\n+\t * with no latency impact on the application.  However, if a machine\n+\t * is overloaded then it may never wait, so this mechanism isn't always\n+\t * sufficient.\n+\t *\n+\t * Homa now reaps in two other places, if reaping while waiting for\n+\t * messages isn't adequate:\n+\t * 1. If too many dead RPCs accumulate, then homa_timer will call\n+\t *    homa_rpc_reap.\n+\t * 2. If the timer thread cannot keep up with all the reaping to be\n+\t *    done then as a last resort homa_dispatch_pkts will reap in small\n+\t *    increments (a few sk_buffs or RPCs) for every incoming batch\n+\t *    of packets. This is undesirable because it will impact Homa's\n+\t *    latency.\n+\t *\n+\t * During the introduction of homa_pools for managing input\n+\t * buffers, freeing of packets for incoming messages was moved to\n+\t * homa_copy_to_user under the assumption that this code wouldn't be\n+\t * on the critical path. However, there is evidence that with\n+\t * fast networks (e.g. 100 Gbps) copying to user space is the\n+\t * bottleneck for incoming messages, and packet freeing takes about\n+\t * 20-25% of the total time in homa_copy_to_user. So, it may eventually\n+\t * be desirable to move packet freeing out of homa_copy_to_user.\n+\t */\n+#define BATCH_MAX_RPCS 5\n+#define BATCH_MAX_FRAGS 30\n+\tstruct homa_rpc *rpcs[BATCH_MAX_RPCS];\n+\tint checked_all_rpcs;\n+\tint total_dead_frags;\n+\tstruct homa_rpc *rpc;\n+\tstruct homa_rpc *tmp;\n+\tint i, num_rpcs;\n+\n+\t/* Each iteration through the following loop will reap\n+\t * up to BATCH_MAX_RPCS RPCs.\n+\t */\n+\tchecked_all_rpcs = list_empty(\u0026hsk-\u003edead_rpcs);\n+\tif (checked_all_rpcs)\n+\t\treturn 0;\n+\tnum_rpcs = 0;\n+\ttotal_dead_frags = 0;\n+\n+\thoma_sock_lock(hsk);\n+\tif (atomic_read(\u0026hsk-\u003eprotect_count)) {\n+\t\thoma_sock_unlock(hsk);\n+\t\treturn 0;\n+\t}\n+\n+\t/* Collect freeable RPCs. */\n+\tlist_for_each_entry_safe(rpc, tmp, \u0026hsk-\u003edead_rpcs, dead_links) {\n+\t\tint refs;\n+\n+\t\tif (num_rpcs \u003e= BATCH_MAX_RPCS ||\n+\t\t    total_dead_frags \u003e= BATCH_MAX_FRAGS)\n+\t\t\tgoto release;\n+\n+\t\t/* Make sure that all outstanding uses of the RPC have\n+\t\t * completed. We can read the reference count safely\n+\t\t * only when we're holding the lock. Note: it isn't\n+\t\t * safe to block while locking the RPC here, since we\n+\t\t * hold the socket lock.\n+\t\t */\n+\t\tif (homa_rpc_try_lock(rpc)) {\n+\t\t\trefs = refcount_read(\u0026rpc-\u003erefs);\n+\t\t\thoma_rpc_unlock(rpc);\n+\t\t} else {\n+\t\t\trefs = 2;\n+\t\t}\n+\t\tif (refs \u003e 1)\n+\t\t\tcontinue;\n+\n+\t\trpcs[num_rpcs] = rpc;\n+\t\tnum_rpcs++;\n+\t\tlist_del(\u0026rpc-\u003edead_links);\n+\t\thsk-\u003edead_frags -= (rpc-\u003emsgout.num_frags + 1);\n+\t\ttotal_dead_frags += rpc-\u003emsgout.num_frags;\n+\t}\n+\tchecked_all_rpcs = true;\n+\n+\t/* Free all of the collected resources; release the socket lock\n+\t * while doing this.\n+\t */\n+release:\n+\thoma_sock_unlock(hsk);\n+\tfor (i = 0; i \u003c num_rpcs; i++) {\n+\t\trpc = rpcs[i];\n+\n+\t\t/* Free any unconsumed input packets and gaps (there\n+\t\t * shouldn't usually be any of either).\n+\t\t */\n+\t\tif (rpc-\u003emsgin.length \u003e= 0) {\n+\t\t\tstruct sk_buff *skb;\n+\n+\t\t\tfor (skb = __skb_dequeue(\u0026rpc-\u003emsgin.packets); skb;\n+\t\t\t     skb = __skb_dequeue(\u0026rpc-\u003emsgin.packets))\n+\t\t\t\tconsume_skb(skb);\n+\t\t\twhile (1) {\n+\t\t\t\tstruct homa_gap *gap;\n+\n+\t\t\t\tgap = list_first_entry_or_null(\u0026rpc-\u003emsgin.gaps,\n+\t\t\t\t\t\t\t       struct homa_gap,\n+\t\t\t\t\t\t\t       links);\n+\t\t\t\tif (!gap)\n+\t\t\t\t\tbreak;\n+\t\t\t\tlist_del(\u0026gap-\u003elinks);\n+\t\t\t\tkfree(gap);\n+\t\t\t}\n+\t\t}\n+\n+\t\tif (rpc-\u003eroute) {\n+\t\t\thoma_route_release(rpc-\u003eroute);\n+\t\t\trpc-\u003eroute = NULL;\n+\t\t}\n+\t\thoma_pool_release(rpc);\n+\t\thoma_tx_pool_free(hsk-\u003ehoma, rpc-\u003emsgout.num_frags,\n+\t\t\t\t  rpc-\u003emsgout.frags);\n+\t\tWARN_ON(refcount_sub_and_test(rpc-\u003emsgout.frag_bytes,\n+\t\t\t\t\t      \u0026hsk-\u003esock.sk_wmem_alloc));\n+\t\tif (rpc-\u003emsgout.frags != \u0026rpc-\u003emsgout.frag)\n+\t\t\tkfree(rpc-\u003emsgout.frags);\n+\t\trpc-\u003estate = 0;\n+\t\trpc-\u003emagic = 0;\n+\t\tkfree(rpc);\n+\t}\n+\thoma_sock_wakeup_wmem(hsk);\n+\tif (hsk-\u003ebuffer_pool)\n+\t\thoma_pool_check_waiting(hsk-\u003ebuffer_pool);\n+\treturn !checked_all_rpcs;\n+}\n+\n+/**\n+ * homa_abort_sock_rpcs() - Abort all outgoing (client-side) RPCs on a given\n+ * socket.\n+ * @hsk:         Socket whose RPCs should be aborted.\n+ * @error:       Zero means that the aborted RPCs should be freed immediately.\n+ *               A nonzero value means that the RPCs should be marked\n+ *               complete, so that they can be returned to the application;\n+ *               this value (a negative errno) will be returned from\n+ *               recvmsg.\n+ */\n+void homa_abort_sock_rpcs(struct homa_sock *hsk, int error)\n+{\n+\tstruct homa_rpc *rpc;\n+\n+\tif (list_empty(\u0026hsk-\u003eactive_rpcs))\n+\t\treturn;\n+\tif (!homa_protect_rpcs(hsk))\n+\t\treturn;\n+\trcu_read_lock();\n+\tlist_for_each_entry_rcu(rpc, \u0026hsk-\u003eactive_rpcs, active_links) {\n+\t\tif (!homa_is_client(rpc-\u003eid))\n+\t\t\tcontinue;\n+\t\thoma_rpc_lock(rpc);\n+\t\tif (rpc-\u003estate == RPC_DEAD) {\n+\t\t\thoma_rpc_unlock(rpc);\n+\t\t\tcontinue;\n+\t\t}\n+\t\tif (error)\n+\t\t\thoma_rpc_abort(rpc, error);\n+\t\telse\n+\t\t\thoma_rpc_end(rpc);\n+\t\thoma_rpc_unlock(rpc);\n+\t}\n+\trcu_read_unlock();\n+\thoma_unprotect_rpcs(hsk);\n+}\n+\n+/**\n+ * homa_rpc_find_client() - Locate client-side information about the RPC that\n+ * a packet belongs to, if there is any. Thread-safe without socket lock.\n+ * @hsk:      Socket via which packet was received.\n+ * @id:       Unique identifier for the RPC.\n+ *\n+ * Return:    A pointer to the homa_rpc for this id, or NULL if none.\n+ *            The RPC will be locked; the caller must eventually unlock it\n+ *            by invoking homa_rpc_unlock.\n+ */\n+struct homa_rpc *homa_rpc_find_client(struct homa_sock *hsk, u64 id)\n+\t__cond_acquires(nonnull, crpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_rpc_bucket *bucket = homa_client_rpc_bucket(hsk, id);\n+\tstruct homa_rpc *crpc;\n+\n+\thoma_bucket_lock(bucket, id);\n+\thlist_for_each_entry(crpc, \u0026bucket-\u003erpcs, hash_links) {\n+\t\tif (crpc-\u003eid == id)\n+\t\t\treturn crpc;\n+\t}\n+\thoma_bucket_unlock(bucket, id);\n+\treturn NULL;\n+}\n+\n+/**\n+ * homa_rpc_find_server() - Locate server-side information about the RPC that\n+ * a packet belongs to, if there is any. Thread-safe without socket lock.\n+ * @hsk:      Socket via which packet was received.\n+ * @saddr:    Address from which the packet was sent.\n+ * @id:       Unique identifier for the RPC (must have server bit set).\n+ *\n+ * Return:    A pointer to the homa_rpc matching the arguments, or NULL\n+ *            if none. The RPC will be locked; the caller must eventually\n+ *            unlock it by invoking homa_rpc_unlock.\n+ */\n+struct homa_rpc *homa_rpc_find_server(struct homa_sock *hsk,\n+\t\t\t\t      const struct in6_addr *saddr, u64 id)\n+\t__cond_acquires(nonnull, srpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_rpc_bucket *bucket = homa_server_rpc_bucket(hsk, id);\n+\tstruct homa_rpc *srpc;\n+\n+\thoma_bucket_lock(bucket, id);\n+\thlist_for_each_entry(srpc, \u0026bucket-\u003erpcs, hash_links) {\n+\t\tif (srpc-\u003eid == id \u0026\u0026 ipv6_addr_equal(\u0026srpc-\u003eroute-\u003epeer-\u003eaddr,\n+\t\t\t\t\t\t      saddr))\n+\t\t\treturn srpc;\n+\t}\n+\thoma_bucket_unlock(bucket, id);\n+\treturn NULL;\n+}\n+\n+/**\n+ * homa_rpc_find_from_skb() - Given an skb for a Homa packet, find the homa_rpc\n+ * associated with the packet and lock it.\n+ * @skb:        Packet buffer; must contain a Homa packet that is \"fully\n+ *              populated\" (e.g. the dev field and IP header are initialized).\n+ * @incoming:   True means this is an incoming packet, false means outgoing.\n+ * Return:      Pointer an RPC that has been locked; the caller is responsible\n+ *              for unlocking it. If no RPC could be found, NULL is returned.\n+ */\n+struct homa_rpc *homa_rpc_find_from_skb(struct sk_buff *skb, bool incoming)\n+{\n+\tstruct homa_common_hdr *h;\n+\tstruct homa_sock *hsk;\n+\tstruct homa_net *hnet;\n+\tstruct homa_rpc *rpc;\n+\tint port;\n+\tu64 id;\n+\n+\t/* Find the appropriate socket.*/\n+\th = (struct homa_common_hdr *)skb_transport_header(skb);\n+\tid = be64_to_cpu(h-\u003esender_id);\n+\tif (incoming) {\n+\t\tport = ntohs(h-\u003edport);\n+\t\tid ^= 1;\n+\t} else {\n+\t\tport = ntohs(h-\u003esport);\n+\t}\n+\thnet = homa_net(dev_net(skb-\u003edev));\n+\thsk = homa_sock_find(hnet, port);\n+\tif (!hsk)\n+\t\treturn NULL;\n+\n+\t/* Look up the RPC (client and server RPCs are handled differently) */\n+\tif (homa_is_client(id)) {\n+\t\trpc = homa_rpc_find_client(hsk, id);\n+\t} else {\n+\t\tif (skb_is_ipv6(skb)) {\n+\t\t\tstruct in6_addr *addr;\n+\n+\t\t\taddr = (incoming) ? \u0026ipv6_hdr(skb)-\u003esaddr :\n+\t\t\t\t\t\u0026ipv6_hdr(skb)-\u003edaddr;\n+\t\t\trpc = homa_rpc_find_server(hsk, addr, id);\n+\t\t} else {\n+\t\t\tstruct in6_addr addr;\n+\n+\t\t\tif (incoming)\n+\t\t\t\tipv6_addr_set_v4mapped(ip_hdr(skb)-\u003esaddr,\n+\t\t\t\t\t\t       \u0026addr);\n+\t\t\telse\n+\t\t\t\tipv6_addr_set_v4mapped(ip_hdr(skb)-\u003edaddr,\n+\t\t\t\t\t\t       \u0026addr);\n+\t\t\trpc = homa_rpc_find_server(hsk, \u0026addr, id);\n+\t\t}\n+\t}\n+\tsock_put(\u0026hsk-\u003esock);\n+\treturn rpc;\n+}\n+\n+/**\n+ * homa_rpc_get_info() - Extract information from an RPC for returning to\n+ * an application via the HOMAIOCINFO ioctl.\n+ * @rpc:   RPC for which information is desired.\n+ * @info:  Structure in which to store the information.\n+ */\n+void homa_rpc_get_info(struct homa_rpc *rpc, struct homa_rpc_info *info)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa_gap *gap;\n+\n+\tmemset(info, 0, sizeof(*info));\n+\tinfo-\u003eid = rpc-\u003eid;\n+\tif (rpc-\u003ehsk-\u003einet.sk.sk_family == AF_INET6) {\n+\t\tinfo-\u003epeer.in6.sin6_family = AF_INET6;\n+\t\tinfo-\u003epeer.in6.sin6_addr = rpc-\u003eroute-\u003epeer-\u003eaddr;\n+\t\tinfo-\u003epeer.in6.sin6_port = htons(rpc-\u003edport);\n+\t} else {\n+\t\tinfo-\u003epeer.in6.sin6_family = AF_INET;\n+\t\tinfo-\u003epeer.in4.sin_addr.s_addr = ipv6_to_ipv4(rpc-\u003eroute-\u003epeer-\u003eaddr);\n+\t\tinfo-\u003epeer.in4.sin_port = htons(rpc-\u003edport);\n+\t}\n+\tinfo-\u003ecompletion_cookie = rpc-\u003ecompletion_cookie;\n+\tif (rpc-\u003emsgout.length \u003e= 0) {\n+\t\tinfo-\u003etx_length = rpc-\u003emsgout.length;\n+\t\tinfo-\u003etx_sent = rpc-\u003emsgout.next_xmit_offset;\n+\t\tinfo-\u003etx_granted = rpc-\u003emsgout.length;\n+\t} else {\n+\t\tinfo-\u003etx_length = -1;\n+\t}\n+\tif (rpc-\u003emsgin.length \u003e= 0) {\n+\t\tinfo-\u003erx_length = rpc-\u003emsgin.length;\n+\t\tinfo-\u003erx_remaining = rpc-\u003emsgin.bytes_remaining;\n+\t\tlist_for_each_entry(gap, \u0026rpc-\u003emsgin.gaps, links) {\n+\t\t\tinfo-\u003erx_gaps++;\n+\t\t\tinfo-\u003erx_gap_bytes += gap-\u003eend - gap-\u003estart;\n+\t\t}\n+\t\tinfo-\u003erx_granted = rpc-\u003emsgin.length;\n+\t\tif (skb_queue_len(\u0026rpc-\u003emsgin.packets) \u003e 0)\n+\t\t\tinfo-\u003eflags |= HOMA_RPC_RX_COPY;\n+\t} else {\n+\t\tinfo-\u003erx_length = -1;\n+\t}\n+\tif (!list_empty(\u0026rpc-\u003ebuf_links))\n+\t\tinfo-\u003eflags |= HOMA_RPC_BUF_STALL;\n+\tif (!list_empty(\u0026rpc-\u003eready_links) \u0026\u0026\n+\t    rpc-\u003emsgin.bytes_remaining == 0 \u0026\u0026\n+\t    skb_queue_len(\u0026rpc-\u003emsgin.packets) == 0)\n+\t\tinfo-\u003eflags |= HOMA_RPC_RX_READY;\n+\tif (rpc-\u003eflags \u0026 RPC_PRIVATE)\n+\t\tinfo-\u003eflags |= HOMA_RPC_PRIVATE;\n+}\ndiff --git a/net/homa/homa_rpc.h b/net/homa/homa_rpc.h\nnew file mode 100644\nindex 0000000000000..fa082d229740a\n--- /dev/null\n+++ b/net/homa/homa_rpc.h\n@@ -0,0 +1,545 @@\n+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */\n+\n+/* This file defines homa_rpc and related structs.  */\n+\n+#ifndef _HOMA_RPC_H\n+#define _HOMA_RPC_H\n+\n+#include \u003clinux/percpu-defs.h\u003e\n+#include \u003clinux/skbuff.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \"homa_sock.h\"\n+#include \"homa_wire.h\"\n+\n+/* Forward references. */\n+struct homa_ack;\n+\n+/**\n+ * struct homa_message_out - Describes a message (either request or response)\n+ * for which this machine is the sender.\n+ */\n+struct homa_message_out {\n+\t/**\n+\t * @length: Total bytes in message (excluding headers).  A value\n+\t * less than 0 means this structure is uninitialized and therefore\n+\t * not in use (all other fields will be zero in this case).\n+\t */\n+\tint length;\n+\n+\t/**\n+\t * @frags: Array of fragments that hold the tx message in a ready-\n+\t * to-transmit form, consisting of segments, each with a\n+\t * homa_seg_hdr followed by the data for that segment. These\n+\t * fragments will be incorporated into skb's to transmit the message.\n+\t * If this doesn't point to @frag below then it is dynamically\n+\t * allocated and must be freed.\n+\t */\n+\tskb_frag_t *frags;\n+\n+\t/** @num_frags: Number of fragments at @frags. */\n+\tint num_frags;\n+\n+\t/**\n+\t * @frag_bytes: Total amount of memory in all of @frags; this is\n+\t * included in sk_wmem_alloc.\n+\t */\n+\tint frag_bytes;\n+\n+\t/**\n+\t * @frag: @frags will point here if the message data all fits in a\n+\t * single fragment (avoid alloc/free overhead).\n+\t */\n+\tskb_frag_t frag;\n+\n+\t/**\n+\t * @max_seg_data: Maximum amount of message data to include in each\n+\t * segment of tx packets.\n+\t */\n+\tint max_seg_data;\n+\n+\t/**\n+\t * @max_gso_segs: Maximum number of segments that can be present in a\n+\t * single GSO packet.\n+\t */\n+\tint max_gso_segs;\n+\n+\t/**\n+\t * @max_gso_data: Maximum amount of message data in a GSO frame\n+\t * (@max_seg_data * @max_gso_segs).\n+\t */\n+\tint max_gso_data;\n+\n+\t/**\n+\t * @copied_from_user: Number of bytes of the message that have\n+\t * been copied from user space into @frags. Used for lockless\n+\t * communication between one core copying in data and another\n+\t * core transmitting the data in skbs.\n+\t */\n+\tint copied_from_user;\n+\n+\t/**\n+\t * @next_xmit_offset: All bytes in the message, up to but not\n+\t * including this one, have been passed to ip_queue_xmit or\n+\t * ip6_xmit at least once.\n+\t */\n+\tint next_xmit_offset;\n+\n+\t/**\n+\t * @init_time: homa_clock() time when this structure was initialized.\n+\t * Used to find the oldest outgoing message.\n+\t */\n+\tu64 init_time;\n+};\n+\n+/**\n+ * struct homa_gap - Represents a range of bytes within a message that have\n+ * not yet been received.\n+ */\n+struct homa_gap {\n+\t/** @start: offset of first byte in this gap. */\n+\tint start;\n+\n+\t/** @end: offset of byte just after last one in this gap. */\n+\tint end;\n+\n+\t/**\n+\t * @time: homa_clock() time when the gap was first detected.\n+\t * As of 7/2024 this isn't used for anything.\n+\t */\n+\tu64 time;\n+\n+\t/** @links: for linking into list in homa_message_in. */\n+\tstruct list_head links;\n+};\n+\n+/**\n+ * struct homa_message_in - Holds the state of a message received by\n+ * this machine; used for both requests and responses.\n+ */\n+struct homa_message_in {\n+\t/**\n+\t * @length: Payload size in bytes. -1 means this structure is\n+\t * uninitialized and therefore not in use.\n+\t */\n+\tint length;\n+\n+\t/**\n+\t * @packets: DATA packets for this message that have been received but\n+\t * not yet copied to user space (ordered by increasing offset). The\n+\t * lock in this structure is not used (the RPC lock is used instead).\n+\t */\n+\tstruct sk_buff_head packets;\n+\n+\t/**\n+\t * @recv_end: Offset of the byte just after the highest one that\n+\t * has been received so far.\n+\t */\n+\tint recv_end;\n+\n+\t/**\n+\t * @gaps: List of homa_gaps describing all of the bytes with\n+\t * offsets less than @recv_end that have not yet been received.\n+\t */\n+\tstruct list_head gaps;\n+\n+\t/**\n+\t * @bytes_remaining: Amount of data for this message that has\n+\t * not yet been received; will determine the message's priority.\n+\t */\n+\tint bytes_remaining;\n+\n+\t/**\n+\t * @num_bpages: The number of entries in @bpage_offsets used for this\n+\t * message (0 means buffers not allocated yet or the buffers have\n+\t * been handed off to the application).\n+\t */\n+\tu32 num_bpages;\n+\n+\t/**\n+\t * @bpage_offsets: Describes buffer space allocated for this message.\n+\t * Each entry is an offset from the start of the buffer region.\n+\t * All but the last pointer refer to areas of size HOMA_BPAGE_SIZE.\n+\t */\n+\tu32 bpage_offsets[HOMA_MAX_BPAGES];\n+\n+};\n+\n+/**\n+ * struct homa_rpc - One of these structures exists for each active\n+ * RPC. The same structure is used to manage both outgoing RPCs on\n+ * clients and incoming RPCs on servers.\n+ */\n+struct homa_rpc {\n+\t/** @hsk:  Socket that owns the RPC. */\n+\tstruct homa_sock *hsk;\n+\n+\t/**\n+\t * @bucket: Pointer to the bucket in hsk-\u003eclient_rpc_buckets or\n+\t * hsk-\u003eserver_rpc_buckets where this RPC is linked. Used primarily\n+\t * for locking the RPC (which is done by locking its bucket).\n+\t */\n+\tstruct homa_rpc_bucket *bucket;\n+\n+\t/**\n+\t * @state: The current state of this RPC:\n+\t *\n+\t * @RPC_OUTGOING:     The RPC is waiting for @msgout to be transmitted\n+\t *                    to the peer.\n+\t * @RPC_INCOMING:     The RPC is waiting for data @msgin to be received\n+\t *                    from the peer; at least one packet has already\n+\t *                    been received.\n+\t * @RPC_IN_SERVICE:   Used only for server RPCs: the request message\n+\t *                    has been read from the socket, but the response\n+\t *                    message has not yet been presented to the kernel.\n+\t * @RPC_DEAD:         The RPC has been killed and is waiting to be\n+\t *                    reaped. The RPC may continue to be used in this\n+\t *                    state using references that existed when\n+\t *                    homa_rpc_end was invoked, but it can no longer\n+\t *                    be discovered and no code may make it\n+\t *                    discoverable.\n+\t *\n+\t * Client RPCs pass through states in the following order:\n+\t * RPC_OUTGOING, RPC_INCOMING, RPC_DEAD.\n+\t *\n+\t * Server RPCs pass through states in the following order:\n+\t * RPC_INCOMING, RPC_IN_SERVICE, RPC_OUTGOING, RPC_DEAD.\n+\t */\n+\tenum {\n+\t\tRPC_OUTGOING            = 5,\n+\t\tRPC_INCOMING            = 6,\n+\t\tRPC_IN_SERVICE          = 8,\n+\t\tRPC_DEAD                = 9\n+\t} state;\n+\n+\t/**\n+\t * @flags: Additional state information: an OR'ed combination of\n+\t * various single-bit flags. See below for definitions. Must be\n+\t * manipulated with atomic operations because some of the manipulations\n+\t * occur without holding the RPC lock.\n+\t */\n+\tunsigned long flags;\n+\n+\t/* Valid bit numbers for @flags:\n+\t * RPC_PKTS_READY -        The RPC has input packets ready to be\n+\t *                         copied to user space.\n+\t * APP_NEEDS_LOCK -        Means that code in the application thread\n+\t *                         needs the RPC lock (e.g. so it can start\n+\t *                         copying data to user space) so others\n+\t *                         (e.g. SoftIRQ processing) should relinquish\n+\t *                         the lock ASAP. Without this, SoftIRQ can\n+\t *                         lock out the application for a long time,\n+\t *                         preventing data copies to user space from\n+\t *                         starting (and they limit throughput at\n+\t *                         high network speeds).\n+\t * RPC_PRIVATE -           This RPC will be waited on in \"private\" mode,\n+\t *                         where the app explicitly requests the\n+\t *                         response from this particular RPC.\n+\t * RPC_GRANTABLE -         1 means this RPC needs help from the grant\n+\t *                         mechanism to receive its incoming message. 0\n+\t *                         means either it is entirely unscheduled or\n+\t *                         the message has been completely received.\n+\t *                         This bit gets set at most once in the life\n+\t *                         of an RPC; once cleared, it never gets set\n+\t *                         again.\n+\t * RPC_GRANT_MANAGED -     1 means this RPC has been inserted in the\n+\t *                         grant management data structures. This\n+\t *                         doesn't happen until the first time\n+\t *                         homa_grant_check_rpc is called, so it is\n+\t *                         possible for RPC_GRANTABLE to be set but\n+\t *                         not RPC_GRANT_MANAGED.\n+\t */\n+#define RPC_PKTS_READY        0\n+#define APP_NEEDS_LOCK        1\n+#define RPC_PRIVATE           2\n+#define RPC_GRANTABLE         3\n+#define RPC_GRANT_MANAGED     4\n+\n+\t/**\n+\t * @refs: Number of references to this RPC, including one for each\n+\t * unmatched call to homa_rpc_hold plus one for the socket's reference\n+\t * in either active_rpcs or dead_rpcs. References are acquired at\n+\t * \"top level\", such as homa_dispatch_pkts or homa_recvmsg. If a\n+\t * function receives a locked RPC as parameter, it can assume\n+\t * that the caller is also holding a reference to it.\n+\t */\n+\trefcount_t refs;\n+\n+\t/**\n+\t * @route: Holds a dst_entry that can be used to route to the peer;\n+\t * also provides indirect access to a homa_peer for the peer. This\n+\t * value can change due to route invalidations, if RPC lock not held.\n+\t */\n+\tstruct homa_route *route;\n+\n+\t/** @dport: Port number on @peer that will handle packets. */\n+\tu16 dport;\n+\n+\t/**\n+\t * @id: Unique identifier for the RPC among all those issued\n+\t * from its port. The low-order bit indicates whether we are\n+\t * server (1) or client (0) for this RPC.\n+\t */\n+\tu64 id;\n+\n+\t/**\n+\t * @completion_cookie: Only used on clients. Contains identifying\n+\t * information about the RPC provided by the application; returned to\n+\t * the application with the RPC's result.\n+\t */\n+\tu64 completion_cookie;\n+\n+\t/**\n+\t * @error: Only used on clients. If nonzero, then the RPC has\n+\t * failed and the value is a negative errno that describes the\n+\t * problem.\n+\t */\n+\tint error;\n+\n+\t/**\n+\t * @msgin: Information about the message we receive for this RPC\n+\t * (for server RPCs this is the request, for client RPCs this is the\n+\t * response).\n+\t */\n+\tstruct homa_message_in msgin;\n+\n+\t/**\n+\t * @msgout: Information about the message we send for this RPC\n+\t * (for client RPCs this is the request, for server RPCs this is the\n+\t * response).\n+\t */\n+\tstruct homa_message_out msgout;\n+\n+\t/**\n+\t * @hash_links: Used to link this object into a hash bucket for\n+\t * either @hsk-\u003eclient_rpc_buckets (for a client RPC), or\n+\t * @hsk-\u003eserver_rpc_buckets (for a server RPC).\n+\t */\n+\tstruct hlist_node hash_links;\n+\n+\t/**\n+\t * @ready_links: Used to link this object into @hsk-\u003eready_rpcs.\n+\t */\n+\tstruct list_head ready_links;\n+\n+\t/**\n+\t * @buf_links: Used to link this RPC into @hsk-\u003ewaiting_for_bufs.\n+\t * If the RPC isn't on @hsk-\u003ewaiting_for_bufs, this is an empty\n+\t * list pointing to itself.\n+\t */\n+\tstruct list_head buf_links;\n+\n+\t/**\n+\t * @active_links: For linking this object into @hsk-\u003eactive_rpcs.\n+\t * The next field will be LIST_POISON1 if this RPC hasn't yet been\n+\t * linked into @hsk-\u003eactive_rpcs. Access with RCU.\n+\t */\n+\tstruct list_head active_links;\n+\n+\t/** @dead_links: For linking this object into @hsk-\u003edead_rpcs. */\n+\tstruct list_head dead_links;\n+\n+\t/**\n+\t * @private_interest: If there is a thread waiting for this RPC in\n+\t * homa_wait_private, then this points to that thread's interest.\n+\t */\n+\tstruct homa_interest *private_interest;\n+\n+\t/**\n+\t * @silent_ticks: Number of times homa_timer has been invoked\n+\t * since the last time a packet indicating progress was received\n+\t * for this RPC, so we don't need to send a resend for a while.\n+\t */\n+\tint silent_ticks;\n+\n+\t/**\n+\t * @resend_timer_ticks: Value of homa-\u003etimer_ticks the last time\n+\t * we sent a RESEND for this RPC.\n+\t */\n+\tu32 resend_timer_ticks;\n+\n+\t/**\n+\t * @done_timer_ticks: The value of homa-\u003etimer_ticks the first\n+\t * time we noticed that this (server) RPC is done (all response\n+\t * packets have been transmitted), so we're ready for an ack.\n+\t * Zero means we haven't reached that point yet.\n+\t */\n+\tu32 done_timer_ticks;\n+\n+\t/**\n+\t * @magic: when the RPC is alive, this holds a distinct value that\n+\t * is unlikely to occur naturally. The value is cleared when the\n+\t * RPC is reaped, so we can detect accidental use of an RPC after\n+\t * it has been reaped.\n+\t */\n+#define HOMA_RPC_MAGIC 0xdeadbeef\n+\tint magic;\n+\n+\t/**\n+\t * @start_time: homa_clock() time when this RPC was created. Used\n+\t * occasionally for testing.\n+\t */\n+\tu64 start_time;\n+};\n+\n+void     homa_abort_rpcs(struct homa *homa, const struct in6_addr *addr,\n+\t\t\t int port, int error);\n+void     homa_abort_sock_rpcs(struct homa_sock *hsk, int error);\n+void     homa_rpc_abort(struct homa_rpc *crpc, int error);\n+void     homa_rpc_ack(struct homa_sock *hsk, struct homa_rpc *rpc,\n+\t\t      const struct in6_addr *saddr, int num_acks,\n+\t\t      struct homa_ack *acks);\n+struct homa_rpc\n+\t*homa_rpc_alloc_client(struct homa_sock *hsk,\n+\t\t\t       const union sockaddr_in_union *dest);\n+struct homa_rpc\n+\t*homa_rpc_alloc_server(struct homa_sock *hsk,\n+\t\t\t       const struct in6_addr *source,\n+\t\t\t       struct homa_data_hdr *h);\n+void     homa_rpc_end(struct homa_rpc *rpc);\n+struct homa_rpc\n+\t*homa_rpc_find_client(struct homa_sock *hsk, u64 id);\n+struct homa_rpc\n+\t*homa_rpc_find_from_skb(struct sk_buff *skb, bool incoming);\n+struct homa_rpc\n+\t*homa_rpc_find_server(struct homa_sock *hsk,\n+\t\t\t      const struct in6_addr *saddr, u64 id);\n+void     homa_rpc_get_info(struct homa_rpc *rpc, struct homa_rpc_info *info);\n+int      homa_rpc_reap(struct homa_sock *hsk);\n+\n+/**\n+ * homa_rpc_lock() - Acquire the lock for an RPC.\n+ * @rpc:    RPC to lock.\n+ */\n+static inline void homa_rpc_lock(struct homa_rpc *rpc)\n+\t__acquires(rpc-\u003ebucket-\u003elock)\n+{\n+\thoma_bucket_lock(rpc-\u003ebucket, rpc-\u003eid);\n+}\n+\n+/**\n+ * homa_rpc_try_lock() - Acquire the lock for an RPC if it is available.\n+ * @rpc:       RPC to lock.\n+ * Return:     Nonzero if lock was successfully acquired, zero if it is\n+ *             currently owned by someone else.\n+ */\n+static inline int homa_rpc_try_lock(struct homa_rpc *rpc)\n+\t__cond_acquires(nonzero, rpc-\u003ebucket-\u003elock)\n+{\n+\tif (!spin_trylock_bh(\u0026rpc-\u003ebucket-\u003elock))\n+\t\treturn 0;\n+\treturn 1;\n+}\n+\n+/**\n+ * homa_rpc_lock_preempt() - Same as homa_rpc_lock, except sets the\n+ * APP_NEEDS_LOCK flags while waiting to encourage the existing lock\n+ * owner to relinquish the lock.\n+ * @rpc:   RPC to lock.\n+ */\n+static inline void homa_rpc_lock_preempt(struct homa_rpc *rpc)\n+\t__acquires(rpc-\u003ebucket-\u003elock)\n+{\n+\tset_bit(APP_NEEDS_LOCK, \u0026rpc-\u003eflags);\n+\thoma_bucket_lock(rpc-\u003ebucket, rpc-\u003eid);\n+\tclear_bit(APP_NEEDS_LOCK, \u0026rpc-\u003eflags);\n+}\n+\n+/**\n+ * homa_rpc_unlock() - Release the lock for an RPC.\n+ * @rpc:   RPC to unlock.\n+ */\n+static inline void homa_rpc_unlock(struct homa_rpc *rpc)\n+\t__releases(rpc-\u003ebucket-\u003elock)\n+{\n+\thoma_bucket_unlock(rpc-\u003ebucket, rpc-\u003eid);\n+}\n+\n+/**\n+ * homa_protect_rpcs() - Ensures that no RPCs will be reaped for a given\n+ * socket until homa_unprotect_rpcs is called. Typically used by functions\n+ * that want to scan the active RPCs for a socket without holding the socket\n+ * lock.  Multiple calls to this function may be in effect at once. See\n+ * \"Homa Locking Strategy\" in homa_impl.h for more info on why this function\n+ * is needed.\n+ * @hsk:    Socket whose RPCs should be protected. Must not be locked\n+ *          by the caller; will be locked here.\n+ *\n+ * Return:  1 for success, 0 if the socket has been shutdown, in which\n+ *          case its RPCs cannot be protected.\n+ */\n+static inline int homa_protect_rpcs(struct homa_sock *hsk)\n+{\n+\tint result;\n+\n+\thoma_sock_lock(hsk);\n+\tresult = !hsk-\u003eshutdown;\n+\tif (result)\n+\t\tatomic_inc(\u0026hsk-\u003eprotect_count);\n+\thoma_sock_unlock(hsk);\n+\treturn result;\n+}\n+\n+/**\n+ * homa_unprotect_rpcs() - Cancel the effect of a previous call to\n+ * homa_protect_rpcs(), so that RPCs can once again be reaped.\n+ * @hsk:    Socket whose RPCs should be unprotected.\n+ */\n+static inline void homa_unprotect_rpcs(struct homa_sock *hsk)\n+{\n+\tatomic_dec(\u0026hsk-\u003eprotect_count);\n+}\n+\n+/**\n+ * homa_rpc_hold() - Increment the reference count on an RPC, which will\n+ * prevent it from being freed until homa_rpc_put() is called. References\n+ * are taken in two situations:\n+ * 1. An RPC is going to be manipulated by a collection of functions. In\n+ *    this case the top-most function that identifies the RPC takes the\n+ *    reference; any function that receives an RPC as an argument can\n+ *    assume that a reference has been taken on the RPC by some higher\n+ *    function on the call stack.\n+ * 2. A pointer to an RPC is stored in an object for use later, such as\n+ *    an interest. A reference must be held as long as the pointer remains\n+ *    accessible in the object.\n+ * @rpc:      RPC on which to take a reference.\n+ */\n+static inline void homa_rpc_hold(struct homa_rpc *rpc)\n+{\n+\trefcount_inc(\u0026rpc-\u003erefs);\n+}\n+\n+/**\n+ * homa_rpc_put() - Release a reference on an RPC (cancels the effect of\n+ * a previous call to homa_rpc_hold).\n+ * @rpc:      RPC to release.\n+ */\n+static inline void homa_rpc_put(struct homa_rpc *rpc)\n+{\n+\trefcount_dec(\u0026rpc-\u003erefs);\n+}\n+\n+/**\n+ * homa_is_client(): returns true if we are the client for a particular RPC,\n+ * false if we are the server.\n+ * @id:  Id of the RPC in question.\n+ * Return: true if we are the client for RPC id, false otherwise\n+ */\n+static inline bool homa_is_client(u64 id)\n+{\n+\treturn (id \u0026 1) == 0;\n+}\n+\n+/**\n+ * homa_rpc_needs_attention() - Returns true if @rpc has failed or if\n+ * its incoming message is ready for attention by an application thread\n+ * (e.g., packets are ready to copy to user space).\n+ * @rpc: RPC to check.\n+ * Return: See above\n+ */\n+static inline bool homa_rpc_needs_attention(struct homa_rpc *rpc)\n+{\n+\treturn (rpc-\u003eerror != 0 || test_bit(RPC_PKTS_READY, \u0026rpc-\u003eflags));\n+}\n+\n+#endif /* _HOMA_RPC_H */\ndiff --git a/net/homa/homa_sock.c b/net/homa/homa_sock.c\nnew file mode 100644\nindex 0000000000000..a5fd321bacf23\n--- /dev/null\n+++ b/net/homa/homa_sock.c\n@@ -0,0 +1,544 @@\n+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+\n+/* This file manages homa_sock and homa_socktab objects. */\n+\n+#include \"homa_impl.h\"\n+#include \"homa_interest.h\"\n+#include \"homa_peer.h\"\n+#include \"homa_pool.h\"\n+\n+/**\n+ * homa_socktab_init() - Constructor for homa_socktabs.\n+ * @socktab:  The object to initialize; previous contents are discarded.\n+ */\n+void homa_socktab_init(struct homa_socktab *socktab)\n+{\n+\tint i;\n+\n+\tspin_lock_init(\u0026socktab-\u003ewrite_lock);\n+\tsocktab-\u003enext_sequence = 1;\n+\tfor (i = 0; i \u003c HOMA_SOCKTAB_BUCKETS; i++)\n+\t\tINIT_HLIST_HEAD(\u0026socktab-\u003ebuckets[i]);\n+}\n+\n+/**\n+ * homa_socktab_destroy() - Destructor for homa_socktabs: deletes all\n+ * existing sockets.\n+ * @socktab:  The object to destroy.\n+ * @hnet:     If non-NULL, only sockets for this namespace are deleted.\n+ */\n+void homa_socktab_destroy(struct homa_socktab *socktab, struct homa_net *hnet)\n+{\n+\tstruct homa_socktab_scan scan;\n+\tstruct homa_sock *hsk;\n+\n+\tfor (hsk = homa_socktab_start_scan(socktab, \u0026scan); hsk;\n+\t\t\thsk = homa_socktab_next(\u0026scan)) {\n+\t\tif (hnet \u0026\u0026 hnet != hsk-\u003ehnet)\n+\t\t\tcontinue;\n+\n+\t\t/* In actual use there should be no sockets left when this\n+\t\t * function is invoked, so the code below will never be\n+\t\t * invoked. However, it is useful during unit tests.\n+\t\t */\n+\t\thoma_sock_shutdown(hsk);\n+\t\thoma_sock_destroy(\u0026hsk-\u003esock);\n+\t}\n+\thoma_socktab_end_scan(\u0026scan);\n+}\n+\n+/**\n+ * homa_socktab_start_scan() - Begin an iteration over all of the sockets\n+ * in a socktab.\n+ * @socktab:   Socktab to scan.\n+ * @scan:      Will hold the current state of the scan; any existing\n+ *             contents are discarded. The caller must eventually pass this\n+ *             to homa_socktab_end_scan.\n+ *\n+ * Return:     The first socket in the table, or NULL if the table is\n+ *             empty. If non-NULL, a reference is held on the socket to\n+ *             prevent its deletion.\n+ *\n+ * Each call to homa_socktab_next will return the next socket in the table.\n+ * All sockets that are present in the table at the time this function is\n+ * invoked will eventually be returned, as long as they are not removed\n+ * from the table. It is safe to remove sockets from the table while the\n+ * scan is in progress. If a socket is removed from the table during the scan,\n+ * it may or may not be returned by homa_socktab_next. New entries added\n+ * during the scan may or may not be returned.\n+ */\n+struct homa_sock *homa_socktab_start_scan(struct homa_socktab *socktab,\n+\t\t\t\t\t  struct homa_socktab_scan *scan)\n+{\n+\tscan-\u003esocktab = socktab;\n+\tscan-\u003ehsk = NULL;\n+\tscan-\u003ecurrent_bucket = 0;\n+\tscan-\u003eavail = 0;\n+\tscan-\u003esequence = U64_MAX;\n+\n+\treturn homa_socktab_next(scan);\n+}\n+\n+/**\n+ * homa_socktab_fill_scan() - Refill the @socks array for a homa_socktab_scan.\n+ * On return, if its @avail member is zero it means all of the sockets in\n+ * the socktab have been scanned.\n+ * @scan:      State of the scan. Normally the @avail member will be zero,\n+ *             but this is not necessary.\n+ */\n+void homa_socktab_fill_scan(struct homa_socktab_scan *scan)\n+{\n+\tstruct homa_sock_link *slink;\n+\tstruct hlist_head *bucket;\n+\tstruct hlist_node *next;\n+\n+\trcu_read_lock();\n+\tbucket = \u0026scan-\u003esocktab-\u003ebuckets[scan-\u003ecurrent_bucket];\n+\tnext = rcu_dereference(hlist_first_rcu(bucket));\n+\twhile (scan-\u003eavail \u003c HOMA_MAX_SCANNED_SOCKS) {\n+\t\tif (!next) {\n+\t\t\tif (scan-\u003ecurrent_bucket \u003e= HOMA_SOCKTAB_BUCKETS - 1)\n+\t\t\t\tbreak;\n+\t\t\tscan-\u003ecurrent_bucket++;\n+\t\t\tscan-\u003esequence = U64_MAX;\n+\t\t\tbucket = \u0026scan-\u003esocktab-\u003ebuckets[scan-\u003ecurrent_bucket];\n+\t\t\tnext = rcu_dereference(hlist_first_rcu(bucket));\n+\t\t\tcontinue;\n+\t\t}\n+\t\tslink = hlist_entry(next, struct homa_sock_link, links);\n+\t\tnext = rcu_dereference(hlist_next_rcu(next));\n+\t\tif (slink-\u003esequence \u003c scan-\u003esequence) {\n+\t\t\tscan-\u003esequence = slink-\u003esequence;\n+\t\t\tscan-\u003esocks[scan-\u003eavail] = slink-\u003ehsk;\n+\t\t\tif (refcount_inc_not_zero(\u0026slink-\u003ehsk-\u003esock.sk_refcnt))\n+\t\t\t\tscan-\u003eavail++;\n+\t\t}\n+\t}\n+\trcu_read_unlock();\n+}\n+\n+/**\n+ * homa_socktab_next() - Return the next socket in an iteration over a socktab.\n+ * @scan:      State of the scan.\n+ *\n+ * Return:     The next socket in the table, or NULL if the iteration has\n+ *             returned all of the sockets in the table.  If non-NULL, a\n+ *             reference is held on the socket to prevent its deletion (this\n+ *             module will release the reference in the next call to\n+ *             homa_socktab_next or homa_socktab_end). Sockets are not returned\n+ *             in any particular order. It's possible that the returned socket\n+ *             has been shutdown.\n+ */\n+struct homa_sock *homa_socktab_next(struct homa_socktab_scan *scan)\n+{\n+\tif (scan-\u003ehsk) {\n+\t\tsock_put(\u0026scan-\u003ehsk-\u003esock);\n+\t\tscan-\u003ehsk = NULL;\n+\t}\n+\n+\tif (scan-\u003eavail == 0) {\n+\t\thoma_socktab_fill_scan(scan);\n+\t\tif (scan-\u003eavail == 0)\n+\t\t\treturn NULL;\n+\t}\n+\n+\tscan-\u003ehsk = scan-\u003esocks[scan-\u003eavail - 1];\n+\tscan-\u003eavail--;\n+\treturn scan-\u003ehsk;\n+}\n+\n+/**\n+ * homa_socktab_end_scan() - Must be invoked on completion of each scan\n+ * to clean up state associated with the scan.\n+ * @scan:      State of the scan.\n+ */\n+void homa_socktab_end_scan(struct homa_socktab_scan *scan)\n+{\n+\tif (scan-\u003ehsk) {\n+\t\tsock_put(\u0026scan-\u003ehsk-\u003esock);\n+\t\tscan-\u003ehsk = NULL;\n+\t}\n+\twhile (scan-\u003eavail \u003e 0) {\n+\t\tsock_put(\u0026scan-\u003esocks[scan-\u003eavail - 1]-\u003esock);\n+\t\tscan-\u003eavail--;\n+\t}\n+}\n+\n+/**\n+ * homa_sock_init() - Constructor for homa_sock objects. This function\n+ * handles Homa-specific initialization.\n+ * @hsk:    Object to initialize. The Homa-specific parts must have been\n+ *          initialized to zeroes by the caller.\n+ *\n+ * Return:  0 for success, otherwise a negative errno.\n+ */\n+int homa_sock_init(struct homa_sock *hsk)\n+{\n+\tstruct homa_pool *buffer_pool;\n+\tstruct homa_socktab *socktab;\n+\tstruct homa_sock *other;\n+\tstruct homa_net *hnet;\n+\tstruct homa *homa;\n+\tint starting_port;\n+\tint result = 0;\n+\tint i;\n+\n+\thnet = (struct homa_net *)net_generic(sock_net(\u0026hsk-\u003esock),\n+\t\t\t\t\t      homa_net_id);\n+\thoma = hnet-\u003ehoma;\n+\tsocktab = homa-\u003esocktab;\n+\n+\t/* Do things requiring memory allocation before locking the socket,\n+\t * so that GFP_ATOMIC is not needed.\n+\t */\n+\tbuffer_pool = homa_pool_alloc(hsk);\n+\tif (IS_ERR(buffer_pool))\n+\t\treturn PTR_ERR(buffer_pool);\n+\n+\t/* Initialize the fields private to Homa. We can initialize\n+\t * everything except the port and hash table links without acquiring\n+\t * the socket table lock.\n+\t */\n+\thsk-\u003ehoma = homa;\n+\thsk-\u003ehnet = hnet;\n+\thsk-\u003ebuffer_pool = buffer_pool;\n+\n+\thsk-\u003eis_server = false;\n+\thsk-\u003eshutdown = false;\n+\thsk-\u003eip_header_length = (hsk-\u003einet.sk.sk_family == AF_INET) ?\n+\t\t\t\tsizeof(struct iphdr) : sizeof(struct ipv6hdr);\n+\thsk-\u003eerror_msg = \"no error\";\n+\tspin_lock_init(\u0026hsk-\u003elock);\n+\tatomic_set(\u0026hsk-\u003eprotect_count, 0);\n+\tINIT_LIST_HEAD(\u0026hsk-\u003eactive_rpcs);\n+\tINIT_LIST_HEAD(\u0026hsk-\u003edead_rpcs);\n+\tINIT_LIST_HEAD(\u0026hsk-\u003ewaiting_for_bufs);\n+\tINIT_LIST_HEAD(\u0026hsk-\u003eready_rpcs);\n+\tINIT_LIST_HEAD(\u0026hsk-\u003einterests);\n+\tfor (i = 0; i \u003c HOMA_CLIENT_RPC_BUCKETS; i++) {\n+\t\tstruct homa_rpc_bucket *bucket = \u0026hsk-\u003eclient_rpc_buckets[i];\n+\n+\t\tspin_lock_init(\u0026bucket-\u003elock);\n+\t\tbucket-\u003eid = i;\n+\t\tINIT_HLIST_HEAD(\u0026bucket-\u003erpcs);\n+\t}\n+\tfor (i = 0; i \u003c HOMA_SERVER_RPC_BUCKETS; i++) {\n+\t\tstruct homa_rpc_bucket *bucket = \u0026hsk-\u003eserver_rpc_buckets[i];\n+\n+\t\tspin_lock_init(\u0026bucket-\u003elock);\n+\t\tbucket-\u003eid = i + 1000000;\n+\t\tINIT_HLIST_HEAD(\u0026bucket-\u003erpcs);\n+\t}\n+\n+\t/* Initialize fields outside the Homa part. */\n+\thsk-\u003esock.sk_sndbuf = homa-\u003ewmem_max;\n+\tsock_set_flag(\u0026hsk-\u003einet.sk, SOCK_RCU_FREE);\n+\n+\t/* This is needed to prevent blocking when allocating memory in\n+\t * functions like ip_route_output_flow, which could be invoked\n+\t * while atomic.\n+\t */\n+\thsk-\u003esock.sk_allocation = GFP_ATOMIC;\n+\n+\t/* Pick a default port. Must keep the socktab locked from now\n+\t * until the new socket is added to the socktab, to ensure that\n+\t * no other socket chooses the same port.\n+\t */\n+\tspin_lock_bh(\u0026socktab-\u003ewrite_lock);\n+\tstarting_port = hnet-\u003eprev_default_port;\n+\twhile (1) {\n+\t\thnet-\u003eprev_default_port++;\n+\t\tif (hnet-\u003eprev_default_port \u003c HOMA_MIN_DEFAULT_PORT)\n+\t\t\thnet-\u003eprev_default_port = HOMA_MIN_DEFAULT_PORT;\n+\t\tother = homa_sock_find(hnet, hnet-\u003eprev_default_port);\n+\t\tif (!other)\n+\t\t\tbreak;\n+\t\tsock_put(\u0026other-\u003esock);\n+\t\tif (hnet-\u003eprev_default_port == starting_port) {\n+\t\t\tspin_unlock_bh(\u0026socktab-\u003ewrite_lock);\n+\t\t\tresult = -EADDRNOTAVAIL;\n+\t\t\tgoto error;\n+\t\t}\n+\t\tspin_unlock_bh(\u0026socktab-\u003ewrite_lock);\n+\t\tcond_resched();\n+\t\tspin_lock_bh(\u0026socktab-\u003ewrite_lock);\n+\t}\n+\tresult = homa_sock_link(hsk, hnet-\u003eprev_default_port);\n+\tspin_unlock_bh(\u0026socktab-\u003ewrite_lock);\n+\tif (result == 0)\n+\t\treturn result;\n+\n+error:\n+\thsk-\u003eshutdown = true;\n+\thsk-\u003ehoma = NULL;\n+\thoma_pool_free(buffer_pool);\n+\treturn result;\n+}\n+\n+/**\n+ * homa_sock_link() - Add a socket to the hash table for its socktab,\n+ * so that it will be discoverable through homa_sock_find. If the socket\n+ * is already linked, the current link will be removed.\n+ * @hsk:    Socket to link in; hsk-\u003eport will be used to determine\n+ *          where the socket is linked in it socktab. Caller must hold\n+ *          the lock for the socket's socktab.\n+ * @port:   Port to use for the socket; if this function succeeds, this\n+ *          number will be stored in hsk.\n+ *\n+ * Return:  0 for success, otherwise a negative errno.\n+ */\n+int homa_sock_link(struct homa_sock *hsk, int port)\n+\t__must_hold(hsk-\u003ehoma-\u003esocktab-\u003ewrite_lock)\n+{\n+\tstruct homa_socktab *socktab = hsk-\u003ehoma-\u003esocktab;\n+\tstruct homa_sock_link *slink;\n+\n+\tslink = kmalloc_obj(*slink, GFP_ATOMIC | __GFP_ACCOUNT);\n+\tif (!slink)\n+\t\treturn -ENOMEM;\n+\thoma_sock_unlink(hsk);\n+\tslink-\u003ehsk = hsk;\n+\tslink-\u003esequence = socktab-\u003enext_sequence;\n+\tsocktab-\u003enext_sequence++;\n+\thlist_add_head_rcu(\u0026slink-\u003elinks,\n+\t\t\t   \u0026socktab-\u003ebuckets[homa_socktab_bucket(hsk-\u003ehnet,\n+\t\t\t\t\t\t\t\t port)]);\n+\thsk-\u003eport = port;\n+\thsk-\u003einet.inet_num = port;\n+\thsk-\u003einet.inet_sport = htons(port);\n+\thsk-\u003eslink = slink;\n+\treturn 0;\n+}\n+\n+/*\n+ * homa_sock_unlink() - Unlinks a socket from its socktab. Once this method\n+ * returns, the socket will not be discoverable through the socktab.\n+ * @hsk:  Socket to unlink. Caller must hold the lock for the socket's\n+ *        socktab.\n+ */\n+void homa_sock_unlink(struct homa_sock *hsk)\n+\t__must_hold(hsk-\u003ehoma-\u003esocktab-\u003ewrite_lock)\n+{\n+\tstruct homa_sock_link *slink;\n+\n+\tslink = hsk-\u003eslink;\n+\tif (!slink)\n+\t\treturn;\n+\thsk-\u003eslink = NULL;\n+\thlist_del_rcu(\u0026slink-\u003elinks);\n+\tkfree_rcu(slink, rcu_head);\n+}\n+\n+/**\n+ * homa_sock_shutdown() - Disable a socket so that it can no longer\n+ * be used for either sending or receiving messages. Any system calls\n+ * currently waiting to send or receive messages will be aborted. This\n+ * function will terminate any existing use of the socket, but it does\n+ * not free up socket resources: that happens in homa_sock_destroy.\n+ * @hsk:       Socket to shut down.\n+ */\n+void homa_sock_shutdown(struct homa_sock *hsk)\n+{\n+\tstruct homa_socktab *socktab;\n+\tstruct homa_rpc *rpc;\n+\n+\thoma_sock_lock(hsk);\n+\tif (hsk-\u003eshutdown || !hsk-\u003ehoma) {\n+\t\thoma_sock_unlock(hsk);\n+\t\treturn;\n+\t}\n+\n+\t/* The order of cleanup is very important, because there could be\n+\t * active operations that hold RPC locks but not the socket lock.\n+\t * 1. Set @shutdown; this ensures that no new RPCs will be created for\n+\t *    this socket (though some creations might already be in progress)\n+\t *    and incoming packets will be dropped.\n+\t * 2. Remove the socket from its socktab, so no-one will ever find\n+\t *    it again.\n+\t * 3. Go through all of the RPCs and delete them; this will\n+\t *    synchronize with any operations in progress.\n+\t * 4. Perform other socket cleanup: at this point we know that\n+\t *    there will be no concurrent activities on individual RPCs.\n+\t * 5. Don't delete the buffer pool until after all of the RPCs\n+\t *    have been reaped.\n+\t * See \"Homa Locking Strategy\" in homa_impl.h for additional information\n+\t * about locking.\n+\t */\n+\thsk-\u003eshutdown = true;\n+\n+\t/* This protects against RPC deletions during the RCU scan of\n+\t * active_rpcs below.\n+\t */\n+\tatomic_inc(\u0026hsk-\u003eprotect_count);\n+\thoma_sock_unlock(hsk);\n+\n+\tsocktab = hsk-\u003ehoma-\u003esocktab;\n+\tspin_lock_bh(\u0026socktab-\u003ewrite_lock);\n+\thoma_sock_unlink(hsk);\n+\tspin_unlock_bh(\u0026socktab-\u003ewrite_lock);\n+\n+\trcu_read_lock();\n+\tlist_for_each_entry_rcu(rpc, \u0026hsk-\u003eactive_rpcs, active_links) {\n+\t\thoma_rpc_lock(rpc);\n+\t\thoma_rpc_end(rpc);\n+\t\thoma_rpc_unlock(rpc);\n+\t}\n+\twake_up_interruptible_poll(sk_sleep(\u0026hsk-\u003esock), EPOLLOUT);\n+\trcu_read_unlock();\n+\thoma_unprotect_rpcs(hsk);\n+\n+\thoma_sock_lock(hsk);\n+\twhile (!list_empty(\u0026hsk-\u003einterests))\n+\t\thoma_interest_notify_shared(hsk, NULL);\n+\thoma_sock_unlock(hsk);\n+}\n+\n+/**\n+ * homa_sock_destroy() - Release all of the internal resources associated\n+ * with a socket; is invoked at time when that is safe (i.e., all references\n+ * on the socket have been dropped).\n+ * @sk:       Socket to destroy.\n+ */\n+void homa_sock_destroy(struct sock *sk)\n+{\n+\tstruct homa_sock *hsk = homa_sk(sk);\n+\n+\tif (!hsk-\u003ehoma)\n+\t\treturn;\n+\n+\twhile (!list_empty(\u0026hsk-\u003edead_rpcs))\n+\t\thoma_rpc_reap(hsk);\n+\n+\tWARN_ON_ONCE(refcount_read(\u0026hsk-\u003esock.sk_wmem_alloc) != 1);\n+\n+\tif (hsk-\u003ebuffer_pool) {\n+\t\thoma_pool_free(hsk-\u003ebuffer_pool);\n+\t\thsk-\u003ebuffer_pool = NULL;\n+\t}\n+}\n+\n+/**\n+ * homa_sock_bind() - Associates a server port with a socket; if there\n+ * was a previous server port assignment for @hsk, it is abandoned.\n+ * @hnet:      Network namespace with which port is associated.\n+ * @hsk:       Homa socket.\n+ * @port:      Desired server port for @hsk. If 0, then this call\n+ *             becomes a no-op: the socket will continue to use\n+ *             its randomly assigned client port.\n+ *\n+ * Return:  0 for success, otherwise a negative errno. If an error is\n+ *          returned, hsk-\u003eerror_msg is set.\n+ */\n+int homa_sock_bind(struct homa_net *hnet, struct homa_sock *hsk,\n+\t\t   u16 port)\n+{\n+\tstruct homa_socktab *socktab = hnet-\u003ehoma-\u003esocktab;\n+\tstruct homa_sock *owner;\n+\tint result = 0;\n+\n+\tif (port == 0)\n+\t\treturn result;\n+\tif (port \u003e= HOMA_MIN_DEFAULT_PORT) {\n+\t\thsk-\u003eerror_msg = \"port number invalid: in the automatically assigned range\";\n+\t\treturn -EINVAL;\n+\t}\n+\thoma_sock_lock(hsk);\n+\tspin_lock_bh(\u0026socktab-\u003ewrite_lock);\n+\tif (hsk-\u003eshutdown) {\n+\t\thsk-\u003eerror_msg = \"socket has been shut down\";\n+\t\tresult = -ESHUTDOWN;\n+\t\tgoto done;\n+\t}\n+\n+\towner = homa_sock_find(hnet, port);\n+\tif (owner) {\n+\t\tsock_put(\u0026owner-\u003esock);\n+\t\tif (owner != hsk) {\n+\t\t\thsk-\u003eerror_msg = \"requested port number is already in use\";\n+\t\t\tresult = -EADDRINUSE;\n+\t\t}\n+\t\tgoto done;\n+\t}\n+\tresult = homa_sock_link(hsk, port);\n+\tif (result == 0)\n+\t\thsk-\u003eis_server = true;\n+done:\n+\tspin_unlock_bh(\u0026socktab-\u003ewrite_lock);\n+\thoma_sock_unlock(hsk);\n+\treturn result;\n+}\n+\n+/**\n+ * homa_sock_find() - Returns the socket associated with a given port.\n+ * @hnet:       Network namespace where the socket will be used.\n+ * @port:       The port of interest.\n+ * Return:      The socket that owns @port, or NULL if none. If non-NULL\n+ *              then this method has taken a reference on the socket and\n+ *              the caller must call sock_put to release it.\n+ */\n+struct homa_sock *homa_sock_find(struct homa_net *hnet, u16 port)\n+{\n+\tint bucket = homa_socktab_bucket(hnet, port);\n+\tstruct homa_sock *result = NULL;\n+\tstruct homa_sock_link *slink;\n+\tstruct homa_sock *hsk;\n+\n+\trcu_read_lock();\n+\thlist_for_each_entry_rcu(slink, \u0026hnet-\u003ehoma-\u003esocktab-\u003ebuckets[bucket],\n+\t\t\t\t links) {\n+\t\thsk = slink-\u003ehsk;\n+\t\tif (hsk \u0026\u0026 hsk-\u003eport == port \u0026\u0026 hsk-\u003ehnet == hnet \u0026\u0026\n+\t\t    !hsk-\u003eshutdown \u0026\u0026\n+\t\t    refcount_inc_not_zero(\u0026hsk-\u003esock.sk_refcnt)) {\n+\t\t\tresult = hsk;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\trcu_read_unlock();\n+\treturn result;\n+}\n+\n+/**\n+ * homa_sock_wait_wmem() - Block the thread until @hsk's usage of tx\n+ * packet memory drops below the socket's limit.\n+ * @hsk:          Socket of interest.\n+ * @nonblocking:  If there's not enough memory, return -EWOLDBLOCK instead\n+ *                of blocking.\n+ * Return: 0 for success, otherwise a negative errno.\n+ */\n+int homa_sock_wait_wmem(struct homa_sock *hsk, int nonblocking)\n+{\n+\tlong timeo = hsk-\u003esock.sk_sndtimeo;\n+\tint result;\n+\n+\t/* Note: we can't use sock_wait_for_wmem because that function\n+\t * is not available to modules (as of August 2025 it's static).\n+\t */\n+\tif (nonblocking)\n+\t\ttimeo = 0;\n+\tset_bit(HOMA_SOCK_NOSPACE, \u0026hsk-\u003eflags);\n+\n+\t/* Must wakeup if either memory becomes available or HOMA_SOCK_NOSPACE\n+\t * gets cleared. The wmem_avl check is needed to handle a race where\n+\t * memory gets freed just before HOMA_SOCK_NOSPACE is set above. The\n+\t * HOMA_SOCK_NOSPACE check is needed to handle a race where multiple\n+\t * threads wakeup and one thread consumes enough memory that the\n+\t * wmem_avl check fails for the other. This approach means that we may\n+\t * exceed the memory limit if multiple threads wake up at once, but\n+\t * it prevents thread starvation that could occur if the second\n+\t * thread were to go back to sleep.\n+\t */\n+\tresult = wait_event_interruptible_timeout(*sk_sleep(\u0026hsk-\u003esock),\n+\t\t\t\t\t\t  homa_sock_wmem_avl(hsk) ||\n+\t\t\t\t\t\t  hsk-\u003eshutdown ||\n+\t\t\t\t\t\t  !test_bit(HOMA_SOCK_NOSPACE,\n+\t\t\t\t\t\t\t    \u0026hsk-\u003eflags),\n+\t\t\t\t\t\t  timeo);\n+\tif (hsk-\u003eshutdown)\n+\t\treturn -ESHUTDOWN;\n+\tif (signal_pending(current))\n+\t\treturn -EINTR;\n+\tif (result == 0)\n+\t\treturn -EWOULDBLOCK;\n+\treturn 0;\n+}\ndiff --git a/net/homa/homa_sock.h b/net/homa/homa_sock.h\nnew file mode 100644\nindex 0000000000000..21a7802a999c0\n--- /dev/null\n+++ b/net/homa/homa_sock.h\n@@ -0,0 +1,513 @@\n+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */\n+\n+/* This file defines structs and other things related to Homa sockets.  */\n+\n+#ifndef _HOMA_SOCK_H\n+#define _HOMA_SOCK_H\n+\n+/* Forward declarations. */\n+struct homa;\n+struct homa_pool;\n+struct homa_sock;\n+\n+/* Number of hash buckets in a homa_socktab. Must be a power of 2. */\n+#define HOMA_SOCKTAB_BUCKET_BITS 10\n+#define HOMA_SOCKTAB_BUCKETS BIT(HOMA_SOCKTAB_BUCKET_BITS)\n+\n+/**\n+ * struct homa_socktab - A hash table that maps from port numbers (either\n+ * client or server) to homa_sock objects.\n+ *\n+ * This table is managed exclusively by homa_socktab.c, using RCU to\n+ * minimize synchronization during lookups.\n+ */\n+struct homa_socktab {\n+\t/**\n+\t * @write_lock: Controls all modifications to this object; not needed\n+\t * for socket lookups (RCU is used instead). Also used to\n+\t * synchronize port allocation.\n+\t */\n+\tspinlock_t write_lock;\n+\n+\t/**\n+\t * @next_sequence: Next sequence number to assign for a\n+\t * homa_sock_link.\n+\t */\n+\tu64 next_sequence;\n+\n+\t/**\n+\t * @buckets: Heads of chains for hash table buckets. Chains\n+\t * consist of homa_sock_link objects, in decreasing order of\n+\t * sequence number.\n+\t */\n+\tstruct hlist_head buckets[HOMA_SOCKTAB_BUCKETS];\n+};\n+\n+/**\n+ * struct homa_sock_link - Used to link a socket into a list associated\n+ * with a bucket in a homa_socktab. This is a separate dynamically\n+ * allocated object because a socket may need to change its position in\n+ * the homa_socktab (because its port number changes); during the\n+ * transition, multiple of these objects may exist for a socket so that\n+ * socktab scans are not disrupted by the change in position. The lifetime\n+ * of these objects is managed with RCU.\n+ */\n+struct homa_sock_link {\n+\t/** @hsk: The socket associated with this link. */\n+\tstruct homa_sock *hsk;\n+\n+\t/**\n+\t * @sequence: Unique sequence number for this struct among all structs\n+\t * in a socktab (smaller means older).\n+\t */\n+\tu64 sequence;\n+\n+\t/**\n+\t * @links: Links this object into the chain for a bucket in a\n+\t * homa_socktab.\n+\t */\n+\tstruct hlist_node links;\n+\n+\t/** @rcu_head: Used for RCU-based freeing of this object. */\n+\tstruct rcu_head rcu_head;\n+};\n+\n+/**\n+ * struct homa_socktab_scan - Records the state of an iteration over all\n+ * the entries in a homa_socktab, in a way that is safe against concurrent\n+ * reclamation of sockets.\n+ */\n+struct homa_socktab_scan {\n+\t/** @socktab: The table that is being scanned. */\n+\tstruct homa_socktab *socktab;\n+\n+\t/**\n+\t * @hsk: Points to the current socket in the iteration, or NULL if\n+\t * we're at the beginning of the iteration or have reached the end of\n+\t * the current bucket. If non-NULL then we are holding a reference\n+\t * to this socket.\n+\t */\n+\tstruct homa_sock *hsk;\n+\n+\t/**\n+\t * @current_bucket: The index of the bucket in socktab-\u003ebuckets\n+\t * currently being scanned.\n+\t */\n+\tint current_bucket;\n+\n+\t/**\n+\t * @avail: The first @avail entries in @links are valid and\n+\t * available for homa_sock_next to return.\n+\t */\n+\tint avail;\n+\n+\t/**\n+\t * @socks: Used to collect a bunch of sockets by scanning hash table\n+\t * bucket chains. Sockets are then returned from here by\n+\t * homa_socktab_next. We own a reference for each of these sockets.\n+\t */\n+#define HOMA_MAX_SCANNED_SOCKS 5\n+\tstruct homa_sock *socks[HOMA_MAX_SCANNED_SOCKS];\n+\n+\t/**\n+\t * @sequence: All homa_sock_links with @sequence numbers \u003e= this\n+\t * have already been scanned from @current_bucket.\n+\t */\n+\tu64 sequence;\n+};\n+\n+/**\n+ * struct homa_rpc_bucket - One bucket in a hash table of RPCs.\n+ */\n+\n+struct homa_rpc_bucket {\n+\t/**\n+\t * @lock: serves as a lock both for this bucket (e.g., when\n+\t * adding and removing RPCs) and also for all of the RPCs in\n+\t * the bucket. Must be held whenever looking up an RPC in\n+\t * this bucket or manipulating an RPC in the bucket. This approach\n+\t * has the following properties:\n+\t * 1. An RPC can be looked up and locked (a common operation) with\n+\t *    a single lock acquisition.\n+\t * 2. Looking up and locking are atomic: there is no window of\n+\t *    vulnerability where someone else could delete an RPC after\n+\t *    it has been looked up and before it has been locked.\n+\t * 3. The lookup mechanism does not use RCU.  This is important because\n+\t *    RPCs are created rapidly and typically live only a few tens of\n+\t *    microseconds.  As of May 2025 RCU introduces a lag of about\n+\t *    25 ms before objects can be deleted; for RPCs this would result\n+\t *    in hundreds or thousands of RPCs accumulating before RCU allows\n+\t *    them to be deleted.\n+\t * This approach has the disadvantage that RPCs within a bucket share\n+\t * locks and thus may not be able to work concurrently, but there are\n+\t * enough buckets in the table to make such colllisions rare.\n+\t *\n+\t * See \"Homa Locking Strategy\" in homa_impl.h for more info about\n+\t * locking.\n+\t */\n+\tspinlock_t lock;\n+\n+\t/**\n+\t * @id: identifier for this bucket, used in error messages etc.\n+\t * It's the index of the bucket within its hash table bucket\n+\t * array, with an additional offset to separate server and\n+\t * client RPCs.\n+\t */\n+\tint id;\n+\n+\t/** @rpcs: list of RPCs that hash to this bucket. */\n+\tstruct hlist_head rpcs;\n+};\n+\n+/**\n+ * define HOMA_CLIENT_RPC_BUCKETS - Number of buckets in hash tables for\n+ * client RPCs. Must be a power of 2.\n+ */\n+#define HOMA_CLIENT_RPC_BUCKETS 1024\n+\n+/**\n+ * define HOMA_SERVER_RPC_BUCKETS - Number of buckets in hash tables for\n+ * server RPCs. Must be a power of 2.\n+ */\n+#define HOMA_SERVER_RPC_BUCKETS 1024\n+\n+/**\n+ * struct homa_sock - Information about an open socket.\n+ */\n+struct homa_sock {\n+\t/* Info for other network layers. Note: IPv6 info (struct ipv6_pinfo\n+\t * comes at the very end of the struct, *after* Homa's data, if this\n+\t * socket uses IPv6).\n+\t */\n+\tunion {\n+\t\t/** @sock: generic socket data; must be the first field. */\n+\t\tstruct sock sock;\n+\n+\t\t/**\n+\t\t * @inet: generic Internet socket data; must also be the\n+\t\t first field (contains sock as its first member).\n+\t\t */\n+\t\tstruct inet_sock inet;\n+\t};\n+\n+\t/**\n+\t * @homa: Overall state about the Homa implementation. NULL\n+\t * means this socket was never initialized or has been deleted.\n+\t */\n+\tstruct homa *homa;\n+\n+\t/**\n+\t * @hnet: Overall state specific to the network namespace for\n+\t * this socket.\n+\t */\n+\tstruct homa_net *hnet;\n+\n+\t/**\n+\t * @buffer_pool: used to allocate buffer space for incoming messages.\n+\t * Storage is dynamically allocated.\n+\t */\n+\tstruct homa_pool *buffer_pool;\n+\n+\t/**\n+\t * @port: Port number: identifies this socket uniquely among all\n+\t * those on this node.\n+\t */\n+\tu16 port;\n+\n+\t/**\n+\t * @is_server: True means that this socket can act as both client\n+\t * and server; false means the socket is client-only.\n+\t */\n+\tbool is_server;\n+\n+\t/**\n+\t * @shutdown: True means the socket is no longer usable (either\n+\t * shutdown has already been invoked, or the socket was never\n+\t * properly initialized). Note: can't use the SOCK_DEAD flag for\n+\t * this because that flag doesn't get set until much later in the\n+\t * process of closing a socket.\n+\t */\n+\tbool shutdown;\n+\n+\t/**\n+\t * @ip_header_length: Length of IP headers for this socket (depends\n+\t * on IPv4 vs. IPv6).\n+\t */\n+\tint ip_header_length;\n+\n+\t/** @slink: Links this socket into a homa_socktab bucket. */\n+\tstruct homa_sock_link *slink;\n+\n+\t/**\n+\t * @error_msg: Static string giving human-readable information about\n+\t * the reason for the last error returned by a Homa kernel call.\n+\t * Applications can fetch this with the HOMAIOCINFO ioctl to figure\n+\t * out why a call failed.\n+\t */\n+\tchar *error_msg;\n+\n+\t/* Information above is (almost) never modified; start a new\n+\t * cache line below for info that is modified frequently.\n+\t */\n+\n+\t/**\n+\t * @lock: Must be held when modifying fields such as interests\n+\t * and lists of RPCs. This lock is used in place of sk-\u003esk_lock\n+\t * because it's used differently (it's always used as a simple\n+\t * spin lock).  See \"Homa Locking Strategy\" in homa_impl.h\n+\t * for more on Homa's synchronization strategy.\n+\t */\n+\tspinlock_t lock ____cacheline_aligned_in_smp;\n+\n+\t/**\n+\t * @protect_count: counts the number of calls to homa_protect_rpcs\n+\t * for which there have not yet been calls to homa_unprotect_rpcs.\n+\t */\n+\tatomic_t protect_count;\n+\n+\t/**\n+\t * @flags: Additional state information: an OR'ed combination of\n+\t * various single-bit flags. See below for definitions. Must be\n+\t * manipulated with test_bit etc. because some of the manipulations\n+\t * occur without holding @lock.\n+\t */\n+\tunsigned long flags;\n+\n+\t/* Valid bit numbers for @flags:\n+\t * HOMA_SOCK_NOSPACE -     Nonzero means that the socket has hit its\n+\t *                         limit on tx buffer space and threads are\n+\t *                         blocked waiting for skbs to be released. Used\n+\t *                         instead of the SOCK_NOSPACE flag in\n+\t *                         @sock.sk_socket-\u003eflags. This is because\n+\t *                         @sock.sk_socket can become NULL unexpectedly\n+\t *                         (especially since Homa never acquires the\n+\t *                         Linux socket lock). Thus code using sk_socket\n+\t *                         requires tricky synchronization and is\n+\t *                         error-prone.\n+\t */\n+#define HOMA_SOCK_NOSPACE        0\n+\n+\t/**\n+\t * @active_rpcs: List of all existing RPCs related to this socket,\n+\t * including both client and server RPCs. This list isn't strictly\n+\t * needed, since RPCs are already in one of the hash tables below,\n+\t * but it's more efficient for homa_timer to have this list\n+\t * (so it doesn't have to scan large numbers of hash buckets).\n+\t * The list is sorted, with the oldest RPC first. Manipulate with\n+\t * RCU so timer can access without locking.\n+\t */\n+\tstruct list_head active_rpcs;\n+\n+\t/**\n+\t * @dead_rpcs: Contains RPCs for which homa_rpc_end has been\n+\t * called, but which have not yet been reaped by homa_rpc_reap.\n+\t */\n+\tstruct list_head dead_rpcs;\n+\n+\t/**\n+\t * @dead_frags: An estimate of the amount of memory tied up in\n+\t * RPCs that are dead but have not yet been reaped. The sum of\n+\t * rpc-\u003emsgout.num_frags + 1 for all of the dead RPCs (the 1 accounts\n+\t * for the RPC itself). Used to detect when the reaper is lagging\n+\t * behind. See \"RPC Reaping Strategy\" in homa_rpc_reap code for\n+\t * deetails.\n+\t */\n+\tu64 dead_frags;\n+\n+\t/**\n+\t * @waiting_for_bufs: Contains RPCs that are blocked because there\n+\t * wasn't enough space in the buffer pool region for their incoming\n+\t * messages. Sorted in increasing order of message length.\n+\t */\n+\tstruct list_head waiting_for_bufs;\n+\n+\t/**\n+\t * @ready_rpcs: List of all RPCs that are ready for attention from\n+\t * an application thread.\n+\t */\n+\tstruct list_head ready_rpcs;\n+\n+\t/**\n+\t * @interests: List of threads that are currently waiting for\n+\t * incoming messages via homa_wait_shared.\n+\t */\n+\tstruct list_head interests;\n+\n+\t/**\n+\t * @client_rpc_buckets: Hash table for fast lookup of client RPCs.\n+\t * Modifications are synchronized with bucket locks, not\n+\t * the socket lock.\n+\t */\n+\tstruct homa_rpc_bucket client_rpc_buckets[HOMA_CLIENT_RPC_BUCKETS];\n+\n+\t/**\n+\t * @server_rpc_buckets: Hash table for fast lookup of server RPCs.\n+\t * Modifications are synchronized with bucket locks, not\n+\t * the socket lock.\n+\t */\n+\tstruct homa_rpc_bucket server_rpc_buckets[HOMA_SERVER_RPC_BUCKETS];\n+};\n+\n+/**\n+ * struct homa_v6_sock - For IPv6, additional IPv6-specific information\n+ * is present in the socket struct after Homa-specific information.\n+ */\n+struct homa_v6_sock {\n+\t/** @homa: All socket info except for IPv6-specific stuff. */\n+\tstruct homa_sock homa;\n+\n+\t/** @inet6: Socket info specific to IPv6. */\n+\tstruct ipv6_pinfo inet6;\n+};\n+\n+int                homa_sock_bind(struct homa_net *hnet, struct homa_sock *hsk,\n+\t\t\t\t  u16 port);\n+void               homa_sock_destroy(struct sock *sk);\n+void               homa_socktab_fill_scan(struct homa_socktab_scan *scan);\n+struct homa_sock  *homa_sock_find(struct homa_net *hnet, u16 port);\n+int                homa_sock_init(struct homa_sock *hsk);\n+int                homa_sock_link(struct homa_sock *hsk, int port);\n+void               homa_sock_shutdown(struct homa_sock *hsk);\n+void               homa_sock_unlink(struct homa_sock *hsk);\n+int                homa_sock_wait_wmem(struct homa_sock *hsk, int nonblocking);\n+void               homa_socktab_destroy(struct homa_socktab *socktab,\n+\t\t\t\t\tstruct homa_net *hnet);\n+void               homa_socktab_end_scan(struct homa_socktab_scan *scan);\n+void               homa_socktab_init(struct homa_socktab *socktab);\n+struct homa_sock  *homa_socktab_next(struct homa_socktab_scan *scan);\n+struct homa_sock  *homa_socktab_start_scan(struct homa_socktab *socktab,\n+\t\t\t\t\t   struct homa_socktab_scan *scan);\n+\n+/**\n+ * homa_sock_lock() - Acquire the lock for a socket.\n+ * @hsk:     Socket to lock.\n+ */\n+static inline void homa_sock_lock(struct homa_sock *hsk)\n+\t__acquires(hsk-\u003elock)\n+{\n+\tspin_lock_bh(\u0026hsk-\u003elock);\n+}\n+\n+/**\n+ * homa_sock_unlock() - Release the lock for a socket.\n+ * @hsk:   Socket to lock.\n+ */\n+static inline void homa_sock_unlock(struct homa_sock *hsk)\n+\t__releases(hsk-\u003elock)\n+{\n+\tspin_unlock_bh(\u0026hsk-\u003elock);\n+}\n+\n+/**\n+ * homa_socktab_bucket() - Compute the bucket number in a homa_socktab\n+ * that will contain a particular socket.\n+ * @hnet:   Network namespace of the desired socket.\n+ * @port:   Port number of the socket.\n+ *\n+ * Return:  The index of the bucket in which a socket matching @hnet and\n+ *          @port will be found (if it exists).\n+ */\n+static inline int homa_socktab_bucket(struct homa_net *hnet, u16 port)\n+{\n+\treturn hash_32((uintptr_t)hnet ^ port, HOMA_SOCKTAB_BUCKET_BITS);\n+}\n+\n+/**\n+ * homa_client_rpc_bucket() - Find the bucket containing a given\n+ * client RPC.\n+ * @hsk:      Socket associated with the RPC.\n+ * @id:       Id of the desired RPC.\n+ *\n+ * Return:    The bucket in which this RPC will appear, if the RPC exists.\n+ */\n+static inline struct homa_rpc_bucket\n+\t\t*homa_client_rpc_bucket(struct homa_sock *hsk, u64 id)\n+{\n+\t/* We can use a really simple hash function here because RPC ids\n+\t * are allocated sequentially.\n+\t */\n+\treturn \u0026hsk-\u003eclient_rpc_buckets[(id \u003e\u003e 1) \u0026\n+\t       (HOMA_CLIENT_RPC_BUCKETS - 1)];\n+}\n+\n+/**\n+ * homa_server_rpc_bucket() - Find the bucket containing a given\n+ * server RPC.\n+ * @hsk:         Socket associated with the RPC.\n+ * @id:          Id of the desired RPC.\n+ *\n+ * Return:    The bucket in which this RPC will appear, if the RPC exists.\n+ */\n+static inline struct homa_rpc_bucket\n+\t\t*homa_server_rpc_bucket(struct homa_sock *hsk, u64 id)\n+{\n+\t/* Each client allocates RPC ids sequentially, so they will\n+\t * naturally distribute themselves across the hash space.\n+\t * Thus we can use the id directly as hash.\n+\t */\n+\treturn \u0026hsk-\u003eserver_rpc_buckets[(id \u003e\u003e 1)\n+\t\t\t\u0026 (HOMA_SERVER_RPC_BUCKETS - 1)];\n+}\n+\n+/**\n+ * homa_bucket_lock() - Acquire the lock for an RPC hash table bucket.\n+ * @bucket:    Bucket to lock.\n+ * @id:        Id of the RPC on whose behalf the bucket is being locked.\n+ *             Used only for metrics.\n+ */\n+static inline void homa_bucket_lock(struct homa_rpc_bucket *bucket, u64 id)\n+\t__acquires(bucket-\u003elock)\n+{\n+\tspin_lock_bh(\u0026bucket-\u003elock);\n+}\n+\n+/**\n+ * homa_bucket_unlock() - Release the lock for an RPC hash table bucket.\n+ * @bucket:   Bucket to unlock.\n+ * @id:       ID of the RPC that was using the lock.\n+ */\n+static inline void homa_bucket_unlock(struct homa_rpc_bucket *bucket, u64 id)\n+\t__releases(bucket-\u003elock)\n+{\n+\tspin_unlock_bh(\u0026bucket-\u003elock);\n+}\n+\n+static inline struct homa_sock *homa_sk(const struct sock *sk)\n+{\n+\treturn (struct homa_sock *)sk;\n+}\n+\n+/**\n+ * homa_sock_wmem_avl() - Returns true if the socket is within its limit\n+ * for output memory usage. False means that no new messages should be sent\n+ * until memory is freed.\n+ * @hsk:   Socket of interest.\n+ * Return: See above.\n+ */\n+static inline bool homa_sock_wmem_avl(struct homa_sock *hsk)\n+{\n+\treturn refcount_read(\u0026hsk-\u003esock.sk_wmem_alloc) \u003c hsk-\u003esock.sk_sndbuf;\n+}\n+\n+/**\n+ * homa_sock_wakeup_wmem() - Invoked when tx packet memory has been freed;\n+ * if memory usage is below the limit and there are tasks waiting for memory,\n+ * wake them up.\n+ * @hsk:   Socket of interest.\n+ */\n+static inline void homa_sock_wakeup_wmem(struct homa_sock *hsk)\n+{\n+\t/* Note: can't use sk_stream_write_space for this functionality\n+\t * because it uses a different test to determine whether enough\n+\t * memory is available.\n+\t */\n+\tif (test_bit(HOMA_SOCK_NOSPACE, \u0026hsk-\u003eflags) \u0026\u0026\n+\t    homa_sock_wmem_avl(hsk)) {\n+\t\tclear_bit(HOMA_SOCK_NOSPACE, \u0026hsk-\u003eflags);\n+\t\trcu_read_lock();\n+\t\twake_up_interruptible_poll(sk_sleep(\u0026hsk-\u003esock), EPOLLOUT);\n+\t\trcu_read_unlock();\n+\t}\n+}\n+\n+#endif /* _HOMA_SOCK_H */\ndiff --git a/net/homa/homa_timer.c b/net/homa/homa_timer.c\nnew file mode 100644\nindex 0000000000000..2fa86f523088d\n--- /dev/null\n+++ b/net/homa/homa_timer.c\n@@ -0,0 +1,136 @@\n+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+\n+/* This file handles timing-related functions for Homa, such as retries\n+ * and timeouts.\n+ */\n+\n+#include \"homa_impl.h\"\n+#include \"homa_peer.h\"\n+#include \"homa_rpc.h\"\n+#include \"homa_tx_pool.h\"\n+\n+/**\n+ * homa_timer_check_rpc() -  Invoked for each RPC during each timer pass; does\n+ * most of the work of checking for time-related actions such as sending\n+ * resends, aborting RPCs for which there is no response, and sending\n+ * requests for acks. It is separate from homa_timer because homa_timer\n+ * got too long and deeply indented.\n+ * @rpc:     RPC to check; must be locked by the caller.\n+ */\n+void homa_timer_check_rpc(struct homa_rpc *rpc)\n+\t__must_hold(rpc-\u003ebucket-\u003elock)\n+{\n+\tstruct homa *homa = rpc-\u003ehsk-\u003ehoma;\n+\tint tx_end = homa_rpc_tx_end(rpc);\n+\n+\t/* See if we need to request an ack for this RPC. */\n+\tif (!homa_is_client(rpc-\u003eid) \u0026\u0026 rpc-\u003estate == RPC_OUTGOING \u0026\u0026\n+\t    tx_end == rpc-\u003emsgout.length) {\n+\t\tif (rpc-\u003edone_timer_ticks == 0) {\n+\t\t\trpc-\u003edone_timer_ticks = homa-\u003etimer_ticks;\n+\t\t} else {\n+\t\t\t/* \u003e= comparison that handles tick wrap-around. */\n+\t\t\tif ((rpc-\u003edone_timer_ticks + homa-\u003erequest_ack_ticks\n+\t\t\t\t\t- 1 - homa-\u003etimer_ticks) \u0026 1 \u003c\u003c 31) {\n+\t\t\t\tstruct homa_need_ack_hdr h;\n+\n+\t\t\t\thoma_xmit_control(NEED_ACK, \u0026h, sizeof(h), rpc);\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\tif (rpc-\u003estate == RPC_INCOMING) {\n+\t\tif (rpc-\u003emsgin.num_bpages == 0) {\n+\t\t\t/* Waiting for buffer space, so no problem. */\n+\t\t\trpc-\u003esilent_ticks = 0;\n+\t\t\treturn;\n+\t\t}\n+\t} else if (!homa_is_client(rpc-\u003eid)) {\n+\t\t/* We're the server and we've received the input message;\n+\t\t * no need to worry about retries.\n+\t\t */\n+\t\trpc-\u003esilent_ticks = 0;\n+\t\treturn;\n+\t}\n+\n+\tif (rpc-\u003estate == RPC_OUTGOING) {\n+\t\tif (tx_end \u003c rpc-\u003emsgout.length) {\n+\t\t\t/* There are granted bytes that we haven't transmitted,\n+\t\t\t * so no need to be concerned; the ball is in our court.\n+\t\t\t */\n+\t\t\trpc-\u003esilent_ticks = 0;\n+\t\t\treturn;\n+\t\t}\n+\t}\n+\n+\tif (rpc-\u003esilent_ticks \u003c homa-\u003eresend_ticks)\n+\t\treturn;\n+\tif (rpc-\u003esilent_ticks \u003e= homa-\u003etimeout_ticks) {\n+\t\thoma_rpc_abort(rpc, -ETIMEDOUT);\n+\t\treturn;\n+\t}\n+\tif (((rpc-\u003esilent_ticks - homa-\u003eresend_ticks) % homa-\u003eresend_interval)\n+\t\t\t== 0)\n+\t\thoma_request_retrans(rpc);\n+}\n+\n+/**\n+ * homa_timer() - This function is invoked at regular intervals (\"ticks\")\n+ * to implement retries and aborts for Homa.\n+ * @homa:    Overall data about the Homa protocol implementation.\n+ */\n+void homa_timer(struct homa *homa)\n+{\n+\tstruct homa_socktab_scan scan;\n+\tstruct homa_sock *hsk;\n+\tstruct homa_rpc *rpc;\n+\tint rpc_count = 0;\n+\n+\thoma-\u003etimer_ticks++;\n+\n+\t/* Scan all existing RPCs in all sockets. */\n+\tfor (hsk = homa_socktab_start_scan(homa-\u003esocktab, \u0026scan);\n+\t\t\thsk; hsk = homa_socktab_next(\u0026scan)) {\n+\t\twhile (hsk-\u003edead_frags \u003e homa-\u003edead_frags_limit)\n+\t\t\t/* If we get here, it means that Homa isn't keeping\n+\t\t\t * up with RPC reaping, so we'll help out.  See\n+\t\t\t * \"RPC Reaping Strategy\" in homa_rpc_reap code for\n+\t\t\t * details.\n+\t\t\t */\n+\t\t\tif (homa_rpc_reap(hsk) == 0)\n+\t\t\t\tbreak;\n+\n+\t\tif (list_empty(\u0026hsk-\u003eactive_rpcs) || hsk-\u003eshutdown)\n+\t\t\tcontinue;\n+\n+\t\tif (!homa_protect_rpcs(hsk))\n+\t\t\tcontinue;\n+\t\trcu_read_lock();\n+\t\tlist_for_each_entry_rcu(rpc, \u0026hsk-\u003eactive_rpcs, active_links) {\n+\t\t\thoma_rpc_lock(rpc);\n+\t\t\tif (rpc-\u003estate == RPC_IN_SERVICE) {\n+\t\t\t\trpc-\u003esilent_ticks = 0;\n+\t\t\t\thoma_rpc_unlock(rpc);\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\trpc-\u003esilent_ticks++;\n+\t\t\thoma_timer_check_rpc(rpc);\n+\t\t\thoma_rpc_unlock(rpc);\n+\t\t\trpc_count++;\n+\t\t\tif (rpc_count \u003e= 10) {\n+\t\t\t\t/* Give other kernel threads a chance to run\n+\t\t\t\t * on this core.\n+\t\t\t\t */\n+\t\t\t\trcu_read_unlock();\n+\t\t\t\tschedule();\n+\t\t\t\trcu_read_lock();\n+\t\t\t\trpc_count = 0;\n+\t\t\t}\n+\t\t}\n+\t\trcu_read_unlock();\n+\t\thoma_unprotect_rpcs(hsk);\n+\t}\n+\thoma_socktab_end_scan(\u0026scan);\n+\thoma_tx_pool_gc(homa);\n+\thoma_route_gc(homa-\u003epeertab);\n+}\ndiff --git a/net/homa/homa_tx_pool.c b/net/homa/homa_tx_pool.c\nnew file mode 100644\nindex 0000000000000..c6420ffe2d19c\n--- /dev/null\n+++ b/net/homa/homa_tx_pool.c\n@@ -0,0 +1,527 @@\n+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+\n+/* This file manages a reusable pools of pages (one per NUMA node), that\n+ * are used to hold the data of outgoing Homa messages. Homa uses these\n+ * custom pools rather than, say, page_pools because Homa can free pages\n+ * from its pools more aggressively than in page_pool. And, this module\n+ * also implements a one-page cache page per core to use for allocating\n+ * smaller chunks of tx memory.\n+ */\n+\n+#include \"homa_impl.h\"\n+#include \"homa_tx_pool.h\"\n+\n+DEFINE_PER_CPU(struct homa_tx_pool_core, homa_tx_pool_core);\n+\n+static void frag_page_set(skb_frag_t *frag, struct page *page)\n+{\n+\tfrag-\u003enetmem = page_to_netmem(page);\n+}\n+\n+/**\n+ * homa_tx_pool_init() - Invoked when a struct homa is created; initializes\n+ * information related to this module.\n+ * @homa:        Shared information about the Homa transport; pool-related\n+ *               fields are assumed to have been initialized to zero.\n+ * Return:       0 for success, negative errno on error\n+ */\n+int homa_tx_pool_init(struct homa *homa)\n+{\n+\tu64 min_kb;\n+\tint i;\n+\n+\thoma-\u003etx_page_pool_min_kb = 1000;\n+\tmin_kb = 3 * HOMA_MAX_MESSAGE_LENGTH;\n+\tdo_div(min_kb, 1000);\n+\thoma-\u003etx_page_pool_min_kb = min_kb;\n+\n+\t/* Initialize NUMA-specfific page pools. */\n+\thoma-\u003emax_numa = -1;\n+\tfor (i = 0; i \u003c nr_cpu_ids; i++) {\n+\t\tstruct homa_tx_pool_core *tx_core;\n+\t\tint numa = cpu_to_node(i);\n+\n+\t\tBUG_ON(numa \u003e= MAX_NUMNODES);\n+\t\tif (numa \u003e homa-\u003emax_numa)\n+\t\t\thoma-\u003emax_numa = numa;\n+\t\tif (!homa-\u003etx_pools[numa]) {\n+\t\t\tstruct homa_tx_pool *pool;\n+\n+\t\t\tpool = kzalloc_obj(*pool, GFP_ATOMIC);\n+\t\t\tif (!pool)\n+\t\t\t\tgoto error;\n+\t\t\thoma-\u003etx_pools[numa] = pool;\n+\t\t}\n+\t\ttx_core = \u0026per_cpu(homa_tx_pool_core, i);\n+\t\ttx_core-\u003epool = homa-\u003etx_pools[numa];\n+\t}\n+\tpr_notice(\"%s found max NUMA node %d\\n\", __func__, homa-\u003emax_numa);\n+\treturn 0;\n+\n+error:\n+\thoma_tx_pool_cleanup(homa);\n+\treturn -ENOMEM;\n+}\n+\n+/**\n+ * homa_tx_pool_cleanup() - Invoked when a struct homa is deleted; cleans\n+ * up information related to this module.\n+ * @homa:  Overall information about the Homa transport.\n+ */\n+void homa_tx_pool_cleanup(struct homa *homa)\n+{\n+\tint i, j;\n+\n+\tfor (i = 0; i \u003c nr_cpu_ids; i++) {\n+\t\tstruct homa_tx_pool_core *tx_core;\n+\n+\t\ttx_core = \u0026per_cpu(homa_tx_pool_core, i);\n+\t\tif (!tx_core)\n+\t\t\tcontinue;\n+\t\tif (tx_core-\u003epage) {\n+\t\t\tput_page(tx_core-\u003epage);\n+\t\t\ttx_core-\u003epage = NULL;\n+\t\t\ttx_core-\u003epage_size = 0;\n+\t\t\ttx_core-\u003eallocated = 0;\n+\t\t}\n+\t\ttx_core-\u003epool = NULL;\n+\t}\n+\n+\tfor (i = 0; i \u003c MAX_NUMNODES; i++) {\n+\t\tstruct homa_tx_pool *pool = homa-\u003etx_pools[i];\n+\n+\t\tif (!pool)\n+\t\t\tcontinue;\n+\t\tfor (j = pool-\u003eavail - 1; j \u003e= 0; j--)\n+\t\t\tput_page(pool-\u003epages[j]);\n+\t\tpool-\u003eavail = 0;\n+\t\tkfree(pool);\n+\t\thoma-\u003etx_pools[i] = NULL;\n+\t}\n+\n+\tkfree(homa-\u003etx_pages_to_free);\n+\thoma-\u003etx_pages_to_free = NULL;\n+\thoma-\u003etx_pages_to_free_slots = 0;\n+}\n+\n+/**\n+ * homa_tx_pool_alloc() - Allocate a block of memory in one or more\n+ * fragments.\n+ * @homa:        Shared information about the Homa transport.\n+ * @length:       Total number of bytes to allocate.\n+ * @num_frags:   Number of fragments of storage initially available at **frags;\n+ *               modified to hold the total number of fragments\n+ *               allocated.\n+ * @frags:       Pointer to pointer to space in which to store fragments;\n+ *               if this initial space is insufficient to hold all of the\n+ *               fragments needed, will be overwritten with a dynamically\n+ *               allocated block.\n+ * Return:       0 for success, negative errno on error.\n+ */\n+int homa_tx_pool_alloc(struct homa *homa, int length, int *num_frags,\n+\t\t       skb_frag_t **frags)\n+{\n+\tstruct homa_tx_pool_core *tx_core;\n+\tskb_frag_t *cur_frags = *frags;\n+\tint max_frags = *num_frags;\n+\tint bytes_left = length;\n+\tint frags_allocated = 0;\n+\tskb_frag_t *frag;\n+\tint err;\n+\n+\t/* Asssure atomicity with respect to SoftIRQ invocations or\n+\t * task preemption (so we can access per-core info without races).\n+\t */\n+\tlocal_bh_disable();\n+\ttx_core = \u0026per_cpu(homa_tx_pool_core, smp_processor_id());\n+\n+\twhile (bytes_left  \u003e 0) {\n+\t\t/* Expand the frag array if needed. */\n+\t\tif (frags_allocated == max_frags) {\n+\t\t\tskb_frag_t *new_frags;\n+\t\t\tint num_new;\n+\n+\t\t\tnum_new = ((bytes_left + HOMA_TX_PAGE_SIZE - 1) \u003e\u003e\n+\t\t\t\t   (PAGE_SHIFT + HOMA_TX_PAGE_ORDER)) +\n+\t\t\t\t  frags_allocated;\n+\t\t\tnew_frags = kvmalloc_array(num_new, sizeof(*new_frags),\n+\t\t\t\t\t\t   GFP_ATOMIC);\n+\t\t\tif (!new_frags) {\n+\t\t\t\terr = -ENOMEM;\n+\t\t\t\tgoto error;\n+\t\t\t}\n+\t\t\tmemcpy(new_frags, cur_frags,\n+\t\t\t       frags_allocated * sizeof(*new_frags));\n+\t\t\tif (cur_frags != *frags)\n+\t\t\t\tkfree(cur_frags);\n+\t\t\tcur_frags = new_frags;\n+\t\t\tmax_frags = num_new;\n+\t\t}\n+\n+\t\tfrag = \u0026cur_frags[frags_allocated];\n+\t\terr = __homa_tx_pool_alloc_frag(tx_core, bytes_left, frag);\n+\t\tif (err != 0)\n+\t\t\tgoto error;\n+\t\tfrags_allocated++;\n+\t\tbytes_left -= skb_frag_size(frag);\n+\t}\n+\tlocal_bh_enable();\n+\t*frags  = cur_frags;\n+\t*num_frags = frags_allocated;\n+\treturn 0;\n+\n+error:\n+\thoma_tx_pool_free(homa, frags_allocated, cur_frags);\n+\tif (cur_frags != *frags)\n+\t\tkfree(cur_frags);\n+\t*num_frags = 0;\n+\tlocal_bh_enable();\n+\treturn err;\n+}\n+\n+/**\n+ * __homa_tx_pool_alloc_frag() - Allocate space for a single fragment.\n+ * Caller must have disabled interrupts.\n+ * @tx_core:   Core-specific information to use for the allocation.\n+ * @length:    Desired length: actual length of fragment may be less\n+ *             than this.\n+ * @frag:      Store information about the allocated fragment here. Its\n+ *             length may be less than @length. A reference will be taken\n+ *             on its page.\n+ * Return:     0 for success, otherwise a negative errno.\n+ */\n+int __homa_tx_pool_alloc_frag(struct homa_tx_pool_core *tx_core, int length,\n+\t\t\t      skb_frag_t *frag)\n+{\n+\tstruct page *page;\n+\tint page_size;\n+\n+\t/* See if the allocation can be handled with the core's cached page. */\n+\tif (tx_core-\u003epage_size - tx_core-\u003eallocated \u003e= length) {\n+\t\tget_page(tx_core-\u003epage);\n+\t\tfrag_page_set(frag, tx_core-\u003epage);\n+\t\tfrag-\u003eoffset = tx_core-\u003eallocated;\n+\t\tskb_frag_size_set(frag, length);\n+\t\ttx_core-\u003eallocated += length;\n+\t\tif (tx_core-\u003eallocated == tx_core-\u003epage_size) {\n+\t\t\tput_page(tx_core-\u003epage);\n+\t\t\ttx_core-\u003epage = NULL;\n+\t\t\ttx_core-\u003epage_size = 0;\n+\t\t\ttx_core-\u003eallocated = 0;\n+\t\t}\n+\t\treturn 0;\n+\t}\n+\n+\t/* Must allocate a new page. */\n+\tpage = homa_tx_pool_alloc_page(tx_core, \u0026page_size);\n+\tif (!page)\n+\t\treturn -ENOMEM;\n+\tfrag_page_set(frag, page);\n+\tfrag-\u003eoffset = 0;\n+\tskb_frag_size_set(frag, min(page_size, length));\n+\n+\t/* Retain the leftover part of the page as the core's cached page,\n+\t * if it has more space available than the current cached page.\n+\t */\n+\tif (!tx_core-\u003epage || (tx_core-\u003epage_size - tx_core-\u003eallocated) \u003c\n+\t\t\t       (page_size - skb_frag_size(frag))) {\n+\t\tif (tx_core-\u003epage)\n+\t\t\tput_page(tx_core-\u003epage);\n+\t\tget_page(page);\n+\t\ttx_core-\u003epage = page;\n+\t\ttx_core-\u003epage_size = page_size;\n+\t\ttx_core-\u003eallocated = skb_frag_size(frag);\n+\t}\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_tx_pool_alloc_frag() - Allocate space for a single fragment.\n+ * @homa:      Overall information about the Homa transport.\n+ * @length:    Desired length: actual length of fragment may be less\n+ *             than this.\n+ * @frag:      Store information about the allocated fragment here. Its\n+ *             length may be less than @length. A reference will be taken\n+ *             on its page.\n+ * Return:     0 for success, otherwise a negative errno.\n+ */\n+int homa_tx_pool_alloc_frag(struct homa *homa, int length, skb_frag_t *frag)\n+{\n+\tstruct homa_tx_pool_core *tx_core;\n+\tint result;\n+\n+\ttx_core = \u0026per_cpu(homa_tx_pool_core, smp_processor_id());\n+\tlocal_bh_disable();\n+\tresult = __homa_tx_pool_alloc_frag(tx_core, length, frag);\n+\tlocal_bh_enable();\n+\treturn result;\n+}\n+\n+/**\n+ * homa_tx_pool_alloc_page() - Allocate a new page for skb allocation for a\n+ * given core. Any existing page is released.\n+ * @tx_core:    Core-specific info; the page will be allocated in this core.\n+ * @length:     The length of the allocated page (if any) will be stored here.\n+ * Return:      The allocated page (with reference count 1) or NULL if\n+ *              no page could be allocated.\n+ */\n+struct page *homa_tx_pool_alloc_page(struct homa_tx_pool_core *tx_core,\n+\t\t\t\t     int *length)\n+{\n+\tstruct homa_tx_pool *pool;\n+\tstruct page *page;\n+\n+\t/* Step 1: can we reuse the core's cached page? */\n+\tpage = tx_core-\u003epage;\n+\tif (page \u0026\u0026 page_ref_count(page) == 1) {\n+\t\t*length = tx_core-\u003epage_size;\n+\t\ttx_core-\u003epage = NULL;\n+\t\ttx_core-\u003epage_size = 0;\n+\t\ttx_core-\u003eallocated = 0;\n+\t\treturn page;\n+\t}\n+\n+\t/* Step 2: can we retrieve a page from the pool for this NUMA node? */\n+\tpool = tx_core-\u003epool;\n+\tif (pool-\u003eavail) {\n+\t\tspin_lock_bh(\u0026pool-\u003emutex);\n+\n+\t\t/* Must recheck: could have changed before locked. */\n+\t\tif (pool-\u003eavail) {\n+\t\t\tpool-\u003eavail--;\n+\t\t\tif (pool-\u003eavail \u003c pool-\u003elow_mark)\n+\t\t\t\tpool-\u003elow_mark = pool-\u003eavail;\n+\t\t\tpage = pool-\u003epages[pool-\u003eavail];\n+\t\t\tspin_unlock_bh(\u0026pool-\u003emutex);\n+\t\t\t*length = HOMA_TX_PAGE_SIZE;\n+\t\t\treturn page;\n+\t\t}\n+\t\tspin_unlock_bh(\u0026pool-\u003emutex);\n+\t}\n+\n+\t/* Step 3: can we allocate a big page? */\n+\tpage = alloc_pages(GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN |\n+\t\t\t   __GFP_NORETRY, HOMA_TX_PAGE_ORDER);\n+\tif (likely(page)) {\n+\t\t*length = HOMA_TX_PAGE_SIZE;\n+\t\treturn page;\n+\t}\n+\n+\t/* Step 4: can we allocate a normal page? */\n+\tpage = alloc_page(GFP_ATOMIC);\n+\tif (likely(page)) {\n+\t\t*length = PAGE_SIZE;\n+\t\treturn page;\n+\t}\n+\treturn NULL;\n+}\n+\n+/**\n+ * homa_tx_pool_free() - Release one or more fragments previously allocated\n+ * by homa_tx_pool_alloc.\n+ * @homa:        Shared information about the Homa transport.\n+ * @num_frags:   Number of fragments at *frags.\n+ * @frags:       Pointer to array of fragments to free; must not be used\n+ *               after this function returns.\n+ */\n+void homa_tx_pool_free(struct homa *homa, int num_frags, skb_frag_t *frags)\n+{\n+\tstruct homa_tx_pool *pool;\n+\tint i;\n+\n+\tif (num_frags \u003c= 0)\n+\t\treturn;\n+\n+\tpool = homa-\u003etx_pools[page_to_nid(skb_frag_page(\u0026frags[0]))];\n+\tspin_lock_bh(\u0026pool-\u003emutex);\n+\tfor (i = 0; i \u003c num_frags; i++) {\n+\t\tstruct page *page = skb_frag_page(\u0026frags[i]);\n+\n+\t\tif (compound_order(page) == HOMA_TX_PAGE_ORDER \u0026\u0026\n+\t\t    page_ref_count(page) == 1 \u0026\u0026\n+\t\t    pool-\u003eavail \u003c HOMA_TX_POOL_LIMIT) {\n+\t\t\tpool-\u003epages[pool-\u003eavail] = page;\n+\t\t\tpool-\u003eavail++;\n+\t\t} else {\n+\t\t\tput_page(page);\n+\t\t}\n+\t}\n+\tspin_unlock_bh(\u0026pool-\u003emutex);\n+}\n+\n+/**\n+ * homa_tx_pool_gc() - This function is invoked occasionally; its\n+ * job is to gradually release pages from the page pools back to\n+ * Linux, based on sysctl parameters such as tx_page_frees_per_sec.\n+ * @homa:  Overall information about the Homa transport.\n+ */\n+void homa_tx_pool_gc(struct homa *homa)\n+{\n+\tint i, max_low_mark, min_pages, release, release_max;\n+\tstruct homa_tx_pool *max_pool;\n+\tu64 now = homa_clock();\n+\n+\tif (now \u003c homa-\u003etx_page_free_time)\n+\t\treturn;\n+\n+\t/* Free pages every 0.5 second. */\n+\thoma-\u003etx_page_free_time = now + (500 * homa_clock_khz());\n+\n+\t/* Make sure we have space in which to collect pages to free. */\n+\trelease_max = homa-\u003etx_page_frees_per_sec / 2;\n+\tif (homa-\u003etx_pages_to_free_slots \u003c release_max) {\n+\t\tstruct page **old = homa-\u003etx_pages_to_free;\n+\n+\t\thoma-\u003etx_pages_to_free = kmalloc_array(release_max,\n+\t\t\t\t\t\t       sizeof(struct page *),\n+\t\t\t\t\t\t       GFP_ATOMIC);\n+\t\tif (homa-\u003etx_pages_to_free) {\n+\t\t\tkfree(old);\n+\t\t\thoma-\u003etx_pages_to_free_slots = release_max;\n+\t\t} else {\n+\t\t\t/* Couldn't allocate space; reuse existing space\n+\t\t\t * and reduce how many pages we'll free.\n+\t\t\t */\n+\t\t\thoma-\u003etx_pages_to_free = old;\n+\t\t\trelease_max = homa-\u003etx_pages_to_free_slots;\n+\t\t}\n+\t}\n+\n+\t/* Find the pool with the largest number of pages that haven't\n+\t * been used recently.\n+\t */\n+\tmax_low_mark = -1;\n+\tfor (i = 0; i \u003c= homa-\u003emax_numa; i++) {\n+\t\tstruct homa_tx_pool *pool = homa-\u003etx_pools[i];\n+\n+\t\tif (!pool)\n+\t\t\tcontinue;\n+\t\tspin_lock_bh(\u0026pool-\u003emutex);\n+\t\tif (pool-\u003elow_mark \u003e max_low_mark) {\n+\t\t\tmax_low_mark = pool-\u003elow_mark;\n+\t\t\tmax_pool = pool;\n+\t\t}\n+\t\tpool-\u003elow_mark = pool-\u003eavail;\n+\t\tspin_unlock_bh(\u0026pool-\u003emutex);\n+\t}\n+\n+\t/* Collect pages to free (but don't free them until after\n+\t * releasing the lock, since freeing is expensive).\n+\t */\n+\tspin_lock_bh(\u0026max_pool-\u003emutex);\n+\tmin_pages = ((homa-\u003etx_page_pool_min_kb * 1000)\n+\t\t\t+ (HOMA_TX_PAGE_SIZE - 1)) \u003e\u003e HOMA_TX_PAGE_SHIFT;\n+\n+\t/* Note: may need to adjust max_low_mark to reflect changes made\n+\t * while lock wasn't held.\n+\t */\n+\tif (max_low_mark \u003e max_pool-\u003elow_mark)\n+\t\tmax_low_mark = max_pool-\u003elow_mark;\n+\trelease = max_low_mark - min_pages;\n+\tif (release \u003e release_max)\n+\t\trelease = release_max;\n+\tfor (i = 0; i \u003c release; i++) {\n+\t\tmax_pool-\u003eavail--;\n+\t\thoma-\u003etx_pages_to_free[i] = max_pool-\u003epages[max_pool-\u003eavail];\n+\t}\n+\tmax_pool-\u003elow_mark = max_pool-\u003eavail;\n+\tspin_unlock_bh(\u0026max_pool-\u003emutex);\n+\n+\t/* Free the pages that were collected. */\n+\tfor (i = 0; i \u003c release; i++) {\n+\t\tstruct page *page = homa-\u003etx_pages_to_free[i];\n+\n+\t\tput_page(page);\n+\t}\n+}\n+\n+/**\n+ * homa_copy_to_frags() - Copy a block of data into an array of fragments.\n+ * @filler:    Describes the current position in the array of fragments;\n+ *             will be updated to reflect the copied data.\n+ * @src:       Copy bytes from here into the fragments.\n+ * @num_bytes: Number of bytes to copy.\n+ * Return:     0 for success; -EINVAL if there isn't enough room in the\n+ *             fragments for the new bytes.\n+ */\n+int homa_copy_to_frags(struct homa_frag_filler *filler, void *src,\n+\t\t       int num_bytes)\n+{\n+\tint p_off, copied, p_len;\n+\tint bytes_this_frag;\n+\tstruct page *p;\n+\tu8 *src_cur;\n+\n+\tsrc_cur = src;\n+\twhile (num_bytes \u003e 0) {\n+\t\tif (filler-\u003eoffset \u003e= skb_frag_size(filler-\u003efrag)) {\n+\t\t\tfiller-\u003efrag++;\n+\t\t\tfiller-\u003enum_frags--;\n+\t\t\tif (filler-\u003enum_frags \u003c= 0)\n+\t\t\t\treturn -EINVAL;\n+\t\t\tfiller-\u003eoffset = 0;\n+\t\t}\n+\t\tbytes_this_frag = min(num_bytes,\n+\t\t\t\t      skb_frag_size(filler-\u003efrag) -\n+\t\t\t\t      filler-\u003eoffset);\n+\t\tskb_frag_foreach_page(filler-\u003efrag,\n+\t\t\t\t      skb_frag_off(filler-\u003efrag) +\n+\t\t\t\t      filler-\u003eoffset, bytes_this_frag, p,\n+\t\t\t\t      p_off, p_len, copied) {\n+\t\t\tu8 *vaddr = kmap_local_page(p);\n+\n+\t\t\tmemcpy(vaddr + p_off, src_cur, p_len);\n+\t\t\tkunmap_local(vaddr);\n+\t\t\tsrc_cur += p_len;\n+\t\t}\n+\t\tfiller-\u003eoffset += bytes_this_frag;\n+\t\tnum_bytes -= bytes_this_frag;\n+\t}\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_copy_iter_to_frags() - Copy data from an iterator (presumably\n+ * referring to user-space data) into an array of fragments.\n+ * @filler:    Describes the current position in the array of fragments;\n+ *             will be updated to reflect the copied data.\n+ * @iter:      Copy bytes from here into the fragments.\n+ * @num_bytes: Number of bytesto copy.\n+ * Return:     0 for success; -EINVAL if there isn't enough room in the\n+ *             fragments for the new bytes.\n+ */\n+int homa_copy_iter_to_frags(struct homa_frag_filler *filler,\n+\t\t\t    struct iov_iter *iter, int num_bytes)\n+{\n+\tint p_off, copied, p_len;\n+\tint bytes_this_frag;\n+\tstruct page *p;\n+\n+\twhile (num_bytes \u003e 0) {\n+\t\tif (filler-\u003eoffset \u003e= skb_frag_size(filler-\u003efrag)) {\n+\t\t\tfiller-\u003efrag++;\n+\t\t\tfiller-\u003enum_frags--;\n+\t\t\tif (filler-\u003enum_frags \u003c= 0)\n+\t\t\t\treturn -EINVAL;\n+\t\t\tfiller-\u003eoffset = 0;\n+\t\t}\n+\t\tbytes_this_frag = min(num_bytes,\n+\t\t\t\t      skb_frag_size(filler-\u003efrag) -\n+\t\t\t\t      filler-\u003eoffset);\n+\t\tskb_frag_foreach_page(filler-\u003efrag,\n+\t\t\t\t      skb_frag_off(filler-\u003efrag) +\n+\t\t\t\t      filler-\u003eoffset, bytes_this_frag, p,\n+\t\t\t\t      p_off, p_len, copied) {\n+\t\t\tint result;\n+\t\t\tvoid *vaddr = kmap_local_page(p);\n+\n+\t\t\tresult = copy_from_iter(vaddr + p_off, p_len, iter);\n+\t\t\tkunmap_local(vaddr);\n+\t\t\tif (result != p_len)\n+\t\t\t\treturn -EFAULT;\n+\t\t}\n+\t\tfiller-\u003eoffset += bytes_this_frag;\n+\t\tnum_bytes -= bytes_this_frag;\n+\t}\n+\treturn 0;\n+}\ndiff --git a/net/homa/homa_tx_pool.h b/net/homa/homa_tx_pool.h\nnew file mode 100644\nindex 0000000000000..aca47f9a3184a\n--- /dev/null\n+++ b/net/homa/homa_tx_pool.h\n@@ -0,0 +1,139 @@\n+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */\n+\n+/* This module manages a pool of memory pages used for outgoing sk_buffs. */\n+\n+#ifndef _HOMA_TX_POOL_H\n+#define _HOMA_TX_POOL_H\n+\n+#include \u003clinux/percpu-defs.h\u003e\n+\n+/**\n+ * define HOMA_TX_PAGE_ORDER - exponent (power of two) determining how\n+ * many pages to allocate in a high-order page for skb pages (e.g.,\n+ * 2 means allocate in units of 4 pages).\n+ */\n+#define HOMA_TX_PAGE_ORDER 4\n+\n+/**\n+ * define HOMA_TX_PAGE_SIZE - number of bytes corresponding to HOMA_PAGE_ORDER.\n+ */\n+#define HOMA_TX_PAGE_SIZE (PAGE_SIZE \u003c\u003c HOMA_TX_PAGE_ORDER)\n+\n+/**\n+ * define HOMA_TX_PAGE_SHIFT: HOMA_PAGE_SIZE == 1 \u003c\u003c HOMA_TX_PAGE_SHIFT\n+ */\n+#define HOMA_TX_PAGE_SHIFT (PAGE_SHIFT + HOMA_TX_PAGE_ORDER)\n+\n+/**\n+ * struct homa_tx_pool - A cache of free pages available for use.\n+ * Each page is of size HOMA_TX_PAGE_SIZE, and a given pool is dedicated for\n+ * use by a single NUMA node.\n+ */\n+struct homa_tx_pool {\n+\t/** @mutex: Used to synchronize access to the fields in this struct. */\n+\tspinlock_t mutex;\n+\n+\t/** @avail: Number of free pages currently in the pool. */\n+\tint avail;\n+\n+\t/**\n+\t * @low_mark: Low water mark: smallest value of avail since the\n+\t * last time homa_tx_pool_gc reset it.\n+\t */\n+\tint low_mark;\n+\n+#define HOMA_TX_POOL_LIMIT 1000\n+\n+\t/**\n+\t * @pages: Pointers to pages that are currently free; the ref count\n+\t * is 1 in each of these pages.\n+\t */\n+\tstruct page *pages[HOMA_TX_POOL_LIMIT];\n+};\n+\n+/**\n+ * struct homa_tx_pool_core - Stores core-specific information related to\n+ * tx memory allocation. All values are assumed to be zero initially.\n+ */\n+struct homa_tx_pool_core {\n+\t/**\n+\t * @pool: NUMA-specific page pool from which to allocate skb pages\n+\t * for this core.\n+\t */\n+\tstruct homa_tx_pool *pool;\n+\n+\t/**\n+\t * @page: a page of data that is \"owned\" by this core and used for\n+\t * allocation on this core (or NULL). This pointer is included in\n+\t * the page's reference count.\n+\t */\n+\tstruct page *page;\n+\n+\t/**\n+\t * @page_size: total number of bytes in @page (including any\n+\t * already allocated).\n+\t */\n+\tint page_size;\n+\n+\t/**\n+\t * @allocated: number of (initial) bytes in @page that have already\n+\t * been allocated for use.\n+\t */\n+\tint allocated;\n+};\n+DECLARE_PER_CPU(struct homa_tx_pool_core, homa_tx_pool_core);\n+\n+/**\n+ * struct homa_frag_filler - Used to iterate over an array of skb_frag_t's\n+ * to copy data into them.\n+ */\n+struct homa_frag_filler {\n+\t/** @frag: Fragment currently being filled (in an array of frags). */\n+\tskb_frag_t *frag;\n+\n+\t/**\n+\t * @offset: Offset within @frag where the next byte of data should be\n+\t * stored.\n+\t */\n+\tint offset;\n+\n+\t/**\n+\t * @num_frags: Number of fragments in the array including @frag:\n+\t * if this reaches zero then we have run out of space.\n+\t */\n+\tint num_frags;\n+};\n+\n+/**\n+ * homa_frag_filler_init() - Initialize a frag filler.\n+ * @filler:     Struct to initialize.\n+ * @num_frags:  Number of fragments available to fill.\n+ * @frags:      First in array of @num_frags fragments.\n+ */\n+static inline void homa_frag_filler_init(struct homa_frag_filler *filler,\n+\t\t\t\t\t int num_frags, skb_frag_t *frags)\n+{\n+\tfiller-\u003efrag = frags;\n+\tfiller-\u003eoffset = 0;\n+\tfiller-\u003enum_frags = num_frags;\n+}\n+\n+int          homa_copy_iter_to_frags(struct homa_frag_filler *filler,\n+\t\t\t\t     struct iov_iter *iter, int num_bytes);\n+int          homa_copy_to_frags(struct homa_frag_filler *filler, void *src,\n+\t\t\t\tint num_bytes);\n+int          homa_tx_pool_alloc(struct homa *homa, int length, int *num_frags,\n+\t\t\t\tskb_frag_t **frags);\n+int          __homa_tx_pool_alloc_frag(struct homa_tx_pool_core *tx_core,\n+\t\t\t\t       int length, skb_frag_t *frag);\n+int          homa_tx_pool_alloc_frag(struct homa *homa, int length,\n+\t\t\t\t     skb_frag_t *frag);\n+struct page *homa_tx_pool_alloc_page(struct homa_tx_pool_core *tx_core,\n+\t\t\t\t     int *length);\n+void         homa_tx_pool_cleanup(struct homa *homa);\n+void         homa_tx_pool_free(struct homa *homa, int num_frags,\n+\t\t\t       skb_frag_t *frags);\n+void         homa_tx_pool_gc(struct homa *homa);\n+int          homa_tx_pool_init(struct homa *homa);\n+\n+#endif /* _HOMA_TX_POOL_H */\ndiff --git a/net/homa/homa_utils.c b/net/homa/homa_utils.c\nnew file mode 100644\nindex 0000000000000..94799976a8ab4\n--- /dev/null\n+++ b/net/homa/homa_utils.c\n@@ -0,0 +1,119 @@\n+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+\n+\n+/* This file contains miscellaneous utility functions for Homa, such\n+ * as initializing and destroying homa structs.\n+ */\n+\n+#include \"homa_impl.h\"\n+#include \"homa_peer.h\"\n+#include \"homa_rpc.h\"\n+#include \"homa_tx_pool.h\"\n+\n+/**\n+ * homa_init() - Constructor for homa objects.\n+ * @homa:   Object to initialize.\n+ *\n+ * Return:  0 on success, or a negative errno if there was an error.\n+ */\n+int homa_init(struct homa *homa)\n+{\n+\tint err;\n+\n+\tmemset(homa, 0, sizeof(*homa));\n+\n+\tatomic64_set(\u0026homa-\u003enext_outgoing_id, 2);\n+\thoma-\u003elink_mbps = 25000;\n+\thoma-\u003epeertab = homa_peer_alloc_peertab();\n+\tif (IS_ERR(homa-\u003epeertab)) {\n+\t\terr = PTR_ERR(homa-\u003epeertab);\n+\t\thoma-\u003epeertab = NULL;\n+\t\tgoto error;\n+\t}\n+\thoma-\u003esocktab = kmalloc(sizeof(*homa-\u003esocktab), GFP_KERNEL);\n+\tif (!homa-\u003esocktab) {\n+\t\terr = -ENOMEM;\n+\t\tgoto error;\n+\t}\n+\thoma_socktab_init(homa-\u003esocktab);\n+\terr = homa_tx_pool_init(homa);\n+\tif (err) {\n+\t\tpr_err(\"Couldn't initialize homa_tx_pool (errno %d)\\n\",\n+\t\t       -err);\n+\t\tgoto error;\n+\t}\n+\n+\t/* Wild guesses to initialize configuration values... */\n+\thoma-\u003eresend_ticks = 5;\n+\thoma-\u003eresend_interval = 5;\n+\thoma-\u003etimeout_ticks = 100;\n+\thoma-\u003etimeout_resends = 5;\n+\thoma-\u003erequest_ack_ticks = 2;\n+\thoma-\u003edead_frags_limit = 100;\n+\thoma-\u003emax_gso_size = 1000;\n+\thoma-\u003ewmem_max = 100000000;\n+\thoma-\u003ebpage_lease_usecs = 10000;\n+\thoma-\u003ebpage_lease_cycles = homa-\u003ebpage_lease_usecs  * 2500;\n+\treturn 0;\n+\n+error:\n+\thoma_destroy(homa);\n+\treturn err;\n+}\n+\n+/**\n+ * homa_destroy() -  Destructor for homa objects.\n+ * @homa:      Object to destroy. It is safe if this object has already\n+ *             been previously destroyed.\n+ */\n+void homa_destroy(struct homa *homa)\n+{\n+\t/* The order of the following cleanups matters! */\n+\tif (homa-\u003esocktab) {\n+\t\thoma_socktab_destroy(homa-\u003esocktab, NULL);\n+\t\tkfree(homa-\u003esocktab);\n+\t\thoma-\u003esocktab = NULL;\n+\t}\n+\tif (homa-\u003epeertab) {\n+\t\thoma_peer_free_peertab(homa-\u003epeertab);\n+\t\thoma-\u003epeertab = NULL;\n+\t}\n+\thoma_tx_pool_cleanup(homa);\n+}\n+\n+/**\n+ * homa_net_init() - Initialize a new struct homa_net.\n+ * @hnet:    Struct to initialize.\n+ * @homa:    The main Homa data structure to use for the net.\n+ * Return:  0 on success, otherwise a negative errno.\n+ */\n+int homa_net_init(struct homa_net *hnet, struct homa *homa)\n+{\n+\tmemset(hnet, 0, sizeof(*hnet));\n+\thnet-\u003ehoma = homa;\n+\thnet-\u003eprev_default_port = HOMA_MIN_DEFAULT_PORT - 1;\n+\treturn 0;\n+}\n+\n+/**\n+ * homa_net_destroy() - Release any resources associated with a homa_net.\n+ * @hnet:    Object to destroy; must not be used again after this function\n+ *           returns.\n+ */\n+void homa_net_destroy(struct homa_net *hnet)\n+{\n+\thoma_socktab_destroy(hnet-\u003ehoma-\u003esocktab, hnet);\n+\thoma_peer_free_net(hnet);\n+}\n+\n+/**\n+ * homa_spin() - Delay (without sleeping) for a given time interval.\n+ * @ns:   How long to delay (in nanoseconds)\n+ */\n+void homa_spin(int ns)\n+{\n+\tu64 end;\n+\n+\tend = homa_clock() + homa_ns_to_cycles(ns);\n+\twhile (homa_clock() \u003c end)\n+\t\tcpu_relax();\n+}\ndiff --git a/net/homa/homa_wire.h b/net/homa/homa_wire.h\nnew file mode 100644\nindex 0000000000000..5bc4a25ec9200\n--- /dev/null\n+++ b/net/homa/homa_wire.h\n@@ -0,0 +1,346 @@\n+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */\n+\n+/* This file defines the on-the-wire format of Homa packets. */\n+\n+#ifndef _HOMA_WIRE_H\n+#define _HOMA_WIRE_H\n+\n+#include \u003clinux/skbuff.h\u003e\n+#include \u003cnet/tcp.h\u003e\n+\n+/* Defines the possible types of Homa packets.\n+ *\n+ * See the xxx_header structs below for more information about each type.\n+ */\n+enum homa_packet_type {\n+\tDATA               = 0x10,\n+\tRESEND             = 0x12,\n+\tRPC_UNKNOWN        = 0x13,\n+\tBUSY               = 0x14,\n+\tNEED_ACK           = 0x17,\n+\tACK                = 0x18,\n+\tMAX_OP             = 0x18,\n+\t/* If you add a new type here, you must also do the following:\n+\t * 1. Change MAX_OP so it is the highest valid opcode\n+\t * 2. Add support for the new opcode in homa_print_packet,\n+\t *    homa_print_packet_short, homa_symbol_for_type, and mock_skb_alloc.\n+\t * 3. Add the header length to header_lengths in homa_plumbing.c.\n+\t */\n+};\n+\n+/**\n+ * define HOMA_SKB_EXTRA - How many bytes of additional space to allow at the\n+ * beginning of each sk_buff, before the Homa header. This includes room for\n+ * either an IPV4 or IPV6 header, Ethernet header, VLAN header, etc. This is\n+ * a bit of an overestimate, since it also includes space for a TCP header.\n+ */\n+#define HOMA_SKB_EXTRA MAX_TCP_HEADER\n+\n+/**\n+ * define HOMA_ETH_FRAME_OVERHEAD - Additional overhead bytes for each\n+ * Ethernet packet that are not included in the packet header (preamble,\n+ * start frame delimiter, CRC, and inter-packet gap).\n+ */\n+#define HOMA_ETH_FRAME_OVERHEAD 24\n+\n+/**\n+ * define HOMA_ETH_OVERHEAD - Number of bytes per Ethernet packet for Ethernet\n+ * header, CRC, preamble, and inter-packet gap.\n+ */\n+#define HOMA_ETH_OVERHEAD (18 + HOMA_ETH_FRAME_OVERHEAD)\n+\n+/**\n+ * define HOMA_MIN_PKT_LENGTH - Every Homa packet must be padded to at least\n+ * this length to meet Ethernet frame size limitations. This number includes\n+ * Homa headers and data, but not IP or Ethernet headers.\n+ */\n+#define HOMA_MIN_PKT_LENGTH 26\n+\n+/**\n+ * define HOMA_MAX_HEADER - Number of bytes in the largest Homa header.\n+ */\n+#define HOMA_MAX_HEADER 90\n+\n+/**\n+ * struct homa_common_hdr - Wire format for the first bytes in every Homa\n+ * packet. This must (mostly) match the format of a TCP header to enable\n+ * Homa packets to actually be transmitted as TCP packets (and thereby\n+ * take advantage of TSO and other features).\n+ */\n+struct homa_common_hdr {\n+\t/**\n+\t * @sport: Port on source machine from which packet was sent.\n+\t * Must be in the same position as in a TCP header.\n+\t */\n+\t__be16 sport;\n+\n+\t/**\n+\t * @dport: Port on destination that is to receive packet. Must be\n+\t * in the same position as in a TCP header.\n+\t */\n+\t__be16 dport;\n+\n+\t/**\n+\t * @sequence: corresponds to the sequence number field in TCP headers;\n+\t * not used by Homa (may be auto-incremented by TSO).\n+\t */\n+\t__be32 sequence;\n+\n+\t/**\n+\t * @ack: Corresponds to the high-order bits of the acknowledgment\n+\t * field in TCP headers; not used by Homa.\n+\t */\n+\tchar ack[3];\n+\n+\t/**\n+\t * @type: Homa packet type (one of the values of the homa_packet_type\n+\t * enum). Corresponds to the low-order byte of the ack in TCP.\n+\t */\n+\tu8 type;\n+\n+\t/**\n+\t * @doff: High order 4 bits correspond to the Data Offset field of a\n+\t * TCP header. In DATA packets they hold the number of 4-byte chunks\n+\t * in a homa_data_hdr; used by TSO to determine where the replicated\n+\t * header portion ends. For other packets the offset is always 5\n+\t * (standard TCP header length); other values may cause some NICs\n+\t * (such as Intel E810-C) to drop outgoing data packets when TCP\n+\t * hijacking is enabled. The low-order bits are always 0.\n+\t */\n+\tu8 doff;\n+\n+\t/** @reserved1: Not used (corresponds to TCP flags). */\n+\tu8 reserved1;\n+\n+\t/**\n+\t * @window: Corresponds to the window field in TCP headers. Not used\n+\t * by HOMA.\n+\t */\n+\t__be16 window;\n+\n+\t/**\n+\t * @checksum: occupies the same bytes as the checksum in a TCP\n+\t * header. Set by Homa only during TCP hijacking.\n+\t */\n+\t__be16 checksum;\n+\n+\t/** @reserved2: Not used (corresponds to TCP urgent field). */\n+\t__be16 reserved2;\n+\n+\t/**\n+\t * @sender_id: the identifier of this RPC as used on the sender (i.e.,\n+\t * if the low-order bit is set, then the sender is the server for\n+\t * this RPC).\n+\t */\n+\t__be64 sender_id;\n+} __packed;\n+\n+/**\n+ * struct homa_ack - Identifies an RPC that can be safely deleted by its\n+ * server. After sending the response for an RPC, the server must retain its\n+ * state for the RPC until it knows that the client has successfully\n+ * received the entire response. An ack indicates this. Clients will\n+ * piggyback acks on future data packets, but if a client doesn't send\n+ * any data to the server, the server will eventually request an ack\n+ * explicitly with a NEED_ACK packet, in which case the client will\n+ * return an explicit ACK.\n+ */\n+struct homa_ack {\n+\t/**\n+\t * @client_id: The client's identifier for the RPC. 0 means this ack\n+\t * is invalid.\n+\t */\n+\t__be64 client_id;\n+\n+\t/** @server_port: The server-side port for the RPC. */\n+\t__be16 server_port;\n+} __packed;\n+\n+/* struct homa_data_hdr - Contains data for part or all of a Homa message.\n+ * An incoming packet consists of a homa_data_hdr followed by message data.\n+ * An outgoing packet can have this simple format as well, or it can be\n+ * structured as a GSO packet with the following format:\n+ *\n+ *    |-----------------------|\n+ *    |                       |\n+ *    |     data_header       |\n+ *    |                       |\n+ *    |---------------------- |\n+ *    |                       |\n+ *    |                       |\n+ *    |     segment data      |\n+ *    |                       |\n+ *    |                       |\n+ *    |-----------------------|\n+ *    |      seg_header       |\n+ *    |-----------------------|\n+ *    |                       |\n+ *    |                       |\n+ *    |     segment data      |\n+ *    |                       |\n+ *    |                       |\n+ *    |-----------------------|\n+ *    |      seg_header       |\n+ *    |-----------------------|\n+ *    |                       |\n+ *    |                       |\n+ *    |     segment data      |\n+ *    |                       |\n+ *    |                       |\n+ *    |-----------------------|\n+ *\n+ * TSO may not adjust @homa_common_hdr.sequence in the segments, so Homa\n+ * sprinkles correct offsets (in homa_seg_hdrs) throughout the segment data;\n+ * TSO/GSO will include a different homa_seg_hdr in each generated packet.\n+ */\n+\n+struct homa_seg_hdr {\n+\t/**\n+\t * @offset: Offset within message of the first byte of data in\n+\t * this segment.\n+\t */\n+\t__be32 offset;\n+} __packed;\n+\n+struct homa_data_hdr {\n+\tstruct homa_common_hdr common;\n+\n+\t/** @message_length: Total #bytes in the message. */\n+\t__be32 message_length;\n+\n+\t__be32 reserved1;\n+\n+\t/** @ack: If the @client_id field of this is nonzero, provides info\n+\t * about an RPC that the recipient can now safely free. Note: in\n+\t * TSO packets this will get duplicated in each of the segments;\n+\t * in order to avoid repeated attempts to ack the same RPC,\n+\t * homa_gro_receive will clear this field in all segments but the\n+\t * first.\n+\t */\n+\tstruct homa_ack ack;\n+\n+\t__be16 reserved2;\n+\n+\t/**\n+\t * @retransmit: 1 means this packet was sent in response to a RESEND\n+\t * (it has already been sent previously).\n+\t */\n+\tu8 retransmit;\n+\n+\tchar pad[3];\n+\n+\t/** @seg: First of possibly many segments. */\n+\tstruct homa_seg_hdr seg;\n+} __packed;\n+\n+/**\n+ * homa_data_len() - Returns the total number of bytes in a DATA packet\n+ * after the homa_data_hdr. Note: if the packet is a GSO packet, the result\n+ * may include metadata as well as packet data.\n+ * @skb:   Incoming data packet\n+ * Return: see above\n+ */\n+static inline u32 homa_data_len(struct sk_buff *skb)\n+{\n+\treturn skb-\u003elen - skb_transport_offset(skb) -\n+\t\t\tsizeof(struct homa_data_hdr);\n+}\n+\n+/**\n+ * struct homa_resend_hdr - Wire format for RESEND packets.\n+ *\n+ * A RESEND is sent by the receiver when it believes that message data may\n+ * have been lost in transmission (or if it is concerned that the sender may\n+ * have crashed). The receiver should resend the specified portion of the\n+ * message, even if it already sent it previously.\n+ */\n+struct homa_resend_hdr {\n+\t/** @common: Fields common to all packet types. */\n+\tstruct homa_common_hdr common;\n+\n+\t/**\n+\t * @offset: Offset within the message of the first byte of data that\n+\t * should be retransmitted.\n+\t */\n+\t__be32 offset;\n+\n+\t/**\n+\t * @length: Number of bytes of data to retransmit. -1 means no data\n+\t * has been received for the message, so everything sent previously\n+\t * should be retransmitted.\n+\t */\n+\t__be32 length;\n+\n+} __packed;\n+\n+/**\n+ * struct homa_rpc_unknown_hdr - Wire format for RPC_UNKNOWN packets.\n+ *\n+ * An RPC_UNKNOWN packet is sent by either server or client when it receives a\n+ * packet for an RPC that is unknown to it. When a client receives an\n+ * RPC_UNKNOWN packet it will typically restart the RPC from the beginning;\n+ * when a server receives an RPC_UNKNOWN packet it will typically discard its\n+ * state for the RPC.\n+ */\n+struct homa_rpc_unknown_hdr {\n+\t/** @common: Fields common to all packet types. */\n+\tstruct homa_common_hdr common;\n+} __packed;\n+\n+/**\n+ * struct homa_busy_hdr - Wire format for BUSY packets.\n+ *\n+ * These packets tell the recipient that the sender is still alive (even if\n+ * it isn't sending data expected by the recipient).\n+ */\n+struct homa_busy_hdr {\n+\t/** @common: Fields common to all packet types. */\n+\tstruct homa_common_hdr common;\n+} __packed;\n+\n+/**\n+ * struct homa_need_ack_hdr - Wire format for NEED_ACK packets.\n+ *\n+ * These packets ask the recipient (a client) to return an ACK message if\n+ * the packet's RPC is no longer active.\n+ */\n+struct homa_need_ack_hdr {\n+\t/** @common: Fields common to all packet types. */\n+\tstruct homa_common_hdr common;\n+} __packed;\n+\n+/**\n+ * struct homa_ack_hdr - Wire format for ACK packets.\n+ *\n+ * These packets are sent from a client to a server to indicate that\n+ * a set of RPCs is no longer active on the client, so the server can\n+ * free any state it may have for them.\n+ */\n+struct homa_ack_hdr {\n+\t/** @common: Fields common to all packet types. */\n+\tstruct homa_common_hdr common;\n+\n+\t/** @num_acks: Number of (leading) elements in @acks that are valid. */\n+\t__be16 num_acks;\n+\n+#define HOMA_MAX_ACKS_PER_PKT 5\n+\t/** @acks: Info about RPCs that are no longer active. */\n+\tstruct homa_ack acks[HOMA_MAX_ACKS_PER_PKT];\n+} __packed;\n+\n+/**\n+ * homa_local_id(): given an RPC identifier from an input packet (which\n+ * is network-encoded), return the decoded id we should use for that\n+ * RPC on this machine.\n+ * @sender_id:  RPC id from an incoming packet, such as h-\u003ecommon.sender_id\n+ * Return: see above\n+ */\n+static inline u64 homa_local_id(__be64 sender_id)\n+{\n+\t/* If the client bit was set on the sender side, it needs to be\n+\t * removed here, and conversely.\n+\t */\n+\treturn be64_to_cpu(sender_id) ^ 1;\n+}\n+\n+#endif /* _HOMA_WIRE_H */\n"
}

2/1 2026/09/15 00:56 agent patch-evaluator
0m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "HOMA",
    "IPV6"
  ],
  "FocusSymbols": [
    "homa_sendmsg",
    "homa_recvmsg",
    "homa_setsockopt",
    "homa_getsockopt",
    "homa_ioctl",
    "homa_ioc_info",
    "homa_bind",
    "homa_socket",
    "homa_softirq",
    "homa_dispatch_pkts",
    "homa_pool_set_region",
    "homa_rpc_reap",
    "homa_rpc_alloc_client",
    "homa_rpc_alloc_server",
    "homa_tx_copy_from_user"
  ],
  "Reasoning": "The patch series introduces the implementation of the Homa transport protocol (IPPROTO_HOMA) in the Linux kernel networking stack. It adds support for AF_INET and AF_INET6 Homa sockets, including sendmsg/recvmsg message passing, user buffer pools, setsockopt/getsockopt, HOMAIOCINFO ioctl, softirq packet dispatching, RPC state management, and custom memory pools. This new protocol is directly reachable from user space in standard virtualized environments and contains complex concurrency, locking, and packet processing logic that warrants thorough fuzzing.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 5dfb61235ce9a7847572ab2527dd1855871d9ab9
Author: syz-cluster <triage@syzkaller.com>
Date:   Tue Sep 15 00:56:16 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst
index 2fc53093752d1..c6cb82ff627e2 100644
--- a/Documentation/userspace-api/ioctl/ioctl-number.rst
+++ b/Documentation/userspace-api/ioctl/ioctl-number.rst
@@ -255,6 +255,7 @@ Code  Seq#    Include File                                             Comments
                                                                        <mailto:zapman@interlan.net>
 'h'   00-1F  linux/hpet.h                                              conflict!
 'h'   80-8F  fs/hfsplus/ioctl.c
+'h'   90-9F  uapi/linux/homa.h
 'i'   00-3F  linux/i2o-dev.h                                           conflict!
 'i'   0B-1F  linux/ipmi.h                                              conflict!
 'i'   80-8F  linux/i8k.h
diff --git a/MAINTAINERS b/MAINTAINERS
index 0e04d92d1b098..56e7651d01716 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -11938,6 +11938,13 @@ F:	lib/test_hmm*
 F:	mm/hmm*
 F:	tools/testing/selftests/mm/*hmm*
 
+HOMA TRANSPORT PROTOCOL
+M:	John Ousterhout <ouster@cs.stanford.edu>
+S:	Maintained
+W:	https://homa-transport.atlassian.net/wiki/spaces/HOMA
+F:	include/uapi/linux/homa.h
+F:	net/homa/
+
 HONEYWELL ABP2030PA PRESSURE SENSOR SERIES IIO DRIVER
 M:	Petre Rodan <petre.rodan@subdimension.ro>
 L:	linux-iio@vger.kernel.org
diff --git a/include/uapi/linux/homa.h b/include/uapi/linux/homa.h
new file mode 100644
index 0000000000000..deeca70f944a1
--- /dev/null
+++ b/include/uapi/linux/homa.h
@@ -0,0 +1,290 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ WITH Linux-syscall-note */
+
+/* This file defines the kernel call interface for the Homa
+ * transport protocol.
+ */
+
+#ifndef _UAPI_LINUX_HOMA_H
+#define _UAPI_LINUX_HOMA_H
+
+#include <linux/in.h>
+#include <linux/in6.h>
+#include <linux/socket.h>
+#include <linux/types.h>
+
+/* IANA-assigned Internet Protocol number for Homa. */
+#define IPPROTO_HOMA 146
+
+/**
+ * define HOMA_MAX_MESSAGE_LENGTH - Maximum bytes of payload in a Homa
+ * request or response message.
+ */
+#define HOMA_MAX_MESSAGE_LENGTH 1000000
+
+/**
+ * define HOMA_BPAGE_SIZE - Number of bytes in pages used for receive
+ * buffers. Must be power of two.
+ */
+#define HOMA_BPAGE_SIZE (1 << HOMA_BPAGE_SHIFT)
+#define HOMA_BPAGE_SHIFT 16
+
+/**
+ * define HOMA_MAX_BPAGES - The largest number of bpages that will be required
+ * to store an incoming message.
+ */
+#define HOMA_MAX_BPAGES ((HOMA_MAX_MESSAGE_LENGTH + HOMA_BPAGE_SIZE - 1) >> \
+		HOMA_BPAGE_SHIFT)
+
+/**
+ * define HOMA_MIN_DEFAULT_PORT - The 16 bit port space is divided into
+ * two nonoverlapping regions. Ports 1-32767 are reserved exclusively
+ * for well-defined server ports. The remaining ports are used for client
+ * ports; these are allocated automatically by Homa. Port 0 is reserved.
+ */
+#define HOMA_MIN_DEFAULT_PORT 0x8000
+
+/**
+ * struct homa_sendmsg_args - Provides information needed by Homa's
+ * sendmsg; passed to sendmsg using the msg_control field.
+ */
+struct homa_sendmsg_args {
+	/**
+	 * @id: (in/out) An initial value of 0 means a new request is
+	 * being sent; nonzero means the message is a reply to the given
+	 * id. If the message is a request, then the value is modified to
+	 * hold the id of the new RPC.
+	 */
+	__u64 id;
+
+	/**
+	 * @completion_cookie: (in) Used only for request messages; will be
+	 * returned by recvmsg when the RPC completes. Typically used to
+	 * locate app-specific info about the RPC.
+	 */
+	__u64 completion_cookie;
+
+	/**
+	 * @flags: (in) OR-ed combination of bits that control the operation.
+	 * See below for values.
+	 */
+	__u32 flags;
+
+	/** @reserved: Not currently used, must be 0. */
+	__u32 reserved;
+};
+
+/* Flag bits for homa_sendmsg_args.flags (see man page for documentation):
+ */
+#define HOMA_SENDMSG_PRIVATE       0x01
+#define HOMA_SENDMSG_VALID_FLAGS   0x01
+
+/**
+ * struct homa_recvmsg_args - Provides information needed by Homa's
+ * recvmsg; passed to recvmsg using the msg_control field.
+ */
+struct homa_recvmsg_args {
+	/**
+	 * @id: (in/out) Initial value is 0 to wait for any shared RPC;
+	 * nonzero means wait for that specific (private) RPC. Returns
+	 * the id of the RPC received.
+	 */
+	__u64 id;
+
+	/**
+	 * @completion_cookie: (out) If the incoming message is a response,
+	 * this will return the completion cookie specified when the
+	 * request was sent. For requests this will always be zero.
+	 */
+	__u64 completion_cookie;
+
+	/**
+	 * @num_bpages: (in/out) Number of valid entries in @bpage_offsets.
+	 * Passes in bpages from previous messages that can now be
+	 * recycled; returns bpages from the new message.
+	 */
+	__u32 num_bpages;
+
+	/** @reserved: Not currently used, must be 0. */
+	__u32 reserved;
+
+	/**
+	 * @bpage_offsets: (in/out) Each entry is an offset into the buffer
+	 * region for the socket pool. When returned from recvmsg, the
+	 * offsets indicate where fragments of the new message are stored. All
+	 * entries but the last refer to full buffer pages (HOMA_BPAGE_SIZE
+	 * bytes) and are bpage-aligned. The last entry may refer to a bpage
+	 * fragment and is not necessarily aligned. The application now owns
+	 * these bpages and must eventually return them to Homa, using
+	 * bpage_offsets in a future recvmsg invocation.
+	 */
+	__u32 bpage_offsets[HOMA_MAX_BPAGES];
+};
+
+/** define SO_HOMA_RCVBUF: setsockopt option for specifying buffer region. */
+#define SO_HOMA_RCVBUF 10
+
+/**
+ * define SO_HOMA_SERVER: setsockopt option for specifying whether a
+ * socket will act as server.
+ */
+#define SO_HOMA_SERVER 11
+
+/** struct homa_rcvbuf_args - setsockopt argument for SO_HOMA_RCVBUF. */
+struct homa_rcvbuf_args {
+	/** @start: Address of first byte of buffer region in user space. */
+	__u64 start;
+
+	/** @length: Total number of bytes available at @start. */
+	__u64 length;
+};
+
+/**
+ * struct homa_rpc_info - Used by HOMAIOCINFO to return information about
+ * a specific RPC.
+ */
+struct homa_rpc_info {
+	/**
+	 * @id: Identifier for the RPC, unique among all RPCs sent by the
+	 * client node. If the low-order bit is 1, this node is the server
+	 * for the RPC; 0 means we are the client.
+	 */
+	__u64 id;
+
+	/** @peer: Address of the peer socket for this RPC. */
+	union {
+		struct __kernel_sockaddr_storage storage;
+		struct sockaddr_in in4;
+		struct sockaddr_in6 in6;
+	} peer;
+
+	/**
+	 * @completion_cookie: For client-side RPCs this gives the completion
+	 * cookie specified when the RPC was initiated. For server-side RPCs
+	 * this is zero.
+	 */
+	__u64 completion_cookie;
+
+	/**
+	 * @tx_length: Length of the outgoing message in bytes, or -1 if
+	 * the sendmsg hasn't yet been called.
+	 */
+	__s32 tx_length;
+
+	/**
+	 * @tx_sent: Number of bytes of the outgoing message that have been
+	 * transmitted at least once.
+	 */
+	__u32 tx_sent;
+
+	/**
+	 * @tx_granted: Number of bytes of the outgoing message that the
+	 * receiver has authorized us to transmit (includes unscheduled
+	 * bytes).
+	 */
+	__u32 tx_granted;
+
+	/** @reserved: Reserved for future use. */
+	__u32 reserved;
+
+	/**
+	 * @rx_length: Length of the incoming message, in bytes. -1 means
+	 * the length is not yet known (this is a client-side RPC and
+	 * no packets have been received).
+	 */
+	__s32 rx_length;
+
+	/**
+	 * @rx_remaining: Number of bytes in the incoming message that have
+	 * not yet been received.
+	 */
+	__u32 rx_remaining;
+
+	/**
+	 * @rx_gaps: The number of gaps in the incoming message. A gap is
+	 * a range of bytes that have not been received yet, but bytes after
+	 * the gap have been received.
+	 */
+	__u32 rx_gaps;
+
+	/**
+	 * @rx_gap_bytes: The total number of bytes in gaps in the incoming
+	 * message.
+	 */
+	__u32 rx_gap_bytes;
+
+	/**
+	 * @rx_granted: The number of bytes in the message that the sender
+	 * is authorized to transmit (includes unscheduled bytes).
+	 */
+	__u32 rx_granted;
+
+	/**
+	 * @flags: Various single-bit values associated with the RPC:
+	 * HOMA_RPC_BUF_STALL:  The incoming message is currently stalled
+	 *                      because there is insufficient receiver buffer
+	 *                      space.
+	 * HOMA_RPC_PRIVATE:    The RPC has been created as "private"; set
+	 *                      only on the client side.
+	 * HOMA_RPC_RX_READY:   The incoming message is complete and has
+	 *                      been queued waiting for a thread to call
+	 *                      recvmsg.
+	 * HOMA_RPC_RX_COPY:    There are packets that have been received,
+	 *                      whose data has not yet been copied from
+	 *                      packet buffers to user space.
+	 */
+	__u16 flags;
+#define HOMA_RPC_BUF_STALL    1
+#define HOMA_RPC_PRIVATE      2
+#define HOMA_RPC_RX_READY     4
+#define HOMA_RPC_RX_COPY      8
+};
+
+/**
+ * struct homa_info - In/out argument passed to HOMAIOCINFO. Fields labeled
+ * as "in" must be set by the application; other fields are returned to the
+ * application from the kernel.
+ */
+struct homa_info {
+	/**
+	 * @rpc_info: (in) Address of memory region in which to store
+	 * information about individual RPCs. Actual type is
+	 * "struct homa_rpc_info *".
+	 */
+	__u64 rpc_info;
+
+	/**
+	 * @rpc_info_length: (in) Number of bytes of storage available at
+	 * rpc_info.
+	 */
+	__u64 rpc_info_length;
+
+	/**
+	 * @bpool_avail_bytes: Number of bytes in the buffer pool for incoming
+	 * messages that is currently available for new messages.
+	 */
+	__u64 bpool_avail_bytes;
+
+	/** @port: Port number handled by this socket. */
+	__u32 port;
+
+	/**
+	 * @num_rpcs: Total number of active RPCs (both server and client) for
+	 * this socket. The number stored at @rpc_info will be less than this
+	 * if @rpc_info_length is too small.
+	 */
+	__u32 num_rpcs;
+
+	/**
+	 * @error_msg: Provides additional information about the last error
+	 * returned by a Homa-related kernel call such as sendmsg, recvmsg,
+	 * or ioctl. Not updated for some obvious return values such as EINTR
+	 * or EWOULDBLOCK.
+	 */
+#define HOMA_ERROR_MSG_SIZE 104
+	char error_msg[HOMA_ERROR_MSG_SIZE];
+};
+
+/* I/O control calls on Homa sockets.*/
+#define HOMAIOCINFO  _IOWR('h', 0x90, struct homa_info)
+
+#endif /* _UAPI_LINUX_HOMA_H */
diff --git a/net/Kconfig b/net/Kconfig
index e384773935515..6780fee341a08 100644
--- a/net/Kconfig
+++ b/net/Kconfig
@@ -252,6 +252,7 @@ source "net/bridge/netfilter/Kconfig"
 endif # if NETFILTER
 
 source "net/sctp/Kconfig"
+source "net/homa/Kconfig"
 source "net/rds/Kconfig"
 source "net/tipc/Kconfig"
 source "net/atm/Kconfig"
diff --git a/net/Makefile b/net/Makefile
index 5b2dd7f07a85e..f9a3c966a83b2 100644
--- a/net/Makefile
+++ b/net/Makefile
@@ -40,6 +40,7 @@ ifneq ($(CONFIG_VLAN_8021Q),)
 obj-y				+= 8021q/
 endif
 obj-$(CONFIG_IP_SCTP)		+= sctp/
+obj-$(CONFIG_HOMA)		+= homa/
 obj-$(CONFIG_RDS)		+= rds/
 obj-$(CONFIG_WIRELESS)		+= wireless/
 obj-$(CONFIG_MAC80211)		+= mac80211/
diff --git a/net/homa/Kconfig b/net/homa/Kconfig
new file mode 100644
index 0000000000000..a420ea18b6c19
--- /dev/null
+++ b/net/homa/Kconfig
@@ -0,0 +1,20 @@
+# SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+#
+# Homa transport protocol
+#
+
+config HOMA
+	tristate "The Homa transport protocol"
+	depends on IPV6
+
+	help
+	  Homa is a network transport protocol for communication within
+	  a datacenter. It provides significantly lower latency than TCP,
+	  particularly for workloads containing a mixture of large and small
+	  messages operating at high network utilization. At present, Homa
+	  has been only partially upstreamed; this version provides bare-bones
+	  functionality but is not performant. For more information see the
+	  homa(7) man page or checkout the Homa Wiki at
+	  https://homa-transport.atlassian.net/wiki/spaces/HOMA/overview.
+
+	  If unsure, say N.
diff --git a/net/homa/Makefile b/net/homa/Makefile
new file mode 100644
index 0000000000000..b36e7fca19b59
--- /dev/null
+++ b/net/homa/Makefile
@@ -0,0 +1,16 @@
+# SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+#
+# Makefile for the Linux implementation of the Homa transport protocol.
+
+obj-$(CONFIG_HOMA) += homa.o
+homa-y:=        homa_incoming.o \
+		homa_interest.o \
+		homa_outgoing.o \
+		homa_peer.o \
+		homa_plumbing.o \
+		homa_pool.o \
+		homa_rpc.o \
+		homa_sock.o \
+		homa_timer.o \
+		homa_tx_pool.o \
+		homa_utils.o
diff --git a/net/homa/homa_impl.h b/net/homa/homa_impl.h
new file mode 100644
index 0000000000000..6172902e5d8c5
--- /dev/null
+++ b/net/homa/homa_impl.h
@@ -0,0 +1,593 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file contains definitions that are shared across the files
+ * that implement Homa for Linux.
+ */
+
+#ifndef _HOMA_IMPL_H
+#define _HOMA_IMPL_H
+
+#include <linux/bug.h>
+
+#include <linux/audit.h>
+#include <linux/icmp.h>
+#include <linux/init.h>
+#include <linux/list.h>
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/kthread.h>
+#include <linux/completion.h>
+#include <linux/proc_fs.h>
+#include <linux/sched/signal.h>
+#include <linux/skbuff.h>
+#include <linux/socket.h>
+#include <linux/vmalloc.h>
+#include <net/icmp.h>
+#include <net/ip.h>
+#include <net/netns/generic.h>
+#include <net/protocol.h>
+#include <net/inet_common.h>
+#include <net/gro.h>
+#include <net/rps.h>
+
+#include <linux/homa.h>
+#include "homa_wire.h"
+
+/* Forward declarations. */
+struct homa;
+struct homa_peer;
+struct homa_rpc;
+struct homa_route;
+struct homa_sock;
+
+/**
+ * union sockaddr_in_union - Holds either an IPv4 or IPv6 address (smaller
+ * and easier to use than sockaddr_storage).
+ */
+union sockaddr_in_union {
+	/** @sa: Used to access as a generic sockaddr. */
+	struct sockaddr sa;
+
+	/** @in4: Used to access as IPv4 socket. */
+	struct sockaddr_in in4;
+
+	/** @in6: Used to access as IPv6 socket.  */
+	struct sockaddr_in6 in6;
+};
+
+/**
+ * struct homa - Stores overall information about the Homa transport, which
+ * is shared across all Homa sockets and all network namespaces.
+ */
+struct homa {
+	/**
+	 * @next_outgoing_id: Id to use for next outgoing RPC request.
+	 * This is always even: it's used only to generate client-side ids.
+	 * Accessed without locks. Note: RPC ids are unique within a
+	 * single client machine.
+	 */
+	atomic64_t next_outgoing_id;
+
+	/**
+	 * @peertab: Info about all the other hosts we have communicated with;
+	 * includes peers from all network namespaces.
+	 */
+	struct homa_peertab *peertab;
+
+	/**
+	 * @socktab: Information about all open sockets. Dynamically
+	 * allocated; must be kfreed.
+	 */
+	struct homa_socktab *socktab;
+
+	/**
+	 * @tx_pools: One tx_page_pool for each NUMA node on the machine.
+	 * If there are no cores for a node, then its value is NULL.
+	 */
+	struct homa_tx_pool *tx_pools[MAX_NUMNODES];
+
+	/** @max_numa: Highest NUMA node id in use by any core. */
+	int max_numa;
+
+	/**
+	 * @tx_page_frees_per_sec: Rate at which to return pages from
+	 * homa_tx_page_pools back to Linux. This is the total rate across
+	 * all pools. Set externally via sysctl.
+	 */
+	int tx_page_frees_per_sec;
+
+	/**
+	 * @tx_pages_to_free: Space in which to collect pages that are
+	 * about to be released. Dynamically allocated.
+	 */
+	struct page **tx_pages_to_free;
+
+	/**
+	 * @tx_pages_to_free_slots: Maximum number of pages that can be
+	 * stored in tx_pages_to_free;
+	 */
+	int tx_pages_to_free_slots;
+
+	/**
+	 * @tx_page_free_time: homa_clock() time when the next tx
+	 * page should be freed. Could be in the past.
+	 */
+	u64 tx_page_free_time;
+
+	/**
+	 * @tx_page_pool_min_kb: A floor on the amount of space for Homa to
+	 * retain in a pool, specified in Kbytes. Set externally via
+	 * sysctl.
+	 */
+	int tx_page_pool_min_kb;
+
+	/**
+	 * @link_mbps: The raw bandwidth of the network uplink, in
+	 * units of 1e06 bits per second.  Set externally via sysctl.
+	 */
+	int link_mbps;
+
+	/**
+	 * @resend_ticks: When an RPC's @silent_ticks reaches this value,
+	 * start sending RESEND requests.
+	 */
+	int resend_ticks;
+
+	/**
+	 * @resend_interval: minimum number of homa timer ticks between
+	 * RESENDs for the same RPC.
+	 */
+	int resend_interval;
+
+	/**
+	 * @timeout_ticks: abort an RPC if its silent_ticks reaches this value.
+	 */
+	int timeout_ticks;
+
+	/**
+	 * @timeout_resends: Assume that a server is dead if it has not
+	 * responded after this many RESENDs have been sent to it.
+	 */
+	int timeout_resends;
+
+	/**
+	 * @request_ack_ticks: How many timer ticks we'll wait for the
+	 * client to ack an RPC before explicitly requesting an ack.
+	 * Set externally via sysctl.
+	 */
+	int request_ack_ticks;
+
+	/**
+	 * @dead_frags_limit: If hsk->dead_frags is less than this number
+	 * for a socket, then Homa reaps RPCs in a way that minimizes impact
+	 * on performance but may permit dead RPCs to accumulate. If
+	 * dead_frags exceeds this value, then Homa switches to a more
+	 * aggressive approach to reaping RPCs. Set externally via sysctl.
+	 */
+	int dead_frags_limit;
+
+	/**
+	 * @max_dead_frags: The largest value of hsk->dead_frags that has
+	 * existed so far for any socket.  Readable via sysctl, and may be
+	 * reset via sysctl to begin recalculating.
+	 */
+	int max_dead_frags;
+
+	/**
+	 * @max_gso_size: Maximum number of bytes that will be included
+	 * in a single output packet that Homa passes to Linux. Can be set
+	 * externally via sysctl to lower the limit already enforced by Linux.
+	 */
+	int max_gso_size;
+
+	/**
+	 * @wmem_max: Limit on the value of sk_sndbuf for any socket. Set
+	 * externally via sysctl.
+	 */
+	int wmem_max;
+
+	/**
+	 * @timer_ticks: number of times that homa_timer has been invoked
+	 * (may wraparound, which is safe).
+	 */
+	u32 timer_ticks;
+
+	/**
+	 * @bpage_lease_usecs: how long a core can own a bpage (microseconds)
+	 * before its ownership can be revoked to reclaim the page.
+	 */
+	int bpage_lease_usecs;
+
+	/**
+	 * @bpage_lease_cycles: same as bpage_lease_usecs except in
+	 * homa_clock() units.
+	 */
+	int bpage_lease_cycles;
+
+	/**
+	 * @next_id: Set via sysctl; causes next_outgoing_id to be set to
+	 * this value; always reads as zero. Typically used while debugging to
+	 * ensure that different nodes use different ranges of ids.
+	 */
+	int next_id;
+
+	/**
+	 * @destroyed: True means that this structure is being destroyed
+	 * so everyone should clean up.
+	 */
+	bool destroyed;
+
+};
+
+/**
+ * struct homa_net - Contains Homa information that is specific to a
+ * particular network namespace.
+ */
+struct homa_net {
+	/** @homa: Global Homa information. */
+	struct homa *homa;
+
+	/**
+	 * @prev_default_port: The most recent port number assigned from
+	 * the range of default ports.
+	 */
+	u16 prev_default_port;
+
+	/**
+	 * @num_routes: The total number of struct homa_peers that exist
+	 * for this namespace. Managed by homa_peer.c under the peertab lock.
+	 */
+	int num_routes;
+};
+
+/**
+ * struct homa_skb_info - Additional information needed by Homa for each
+ * outbound DATA packet. Space is allocated for this at the very end of the
+ * linear part of the skb.
+ */
+struct homa_skb_info {
+	/**
+	 * @data_bytes: total bytes of message data across all of the
+	 * segments in this packet.
+	 */
+	int data_bytes;
+
+	/**
+	 * @dont_defer: True means that homa_qdisc_enqueue should pass this
+	 * packet along without considering NIC congestion. This flag is set
+	 * by the pacer when it retransmits packets after deferral.
+	 */
+	bool dont_defer;
+};
+
+/**
+ * homa_get_skb_info() - Return the address of Homa's private information
+ * for an sk_buff.
+ * @skb:     Socket buffer whose info is needed.
+ * Return: address of Homa's private information for @skb.
+ */
+static inline struct homa_skb_info *homa_get_skb_info(struct sk_buff *skb)
+{
+	return (struct homa_skb_info *)(skb_end_pointer(skb)) - 1;
+}
+
+/**
+ * homa_set_doff() - Fills in the doff TCP header field for a packet.
+ * @skb:   Packet whose doff field is to be set.
+ * @size:  Size of the "header" in bytes (must be a multiple of 4). This is
+ *         needed for two reasons. First, for TSO to work it must indicate
+ *         the number of bytes that should be replicated in each segment.
+ *         The bytes after this will be distributed among segments. Second,
+ *         for TCP hijacking to work it must have a valid value (20 is a
+ *         good choice if the packet isn't a TSO frame).
+ */
+static inline void homa_set_doff(struct sk_buff *skb, int size)
+{
+	tcp_hdr(skb)->doff = size >> 2;
+}
+
+/** skb_is_ipv6() - Return true if the packet is encapsulated with IPv6,
+ *  false otherwise (presumably it's IPv4).
+ */
+static inline bool skb_is_ipv6(const struct sk_buff *skb)
+{
+	return ipv6_hdr(skb)->version == 6;
+}
+
+/**
+ * ipv6_to_ipv4() - Given an IPv6 address produced by ipv4_to_ipv6, return
+ * the original IPv4 address (in network byte order).
+ * @ip6:  IPv6 address; assumed to be a mapped IPv4 address.
+ * Return: IPv4 address stored in @ip6.
+ */
+static inline __be32 ipv6_to_ipv4(const struct in6_addr ip6)
+{
+	return ip6.in6_u.u6_addr32[3];
+}
+
+/**
+ * canonical_ipv6_addr() - Convert a socket address to the "standard"
+ * form used in Homa, which is always an IPv6 address; if the original address
+ * was IPv4, convert it to an IPv4-mapped IPv6 address.
+ * @addr:   Address to canonicalize (if NULL, "any" is returned).
+ * Return: IPv6 address corresponding to @addr.
+ */
+static inline struct in6_addr canonical_ipv6_addr(const union sockaddr_in_union
+						  *addr)
+{
+	struct in6_addr mapped;
+
+	if (addr) {
+		if (addr->sa.sa_family == AF_INET6)
+			return addr->in6.sin6_addr;
+		ipv6_addr_set_v4mapped(addr->in4.sin_addr.s_addr, &mapped);
+		return mapped;
+	}
+	return in6addr_any;
+}
+
+/**
+ * skb_canonical_ipv6_saddr() - Given a packet buffer, return its source
+ * address in the "standard" form used in Homa, which is always an IPv6
+ * address; if the original address was IPv4, convert it to an IPv4-mapped
+ * IPv6 address.
+ * @skb:   The source address will be extracted from this packet buffer.
+ * Return: IPv6 address for @skb's source machine.
+ */
+static inline struct in6_addr skb_canonical_ipv6_saddr(struct sk_buff *skb)
+{
+	struct in6_addr mapped;
+
+	if (skb_is_ipv6(skb))
+		return ipv6_hdr(skb)->saddr;
+	ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr, &mapped);
+	return mapped;
+}
+
+/**
+ * homa_make_header_avl() - Invokes pskb_may_pull to make sure that all the
+ * Homa header information for a packet is in the linear part of the skb
+ * where it can be addressed using skb_transport_header.
+ * @skb:     Packet for which header is needed.
+ * Return:   The result of pskb_may_pull (true for success)
+ */
+static inline bool homa_make_header_avl(struct sk_buff *skb)
+{
+	int pull_length;
+
+	pull_length = skb_transport_header(skb) - skb->data + HOMA_MAX_HEADER;
+	if (pull_length > skb->len)
+		pull_length = skb->len;
+	return pskb_may_pull(skb, pull_length);
+}
+
+extern unsigned int homa_net_id;
+
+void     homa_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,
+		      struct homa_rpc *rpc);
+enum skb_drop_reason homa_add_packet(struct homa_rpc *rpc, struct sk_buff *skb);
+int      homa_bind(struct socket *sk, struct sockaddr_unsized *addr,
+		   int addr_len);
+void     homa_close(struct sock *sock, long timeout);
+int      homa_copy_to_user(struct homa_rpc *rpc);
+void     homa_data_pkt(struct sk_buff *skb, struct homa_rpc *rpc);
+void     homa_destroy(struct homa *homa);
+void     homa_dispatch_pkts(struct sk_buff *skb);
+int      homa_err_handler_v4(struct sk_buff *skb, u32 info);
+int      homa_err_handler_v6(struct sk_buff *skb,
+			     struct inet6_skb_parm *opt, u8 type,  u8 code,
+			     int offset, __be32 info);
+struct homa_gap *homa_gap_alloc(struct list_head *next, int start, int end);
+int      homa_getsockopt(struct sock *sk, int level, int optname,
+			 char __user *optval, int __user *optlen);
+int      homa_hash(struct sock *sk);
+enum hrtimer_restart homa_hrtimer(struct hrtimer *timer);
+int      homa_init(struct homa *homa);
+int      homa_ioc_info(struct socket *sock, unsigned long arg);
+int      homa_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg);
+int      homa_load(void);
+void     homa_message_out_init(struct homa_rpc *rpc, int length);
+void     homa_need_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,
+			   struct homa_rpc *rpc);
+void     homa_net_destroy(struct homa_net *hnet);
+void     homa_net_exit(struct net *net);
+int      homa_net_init(struct homa_net *hnet, struct homa *homa);
+int      homa_net_start(struct net *net);
+__poll_t homa_poll(struct file *file, struct socket *sock,
+		   struct poll_table_struct *wait);
+int      homa_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
+		      int flags);
+void     homa_request_retrans(struct homa_rpc *rpc);
+int      homa_resend_data(struct homa_rpc *rpc, int start, int end);
+void     homa_resend_pkt(struct sk_buff *skb, struct homa_rpc *rpc,
+			 struct homa_sock *hsk);
+void     homa_rpc_handoff(struct homa_rpc *rpc);
+int      homa_rpc_tx_end(struct homa_rpc *rpc);
+int      homa_sendmsg(struct sock *sk, struct msghdr *msg, size_t len);
+int      homa_setsockopt(struct sock *sk, int level, int optname,
+			 sockptr_t optval, unsigned int optlen);
+int      homa_shutdown(struct socket *sock, int how);
+struct sk_buff *__homa_skb_alloc(int length);
+int      homa_socket(struct sock *sk);
+int      homa_softirq(struct sk_buff *skb);
+void     homa_spin(int ns);
+void     homa_timer(struct homa *homa);
+void     homa_timer_check_rpc(struct homa_rpc *rpc);
+int      homa_timer_main(void *transport);
+int      homa_tx_copy_from_user(struct homa_rpc *rpc, struct iov_iter *iter,
+				bool xmit);
+struct sk_buff *homa_tx_skb_alloc(struct homa_rpc *rpc, u32 offset, u32 *end);
+int      homa_tx_skb_send(struct homa_rpc *rpc, u32 offset, u32 *end);
+void     homa_unhash(struct sock *sk);
+void     homa_rpc_unknown_pkt(struct sk_buff *skb, struct homa_rpc *rpc);
+void     homa_unload(void);
+int      homa_wait_private(struct homa_rpc *rpc, int nonblocking);
+struct homa_rpc *homa_wait_shared(struct homa_sock *hsk, int nonblocking);
+int      homa_xmit_control(enum homa_packet_type type, void *contents,
+			   size_t length, struct homa_rpc *rpc);
+int      __homa_xmit_control(void *contents, size_t length,
+			     struct homa_route *route, struct homa_sock *hsk);
+void     homa_xmit_data(struct homa_rpc *rpc);
+void     homa_xmit_unknown(struct sk_buff *skb, struct homa_sock *hsk);
+
+int      homa_message_in_init(struct homa_rpc *rpc, int length);
+
+/**
+ * homa_net() - Return the struct homa_net associated with a particular
+ * struct net.
+ * @net:     Get the Homa data for this net namespace.
+ * Return:   see above.
+ */
+static inline struct homa_net *homa_net(struct net *net)
+{
+	return (struct homa_net *)net_generic(net, homa_net_id);
+}
+
+/**
+ * homa_clock() - Return a fine-grain clock value that is monotonic and
+ * consistent across cores.
+ * Return: see above.
+ */
+static inline u64 homa_clock(void)
+{
+	/* This function exists to make it easy to switch time sources
+	 * if/when new or better sources become available.
+	 */
+	return ktime_get_ns();
+}
+
+/**
+ * homa_clock_khz() - Return the frequency of the values returned by
+ * homa_clock, in units of KHz.
+ * Return: see above.
+ */
+static inline u64 homa_clock_khz(void)
+{
+	return 1000000;
+}
+
+/**
+ * homa_ns_to_cycles() - Convert from units of nanoseconds to units of
+ * homa_clock().
+ * @ns:      A time measurement in nanoseconds
+ * Return:   The time in homa_clock() units corresponding to @ns.
+ */
+static inline u64 homa_ns_to_cycles(u64 ns)
+{
+	u64 tmp;
+
+	tmp = ns * homa_clock_khz();
+	do_div(tmp, 1000000);
+	return tmp;
+}
+
+/* Homa Locking Strategy:
+ *
+ * (Note: this documentation is referenced in several other places in the
+ * Homa code)
+ *
+ * In the Linux TCP/IP stack the primary locking mechanism is a sleep-lock
+ * per socket. However, per-socket locks aren't adequate for Homa, because
+ * sockets are "larger" in Homa. In TCP, a socket corresponds to a single
+ * connection between two peers; an application can have hundreds or
+ * thousands of sockets open at once, so per-socket locks leave lots of
+ * opportunities for concurrency. With Homa, a single socket can be used for
+ * communicating with any number of peers, so there will typically be just
+ * one socket per thread. As a result, a single Homa socket must support many
+ * concurrent RPCs efficiently, and a per-socket lock would create a bottleneck
+ * (Homa tried this approach initially).
+ *
+ * Thus, the primary locks used in Homa spinlocks at RPC granularity. This
+ * allows operations on different RPCs for the same socket to proceed
+ * concurrently. Homa also has socket locks (which are spinlocks different
+ * from the official socket sleep-locks) but these are used much less
+ * frequently than RPC locks.
+ *
+ * Lock Ordering:
+ *
+ * There are several other locks in Homa besides RPC locks, all of which
+ * are spinlocks. When multiple locks are held, they must be acquired in a
+ * consistent order in order to prevent deadlock. Here are the rules for Homa:
+ * 1. Except for RPC locks, socket locks, and the grant lock, all locks
+ *    should be considered "leaf" locks: don't acquire other locks while
+ *    holding them.
+ * 2. The lock order is:
+ *    * Grant lock
+ *    * RPC lock
+ *    * Socket lock
+ *    * Other lock
+ *
+ * It may seem surprising that RPC locks are acquired *before* socket locks,
+ * but this is essential for high performance. Homa has been designed so that
+ * many common operations (such as processing input packets) can be performed
+ * while holding only an RPC lock; this allows operations on different RPCs
+ * to proceed in parallel. Only a few operations, such as handing off an
+ * incoming message to a waiting thread, require the socket lock. If socket
+ * locks had to be acquired first, any operation that might eventually need
+ * the socket lock would have to acquire it before the RPC lock, which would
+ * severely restrict concurrency.
+ *
+ * Socket Shutdown:
+ *
+ * It is possible for socket shutdown to begin while operations are underway
+ * that hold RPC locks but not the socket lock. For example, a new RPC
+ * creation might be underway when a socket is shut down. The RPC creation
+ * will eventually acquire the socket lock and add the new RPC to those
+ * for the socket; it would be very bad if this were to happen after
+ * homa_sock_shutdown thinks it has deleted all RPCs for the socket.
+ * In general, any operation that acquires a socket lock must check
+ * hsk->shutdown after acquiring the lock and abort if hsk->shutdown is set.
+ *
+ * Spinlock Implications:
+ *
+ * Homa uses spinlocks exclusively; this is needed because locks typically
+ * need to be acquired at atomic level, such as in SoftIRQ code.
+ *
+ * Operations that can block, such as memory allocation and copying data
+ * to/from user space, are not permitted while holding spinlocks (spinlocks
+ * disable interrupts, so the holder must not block. This results in awkward
+ * code in several places to move restricted operations outside locked
+ * regions. Such code typically looks like this:
+ *   - Acquire a reference on an object such as an RPC, in order to prevent
+ *     the object from being deleted.
+ *   - Release the object's lock.
+ *   - Perform the restricted operation.
+ *   - Re-acquire the lock.
+ *   - Release the reference.
+ * It is possible that the object may have been modified by some other party
+ * while it was unlocked, so additional checks may be needed after reacquiring
+ * the lock. As one example, an RPC may have been terminated, in which case
+ * any operation in progress on that RPC should be aborted after reacquiring
+ * the lock.
+ *
+ * Lists of RPCs:
+ *
+ * There are a few places where Homa needs to process all of the RPCs
+ * associated with a socket, such as the timer. Such code must first lock
+ * the socket (to protect access to the link pointers) then lock
+ * individual RPCs on the list. However, this violates the rules for locking
+ * order. It isn't safe to unlock the socket before locking the individual RPCs,
+ * because RPCs could be deleted and their memory recycled between the unlock
+ * of the socket lock and the lock of the RPC; this could result in corruption.
+ * Homa uses two different approaches to handle this situation:
+ * 1. Use ``homa_protect_rpcs`` to prevent RPC reaping for a socket. RPCs can
+ *    still be terminated, but their memory won't go away until
+ *    homa_unprotect_rpcs is invoked. This allows the socket lock to be
+ *    released before acquiring RPC locks; after acquiring each RPC lock,
+ *    the RPC must be checked to see if it has been terminated; if so, skip it.
+ * 2. Use ``spin_trylock_bh`` to acquire the RPC lock while still holding the
+ *    socket lock. If this fails, then release the socket lock and retry
+ *    both the socket lock and the RPC lock. Of course, the state of both
+ *    socket and RPC could change before the locks are finally acquired.
+ *
+ * Locks and Packet Transmission:
+ *
+ * Homa must not hold locks while transmitting packets (e.g. by calling
+ * ip_queue_xmit or ip6_xmit). This is because homa_qdisc could be invoked
+ * during the transmission process, and it may need to acquire locks under
+ * some conditions (such as an RPC lock). Homa_qdisc is invoked with the
+ * qdisc lock held, so invoking ip*xmit with a lock held can result in
+ * AB-BA deadlocks.
+ */
+
+#endif /* _HOMA_IMPL_H */
diff --git a/net/homa/homa_incoming.c b/net/homa/homa_incoming.c
new file mode 100644
index 0000000000000..d85dd325de4d1
--- /dev/null
+++ b/net/homa/homa_incoming.c
@@ -0,0 +1,886 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file contains functions that handle incoming Homa messages. */
+
+#include "homa_impl.h"
+#include "homa_interest.h"
+#include "homa_peer.h"
+#include "homa_pool.h"
+
+/**
+ * homa_message_in_init() - Constructor for homa_message_in.
+ * @rpc:          RPC whose msgin structure should be initialized. The
+ *                msgin struct is assumed to be zeroes.
+ * @length:       Total number of bytes in message.
+ * Return:        Zero for successful initialization, or a negative errno
+ *                if rpc->msgin could not be initialized.
+ */
+int homa_message_in_init(struct homa_rpc *rpc, int length)
+	__must_hold(rpc->bucket->lock)
+{
+	int err;
+
+	if (((unsigned int)length) > HOMA_MAX_MESSAGE_LENGTH)
+		return -EINVAL;
+
+	rpc->msgin.length = length;
+	__skb_queue_head_init(&rpc->msgin.packets);
+	INIT_LIST_HEAD(&rpc->msgin.gaps);
+	rpc->msgin.bytes_remaining = length;
+	err = homa_pool_alloc_msg(rpc);
+	if (err != 0) {
+		rpc->msgin.length = -1;
+		return err;
+	}
+	return 0;
+}
+
+/**
+ * homa_gap_alloc() - Allocate a new gap and add it to a gap list.
+ * @next:   Add the new gap just before this list element.
+ * @start:  Offset of first byte covered by the gap.
+ * @end:    Offset of byte just after the last one covered by the gap.
+ * Return:  Pointer to the new gap, or NULL if memory couldn't be allocated
+ *          for the gap object.
+ */
+struct homa_gap *homa_gap_alloc(struct list_head *next, int start, int end)
+{
+	struct homa_gap *gap;
+
+	gap = kmalloc_obj(*gap, GFP_ATOMIC);
+	if (!gap)
+		return NULL;
+	gap->start = start;
+	gap->end = end;
+	gap->time = homa_clock();
+	list_add_tail(&gap->links, next);
+	return gap;
+}
+
+/**
+ * homa_request_retrans() - The function is invoked when it appears that
+ * data packets for a message have been lost. It issues RESEND requests
+ * as appropriate and may modify the state of the RPC.
+ * @rpc:     RPC for which incoming data is delinquent; must be locked by
+ *           caller.
+ */
+void homa_request_retrans(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_resend_hdr *resends;
+	struct homa_resend_hdr resend;
+	struct homa_gap *gap;
+	int offset, length;
+	int num_gaps, i;
+
+	if (rpc->msgin.length >= 0) {
+		/* Issue RESENDS for any gaps in incoming data.  Must
+		 * pre-allocate space for all of the packet headers because
+		 * so we don't have to release the RPC lock while iterating
+		 * the gap list.
+		 */
+		num_gaps = list_count_nodes(&rpc->msgin.gaps);
+		resends = kzalloc_objs(*resends, num_gaps, GFP_ATOMIC);
+		if (!resends)
+			return;
+		i = 0;
+		list_for_each_entry(gap, &rpc->msgin.gaps, links) {
+			resends[i].offset = htonl(gap->start);
+			resends[i].length = htonl(gap->end - gap->start);
+			i++;
+		}
+		for (i = 0; i < num_gaps; i++)
+			homa_xmit_control(RESEND, &resends[i],
+					  sizeof(resends[i]), rpc);
+		kfree(resends);
+
+		/* Issue a RESEND for any granted data after the last gap. */
+		offset = rpc->msgin.recv_end;
+		length = rpc->msgin.length - rpc->msgin.recv_end;
+		if (length <= 0)
+			return;
+	} else {
+		/* No data has been received for the RPC. Ask the sender to
+		 * resend everything it has sent so far.
+		 */
+		offset = 0;
+		length = -1;
+	}
+
+	memset(&resend, 0, sizeof(resend));
+	resend.offset = htonl(offset);
+	resend.length = htonl(length);
+	homa_xmit_control(RESEND, &resend, sizeof(resend), rpc);
+}
+
+/**
+ * homa_add_packet() - Add an incoming packet to the contents of a
+ * partially received message.
+ * @rpc:   Add the packet to the msgin for this RPC.
+ * @skb:   The new packet. If the packet is linked into rpc then an additional
+ *         reference will be taken on it.
+ * Return: 0 if the packet was successfully linked into rpc, otherwise the
+ *         reason why the packet was not linked in.
+ */
+enum skb_drop_reason homa_add_packet(struct homa_rpc *rpc, struct sk_buff *skb)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_data_hdr *h = (struct homa_data_hdr *)skb->data;
+	struct homa_gap *gap, *dummy, *gap2;
+	u32 start = ntohl(h->seg.offset);
+	u32 length = homa_data_len(skb);
+	enum skb_drop_reason reason = 0;
+	u32 end = start + length;
+
+	if (start >= rpc->msgin.length ||
+	    length > (rpc->msgin.length - start)) {
+		reason = SKB_DROP_REASON_PKT_TOO_BIG;
+		goto ignore;
+	}
+
+	if (start == rpc->msgin.recv_end) {
+		/* Common case: packet is sequential. */
+		rpc->msgin.recv_end += length;
+		goto keep;
+	}
+
+	if (start > rpc->msgin.recv_end) {
+		/* Packet creates a new gap. */
+		if (!homa_gap_alloc(&rpc->msgin.gaps,
+				    rpc->msgin.recv_end, start)) {
+			reason = SKB_DROP_REASON_NOMEM;
+			goto ignore;
+		}
+		rpc->msgin.recv_end = end;
+		goto keep;
+	}
+
+	/* Must now check to see if the packet fills in part or all of
+	 * an existing gap.
+	 */
+	list_for_each_entry_safe(gap, dummy, &rpc->msgin.gaps, links) {
+		/* Is packet at the start of this gap? */
+		if (start <= gap->start) {
+			if (end <= gap->start)
+				continue;
+			if (start < gap->start) {
+				reason = SKB_DROP_REASON_DUP_FRAG;
+				goto ignore;
+			}
+			if (end > gap->end) {
+				reason = SKB_DROP_REASON_DUP_FRAG;
+				goto ignore;
+			}
+			gap->start = end;
+			if (gap->start >= gap->end) {
+				list_del(&gap->links);
+				kfree(gap);
+			}
+			goto keep;
+		}
+
+		/* Is packet at the end of this gap? BTW, at this point we know
+		 * the packet can't cover the entire gap.
+		 */
+		if (end >= gap->end) {
+			if (start >= gap->end)
+				continue;
+			if (end > gap->end) {
+				reason = SKB_DROP_REASON_DUP_FRAG;
+				goto ignore;
+			}
+			gap->end = start;
+			goto keep;
+		}
+
+		/* Packet is in the middle of the gap; must split the gap. */
+		gap2 = homa_gap_alloc(&gap->links, gap->start, start);
+		if (!gap2) {
+			reason = SKB_DROP_REASON_NOMEM;
+			goto ignore;
+		}
+		gap2->time = gap->time;
+		gap->start = end;
+		goto keep;
+	}
+	/* Packet doesn't overlap any gap, so it is a duplicate. */
+	reason = SKB_DROP_REASON_DUP_FRAG;
+
+ignore:
+	return reason;
+
+keep:
+	__skb_queue_tail(&rpc->msgin.packets, skb);
+	skb_get(skb);
+	rpc->msgin.bytes_remaining -= length;
+	return 0;
+}
+
+/**
+ * homa_copy_to_user() - Copy as much data as possible from incoming
+ * packet buffers to buffers in user space.
+ * @rpc:     RPC for which data should be copied. Must be locked by caller.
+ * Return:   Zero for success or a negative errno if there is an error.
+ *           It is possible for the RPC to be freed while this function
+ *           executes (it releases and reacquires the RPC lock). If that
+ *           happens, -EINVAL will be returned and the state of @rpc
+ *           will be RPC_DEAD. Clears the RPC_PKTS_READY bit in @rpc->flags
+ *           if all available packets have been copied out.
+ */
+int homa_copy_to_user(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+#define MAX_SKBS 20
+	struct sk_buff *skbs[MAX_SKBS];
+	int error = 0;
+	int n = 0;             /* Number of filled entries in skbs. */
+	int i;
+
+	/* Tricky note: we can't hold the RPC lock while we're actually
+	 * copying to user space, because (a) it's illegal to hold a spinlock
+	 * while copying to user space and (b) we'd like for homa_softirq
+	 * to add more packets to the RPC while we're copying these out.
+	 * So, collect a bunch of packets to copy, then release the lock,
+	 * copy them, and reacquire the lock.
+	 */
+	while (true) {
+		struct sk_buff *skb;
+
+		if (rpc->state == RPC_DEAD) {
+			error = -EINVAL;
+			break;
+		}
+
+		skb = __skb_dequeue(&rpc->msgin.packets);
+		if (skb) {
+			skbs[n] = skb;
+			n++;
+			if (n < MAX_SKBS)
+				continue;
+		}
+		if (n == 0) {
+			clear_bit(RPC_PKTS_READY, &rpc->flags);
+			break;
+		}
+
+		/* At this point we've collected a batch of packets (or
+		 * run out of packets); copy any available packets out to
+		 * user space.
+		 */
+		homa_rpc_unlock(rpc);
+
+		/* Each iteration of this loop copies out one skb. */
+		for (i = 0; i < n; i++) {
+			struct homa_data_hdr *h = (struct homa_data_hdr *)
+					skbs[i]->data;
+			int pkt_length = homa_data_len(skbs[i]);
+			int offset = ntohl(h->seg.offset);
+			int buf_bytes, chunk_size;
+			struct iov_iter iter;
+			int copied = 0;
+			char __user *dst;
+
+			/* Each iteration of this loop copies to one
+			 * user buffer.
+			 */
+			while (copied < pkt_length) {
+				chunk_size = pkt_length - copied;
+				dst = homa_pool_get_buffer(rpc, offset + copied,
+							   &buf_bytes);
+				if (buf_bytes < chunk_size) {
+					if (buf_bytes == 0) {
+						/* skb has data beyond message
+						 * end?
+						 */
+						break;
+					}
+					chunk_size = buf_bytes;
+				}
+				error = import_ubuf(READ, dst, chunk_size,
+						    &iter);
+				if (error)
+					goto free_skbs;
+				error = skb_copy_datagram_iter(skbs[i],
+							       sizeof(*h) +
+							       copied,  &iter,
+							       chunk_size);
+				if (error)
+					goto free_skbs;
+				copied += chunk_size;
+			}
+		}
+
+free_skbs:
+		for (i = 0; i < n; i++)
+			consume_skb(skbs[i]);
+		n = 0;
+		homa_rpc_lock_preempt(rpc);
+		if (error)
+			break;
+	}
+	return error;
+}
+
+/**
+ * homa_dispatch_pkts() - Top-level function that processes a batch of packets,
+ * all related to the same RPC.
+ * @skb:       First packet in the batch, linked through skb->next.
+ */
+void homa_dispatch_pkts(struct sk_buff *skb)
+{
+	const struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);
+	struct homa_data_hdr *h = (struct homa_data_hdr *)skb->data;
+	u64 id = homa_local_id(h->common.sender_id);
+	int dport = ntohs(h->common.dport);
+	struct homa_rpc *rpc = NULL;
+	struct homa_sock *hsk;
+	struct homa_net *hnet;
+	struct sk_buff *next;
+
+	/* Find the appropriate socket.*/
+	hnet = homa_net(dev_net(skb->dev));
+	hsk = homa_sock_find(hnet, dport);
+	if (!hsk || (!homa_is_client(id) && !hsk->is_server)) {
+		if (skb_is_ipv6(skb))
+			icmp6_send(skb, ICMPV6_DEST_UNREACH,
+				   ICMPV6_PORT_UNREACH, 0, NULL, IP6CB(skb));
+		else
+			icmp_send(skb, ICMP_DEST_UNREACH,
+				  ICMP_PORT_UNREACH, 0);
+		while (skb) {
+			next = skb->next;
+			kfree_skb(skb);
+			skb = next;
+		}
+		if (hsk)
+			sock_put(&hsk->sock);
+		return;
+	}
+
+	/* Each iteration through the following loop processes one packet. */
+	for (; skb; skb = next) {
+		h = (struct homa_data_hdr *)skb->data;
+		next = skb->next;
+
+		/* Relinquish the RPC lock temporarily if it's needed
+		 * elsewhere.
+		 */
+		if (rpc) {
+			if (test_bit(APP_NEEDS_LOCK, &rpc->flags)) {
+				homa_rpc_unlock(rpc);
+
+				/* This short spin is needed to ensure that the
+				 * other thread gets the lock before this thread
+				 * grabs it again below (the need for this
+				 * was confirmed experimentally in 2/2025;
+				 * without it, the handoff fails 20-25% of the
+				 * time). Furthermore, the call to homa_spin
+				 * seems to allow the other thread to acquire
+				 * the lock more quickly.
+				 */
+				homa_spin(100);
+				homa_rpc_lock(rpc);
+			}
+		}
+
+		/* If we don't already have an RPC, find it, lock it,
+		 * and create a reference on it.
+		 */
+		if (!rpc) {
+			if (!homa_is_client(id)) {
+				/* We are the server for this RPC. */
+				if (h->common.type == DATA) {
+					/* Create a new RPC if one doesn't
+					 * already exist.
+					 */
+					rpc = homa_rpc_alloc_server(hsk, &saddr,
+								    h);
+					if (IS_ERR(rpc)) {
+						rpc = NULL;
+						goto discard;
+					}
+				} else {
+					rpc = homa_rpc_find_server(hsk, &saddr,
+								   id);
+				}
+			} else {
+				rpc = homa_rpc_find_client(hsk, id);
+			}
+			if (rpc)
+				homa_rpc_hold(rpc);
+		}
+		if (unlikely(!rpc)) {
+			if (h->common.type != NEED_ACK &&
+			    h->common.type != ACK &&
+			    h->common.type != RESEND)
+				goto discard;
+		} else {
+			if (h->common.type == DATA ||
+			    h->common.type == BUSY)
+				rpc->silent_ticks = 0;
+		}
+
+		switch (h->common.type) {
+		case DATA:
+			homa_data_pkt(skb, rpc);
+			break;
+		case RESEND:
+			homa_resend_pkt(skb, rpc, hsk);
+			break;
+		case RPC_UNKNOWN:
+			homa_rpc_unknown_pkt(skb, rpc);
+			break;
+		case BUSY:
+			/* Nothing to do for these packets except reset
+			 * silent_ticks, which happened above.
+			 */
+			goto discard;
+		case NEED_ACK:
+			homa_need_ack_pkt(skb, hsk, rpc);
+			break;
+		case ACK:
+			homa_ack_pkt(skb, hsk, rpc);
+			break;
+		default:
+			goto discard;
+		}
+		continue;
+
+discard:
+		kfree_skb(skb);
+	}
+	if (rpc) {
+		homa_rpc_put(rpc);
+		homa_rpc_unlock(rpc);
+	}
+
+	/* We need to reap dead RPCs here under two conditions:
+	 * 1. The socket has hit its limit on tx buffer space and threads are
+	 *    blocked waiting for skbs to be released.
+	 * 2. A large number of dead RPCs have accumulated, and it seems
+	 *    that the reaper isn't keeping up when invoked only at
+	 *    "convenient" times (see "RPC Reaping Strategy" in homa_rpc_reap
+	 *    code for details).
+	 */
+	if (hsk->dead_frags > 0) {
+		while (test_bit(HOMA_SOCK_NOSPACE, &hsk->flags) ||
+		       hsk->dead_frags >= 2 * hsk->homa->dead_frags_limit) {
+			int more;
+
+			more = homa_rpc_reap(hsk);
+			if (!more)
+				break;
+		}
+	}
+	sock_put(&hsk->sock);
+}
+
+/**
+ * homa_data_pkt() - Handler for incoming DATA packets
+ * @skb:     Incoming packet; size known to be large enough for the header.
+ *           This function now owns the packet.
+ * @rpc:     Information about the RPC corresponding to this packet.
+ *           Must be locked by the caller.
+ */
+void homa_data_pkt(struct sk_buff *skb, struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	enum skb_drop_reason drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
+	struct homa_data_hdr *h = (struct homa_data_hdr *)skb->data;
+
+	if (rpc->state != RPC_INCOMING && homa_is_client(rpc->id)) {
+		if (unlikely(rpc->state != RPC_OUTGOING))
+			goto handle_ack;
+		rpc->state = RPC_INCOMING;
+		if (homa_message_in_init(rpc, ntohl(h->message_length)) != 0) {
+			drop_reason = SKB_DROP_REASON_NOMEM;
+			goto handle_ack;
+		}
+	} else if (rpc->state != RPC_INCOMING) {
+		/* Must be server; note that homa_rpc_alloc_server already
+		 * initialized msgin and allocated buffers.
+		 */
+		if (unlikely(rpc->msgin.length >= 0))
+			goto handle_ack;
+	}
+
+	if (rpc->msgin.num_bpages == 0) {
+		/* Drop packets that arrive when we can't allocate buffer
+		 * space. If we keep them around, packet buffer usage can
+		 * exceed available cache space, resulting in poor
+		 * performance.
+		 */
+		drop_reason = SKB_DROP_REASON_NOMEM;
+		goto handle_ack;
+	}
+
+	drop_reason = homa_add_packet(rpc, skb);
+
+	if (skb_queue_len(&rpc->msgin.packets) != 0 &&
+	    !test_bit(RPC_PKTS_READY, &rpc->flags)) {
+		set_bit(RPC_PKTS_READY, &rpc->flags);
+		homa_rpc_handoff(rpc);
+	}
+
+handle_ack:
+	/* It's important to handle acks *after* calling homa_add_packet.
+	 * Otherwise we can end up with extraneous handoffs: we have to release
+	 * the RPC lock to handle acks, but that could allow some other thread
+	 * to receive a previous handoff made by homa_rpc_alloc_server, even
+	 * though the packet hasn't been added to the RPC. If this happens
+	 * the call to homa_rpc_handoff above will have to make an additional
+	 * handoff.
+	 */
+	if (h->ack.client_id) {
+		const struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);
+
+		homa_rpc_ack(rpc->hsk, rpc, &saddr, 1, &h->ack);
+	}
+	kfree_skb_reason(skb, drop_reason);
+}
+
+/**
+ * homa_resend_pkt() - Handler for incoming RESEND packets
+ * @skb:     Incoming packet; size already verified large enough for header.
+ *           This function now owns the packet.
+ * @rpc:     Information about the RPC corresponding to this packet; must
+ *           be locked by caller, but may be NULL if there is no RPC matching
+ *           this packet
+ * @hsk:     Socket on which the packet was received.
+ */
+void homa_resend_pkt(struct sk_buff *skb, struct homa_rpc *rpc,
+		     struct homa_sock *hsk)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_resend_hdr *h = (struct homa_resend_hdr *)skb->data;
+	int offset = ntohl(h->offset);
+	int length = ntohl(h->length);
+	int end = offset + length;
+	struct homa_busy_hdr busy;
+	int tx_end;
+
+	if (!rpc) {
+		homa_xmit_unknown(skb, hsk);
+		goto done;
+	}
+
+	tx_end = homa_rpc_tx_end(rpc);
+	if (!homa_is_client(rpc->id) && rpc->state != RPC_OUTGOING) {
+		/* We are the server for this RPC and don't yet have a
+		 * response message, so send BUSY to keep the client
+		 * waiting.
+		 */
+		homa_xmit_control(BUSY, &busy, sizeof(busy), rpc);
+		goto done;
+	}
+
+	if (length == -1)
+		end = tx_end;
+
+	/* Don't retransmit data that we haven't transmitted for the first
+	 * time: we're not ready to send that data yet (we'll send a BUSY
+	 * packet below if needed).
+	 */
+	homa_resend_data(rpc, offset, (end > tx_end) ? tx_end : end);
+	if (rpc->state == RPC_DEAD)
+		goto done;
+
+	if (offset >= tx_end) {
+		/* We have chosen not to transmit any of the requested data;
+		 * send BUSY so the receiver knows we are alive.
+		 */
+		homa_xmit_control(BUSY, &busy, sizeof(busy), rpc);
+		goto done;
+	}
+
+done:
+	consume_skb(skb);
+}
+
+/**
+ * homa_rpc_unknown_pkt() - Handler for incoming RPC_UNKNOWN packets.
+ * @skb:     Incoming packet; size known to be large enough for the header.
+ *           This function now owns the packet.
+ * @rpc:     Information about the RPC corresponding to this packet. Must
+ *           be locked by caller.
+ */
+void homa_rpc_unknown_pkt(struct sk_buff *skb, struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	if (homa_is_client(rpc->id)) {
+		if (rpc->state == RPC_OUTGOING) {
+			int tx_end = homa_rpc_tx_end(rpc);
+
+			/* It appears that everything we've already transmitted
+			 * has been lost; retransmit it.
+			 */
+			homa_resend_data(rpc, 0, tx_end);
+			goto done;
+		}
+	} else {
+		homa_rpc_end(rpc);
+	}
+done:
+	consume_skb(skb);
+}
+
+/**
+ * homa_need_ack_pkt() - Handler for incoming NEED_ACK packets
+ * @skb:     Incoming packet; size already verified large enough for header.
+ *           This function now owns the packet.
+ * @hsk:     Socket on which the packet was received.
+ * @rpc:     The RPC named in the packet header, or NULL if no such
+ *           RPC exists. The RPC must have been locked by the caller.
+ */
+void homa_need_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,
+		       struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_common_hdr *h = (struct homa_common_hdr *)skb->data;
+	const struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);
+	u64 id = homa_local_id(h->sender_id);
+	struct homa_route *route;
+	struct homa_ack_hdr ack;
+
+	/* Don't ack if it's not safe for the peer to purge its state
+	 * for this RPC (the RPC still exists and we haven't received
+	 * the entire response), or if we can't find peer info.
+	 */
+	if (rpc && (rpc->state != RPC_INCOMING ||
+		    rpc->msgin.bytes_remaining)) {
+		homa_request_retrans(rpc);
+		goto done;
+	}
+	route = homa_route_get(hsk, &saddr);
+	if (IS_ERR(route))
+		goto done;
+
+	/* Send an ACK for this RPC. At the same time, include all of the
+	 * other acks available for the peer. Note: can't use rpc below,
+	 * since it may be NULL.
+	 */
+	memset(&ack, 0, sizeof(ack));
+	ack.common.type = ACK;
+	ack.common.sport = h->dport;
+	ack.common.dport = h->sport;
+	ack.common.sender_id = cpu_to_be64(id);
+	ack.num_acks = htons(homa_peer_get_acks(route->peer,
+						HOMA_MAX_ACKS_PER_PKT,
+						ack.acks));
+	if (rpc)
+		homa_rpc_unlock(rpc);
+	__homa_xmit_control(&ack, sizeof(ack), route, hsk);
+	if (rpc)
+		homa_rpc_lock(rpc);
+	homa_route_release(route);
+
+done:
+	consume_skb(skb);
+}
+
+/**
+ * homa_ack_pkt() - Handler for incoming ACK packets
+ * @skb:     Incoming packet; size already verified large enough for header.
+ *           This function now owns the packet.
+ * @hsk:     Socket on which the packet was received.
+ * @rpc:     The RPC named in the packet header, or NULL if no such
+ *           RPC exists. The RPC must be locked by the caller.
+ */
+void homa_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,
+		  struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	const struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);
+	struct homa_ack_hdr *h = (struct homa_ack_hdr *)skb->data;
+	int count;
+
+	if (rpc)
+		homa_rpc_end(rpc);
+
+	count = ntohs(h->num_acks);
+	if (count > HOMA_MAX_ACKS_PER_PKT)
+		count = HOMA_MAX_ACKS_PER_PKT;
+	if (count > 0)
+		homa_rpc_ack(hsk, rpc, &saddr, count, h->acks);
+	consume_skb(skb);
+}
+
+/**
+ * homa_wait_private() - Waits until the response has been received for
+ * a specific RPC or the RPC has failed with an error.
+ * @rpc:          RPC to wait for; an error will be returned if the RPC is
+ *                not a client RPC or not private. Must be locked by caller.
+ * @nonblocking:  Nonzero means return immediately if @rpc not ready.
+ * Return:        0 means that @rpc is ready for attention: either its response
+ *                has been received or it has an unrecoverable error such as
+ *                ETIMEDOUT (in rpc->error). Nonzero means some other error
+ *                (such as EINTR or EINVAL) occurred before @rpc became ready
+ *                for attention; in this case the return value is a negative
+ *                errno.
+ */
+int homa_wait_private(struct homa_rpc *rpc, int nonblocking)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_interest interest;
+	int result;
+
+	if (!test_bit(RPC_PRIVATE, &rpc->flags))
+		return -EINVAL;
+
+	/* Each iteration through this loop waits until rpc needs attention
+	 * in some way (e.g. packets have arrived), then deals with that need
+	 * (e.g. copy to user space). It may take many iterations until the
+	 * RPC is ready for the application.
+	 */
+	while (1) {
+		result = 0;
+		if (!rpc->error)
+			rpc->error = homa_copy_to_user(rpc);
+		if (rpc->error)
+			break;
+		if (rpc->msgin.length >= 0 &&
+		    rpc->msgin.bytes_remaining == 0 &&
+		    skb_queue_len(&rpc->msgin.packets) == 0)
+			break;
+
+		if (nonblocking) {
+			result = -EAGAIN;
+			break;
+		}
+
+		result = homa_interest_init_private(&interest, rpc);
+		if (result != 0)
+			break;
+
+		homa_rpc_unlock(rpc);
+		result = homa_interest_wait(&interest);
+
+		homa_rpc_lock_preempt(rpc);
+		homa_interest_unlink_private(&interest);
+		if (result != 0)
+			break;
+	}
+
+	return result;
+}
+
+/**
+ * homa_wait_shared() - Wait for the completion of any non-private
+ * incoming message on a socket.
+ * @hsk:          Socket on which to wait. Must not be locked.
+ * @nonblocking:  Nonzero means return immediately if no RPC is ready.
+ *
+ * Return:    Pointer to an RPC with a complete incoming message or nonzero
+ *            error field, or a negative errno (usually -EINTR). If an RPC
+ *            is returned it will be locked and referenced; the caller
+ *            must release the lock and the reference.
+ */
+struct homa_rpc *homa_wait_shared(struct homa_sock *hsk, int nonblocking)
+	__cond_acquires(nonnull, rpc->bucket->lock)
+{
+	struct homa_interest interest;
+	struct homa_rpc *rpc;
+	int result;
+
+	/* Each iteration through this loop waits until an RPC needs attention
+	 * in some way (e.g. packets have arrived), then deals with that need
+	 * (e.g. copy to user space). It may take many iterations until an
+	 * RPC is ready for the application.
+	 */
+	while (1) {
+		homa_sock_lock(hsk);
+		if (hsk->shutdown) {
+			rpc = ERR_PTR(-ESHUTDOWN);
+			homa_sock_unlock(hsk);
+			goto done;
+		}
+		if (!list_empty(&hsk->ready_rpcs)) {
+			rpc = list_first_entry(&hsk->ready_rpcs,
+					       struct homa_rpc,
+					       ready_links);
+			homa_rpc_hold(rpc);
+			list_del_init(&rpc->ready_links);
+			if (!list_empty(&hsk->ready_rpcs)) {
+				/* There are still more RPCs available, so
+				 * let Linux know.
+				 */
+				hsk->sock.sk_data_ready(&hsk->sock);
+			}
+			homa_sock_unlock(hsk);
+		} else if (nonblocking) {
+			rpc = ERR_PTR(-EAGAIN);
+			homa_sock_unlock(hsk);
+
+			/* This is a good time to cleanup dead RPCS. */
+			homa_rpc_reap(hsk);
+			goto done;
+		} else {
+			homa_interest_init_shared(&interest, hsk);
+			homa_sock_unlock(hsk);
+			result = homa_interest_wait(&interest);
+
+			if (result != 0) {
+				rpc = ERR_PTR(result);
+				goto done;
+			}
+
+			rpc = interest.rpc;
+			if (!rpc) {
+				rpc = ERR_PTR(-ESHUTDOWN);
+				goto done;
+			}
+		}
+
+		homa_rpc_lock_preempt(rpc);
+		if (!rpc->error)
+			rpc->error = homa_copy_to_user(rpc);
+		if (rpc->error) {
+			if (rpc->state != RPC_DEAD)
+				break;
+		} else if (rpc->msgin.bytes_remaining == 0 &&
+		    skb_queue_len(&rpc->msgin.packets) == 0)
+			break;
+		homa_rpc_put(rpc);
+		homa_rpc_unlock(rpc);
+	}
+
+done:
+	return rpc;
+}
+
+/**
+ * homa_rpc_handoff() - This function is called when the input message for
+ * an RPC is ready for attention from a user thread. It notifies a waiting
+ * reader and/or queues the RPC, as appropriate.
+ * @rpc:                RPC to handoff; must be locked.
+ */
+void homa_rpc_handoff(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_sock *hsk = rpc->hsk;
+
+	if (rpc->state == RPC_DEAD)
+		return;
+
+	if (test_bit(RPC_PRIVATE, &rpc->flags)) {
+		homa_interest_notify_private(rpc);
+		return;
+	}
+
+	/* Shared RPC; if there is a waiting thread, hand off the RPC;
+	 * otherwise enqueue it.
+	 */
+	homa_sock_lock(hsk);
+	if (hsk->shutdown) {
+		homa_sock_unlock(hsk);
+		return;
+	}
+	if (!list_empty(&hsk->interests)) {
+		homa_rpc_hold(rpc);
+		homa_interest_notify_shared(hsk, rpc);
+	} else if (list_empty(&rpc->ready_links)) {
+		list_add_tail(&rpc->ready_links, &hsk->ready_rpcs);
+		hsk->sock.sk_data_ready(&hsk->sock);
+	}
+	homa_sock_unlock(hsk);
+}
diff --git a/net/homa/homa_interest.c b/net/homa/homa_interest.c
new file mode 100644
index 0000000000000..66ea429aac274
--- /dev/null
+++ b/net/homa/homa_interest.c
@@ -0,0 +1,192 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file contains functions for managing homa_interest structs. */
+
+#include "homa_impl.h"
+#include "homa_interest.h"
+#include "homa_rpc.h"
+#include "homa_sock.h"
+
+/* DESIGN NOTES:
+ * The key idea behind the design of the interest mechanism is to reduce usage
+ * of socket locks while handing off ready RPCs to application threads. Private
+ * handoffs do not require the socket lock to be acquired at all. Shared
+ * handoffs must acquire the socket lock to select one thread from a pool of
+ * waiting threads. But in the normal case the thread receiving the ready RPC
+ * does not need to acquire the socket lock again after the RPC has been
+ * handed off to it. The HOMA_INTEREST_HANDOFF_ACTIVE mechanism eliminates
+ * races that would otherwise be present in the absence of locking.
+ */
+
+/**
+ * homa_interest_init_shared() - Initialize an interest and queue it up on
+ * a socket.
+ * @interest:  Interest to initialize
+ * @hsk:       Socket on which the interests should be queued. Must be locked
+ *             by caller.
+ */
+void homa_interest_init_shared(struct homa_interest *interest,
+			       struct homa_sock *hsk)
+	__must_hold(hsk->lock)
+{
+	interest->rpc = NULL;
+	atomic_set(&interest->state, 0);
+	interest->blocked = 0;
+	init_waitqueue_head(&interest->wait_queue);
+	interest->hsk = hsk;
+	list_add(&interest->links, &hsk->interests);
+}
+
+/**
+ * homa_interest_init_private() - Initialize an interest that will wait
+ * on a particular (private) RPC, and link it to that RPC.
+ * @interest:   Interest to initialize.
+ * @rpc:        RPC to associate with the interest. Must be private, and
+ *              caller must have locked it.
+ *
+ * Return:      0 for success, otherwise a negative errno.
+ */
+int homa_interest_init_private(struct homa_interest *interest,
+			       struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	if (rpc->private_interest)
+		return -EINVAL;
+
+	interest->rpc = rpc;
+	atomic_set(&interest->state, 0);
+	interest->blocked = 0;
+	init_waitqueue_head(&interest->wait_queue);
+	interest->hsk = rpc->hsk;
+	INIT_LIST_HEAD(&interest->links);
+	rpc->private_interest = interest;
+	return 0;
+}
+
+/**
+ * homa_interest_wait() - Wait for an interest to have an actionable RPC,
+ * or for an error to occur.
+ * @interest:     Interest to wait for; must previously have been initialized
+ *                and linked to a socket or RPC. On return, the interest
+ *                will have been unlinked if it is shared and its ready flag
+ *                is set; otherwise it may still be linked.
+ *
+ * Return: 0 for success (the ready flag is set in the interest), or -EINTR
+ * if the thread received an interrupt. When this function returns, the
+ * interest will no longer be linked to a socket (if it ever was).
+ */
+int homa_interest_wait(struct homa_interest *interest)
+{
+	struct homa_sock *hsk = interest->hsk;
+	int result = 0;
+	int iteration;
+	int wait_err;
+
+	interest->blocked = 0;
+
+	/* This loop iterates in order to poll and/or reap dead RPCS. */
+	for (iteration = 0; ; iteration++) {
+		if (iteration != 0)
+			/* Give NAPI/SoftIRQ tasks a chance to run. */
+			schedule();
+
+		if (atomic_read_acquire(&interest->state) & HOMA_INTEREST_READY)
+			goto done;
+
+		if (signal_pending(current)) {
+			wait_err = -ERESTARTSYS;
+			goto check_err;
+		}
+
+		/* See if we can cleanup dead RPCs while waiting. */
+		if (homa_rpc_reap(hsk) != 0)
+			continue;
+
+		break;
+	}
+
+	interest->blocked = 1;
+	wait_err = wait_event_interruptible_exclusive(interest->wait_queue,
+						      atomic_read_acquire(&interest->state) &
+						      HOMA_INTEREST_READY);
+
+check_err:
+	if (wait_err == -ERESTARTSYS) {
+		int ready;
+
+		/* An interrupt occurred. We have to do two things.  First,
+		 * unlink the interest from the socket (if it was linked).
+		 * Second, check to see if in the meantime the interest
+		 * received a handoff. If so, ignore the interrupt. Must hold
+		 * the socket lock while checking, in order to eliminate races
+		 * with homa_rpc_handoff. Technically these are only needed
+		 * for shared interests, but it's harmless to do them for
+		 * private interests as well.
+		 */
+		homa_sock_lock(hsk);
+		list_del_init(&interest->links);
+		ready = atomic_read_acquire(&interest->state) &
+			HOMA_INTEREST_READY;
+		homa_sock_unlock(hsk);
+		if (ready == 0)
+			result = -EINTR;
+	}
+
+done:
+	/* Make sure that the handing off thread has completely finished
+	 * accessing the interest, so that it's safe for our caller to
+	 * reuse the interest's memory.
+	 */
+	while (atomic_read(&interest->state) & HOMA_INTEREST_HANDOFF_ACTIVE)
+		cpu_relax();
+	return result;
+}
+
+/**
+ * homa_interest_notify_private() - If a thread is waiting on the private
+ * interest for an RPC, wake it up.
+ * @rpc:      RPC that may (potentially) have a private interest. Must be
+ *            locked by the caller.
+ */
+void homa_interest_notify_private(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	if (rpc->private_interest) {
+		/* See comment in homa_interest_notify_shared. */
+		atomic_set_release(&rpc->private_interest->state,
+				   HOMA_INTEREST_READY |
+				   HOMA_INTEREST_HANDOFF_ACTIVE);
+		wake_up(&rpc->private_interest->wait_queue);
+		atomic_set_release(&rpc->private_interest->state,
+				   HOMA_INTEREST_READY);
+	}
+}
+
+/**
+ * homa_interest_notify_shared() - Hand an RPC off to one of the interests
+ * available for a socket.
+ * @hsk:      Socket for the handoff; must have at least one interest.
+ *            Must be locked by caller.
+ * @rpc:      RPC to handoff; can be NULL to indicate that the socket
+ *            has been shutdown. Caller must have taken a reference.
+ */
+void homa_interest_notify_shared(struct homa_sock *hsk, struct homa_rpc *rpc)
+	__must_hold(hsk->lock)
+{
+	struct homa_interest *interest;
+
+	interest = list_first_entry(&hsk->interests,
+				    struct homa_interest, links);
+	list_del_init(&interest->links);
+	interest->rpc = rpc;
+
+	/* The dance below eliminates two race conditions: (a) a waking up
+	 * thread doesn't see the change to state and (b) a waking up thread
+	 * recycles the memory of the interest before we have finished
+	 * accessing it in wake_up.
+	 */
+	atomic_set_release(&interest->state,
+			   HOMA_INTEREST_READY | HOMA_INTEREST_HANDOFF_ACTIVE);
+	wake_up(&interest->wait_queue);
+	atomic_set_release(&interest->state, HOMA_INTEREST_READY);
+}
diff --git a/net/homa/homa_interest.h b/net/homa/homa_interest.h
new file mode 100644
index 0000000000000..cb0b3f0d4f183
--- /dev/null
+++ b/net/homa/homa_interest.h
@@ -0,0 +1,92 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file defines struct homa_interest and related functions.  */
+
+#ifndef _HOMA_INTEREST_H
+#define _HOMA_INTEREST_H
+
+#include "homa_rpc.h"
+#include "homa_sock.h"
+
+/**
+ * struct homa_interest - Holds info that allows applications to wait for
+ * incoming RPC messages. An interest can be either private, in which case
+ * the application is waiting for a single specific RPC response and the
+ * interest is referenced by an rpc->private_interest, or shared, in which
+ * case the application is waiting for any incoming message that isn't
+ * private and the interest is present on hsk->interests.
+ */
+struct homa_interest {
+	/**
+	 * @rpc: If ready is set, then this holds an RPC that needs
+	 * attention, or NULL if this is a shared interest and hsk has
+	 * been shutdown. If ready is not set, this will be NULL if the
+	 * interest is shared; if it's private, it holds the RPC the
+	 * interest is associated with. If non-NULL, a reference has been
+	 * taken on the RPC.
+	 */
+	struct homa_rpc *rpc;
+
+	/**
+	 * @state: Used to manage the process of handing off an RPC.  Consists
+	 * of the following bits:
+	 * HOMA_INTEREST_READY:
+	 *     Nonzero means the interest is ready for attention: either there
+	 *     is an RPC that needs attention or @hsk has been shutdown.
+	 * HOMA_INTEREST_HANDOFF_ACTIVE:
+	 *     Nonzero means a handing-off thread is still accessing the
+	 *     interest. Used to ensure that the handing-off thread is
+	 *     completely finished before homa_interest_wait returns (so
+	 *     that the interest can safely be deleted).
+	 */
+#define HOMA_INTEREST_READY           1
+#define HOMA_INTEREST_HANDOFF_ACTIVE  2
+	atomic_t state;
+
+	/**
+	 * @blocked: Zero means a handoff was received without the thread
+	 * needing to block; nonzero means the thread blocked.
+	 */
+	int blocked;
+
+	/**
+	 * @wait_queue: Used to block the thread while waiting (will never
+	 * have more than one queued thread).
+	 */
+	struct wait_queue_head wait_queue;
+
+	/** @hsk: Socket that the interest is associated with. */
+	struct homa_sock *hsk;
+
+	/**
+	 * @links: If the interest is shared, used to link this object into
+	 * @hsk->interests.
+	 */
+	struct list_head links;
+};
+
+/**
+ * homa_interest_unlink_private() - Detach a private interest from its
+ * RPC. Note: this can race with homa_rpc_handoff, so on return it's
+ * possible that the interest is ready.
+ * @interest:    Interest to remove. Must have been initialized with
+ *               homa_interest_init_private. Its RPC must be locked by
+ *               the caller.
+ */
+static inline void homa_interest_unlink_private(struct homa_interest *interest)
+	__must_hold(interest->rpc->bucket->lock)
+{
+	if (interest == interest->rpc->private_interest)
+		interest->rpc->private_interest = NULL;
+}
+
+void     homa_interest_init_shared(struct homa_interest *interest,
+				   struct homa_sock *hsk);
+int      homa_interest_init_private(struct homa_interest *interest,
+				    struct homa_rpc *rpc);
+void     homa_interest_notify_private(struct homa_rpc *rpc);
+void     homa_interest_notify_shared(struct homa_sock *hsk,
+				     struct homa_rpc *rpc);
+int      homa_interest_wait(struct homa_interest *interest);
+
+#endif /* _HOMA_INTEREST_H */
diff --git a/net/homa/homa_outgoing.c b/net/homa/homa_outgoing.c
new file mode 100644
index 0000000000000..afc7c034d1453
--- /dev/null
+++ b/net/homa/homa_outgoing.c
@@ -0,0 +1,537 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file contains functions related to the sender side of message
+ * transmission. It also contains utility functions for sending packets.
+ */
+
+#include "homa_impl.h"
+#include "homa_peer.h"
+#include "homa_rpc.h"
+#include "homa_tx_pool.h"
+#include "homa_wire.h"
+
+/**
+ * homa_message_out_init() - Initialize rpc->msgout. This function doesn't
+ * read data from user space or create sk_buffs, but it sets up information
+ * such as the message geometry.
+ * @rpc:       RPC whose output message should be initialized. Must be
+ *             locked by caller. Fields in rpc->msgout should have been
+ *             zeroed by the caller.
+ * @length:    Number of bytes that will eventually be in rpc->msgout.
+ */
+void homa_message_out_init(struct homa_rpc *rpc, int length)
+	__must_hold(rpc->bucket->lock)
+{
+	struct dst_entry *dst;
+	u64 max_segs;
+	int mtu;
+
+	memset(&rpc->msgout, 0, sizeof(rpc->msgout));
+	rpc->msgout.length = length;
+	rpc->msgout.init_time = homa_clock();
+
+	/* Compute the geometry of packets. */
+	rcu_read_lock();
+	dst = rcu_dereference(rpc->route->dst);
+	mtu = dst_mtu(dst);
+	rpc->msgout.max_seg_data = mtu - rpc->hsk->ip_header_length -
+				   sizeof(struct homa_data_hdr);
+	max_segs = min_t(u32, rpc->hsk->homa->max_gso_size,
+			 dst->dev->gso_max_size) -
+		   (sizeof(struct homa_data_hdr) + HOMA_SKB_EXTRA);
+	do_div(max_segs, rpc->msgout.max_seg_data +
+			 sizeof(struct homa_seg_hdr));
+	if (max_segs > dst->dev->gso_max_segs)
+		max_segs = dst->dev->gso_max_segs;
+	if (max_segs < 1)
+		max_segs = 1;
+	rpc->msgout.max_gso_segs = max_segs;
+	rpc->msgout.max_gso_data = max_segs * rpc->msgout.max_seg_data;
+	rcu_read_unlock();
+}
+
+/**
+ * homa_tx_copy_from_user() - Copy outbound message data for an RPC from
+ * user space into kernel memory and (possibly) start transmitting packets.
+ * @rpc:      RPC whose tx message is to be copied.
+ * @iter:     Describes the location in user space of the message
+ *            data.
+ * @xmit:     True means this function should also start transmitting packets.
+ *            False means only copy data; don't transmit packets.
+ * Return:    Zero for success, otherwise a negative errno.
+ */
+int homa_tx_copy_from_user(struct homa_rpc *rpc, struct iov_iter *iter,
+			   bool xmit)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_frag_filler filler;
+	int err, hdr_space;
+	u64 num_segs;
+	int offset;
+
+	homa_message_out_init(rpc, iter->count);
+
+	/* Allocate kernel memory to hold the message data (note that we
+	 * need to allocate extra space for homa_seg_hdrs).
+	 */
+	num_segs = rpc->msgout.length + rpc->msgout.max_seg_data - 1;
+	do_div(num_segs, rpc->msgout.max_seg_data);
+	hdr_space = num_segs * sizeof(struct homa_seg_hdr);
+	rpc->msgout.frags = &rpc->msgout.frag;
+	rpc->msgout.num_frags = 1;
+	err = homa_tx_pool_alloc(rpc->hsk->homa, rpc->msgout.length + hdr_space,
+				 &rpc->msgout.num_frags, &rpc->msgout.frags);
+	if (err != 0)
+		return err;
+	rpc->msgout.frag_bytes = rpc->msgout.length + hdr_space;
+	refcount_add(rpc->msgout.frag_bytes, &rpc->hsk->sock.sk_wmem_alloc);
+
+	/* Copy the data in from user space, preceding each segment of data
+	 * with its homa_seg_hdr.
+	 */
+	homa_rpc_unlock(rpc);
+	homa_frag_filler_init(&filler, rpc->msgout.num_frags,
+			      rpc->msgout.frags);
+	offset = 0;
+	while (offset < rpc->msgout.length) {
+		int seg_size = min(rpc->msgout.length - offset,
+				   rpc->msgout.max_seg_data);
+		struct homa_seg_hdr seg_hdr;
+
+		seg_hdr.offset = htonl(offset);
+		err = homa_copy_to_frags(&filler, &seg_hdr, sizeof(seg_hdr));
+		if (unlikely(err != 0))
+			goto done;
+		err = homa_copy_iter_to_frags(&filler, iter, seg_size);
+		if (unlikely(err != 0))
+			goto done;
+		offset += seg_size;
+
+		/* Make sure that anyone seeing a change in copied_from_user
+		 * also sees related changes to rpc->msgout.
+		 */
+		smp_store_release(&rpc->msgout.copied_from_user, offset);
+	}
+
+done:
+	homa_rpc_lock(rpc);
+	if (xmit && err == 0)
+		homa_xmit_data(rpc);
+	return err;
+}
+
+/**
+ * __homa_skb_alloc() - Allocate a new (empty) sk_buff for use in transmitting
+ * data or control info.
+ * @length:       Number of bytes of data that the caller would like to
+ *                have available in the linear part of the sk_buff for
+ *                the Homa header and additional data beyond that. This
+ *                function will allocate additional space for IP and
+ *                Ethernet headers, as well as for the homa_skb_info.
+ * Return:        New sk_buff, or NULL if there was insufficient memory.
+ *                The sk_buff will be configured so that the next
+ *                skb_put will be for the transport (Homa) header. The
+ *                homa_skb_info is not initialized.
+ */
+struct sk_buff *__homa_skb_alloc(int length)
+{
+	struct sk_buff *skb;
+
+	skb = alloc_skb(HOMA_SKB_EXTRA + sizeof(struct homa_skb_info) + length,
+			GFP_ATOMIC);
+	if (likely(skb)) {
+		skb_reserve(skb, HOMA_SKB_EXTRA);
+		skb_reset_transport_header(skb);
+	}
+	return skb;
+}
+
+/**
+ * homa_tx_skb_alloc() - Create an outgoing data packet for a Homa message.
+ * @rpc:      RPC for the message. Its @msgout must have been initialized
+ *            (e.g. the packet geometry will be determined by information
+ *            in @rpc->msgout).
+ * @offset:   Offset within the message of the first byte of data for
+ *            this packet.
+ * @end:      Offset within the message of the byte just after the last
+ *            one to include in this packet. The skb may actually end either
+ *            before or after this offset; this value is modified to hold
+ *            the actual end.
+ * Return:    A pointer to the sk_buff, or a negative errno for error.
+ */
+struct sk_buff *homa_tx_skb_alloc(struct homa_rpc *rpc, u32 offset, u32 *end)
+	__must_hold(rpc->bucket->lock)
+{
+	int msg_frags_left, bytes_left, bytes_to_skip, rem;
+	struct homa_sock *hsk = rpc->hsk;
+	struct homa_skb_info *homa_info;
+	skb_frag_t *msg_frag, *skb_frag;
+	struct skb_shared_info *shinfo;
+	u64 seg_index, num_segs;
+	struct homa_data_hdr *h;
+	struct sk_buff *skb;
+	int err;
+
+	if (offset >= rpc->msgout.length)
+		return ERR_PTR(-EINVAL);
+	if (*end > rpc->msgout.length)
+		*end = rpc->msgout.length;
+
+	/* Find the location within rpc->msgin.frags of the data for the
+	 * first segment to output (skipping its homa_seg_hdr, since that
+	 * will be in the linear part of the skb). Also, round offset down
+	 * to the start of its segment.
+	 */
+	seg_index = offset;
+	rem = do_div(seg_index, rpc->msgout.max_seg_data);
+	offset -= rem;
+	bytes_to_skip = seg_index * (rpc->msgout.max_seg_data +
+				     sizeof(struct homa_seg_hdr)) +
+			sizeof(struct homa_seg_hdr);
+	for (msg_frags_left = rpc->msgout.num_frags,
+	     msg_frag = rpc->msgout.frags; ; msg_frags_left--, msg_frag++) {
+		if (bytes_to_skip < skb_frag_size(msg_frag))
+			break;
+		bytes_to_skip -= skb_frag_size(msg_frag);
+	}
+
+	/* Compute how much data from rpc->msgout.frags to include in the
+	 * packet.
+	 */
+	num_segs = *end - offset + rpc->msgout.max_seg_data - 1;
+	do_div(num_segs, rpc->msgout.max_seg_data);
+	if (num_segs > rpc->msgout.max_gso_segs)
+		num_segs = rpc->msgout.max_gso_segs;
+	bytes_left = num_segs * (rpc->msgout.max_seg_data +
+				 sizeof(struct homa_seg_hdr)) -
+		     sizeof(struct homa_seg_hdr);
+
+	skb = __homa_skb_alloc(sizeof(struct homa_data_hdr));
+	if (unlikely(!skb))
+		return ERR_PTR(-ENOMEM);
+	skb->ooo_okay = 1;
+	shinfo = skb_shinfo(skb);
+
+	/* Fill in the Homa header (which will be replicated in every
+	 * segment by GSO). The header in the linear portion contains the
+	 * homa_seg_hdr for the first fragment.
+	 */
+	h = (struct homa_data_hdr *)skb_put(skb, sizeof(struct homa_data_hdr));
+	memset(h, 0, sizeof(*h));
+	h->common.sport = htons(hsk->port);
+	h->common.dport = htons(rpc->dport);
+	h->common.type = DATA;
+	homa_set_doff(skb, sizeof(struct homa_data_hdr) -
+			   sizeof(struct homa_seg_hdr));
+	h->common.sender_id = cpu_to_be64(rpc->id);
+	h->message_length = htonl(rpc->msgout.length);
+	homa_peer_get_acks(rpc->route->peer, 1, &h->ack);
+	if (offset < rpc->msgout.next_xmit_offset)
+		h->retransmit = 1;
+	h->seg.offset = htonl(offset);
+
+	/* Virtually copy data from rpc->msgout.frags to the skb; each
+	 * iteration of the following loop copies one frag.
+	 */
+	while (bytes_left > 0 && shinfo->nr_frags < MAX_SKB_FRAGS &&
+	       msg_frags_left > 0) {
+		skb_frag_t *skb_frag = &shinfo->frags[shinfo->nr_frags];
+		struct page *page;
+		int frag_bytes;
+
+		frag_bytes = min(skb_frag_size(msg_frag) - bytes_to_skip,
+				 bytes_left);
+		page = skb_frag_page(msg_frag);
+		get_page(page);
+		skb_frag->netmem = page_to_netmem(page);
+		skb_frag->offset = msg_frag->offset + bytes_to_skip;
+		skb_frag_size_set(skb_frag, frag_bytes);
+		skb_len_add(skb, frag_bytes);
+
+		bytes_left -= frag_bytes;
+		bytes_to_skip = 0;
+		msg_frag++;
+		msg_frags_left--;
+		shinfo->nr_frags++;
+	}
+
+	if (bytes_left > 0 && msg_frags_left > 0 &&
+	    shinfo->nr_frags >= MAX_SKB_FRAGS) {
+		/* There wasn't enough fragment space in skb to store all the
+		 * desired segments. Round the skb back to the nearest segment
+		 * boundary.
+		 */
+		while (bytes_left > 0) {
+			bytes_left -= rpc->msgout.max_seg_data +
+				      sizeof(struct homa_seg_hdr);
+			num_segs--;
+		}
+		if (num_segs == 0) {
+			err = -EINVAL;
+			goto error;
+		}
+		while (bytes_left < 0) {
+			skb_frag = &shinfo->frags[shinfo->nr_frags - 1];
+			if (-bytes_left < skb_frag_size(skb_frag)) {
+				skb_frag_size_sub(skb_frag, -bytes_left);
+				skb_len_add(skb, bytes_left);
+				break;
+			}
+			bytes_left += skb_frag_size(skb_frag);
+			skb_len_add(skb, -skb_frag_size(skb_frag));
+			put_page(skb_frag_page(skb_frag));
+			shinfo->nr_frags--;
+		}
+	}
+	*end = min_t(u32, offset + num_segs * rpc->msgout.max_seg_data,
+		     rpc->msgout.length);
+
+	/* Fill in fields in shinfo. */
+	if (num_segs > 1) {
+		shinfo->gso_segs = num_segs;
+		shinfo->gso_size = rpc->msgout.max_seg_data +
+				   sizeof(struct homa_seg_hdr);
+		shinfo->gso_type = (hsk->inet.sk.sk_family ==
+				    AF_INET6) ? SKB_GSO_TCPV6 :
+				    SKB_GSO_TCPV4;
+	}
+
+	/* Initialize homa_skb_info for the packet. */
+	homa_info = homa_get_skb_info(skb);
+	memset(homa_info, 0, sizeof(*homa_info));
+	homa_info->data_bytes = *end - offset;
+	homa_info->dont_defer = false;
+	return skb;
+
+error:
+	kfree_skb_reason(skb, SKB_DROP_REASON_NOT_SPECIFIED);
+	return ERR_PTR(err);
+}
+
+/**
+ * homa_tx_skb_send() - Create and send one (GSO) data packet for an RPC. The
+ * dimensions of the packet transmitted may change from those specified
+ * in the argument depending on factors such as availability of GSO,
+ * MTU, etc.
+ * @rpc:         RPC for which to send the packet. This function releases
+ *               and then re-requires rpc's lock, so the RPC could be
+ *               dead when this function returns.
+ * @offset:      The packet must contain this offset.
+ * @end:         Offset of the message byte just after the last one
+ *               the caller would like included in the packet. Modified
+ *               to hold the offset just after the last byte actually
+ *               included in the packet.
+ * Return:       0 for success, otherwise a negative errno.
+ */
+int homa_tx_skb_send(struct homa_rpc *rpc, u32 offset, u32 *end)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_route *route;
+	struct sk_buff *skb;
+	int err;
+
+	skb = homa_tx_skb_alloc(rpc, offset, end);
+	if (IS_ERR(skb))
+		return PTR_ERR(skb);
+
+	/* Note: must update next_xmit_offset here, before releasing the
+	 * RPC lock below; otherwise some other thread might decide to
+	 * transmit the same bytes.
+	 */
+	if (*end > rpc->msgout.next_xmit_offset)
+		rpc->msgout.next_xmit_offset = *end;
+
+	err = homa_route_validate(rpc);
+	if (err != 0) {
+		kfree_skb_reason(skb, SKB_DROP_REASON_IP_OUTNOROUTES);
+		return err;
+	}
+	route = rpc->route;
+
+	/* Take a reference on the route so we can safely use it even after
+	 * the RPC lock has been released (rpc->route may change, but not
+	 * route).
+	 */
+	homa_route_hold(route);
+	homa_rpc_unlock(rpc);
+	err = homa_route_xmit(skb, rpc->hsk, route, 0);
+	homa_route_release(route);
+	homa_rpc_lock(rpc);
+	return err;
+}
+
+/**
+ * homa_xmit_control() - Send a control packet to the other end of an RPC.
+ * @type:      Packet type, such as DATA.
+ * @contents:  Address of buffer containing the contents of the packet.
+ *             Only information after the common header must be valid;
+ *             the common header will be filled in by this function.
+ * @length:    Length of @contents (including the common header).
+ * @rpc:       The packet will go to the socket that handles the other end
+ *             of this RPC. Addressing info for the packet, including all of
+ *             the fields of homa_common_hdr except type, will be set from this.
+ *
+ * Return:     Either zero (for success), or a negative errno value if there
+ *             was a problem.
+ */
+int homa_xmit_control(enum homa_packet_type type, void *contents,
+		      size_t length, struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_common_hdr *h = contents;
+	struct homa_route *route;
+	int err;
+
+	memset(h, 0, sizeof(*h));
+	h->type = type;
+	h->sport = htons(rpc->hsk->port);
+	h->dport = htons(rpc->dport);
+	h->sender_id = cpu_to_be64(rpc->id);
+	err = homa_route_validate(rpc);
+	if (err != 0)
+		return err;
+	route = rpc->route;
+
+	/* Must take a reference on route to ensure it persists through
+	 * packet transmission (rpc->route could get replaced once we
+	 * release the RPC lock).
+	 */
+	homa_route_hold(route);
+	homa_rpc_unlock(rpc);
+	err = __homa_xmit_control(contents, length, route, rpc->hsk);
+	homa_route_release(route);
+	homa_rpc_lock(rpc);
+	return err;
+}
+
+/**
+ * __homa_xmit_control() - Lower-level version of homa_xmit_control: sends
+ * a control packet.
+ * @contents:  Address of buffer containing the contents of the packet.
+ *             The caller must have filled in all of the information,
+ *             including the common header.
+ * @length:    Length of @contents.
+ * @route:     Route via which to send packet (includes destination).
+ * @hsk:       Socket via which the packet will be sent.
+ *
+ * Return:     Either zero (for success), or a negative errno value if there
+ *             was a problem.
+ */
+int __homa_xmit_control(void *contents, size_t length, struct homa_route *route,
+			struct homa_sock *hsk)
+{
+	struct homa_common_hdr *h;
+	struct sk_buff *skb;
+	int extra_bytes;
+	int err;
+
+	skb = __homa_skb_alloc(HOMA_MAX_HEADER);
+	if (unlikely(!skb))
+		return -ENOBUFS;
+
+	h = skb_put(skb, length);
+	memcpy(h, contents, length);
+	extra_bytes = HOMA_MIN_PKT_LENGTH - length;
+	if (extra_bytes > 0)
+		memset(skb_put(skb, extra_bytes), 0, extra_bytes);
+	skb->ooo_okay = 1;
+	homa_set_doff(skb, 20);
+	err = homa_route_xmit(skb, hsk, route, 0);
+	return err;
+}
+
+/**
+ * homa_xmit_unknown() - Send an RPC_UNKNOWN packet to a peer.
+ * @skb:         Buffer containing an incoming packet; identifies the peer to
+ *               which the RPC_UNKNOWN packet should be sent.
+ * @hsk:         Socket that should be used to send the RPC_UNKNOWN packet.
+ */
+void homa_xmit_unknown(struct sk_buff *skb, struct homa_sock *hsk)
+{
+	struct homa_common_hdr *h = (struct homa_common_hdr *)skb->data;
+	struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);
+	struct homa_rpc_unknown_hdr unknown;
+	struct homa_route *route;
+
+	memset(&unknown, 0, sizeof(unknown));
+	unknown.common.sport = h->dport;
+	unknown.common.dport = h->sport;
+	unknown.common.type = RPC_UNKNOWN;
+	unknown.common.sender_id = cpu_to_be64(homa_local_id(h->sender_id));
+	route = homa_route_get(hsk, &saddr);
+	if (!IS_ERR(route)) {
+		__homa_xmit_control(&unknown, sizeof(unknown), route, hsk);
+		homa_route_release(route);
+	}
+}
+
+/**
+ * homa_xmit_data() - If an RPC has outbound data packets that are permitted
+ * to be transmitted according to the scheduling mechanism, arrange for
+ * them to be sent.
+ * @rpc:       RPC to check for transmittable packets. Must be locked by
+ *             caller.
+ */
+void homa_xmit_data(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	u32 xmit_offset, end;
+
+	while (rpc->state != RPC_DEAD) {
+		xmit_offset = rpc->msgout.next_xmit_offset;
+
+		/* Don't transmit unless enough data has been copied from user
+		 * space for a maximum-size packet.
+		 */
+		if (xmit_offset + rpc->msgout.max_gso_data >
+		    rpc->msgout.copied_from_user &&
+		    rpc->msgout.copied_from_user < rpc->msgout.length)
+			break;
+
+		if (xmit_offset >= rpc->msgout.length)
+			break;
+		end = rpc->msgout.length;
+		homa_tx_skb_send(rpc, xmit_offset, &end);
+	}
+}
+
+/**
+ * homa_resend_data() - This function is invoked as part of handling RESEND
+ * requests. It retransmits the packet(s) containing a given range of bytes
+ * from a message.
+ * @rpc:      RPC for which data should be resent. Must be locked by caller.
+ * @start:    Offset within @rpc->msgout of the first byte to retransmit.
+ * @end:      Offset within @rpc->msgout of the byte just after the last one
+ *            to retransmit.
+ * Return:    0 for success, otherwise a negative errno.
+ */
+int homa_resend_data(struct homa_rpc *rpc, int start, int end)
+	__must_hold(rpc->bucket->lock)
+{
+	u32 offset, pkt_end;
+	int err = 0;
+
+	for (offset = start; offset < end; offset = pkt_end) {
+		pkt_end = end;
+		err = homa_tx_skb_send(rpc, offset, &pkt_end);
+		if (err != 0)
+			break;
+		if (rpc->state == RPC_DEAD)
+			break;
+	}
+	return err;
+}
+
+/**
+ * homa_rpc_tx_end() - Return the offset of the first byte in an
+ * RPC's outgoing message that has not (with high probability) been
+ * passed to the NIC (i.e. offsets beyond this point have not been
+ * passed to ip*xmit or are deferred in homa_qdisc).
+ * @rpc:    RPC to check
+ * Return:  See above. If the message has been fully transmitted then
+ *          rpc->msgout.length is returned.
+ */
+int homa_rpc_tx_end(struct homa_rpc *rpc)
+{
+	return rpc->msgout.next_xmit_offset;
+}
diff --git a/net/homa/homa_peer.c b/net/homa/homa_peer.c
new file mode 100644
index 0000000000000..e387a399299bd
--- /dev/null
+++ b/net/homa/homa_peer.c
@@ -0,0 +1,669 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file provides functions related to homa_peer, homa_route, and
+ * homa_peertab objects.
+ */
+
+#include "homa_impl.h"
+#include "homa_peer.h"
+#include "homa_rpc.h"
+
+#include <linux/xxhash.h>
+
+/* Wrapper to allow xxhash to be used as rhashtable hash function. */
+static u32 xxh32_hash(const void *data, u32 len, u32 seed)
+{
+	return xxh32(data, len, seed);
+}
+
+const struct rhashtable_params peer_ht_params = {
+	.key_len     = sizeof(struct homa_peer_key),
+	.key_offset  = offsetof(struct homa_peer, ht_key),
+	.head_offset = offsetof(struct homa_peer, ht_linkage),
+	.nelem_hint = 10000,
+	.hashfn = xxh32_hash,
+	.obj_cmpfn = homa_peer_compare
+};
+
+const struct rhashtable_params route_ht_params = {
+	.key_len     = sizeof(struct homa_route_key),
+	.key_offset  = offsetof(struct homa_route, key),
+	.head_offset = offsetof(struct homa_route, ht_linkage),
+	.nelem_hint = 10000,
+	.hashfn = xxh32_hash
+};
+
+/**
+ * homa_peer_alloc_peertab() - Allocate and initialize a homa_peertab.
+ *
+ * Return:    A pointer to the new homa_peertab, or ERR_PTR(-errno) if there
+ *            was a problem.
+ */
+struct homa_peertab *homa_peer_alloc_peertab(void)
+{
+	struct homa_peertab *peertab;
+	int err;
+
+	peertab = kzalloc_obj(*peertab, GFP_KERNEL);
+	if (!peertab)
+		return ERR_PTR(-ENOMEM);
+
+	spin_lock_init(&peertab->lock);
+	err = rhashtable_init(&peertab->peer_ht, &peer_ht_params);
+	if (err)
+		goto error;
+	err = rhashtable_init(&peertab->route_ht, &route_ht_params);
+	if (err) {
+		rhashtable_destroy(&peertab->peer_ht);
+		goto error;
+	}
+	peertab->route_ht_valid = true;
+	rhashtable_walk_enter(&peertab->route_ht, &peertab->route_ht_iter);
+	peertab->gc_threshold = 5000;
+	peertab->net_max = 10000;
+	peertab->idle_secs_min = 10;
+	peertab->idle_secs_max = 120;
+
+	homa_peer_update_sysctl_deps(peertab);
+	return peertab;
+
+error:
+	homa_peer_free_peertab(peertab);
+	return ERR_PTR(err);
+}
+
+/**
+ * homa_peer_free_net() - Garbage collect all of the peer information
+ * associated with a particular network namespace.
+ * @hnet:    Network namespace whose peers should be freed. There must not
+ *           be any active sockets or RPCs for this namespace.
+ */
+void homa_peer_free_net(struct homa_net *hnet)
+{
+	struct homa_peertab *peertab = hnet->homa->peertab;
+	struct rhashtable_iter iter;
+	struct homa_route *route;
+
+	spin_lock_bh(&peertab->lock);
+	rhashtable_walk_enter(&peertab->route_ht, &iter);
+	rhashtable_walk_start(&iter);
+	while (1) {
+		route = rhashtable_walk_next(&iter);
+		if (!route)
+			break;
+		if (IS_ERR(route))
+			continue;
+		if (route->key.hnet != hnet)
+			continue;
+		if (rhashtable_remove_fast(&peertab->route_ht,
+					   &route->ht_linkage,
+					   route_ht_params) == 0) {
+			homa_route_release(route);
+			hnet->num_routes--;
+			peertab->num_routes--;
+		}
+	}
+	rhashtable_walk_stop(&iter);
+	rhashtable_walk_exit(&iter);
+	WARN(hnet->num_routes != 0, "%s ended up with hnet->num_routes %d",
+	     __func__, hnet->num_routes);
+	spin_unlock_bh(&peertab->lock);
+}
+
+/**
+ * homa_route_delete_fn() - This function is invoked for each entry in
+ * the route_ht hash table by the rhashtable code when the table is being
+ * deleted. It frees its argument.
+ * @object:     homa_peer to free.
+ * @dummy:      Not used.
+ */
+void homa_route_delete_fn(void *object, void *dummy)
+	__must_hold(((struct homa_route *)object)->key.hnet->homa->peertab->lock)
+{
+	struct homa_route *route = object;
+
+	/* Must unlink from the peer here (peertab is going away so
+	 * it won't be safe to do it later, if the reference count doesn't
+	 * drop to zero here).
+	 */
+	homa_peer_unlink(route);
+	homa_route_release(route);
+}
+
+/**
+ * homa_peer_free_peertab() - Destructor for homa_peertabs.
+ * @peertab:  The table to destroy. Caller must ensure that it will never
+ *            be accessed again.
+ */
+void homa_peer_free_peertab(struct homa_peertab *peertab)
+{
+	if (peertab->route_ht_valid) {
+		rhashtable_walk_exit(&peertab->route_ht_iter);
+		rhashtable_free_and_destroy(&peertab->route_ht,
+					    homa_route_delete_fn,
+					    NULL);
+		rcu_barrier();
+		rhashtable_destroy(&peertab->peer_ht);
+		peertab->route_ht_valid = false;
+	}
+	kfree(peertab);
+}
+
+/**
+ * homa_peer_alloc() - Allocate and initialize a new homa_peer object.
+ * @hsk:        Socket for which the peer will be used.
+ * @addr:       Address of the desired host: IPv4 addresses are represented
+ *              as IPv4-mapped IPv6 addresses.
+ * Return:      The peer associated with @addr, or a negative errno if an
+ *              error occurred. On a successful return the reference count
+ *              will be incremented for the returned peer. Sets hsk->error_msg
+ *              on errors.
+ */
+struct homa_peer *homa_peer_alloc(struct homa_sock *hsk,
+				  const struct in6_addr *addr)
+{
+	struct homa_peer *peer;
+
+	peer = kzalloc_obj(*peer, GFP_ATOMIC);
+	if (!peer) {
+		hsk->error_msg = "couldn't allocate memory for homa_peer";
+		return (struct homa_peer *)ERR_PTR(-ENOMEM);
+	}
+	peer->ht_key.addr = *addr;
+	peer->ht_key.hnet = hsk->hnet;
+	refcount_set(&peer->refs, 1);
+	spin_lock_init(&peer->lock);
+
+	return peer;
+}
+
+/**
+ * homa_peer_free() - Release any resources in a peer and free the homa_peer
+ * struct.
+ * @peer:   Peer to free. The @refs field must be zero (this also implies
+ *          for example, that the peer is not on any lists and
+ *          peer->grantable_rpcs is empty).
+ */
+void homa_peer_free(struct homa_peer *peer)
+{
+	kfree(peer);
+}
+
+/**
+ * homa_peer_get() - Returns the peer associated with a given host; creates
+ * a new homa_peer if one doesn't already exist.
+ * @hsk:        Socket where the peer will be used.
+ * @addr:       Address of the desired host: IPv4 addresses are represented
+ *              as IPv4-mapped IPv6 addresses.
+ *
+ * Return:      The peer associated with @addr, or a negative errno if an
+ *              error occurred. On a successful return the reference count
+ *              will be incremented for the returned peer. The caller must
+ *              eventually call homa_peer_release to release the reference.
+ */
+struct homa_peer *homa_peer_get(struct homa_sock *hsk,
+				const struct in6_addr *addr)
+	__must_hold(hsk->homa->peertab->lock)
+{
+	struct homa_peertab *peertab = hsk->homa->peertab;
+	struct homa_peer_key key;
+	struct homa_peer *peer;
+	int status;
+
+	key.addr = *addr;
+	key.hnet = hsk->hnet;
+
+	/* Fast path: use existing entry if it exists. */
+	peer = rhashtable_lookup(&peertab->peer_ht, &key, peer_ht_params);
+	if (peer) {
+		refcount_inc(&peer->refs);
+		return peer;
+	}
+
+	/* No existing entry, so we have to create a new one. */
+	peer = homa_peer_alloc(hsk, addr);
+	if (IS_ERR(peer))
+		return peer;
+	status = rhashtable_lookup_insert_fast(&peertab->peer_ht,
+					       &peer->ht_linkage,
+					       peer_ht_params);
+	if (status != 0) {
+		pr_err("homa_peer_get received unexpected error return from rhashtable_lookup_insert_fast");
+		hsk->error_msg = "unexpected error return from rhashtable_lookup_insert_fast";
+		homa_peer_free(peer);
+		return ERR_PTR(status);
+	}
+	return peer;
+}
+
+/**
+ * homa_route_alloc() - Allocate and initialize a new homa_route.
+ * object.
+ * @hsk:       Socket for which the homa_route will be used.
+ * @key:       Key that will be used for this entry in peertab->route_ht.
+ *             Contains the destination address and other information needed
+ *             to create a flowi and a dst_entry.
+ * Return:     A new homa_route corresdponding to @hsk and @key, or a
+ *             negative errno if an error occurred. Sets hsk->error_msg on
+ *             errors. On success, all fields have been initialized except
+ *             @peer; the route has not been inserted in route_ht and its
+ *             reference count will be one.
+ */
+struct homa_route *homa_route_alloc(struct homa_sock *hsk,
+				    const struct homa_route_key *key)
+{
+	struct homa_route *route;
+	struct dst_entry *dst;
+	int err;
+
+	route = kzalloc_obj(*route, GFP_ATOMIC);
+	if (!route) {
+		hsk->error_msg = "couldn't allocate memory for homa_route";
+		return ERR_PTR(-ENOMEM);
+	}
+	spin_lock_init(&route->lock);
+	refcount_set(&route->refs, 1);
+	route->access_jiffies = jiffies;
+	route->key = *key;
+
+	/* Find a dst_entry to use for this route. */
+	route->flow.flowi_secid = key->secid;
+	if (ipv6_addr_v4mapped(&route->key.daddr)) {
+		struct rtable *rt;
+
+		flowi4_init_output(&route->flow.u.ip4, key->bound_dev_if,
+				   key->mark, 0, RT_SCOPE_UNIVERSE,
+				   IPPROTO_HOMA, 0,
+				   ipv6_to_ipv4(route->key.daddr),
+				   ipv6_to_ipv4(route->key.saddr), 0, 0,
+				   key->uid);
+		rt = ip_route_output_flow(sock_net(&hsk->sock),
+					  &route->flow.u.ip4, &hsk->sock);
+		if (IS_ERR(rt)) {
+			err = PTR_ERR(rt);
+			goto error;
+		}
+		rcu_assign_pointer(route->dst, &rt->dst);
+	} else {
+		/* This code is derived from code in tcp_v6_connect. */
+		route->flow.u.ip6.flowi6_proto = IPPROTO_HOMA;
+		route->flow.u.ip6.daddr = route->key.daddr;
+		route->flow.u.ip6.saddr = route->key.saddr;
+		route->flow.u.ip6.flowlabel = ip6_make_flowinfo(0, 0);
+		route->flow.u.ip6.flowi6_oif = key->bound_dev_if;
+		route->flow.u.ip6.flowi6_mark = key->mark;
+		route->flow.u.ip6.fl6_dport = 0;
+		route->flow.u.ip6.fl6_sport = 0;
+		route->flow.u.ip6.flowi6_uid = key->uid;
+		dst = ip6_dst_lookup_flow(sock_net(&hsk->sock), &hsk->sock,
+						   &route->flow.u.ip6, NULL);
+		rcu_assign_pointer(route->dst, dst);
+
+		if (IS_ERR(route->dst)) {
+			err = PTR_ERR(route->dst);
+			goto error;
+		}
+		route->dst_cookie = rt6_get_cookie(dst_rt6_info(dst));
+	}
+	return route;
+error:
+	hsk->error_msg = "couldn't find route for peer";
+	kfree(route);
+	return ERR_PTR(err);
+}
+
+/**
+ * homa_route_free() - Release any resources in a homa_route and
+ * free the object's memory. May be invoked either as an RCU callback
+ * or directly (if invoked directly, caller must ensure exclusive
+ * access to the object, e.g. it was never actually published in
+ * route_ht).
+ * @head:     @rcu_head field  in the route to free.
+ */
+void homa_route_free(struct rcu_head *head)
+{
+	struct homa_route *route;
+
+	route = container_of(head, struct homa_route, rcu_head);
+	dst_release(rcu_dereference_protected(route->dst, 1));
+	spin_lock_bh(&route->key.hnet->homa->peertab->lock);
+	homa_peer_unlink(route);
+	spin_unlock_bh(&route->key.hnet->homa->peertab->lock);
+	kfree(route);
+}
+
+/**
+ * homa_route_get() - Returns a homa_route object that can be
+ * used to communicate with a given host over a given socket. Indirectly
+ * provides access to a homa_peer object for @addr.
+ * @hsk:        Socket where the peer will be used.
+ * @addr:       Address of the desired host: IPv4 addresses are represented
+ *              as IPv4-mapped IPv6 addresses.
+ *
+ * Return:      The homa_route associated with @addr, or a negative
+ *              errno if an error occurred. On a successful return the
+ *              reference count will be incremented for the returned object.
+ *              The caller must eventually call homa_peer_route_release to
+ *              release the reference.
+ */
+struct homa_route *homa_route_get(struct homa_sock *hsk,
+				  const struct in6_addr *addr)
+{
+	struct homa_peertab *peertab = hsk->homa->peertab;
+	struct homa_route *route, *other;
+	struct homa_route_key route_key;
+	struct homa_peer *peer;
+
+	/* See if we already have a suitable route cached. */
+	rcu_read_lock();
+	homa_route_key_init(&route_key, hsk, addr);
+	route = rhashtable_lookup(&peertab->route_ht, &route_key,
+				  route_ht_params);
+	if (route && refcount_inc_not_zero(&route->refs)) {
+		route->access_jiffies = jiffies;
+		rcu_read_unlock();
+		return route;
+	}
+
+	/* No existing entry, so we have to create a new one. Switch from
+	 * RCU to real locking for this.
+	 */
+	rcu_read_unlock();
+	route = homa_route_alloc(hsk, &route_key);
+	if (IS_ERR(route))
+		return route;
+
+	spin_lock_bh(&peertab->lock);
+	peer = homa_peer_get(hsk, addr);
+	if (IS_ERR(peer)) {
+		spin_unlock_bh(&peertab->lock);
+		homa_route_free(&route->rcu_head);
+		route = ERR_PTR(PTR_ERR(peer));
+		return route;
+	}
+	route->peer = peer;
+
+	/* Insert the new entry in the flow table. It's possible that
+	 * someone else already created the entry concurrently.
+	 */
+	other = rhashtable_lookup_get_insert_fast(&peertab->route_ht,
+						  &route->ht_linkage,
+						  route_ht_params);
+	if (IS_ERR(other)) {
+		/* Couldn't insert; return the error info. */
+		hsk->error_msg = "rhashtable_lookup_get_insert_key failed in homa_route_get";
+		spin_unlock_bh(&peertab->lock);
+		homa_route_free(&route->rcu_head);
+		route = other;
+	} else if (other) {
+		/* Someone else already created the desired object; use that
+		 * one instead of ours.
+		 */
+		refcount_inc(&other->refs);
+		spin_unlock_bh(&peertab->lock);
+		homa_route_free(&route->rcu_head);
+		route = other;
+		route->access_jiffies = jiffies;
+	} else {
+		/* The new object was inserted in the hash table. */
+		refcount_inc(&route->refs);
+		peertab->num_routes++;
+		route_key.hnet->num_routes++;
+		spin_unlock_bh(&peertab->lock);
+	}
+	return route;
+}
+
+/**
+ * homa_route_validate() - Check to be sure that the information in the
+ * route for an RPC is still valid; if not, try to allocate a new route
+ * for the RPC.
+ * @rpc:    RPC whose routing information should be checked.
+ * Return:  Zero for success, or a negative errno if the route was invalid
+ *          and no new route could be created.
+ */
+int homa_route_validate(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_route *route, *old;
+	struct dst_entry *dst;
+
+	old = rpc->route;
+	rcu_read_lock();
+	dst = rcu_dereference_protected(old->dst, 1);
+	rcu_read_unlock();
+	if (!dst_check(dst, rpc->route->dst_cookie)) {
+		struct homa_peertab *peertab = rpc->hsk->homa->peertab;
+
+		/* Existing route is no longer valid; remove it from
+		 * the hash table and try to create a new one.
+		 */
+		spin_lock_bh(&peertab->lock);
+		if (rhashtable_remove_fast(&peertab->route_ht, &old->ht_linkage,
+					   route_ht_params) == 0) {
+			homa_route_release(old);
+			peertab->num_routes--;
+			old->key.hnet->num_routes--;
+		}
+		spin_unlock_bh(&peertab->lock);
+		route = homa_route_get(rpc->hsk, &rpc->route->peer->addr);
+		if (IS_ERR(route))
+			return PTR_ERR(route);
+		old = xchg(&rpc->route, route);
+		homa_route_release(old);
+	}
+	return 0;
+}
+
+/**
+ * homa_route_gc() - This function is invoked by Homa at regular intervals;
+ * its job is to ensure that the number of routes stays within limits. If
+ * the number grows too large, it selectively deletes routes (and peers)
+ * to get back under the limit.
+ * @peertab:   Structure to garbage-collect.
+ */
+void homa_route_gc(struct homa_peertab *peertab)
+{
+#define EVICT_BATCH_SIZE 5
+	struct homa_route *victims[EVICT_BATCH_SIZE];
+	int num_victims;
+	int i;
+
+	spin_lock_bh(&peertab->lock);
+	if (peertab->num_routes < peertab->gc_threshold)
+		goto done;
+	num_victims = homa_route_pick_victims(peertab, victims,
+					      EVICT_BATCH_SIZE);
+	if (num_victims == 0)
+		goto done;
+
+	for (i = 0; i < num_victims; i++) {
+		struct homa_route *route = victims[i];
+
+		if (rhashtable_remove_fast(&peertab->route_ht,
+					   &route->ht_linkage,
+					   route_ht_params) == 0) {
+			peertab->num_routes--;
+			route->key.hnet->num_routes--;
+			homa_route_release(route);
+		}
+	}
+done:
+	spin_unlock_bh(&peertab->lock);
+}
+
+/**
+ * homa_route_pick_victims() - Select a few routes that can be freed.
+ * @peertab:      Choose routes that are stored here.
+ * @victims:      Return addresses of victims here.
+ * @max_victims:  Limit on how many victims to choose (and size of @victims
+ *                array).
+ * Return:        The number of routes stored in @victims; may be zero.
+ */
+int homa_route_pick_victims(struct homa_peertab *peertab,
+			    struct homa_route *victims[], int max_victims)
+{
+	struct homa_route *route;
+	int num_victims = 0;
+	int to_scan;
+	int i, idle;
+
+	/* Scan 2 routes for every potential victim and keep the "best"
+	 * routes for removal.
+	 */
+	rhashtable_walk_start(&peertab->route_ht_iter);
+	for (to_scan = 2 * max_victims; to_scan > 0; to_scan--) {
+		route = rhashtable_walk_next(&peertab->route_ht_iter);
+		if (!route) {
+			/* Reached the end of the table; restart at
+			 * the beginning.
+			 */
+			rhashtable_walk_stop(&peertab->route_ht_iter);
+			rhashtable_walk_exit(&peertab->route_ht_iter);
+			rhashtable_walk_enter(&peertab->peer_ht,
+					      &peertab->route_ht_iter);
+			rhashtable_walk_start(&peertab->route_ht_iter);
+			route = rhashtable_walk_next(&peertab->route_ht_iter);
+			if (!route)
+				break;
+		}
+		if (IS_ERR(route)) {
+			/* rhashtable decided to restart the search at the
+			 * beginning.
+			 */
+			route = rhashtable_walk_next(&peertab->route_ht_iter);
+			if (!route || IS_ERR(route))
+				break;
+		}
+
+		/* Has this route been idle long enough to be candidate for
+		 * eviction?
+		 */
+		idle = jiffies - route->access_jiffies;
+		if (idle < peertab->idle_jiffies_min)
+			continue;
+		if (idle < peertab->idle_jiffies_max &&
+		    route->key.hnet->num_routes <= peertab->net_max)
+			continue;
+
+		/* Sort the candidate into the existing list of victims. */
+		for (i = 0; i < num_victims; i++) {
+			if (route == victims[i]) {
+				/* This can happen if there aren't very many
+				 * routes and we wrapped around in the hash
+				 * table.
+				 */
+				route = NULL;
+				break;
+			}
+			if (homa_route_prefer_evict(peertab, route, victims[i]))
+				swap(route, victims[i]);
+		}
+
+		if (num_victims < max_victims && route) {
+			victims[num_victims] = route;
+			num_victims++;
+		}
+	}
+	rhashtable_walk_stop(&peertab->route_ht_iter);
+	return num_victims;
+}
+
+/**
+ * homa_route_prefer_evict() - Given two routes, determine which one is
+ * a better candidate for eviction.
+ * @peertab:    Overall information used to manage routes.
+ * @route1:     First route.
+ * @route2:     Second route.
+ * Return:      True if @route1 is a better candidate for eviction than @route2.
+ */
+int homa_route_prefer_evict(struct homa_peertab *peertab,
+			    struct homa_route *route1,
+			    struct homa_route *route2)
+{
+	/* Prefer a route whose homa_net is over its limit; if both are either
+	 * over or under, then prefer the route with the longest idle time.
+	 */
+	if (route1->key.hnet->num_routes > peertab->net_max) {
+		if (route2->key.hnet->num_routes <= peertab->net_max)
+			return true;
+		else
+			return time_before(route1->access_jiffies,
+					   route2->access_jiffies);
+	}
+	if (route2->key.hnet->num_routes > peertab->net_max)
+		return false;
+	else
+		return time_before(route1->access_jiffies,
+				   route2->access_jiffies);
+}
+
+/**
+ * homa_peer_add_ack() - Add a given RPC to the list of unacked
+ * RPCs for its server. Once this method has been invoked, it's safe
+ * to delete the RPC, since it will eventually be acked to the server.
+ * @rpc:    Client RPC that has now completed. Must be locked by caller.
+ */
+void homa_peer_add_ack(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_peer *peer = rpc->route->peer;
+	struct homa_ack_hdr ack;
+
+	homa_peer_lock(peer);
+	if (peer->num_acks < HOMA_MAX_ACKS_PER_PKT) {
+		peer->acks[peer->num_acks].client_id = cpu_to_be64(rpc->id);
+		peer->acks[peer->num_acks].server_port = htons(rpc->dport);
+		peer->num_acks++;
+		homa_peer_unlock(peer);
+		return;
+	}
+
+	/* The peer has filled up; send an ACK message to empty it. The
+	 * RPC in the message header will also be considered ACKed.
+	 */
+	memcpy(ack.acks, peer->acks, sizeof(peer->acks));
+	ack.num_acks = htons(peer->num_acks);
+	peer->num_acks = 0;
+	homa_peer_unlock(peer);
+	homa_xmit_control(ACK, &ack, sizeof(ack), rpc);
+}
+
+/**
+ * homa_peer_get_acks() - Copy acks out of a peer, and remove them from the
+ * peer.
+ * @peer:    Peer to check for possible unacked RPCs.
+ * @count:   Maximum number of acks to return.
+ * @dst:     The acks are copied to this location.
+ *
+ * Return:   The number of acks extracted from the peer (<= count).
+ */
+int homa_peer_get_acks(struct homa_peer *peer, int count, struct homa_ack *dst)
+{
+	/* Don't waste time acquiring the lock if there are no ids available. */
+	if (peer->num_acks == 0)
+		return 0;
+
+	homa_peer_lock(peer);
+
+	if (count > peer->num_acks)
+		count = peer->num_acks;
+	memcpy(dst, &peer->acks[peer->num_acks - count],
+	       count * sizeof(peer->acks[0]));
+	peer->num_acks -= count;
+
+	homa_peer_unlock(peer);
+	return count;
+}
+
+/**
+ * homa_peer_update_sysctl_deps() - Update any peertab fields that depend
+ * on values set by sysctl. This function is invoked anytime a peer sysctl
+ * value is updated.
+ * @peertab:   Struct to update.
+ */
+void homa_peer_update_sysctl_deps(struct homa_peertab *peertab)
+{
+	peertab->idle_jiffies_min = peertab->idle_secs_min * HZ;
+	peertab->idle_jiffies_max = peertab->idle_secs_max * HZ;
+}
diff --git a/net/homa/homa_peer.h b/net/homa/homa_peer.h
new file mode 100644
index 0000000000000..a0c80997ce199
--- /dev/null
+++ b/net/homa/homa_peer.h
@@ -0,0 +1,457 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file contains definitions related to managing peers and routes
+ * (homa_peer, homa_route, homa_peertab).
+ */
+
+#ifndef _HOMA_PEER_H
+#define _HOMA_PEER_H
+
+#include "homa_wire.h"
+#include "homa_sock.h"
+
+#include <linux/rhashtable.h>
+
+struct homa_rpc;
+
+/**
+ * struct homa_peertab - Stores homa_peer and homa_route objects. There is
+ * one of these per struct homa.
+ */
+struct homa_peertab {
+	/**
+	 * @lock: Used to synchronize updates to @peer_ht, @route_ht, as well
+	 * as other operations on this object.
+	 */
+	spinlock_t lock;
+
+	/** @peer_ht: Hash table that stores struct peers. */
+	struct rhashtable peer_ht;
+
+	/**
+	 * @route_ht:  Hash table that stores homa_peer_flow objects.
+	 * There can be multiple entries in this table for each peer.
+	 */
+	struct rhashtable route_ht;
+
+	/**
+	 * @route_ht_iter: Used to scan route_ht to find routes to garbage
+	 * collect.
+	 */
+	struct rhashtable_iter route_ht_iter;
+
+	/** @num_routes: Total number of objects currently in @route_ht. */
+	int num_routes;
+
+	/**
+	 * @route_ht_valid: True means route_ht has been initialized and must
+	 * eventually be destroyed (it also means peer_ht has been initialized).
+	 */
+	bool route_ht_valid;
+
+	/**
+	 * @gc_stop_count: Nonzero means that route garbage collection
+	 * should not be performed (conflicting state changes are underway).
+	 */
+	int gc_stop_count;
+
+	/**
+	 * @gc_threshold: If @num_routes is less than this, don't bother
+	 * doing any peer garbage collection. Set externally via sysctl.
+	 */
+	int gc_threshold;
+
+	/**
+	 * @net_max: If the number of peers for a homa_net exceeds this number,
+	 * work aggressively to reclaim peers for that homa_net. Set
+	 * externally via sysctl.
+	 */
+	int net_max;
+
+	/**
+	 * @idle_secs_min: A peer will not be considered for garbage collection
+	 * under any circumstances if it has been idle less than this many
+	 * seconds. Set externally via sysctl.
+	 */
+	int idle_secs_min;
+
+	/**
+	 * @idle_jiffies_min: Same as idle_secs_min except in units
+	 * of jiffies.
+	 */
+	int idle_jiffies_min;
+
+	/**
+	 * @idle_secs_max: A peer that has been idle for less than
+	 * this many seconds will not be considered for garbage collection
+	 * unless its homa_net has more than @net_threshold peers. Set
+	 * externally via sysctl.
+	 */
+	int idle_secs_max;
+
+	/**
+	 * @idle_jiffies_max: Same as idle_secs_max except in units
+	 * of jiffies.
+	 */
+	int idle_jiffies_max;
+
+	/** @rcu_head: Holds state of a pending call_rcu invocation. */
+	struct rcu_head rcu_head;
+};
+
+/**
+ * struct homa_peer_key - Used to look up homa_peer structs in homa_peertab->peer_ht.
+ */
+struct homa_peer_key {
+	/**
+	 * @addr: Address of the desired host. IPv4 addresses are represented
+	 * with IPv4-mapped IPv6 addresses. Must be the first variable in
+	 * the struct, because of union in homa_peer.
+	 */
+	struct in6_addr addr;
+
+	/** @hnet: The network namespace in which this peer is valid. */
+	struct homa_net *hnet;
+};
+
+/**
+ * struct homa_peer - One of these objects exists for each machine that we
+ * have communicated with (either as client or server). This struct contains
+ * information that is common to all uses of the peer.
+ */
+struct homa_peer {
+	union {
+		/**
+		 * @addr: IPv6 address for the machine (IPv4 addresses are
+		 * stored as IPv4-mapped IPv6 addresses).
+		 */
+		struct in6_addr addr;
+
+		/** @ht_key: The hash table key for this peer in peertab->peer_ht. */
+		struct homa_peer_key ht_key;
+	};
+
+	/**
+	 * @refs: Number of outstanding references to this peer. Does *not*
+	 * include a reference for the entry in peertab->peer_ht. The peer
+	 * can be freed when this value becomes zero.
+	 */
+	refcount_t refs;
+
+	/**
+	 * @ht_linkage: Used by rashtable implement to link this peer into
+	 * peertab->peer_ht.
+	 */
+	struct rhash_head ht_linkage;
+
+	/**
+	 * @lock: used to synchronize access to fields in this struct, such
+	 * as @num_acks, @acks, @dst, and @dst_cookie.
+	 */
+	spinlock_t lock ____cacheline_aligned_in_smp;
+
+	/**
+	 * @num_acks: the number of (initial) entries in @acks that
+	 * currently hold valid information.
+	 */
+	int num_acks;
+
+	/**
+	 * @acks: info about client RPCs whose results have been completely
+	 * received.
+	 */
+	struct homa_ack acks[HOMA_MAX_ACKS_PER_PKT];
+
+};
+
+/**
+ * struct homa_route_key - Used to look up homa_route structs in
+ * homa_peertab_route_ht. These fields represent all of the information
+ * that could impact the choice of a particular struct dst_entry.
+ */
+struct homa_route_key {
+	/**
+	 * @saddr: Source network address. IPv4 addresses are represented
+	 * with IPv4-mapped IPv6 addresses.
+	 */
+	struct in6_addr saddr;
+	/**
+	 * @daddr: Destination network address. IPv4 addresses are represented
+	 * with IPv4-mapped IPv6 addresses.
+	 */
+	struct in6_addr daddr;
+
+	/**
+	 * @hnet: The network namespace in which this route is valid. This
+	 * needs to be a homa_hnet pointer, not just struct net, in order
+	 * to access homa_hnet->num_routes.
+	 */
+	struct homa_net *hnet;
+
+	/**
+	 * @sk_policy_out: sk->sk_policy[XFRM_POLICY_OUT]: uniquely
+	 * determines IPsec policy, if any.
+	 */
+	struct xfrm_policy *sk_policy_out;
+
+	/** @uid: sock->sk_sk_uid */
+	kuid_t uid;
+
+	/** @mark: sock->sk_mark */
+	u32 mark;
+
+	/** @secid: flowic.secid produced by security_sk_classify_flow. */
+	u32 secid;
+
+	/** @bound_dev_if: sock->sk_bound_dev_if */
+	int bound_dev_if;
+};
+
+/**
+ * struct homa_route - Holds a dst_entry for communicating with a
+ * particular peer, as well as information needed to cache the dst_entry
+ * and share it for multiple RPCs. There can be more than one of these
+ * objects per peer, which have different homa_route_keys.
+ */
+struct homa_route {
+	/**
+	 * @lock: used to synchronize uypdates to this struct.
+	 */
+	spinlock_t lock;
+
+	/**
+	 * @refs: Number of outstanding references to this object. Includes
+	 * one reference for the entry in peertab->route_ht, plus one for each
+	 * call to homa_route_get that has not been canceled by a call to
+	 * homa_peer_route_release; the object will be freed (via RCU) when
+	 * this count becomes zero.
+	 */
+	refcount_t refs;
+
+	/**
+	 * @access_jiffies: Time in jiffies of most recent access to this
+	 * object; used for garbage collection.
+	 */
+	unsigned long access_jiffies;
+
+	/** @key: Identifies this entry in peertab->route_ht. */
+	struct homa_route_key key;
+
+	/**
+	 * @peer: Peer with which this route is associated. This object holds a
+	 * reference on the peer.
+	 */
+	struct homa_peer *peer;
+
+	/**
+	 * @dst: Used to route packets to this peer; this object owns a
+	 * reference that must eventually be released.
+	 */
+	struct dst_entry __rcu *dst;
+
+	/**
+	 * @dst_cookie: Used to check whether dst is still valid. This is
+	 * accessed without synchronization, which is racy, but the worst
+	 * that can happen is using an obsolete dst.
+	 */
+	u32 dst_cookie;
+
+	/**
+	 * @flow: Contains parameters used to generate @dst; must be
+	 * retained and passed to ip*xmit.
+	 */
+	struct flowi flow;
+
+	/**
+	 * @ht_linkage: Used by rashtable to link this object into
+	 * peertab->route_ht.
+	 */
+	struct rhash_head ht_linkage;
+
+	/** @rcu_head: Holds state of a pending call_rcu invocation. */
+	struct rcu_head rcu_head;
+};
+
+void     homa_dst_refresh(struct homa_peertab *peertab,
+			  struct homa_peer *peer, struct homa_sock *hsk);
+void     homa_peer_add_ack(struct homa_rpc *rpc);
+struct homa_peer
+	*homa_peer_alloc(struct homa_sock *hsk, const struct in6_addr *addr);
+struct homa_peertab
+	*homa_peer_alloc_peertab(void);
+int      homa_peer_dointvec(const struct ctl_table *table, int write,
+			    void *buffer, size_t *lenp, loff_t *ppos);
+void     homa_peer_free(struct homa_peer *peer);
+void     homa_peer_free_net(struct homa_net *hnet);
+void     homa_peer_free_peertab(struct homa_peertab *peertab);
+struct homa_peer
+	*homa_peer_get(struct homa_sock *hsk, const struct in6_addr *addr);
+int      homa_peer_get_acks(struct homa_peer *peer, int count,
+			    struct homa_ack *dst);
+void     homa_peer_lock_slow(struct homa_peer *peer);
+void     homa_peer_release_fn(void *object, void *dummy);
+void     homa_peer_update_sysctl_deps(struct homa_peertab *peertab);
+void     homa_peer_set_cutoffs(struct homa_peer *peer, int c0, int c1,
+			       int c2, int c3, int c4, int c5, int c6, int c7);
+struct homa_route
+	*homa_route_alloc(struct homa_sock *hsk,
+			  const struct homa_route_key *key);
+void     homa_route_delete_fn(void *object, void *dummy);
+void     homa_route_free(struct rcu_head *head);
+void     homa_route_gc(struct homa_peertab *peertab);
+struct homa_route
+	*homa_route_get(struct homa_sock *hsk,
+				    const struct in6_addr *addr);
+u32      homa_route_hash(const void *data, u32 len, u32 seed);
+int      homa_route_pick_victims(struct homa_peertab *peertab,
+				 struct homa_route *victims[], int max_victims);
+int      homa_route_prefer_evict(struct homa_peertab *peertab,
+				 struct homa_route *route1,
+				 struct homa_route *route2);
+int      homa_route_validate(struct homa_rpc *rpc);
+
+extern const struct rhashtable_params peer_ht_params;
+extern const struct rhashtable_params route_ht_params;
+
+/**
+ * homa_peer_lock() - Acquire the lock for a peer.
+ * @peer:    Peer to lock.
+ */
+static inline void homa_peer_lock(struct homa_peer *peer)
+	__acquires(peer->lock)
+{
+	spin_lock_bh(&peer->lock);
+}
+
+/**
+ * homa_peer_unlock() - Release the lock for a peer.
+ * @peer:   Peer to lock.
+ */
+static inline void homa_peer_unlock(struct homa_peer *peer)
+	__releases(peer->lock)
+{
+	spin_unlock_bh(&peer->lock);
+}
+
+/**
+ * homa_route_hold() - Increment the reference count on a route.
+ * Caller must eventually invoke homa_route_release to decrement the
+ * reference count again.
+ * @route:   Route whose reference count should be incremented. Caller must
+ *           already hold a reference to this.
+ */
+static inline void homa_route_hold(struct homa_route *route)
+{
+	refcount_inc(&route->refs);
+}
+
+/**
+ * homa_route_release() - Release a reference on a route (cancels the effect of
+ * a previous call to homa_route_hold). If the reference count becomes zero
+ * then the route may be deleted at any time.
+ * @route:      Object to release.
+ */
+static inline void homa_route_release(struct homa_route *route)
+{
+	if (refcount_dec_and_test(&route->refs))
+		call_rcu(&route->rcu_head, homa_route_free);
+}
+
+/**
+ * homa_peer_compare() - Comparison function for entries in @peertab->peer_ht.
+ * @arg:   Contains one of the keys to compare.
+ * @obj:   homa_peer object containing the other key to compare.
+ * Return: 0 means the keys match, 1 means mismatch.
+ */
+static inline int homa_peer_compare(struct rhashtable_compare_arg *arg,
+				    const void *obj)
+{
+	const struct homa_peer_key *key = arg->key;
+	const struct homa_peer *peer = obj;
+
+	return !(ipv6_addr_equal(&key->addr, &peer->ht_key.addr) &&
+		 peer->ht_key.hnet == key->hnet);
+}
+
+/**
+ * homa_route_xmit() - Transmit a packet according to a given route.
+ * @skb:      Packet to transmit.
+ * @hsk:      Socket on which to transmit packet.
+ * @route:    Route to use to transmit packet.
+ * @priority: Priority for packet.
+ * Return:    0 for success, otherwise a negative errno.
+ */
+static inline int homa_route_xmit(struct sk_buff *skb, struct homa_sock *hsk,
+				  struct homa_route *route, int priority)
+{
+	rcu_read_lock();
+	dst_hold(rcu_dereference(route->dst));
+	skb_dst_set(skb, rcu_dereference(route->dst));
+	rcu_read_unlock();
+	if (ipv6_addr_v4mapped(&route->peer->addr)) {
+		hsk->inet.tos = priority << 5;
+		return ip_queue_xmit(&hsk->inet.sk, skb, &route->flow);
+	}
+	return ip6_xmit(&hsk->inet.sk, skb, &route->flow.u.ip6, 0,
+			NULL, priority << 5, 0);
+}
+
+/**
+ * homa_peer_unlink() - Remove the connection between a route and its peer,
+ * potentially freeing the peer in the process.
+ * @route:    Route to disconnect.
+ */
+static inline void homa_peer_unlink(struct homa_route *route)
+	__must_hold(route->hnet->homa->peertab->lock)
+{
+	struct homa_peertab *peertab;
+
+	if (!route->peer)
+		return;
+
+	/* Note: we don't need to use RCU for freeing peers because we have
+	 * already used RCU for freeing routes, so we know there are no
+	 * outstanding uses. By holding the peertab lock we have locked
+	 * out calls to homa_peer_get.
+	 */
+	peertab = route->key.hnet->homa->peertab;
+	if (refcount_dec_and_test(&route->peer->refs)) {
+		rhashtable_remove_fast(&peertab->peer_ht,
+				       &route->peer->ht_linkage,
+				       peer_ht_params);
+		homa_peer_free(route->peer);
+	}
+	route->peer = NULL;
+}
+
+/**
+ * homa_route_key_init() - Initialize the fields of a key for
+ * peertab->route_ht. Note: caller must hold an RCU read lock.
+ * @key:      Key to initialize
+ * @hsk:      Socket from which to pull fields for the key other than
+ *            daddr.
+ * @daddr:    Destination address for the key.
+ */
+static inline void homa_route_key_init(struct homa_route_key *key,
+				       const struct homa_sock *hsk,
+				       const struct in6_addr *daddr)
+{
+	struct flowi_common flowic;
+
+	memset(key, 0, sizeof(*key));
+	if (hsk->sock.sk_family == AF_INET)
+		ipv6_addr_set_v4mapped(hsk->inet.inet_saddr, &key->saddr);
+	else
+		key->saddr = hsk->inet.pinet6->saddr;
+	key->daddr = *daddr;
+	key->hnet = hsk->hnet;
+	key->sk_policy_out = rcu_dereference(hsk->sock.sk_policy[XFRM_POLICY_OUT]);
+	key->uid = hsk->sock.sk_uid;
+	key->mark = hsk->sock.sk_mark;
+	flowic.flowic_secid = 0;
+	security_sk_classify_flow(&hsk->sock, &flowic);
+	key->secid = flowic.flowic_secid;
+	key->bound_dev_if = hsk->sock.sk_bound_dev_if;
+}
+
+#endif /* _HOMA_PEER_H */
diff --git a/net/homa/homa_plumbing.c b/net/homa/homa_plumbing.c
new file mode 100644
index 0000000000000..de3483b21d489
--- /dev/null
+++ b/net/homa/homa_plumbing.c
@@ -0,0 +1,1302 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file consists mostly of "glue" that hooks Homa into the rest of
+ * the Linux kernel. The guts of the protocol are in other files.
+ */
+
+#include "homa_impl.h"
+#include "homa_peer.h"
+#include "homa_pool.h"
+
+/* Identifier for retrieving Homa-specific data for a struct net. */
+unsigned int homa_net_id;
+
+/* This structure defines functions that allow Homa to be used as a
+ * pernet subsystem.
+ */
+static struct pernet_operations homa_net_ops = {
+	.init = homa_net_start,
+	.exit = homa_net_exit,
+	.id = &homa_net_id,
+	.size = sizeof(struct homa_net)
+};
+
+/* Global data for Homa. Avoid referencing directly except when there is
+ * no alternative (instead, use a homa pointer stored in a struct or
+ * passed via a parameter). This allows overriding during unit tests.
+ */
+static struct homa homa_data;
+
+/* This structure defines functions that handle various operations on
+ * Homa sockets. These functions are relatively generic: they are called
+ * to implement top-level system calls. Many of these operations can
+ * be implemented by PF_INET6 functions that are independent of the
+ * Homa protocol.
+ */
+static const struct proto_ops homa_proto_ops = {
+	.family		   = PF_INET,
+	.owner		   = THIS_MODULE,
+	.release	   = inet_release,
+	.bind		   = homa_bind,
+	.connect	   = inet_dgram_connect,
+	.socketpair	   = sock_no_socketpair,
+	.accept		   = sock_no_accept,
+	.getname	   = inet_getname,
+	.poll		   = homa_poll,
+	.ioctl		   = homa_ioctl,
+	.listen		   = sock_no_listen,
+	.shutdown	   = homa_shutdown,
+	.setsockopt	   = sock_common_setsockopt,
+	.getsockopt	   = sock_common_getsockopt,
+	.sendmsg	   = inet_sendmsg,
+	.recvmsg	   = inet_recvmsg,
+	.mmap		   = sock_no_mmap,
+	.set_peek_off	   = sk_set_peek_off,
+};
+
+static const struct proto_ops homav6_proto_ops = {
+	.family		   = PF_INET6,
+	.owner		   = THIS_MODULE,
+	.release	   = inet6_release,
+	.bind		   = homa_bind,
+	.connect	   = inet_dgram_connect,
+	.socketpair	   = sock_no_socketpair,
+	.accept		   = sock_no_accept,
+	.getname	   = inet6_getname,
+	.poll		   = homa_poll,
+	.ioctl		   = homa_ioctl,
+	.listen		   = sock_no_listen,
+	.shutdown	   = homa_shutdown,
+	.setsockopt	   = sock_common_setsockopt,
+	.getsockopt	   = sock_common_getsockopt,
+	.sendmsg	   = inet_sendmsg,
+	.recvmsg	   = inet_recvmsg,
+	.mmap		   = sock_no_mmap,
+	.set_peek_off	   = sk_set_peek_off,
+};
+
+/* This structure also defines functions that handle various operations
+ * on Homa sockets. However, these functions are lower-level than those
+ * in homa_proto_ops: they are specific to the PF_INET or PF_INET6
+ * protocol family, and in many cases they are invoked by functions in
+ * homa_proto_ops. Most of these functions have Homa-specific implementations.
+ */
+static struct proto homa_prot = {
+	.name		   = "HOMA",
+	.owner		   = THIS_MODULE,
+	.close		   = homa_close,
+	.connect	   = ip4_datagram_connect,
+	.init		   = homa_socket,
+	.destroy	   = homa_sock_destroy,
+	.setsockopt	   = homa_setsockopt,
+	.getsockopt	   = homa_getsockopt,
+	.sendmsg	   = homa_sendmsg,
+	.recvmsg	   = homa_recvmsg,
+	.hash		   = homa_hash,
+	.unhash		   = homa_unhash,
+	.obj_size	   = sizeof(struct homa_sock),
+	.no_autobind       = 1,
+};
+
+static struct proto homav6_prot = {
+	.name		   = "HOMAv6",
+	.owner		   = THIS_MODULE,
+	.close		   = homa_close,
+	.connect	   = ip6_datagram_connect,
+	.init		   = homa_socket,
+	.destroy	   = homa_sock_destroy,
+	.setsockopt	   = homa_setsockopt,
+	.getsockopt	   = homa_getsockopt,
+	.sendmsg	   = homa_sendmsg,
+	.recvmsg	   = homa_recvmsg,
+	.hash		   = homa_hash,
+	.unhash		   = homa_unhash,
+	.obj_size	   = sizeof(struct homa_v6_sock),
+	.ipv6_pinfo_offset = offsetof(struct homa_v6_sock, inet6),
+	.no_autobind       = 1,
+};
+
+/* Top-level structure describing the Homa protocol. */
+static struct inet_protosw homa_protosw = {
+	.type              = SOCK_DGRAM,
+	.protocol          = IPPROTO_HOMA,
+	.prot              = &homa_prot,
+	.ops               = &homa_proto_ops,
+	.flags             = INET_PROTOSW_REUSE,
+};
+
+static struct inet_protosw homav6_protosw = {
+	.type              = SOCK_DGRAM,
+	.protocol          = IPPROTO_HOMA,
+	.prot              = &homav6_prot,
+	.ops               = &homav6_proto_ops,
+	.flags             = INET_PROTOSW_REUSE,
+};
+
+/* This structure is used by IP to deliver incoming Homa packets to us. */
+static struct net_protocol homa_protocol = {
+	.handler =	homa_softirq,
+	.err_handler =	homa_err_handler_v4,
+	.no_policy =     1,
+};
+
+static struct inet6_protocol homav6_protocol = {
+	.handler =	homa_softirq,
+	.err_handler =	homa_err_handler_v6,
+	.flags =        INET6_PROTO_NOPOLICY | INET6_PROTO_FINAL,
+};
+
+/* Sizes of the headers for each Homa packet type, in bytes. */
+static u16 header_lengths[] = {
+	sizeof(struct homa_data_hdr),
+	0,
+	sizeof(struct homa_resend_hdr),
+	sizeof(struct homa_rpc_unknown_hdr),
+	sizeof(struct homa_busy_hdr),
+	0,
+	0,
+	sizeof(struct homa_need_ack_hdr),
+	sizeof(struct homa_ack_hdr)
+};
+
+/* Thread that runs timer code to detect lost packets and crashed peers. */
+static struct task_struct *timer_kthread;
+
+/* Used to wakeup timer_kthread at regular intervals. */
+static struct hrtimer hrtimer;
+
+/**
+ * homa_load() - invoked when this module is loaded into the Linux kernel
+ * Return: 0 on success, otherwise a negative errno.
+ */
+int __init homa_load(void)
+{
+	struct homa *homa = &homa_data;
+	bool init_protocol6 = false;
+	bool init_protosw6 = false;
+	bool init_protocol = false;
+	bool init_protosw = false;
+	bool init_net_ops = false;
+	bool init_proto6 = false;
+	bool init_proto = false;
+	bool init_homa = false;
+	int status;
+
+	/* Compile-time validations that no packet header is longer
+	 * than HOMA_MAX_HEADER.
+	 */
+	BUILD_BUG_ON(sizeof(struct homa_data_hdr) > HOMA_MAX_HEADER);
+	BUILD_BUG_ON(sizeof(struct homa_resend_hdr) > HOMA_MAX_HEADER);
+	BUILD_BUG_ON(sizeof(struct homa_rpc_unknown_hdr) > HOMA_MAX_HEADER);
+	BUILD_BUG_ON(sizeof(struct homa_busy_hdr) > HOMA_MAX_HEADER);
+	BUILD_BUG_ON(sizeof(struct homa_need_ack_hdr) > HOMA_MAX_HEADER);
+	BUILD_BUG_ON(sizeof(struct homa_ack_hdr) > HOMA_MAX_HEADER);
+
+	/* Extra constraints on data packets:
+	 * - Ensure minimum header length so Homa doesn't have to worry about
+	 *   padding data packets.
+	 * - Make sure data packet headers are a multiple of 4 bytes (needed
+	 *   for TCP/TSO compatibility).
+	 */
+	BUILD_BUG_ON(sizeof(struct homa_data_hdr) < HOMA_MIN_PKT_LENGTH);
+	BUILD_BUG_ON((sizeof(struct homa_data_hdr) -
+		      sizeof(struct homa_seg_hdr)) & 0x3);
+
+	/* Detect size changes in uAPI structs. */
+	BUILD_BUG_ON(sizeof(struct homa_sendmsg_args) != 24);
+	BUILD_BUG_ON(sizeof(struct homa_recvmsg_args) != 88);
+
+	status = homa_init(homa);
+	if (status)
+		goto error;
+	init_homa = true;
+
+	status = register_pernet_subsys(&homa_net_ops);
+	if (status != 0) {
+		pr_err("Homa got error from register_pernet_subsys: %d\n",
+		       status);
+		goto error;
+	}
+	init_net_ops = true;
+
+	status = proto_register(&homa_prot, 1);
+	if (status != 0) {
+		pr_err("proto_register failed for homa_prot: %d\n", status);
+		goto error;
+	}
+	init_proto = true;
+
+	status = proto_register(&homav6_prot, 1);
+	if (status != 0) {
+		pr_err("proto_register failed for homav6_prot: %d\n", status);
+		goto error;
+	}
+	init_proto6 = true;
+
+	inet_register_protosw(&homa_protosw);
+	init_protosw = true;
+
+	status = inet6_register_protosw(&homav6_protosw);
+	if (status != 0) {
+		pr_err("inet6_register_protosw failed in %s: %d\n", __func__,
+		       status);
+		goto error;
+	}
+	init_protosw6 = true;
+
+	status = inet_add_protocol(&homa_protocol, IPPROTO_HOMA);
+	if (status != 0) {
+		pr_err("inet_add_protocol failed in %s: %d\n", __func__,
+		       status);
+		goto error;
+	}
+	init_protocol = true;
+
+	status = inet6_add_protocol(&homav6_protocol, IPPROTO_HOMA);
+	if (status != 0) {
+		pr_err("inet6_add_protocol failed in %s: %d\n",  __func__,
+		       status);
+		goto error;
+	}
+	init_protocol6 = true;
+
+	timer_kthread = kthread_run(homa_timer_main, homa, "homa_timer");
+	if (IS_ERR(timer_kthread)) {
+		status = PTR_ERR(timer_kthread);
+		pr_err("couldn't create Homa timer thread: error %d\n",
+		       status);
+		timer_kthread = NULL;
+		goto error;
+	}
+
+	return 0;
+
+error:
+	if (timer_kthread)
+		kthread_stop(timer_kthread);
+	if (init_homa)
+		homa_destroy(homa);
+	if (init_protocol)
+		inet_del_protocol(&homa_protocol, IPPROTO_HOMA);
+	if (init_protocol6)
+		inet6_del_protocol(&homav6_protocol, IPPROTO_HOMA);
+	if (init_protosw)
+		inet_unregister_protosw(&homa_protosw);
+	if (init_protosw6)
+		inet6_unregister_protosw(&homav6_protosw);
+	if (init_proto)
+		proto_unregister(&homa_prot);
+	if (init_proto6)
+		proto_unregister(&homav6_prot);
+	if (init_net_ops)
+		unregister_pernet_subsys(&homa_net_ops);
+	return status;
+}
+
+/**
+ * homa_unload() - invoked when this module is unloaded from the Linux kernel.
+ */
+void __exit homa_unload(void)
+{
+	struct homa *homa = &homa_data;
+
+	pr_notice("Homa module unloading\n");
+
+	if (timer_kthread)
+		kthread_stop(timer_kthread);
+	inet_del_protocol(&homa_protocol, IPPROTO_HOMA);
+	inet_unregister_protosw(&homa_protosw);
+	inet6_del_protocol(&homav6_protocol, IPPROTO_HOMA);
+	inet6_unregister_protosw(&homav6_protosw);
+	proto_unregister(&homa_prot);
+	proto_unregister(&homav6_prot);
+	unregister_pernet_subsys(&homa_net_ops);
+	homa_destroy(homa);
+}
+
+module_init(homa_load);
+module_exit(homa_unload);
+
+/**
+ * homa_net_start() - Initialize Homa for a new network namespace.
+ * @net:    The net that Homa will be associated with.
+ * Return:  0 on success, otherwise a negative errno.
+ */
+int homa_net_start(struct net *net)
+{
+	pr_notice("Homa attaching to net namespace\n");
+	return homa_net_init(homa_net(net), &homa_data);
+}
+
+/**
+ * homa_net_exit() - Perform Homa cleanup needed when a network namespace
+ * is destroyed.
+ * @net:    The net from which Homa should be removed.
+ */
+void homa_net_exit(struct net *net)
+{
+	pr_notice("Homa detaching from net namespace\n");
+	homa_net_destroy(homa_net(net));
+}
+
+/**
+ * homa_bind() - Implements the bind system call for Homa sockets: associates
+ * a well-known service port with a socket. Unlike other AF_INET6 protocols,
+ * there is no need to invoke this system call for sockets that are only
+ * used as clients.
+ * @sock:     Socket on which the system call was invoked.
+ * @addr:     Contains the desired port number.
+ * @addr_len: Number of bytes in uaddr.
+ * Return:    0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *            on errors.
+ */
+int homa_bind(struct socket *sock, struct sockaddr_unsized *addr, int addr_len)
+{
+	union sockaddr_in_union *addr_in = (union sockaddr_in_union *)addr;
+	struct homa_sock *hsk = homa_sk(sock->sk);
+	int port = 0;
+
+	if (unlikely(addr->sa_family != sock->sk->sk_family)) {
+		hsk->error_msg = "address family in bind address didn't match socket";
+		return -EAFNOSUPPORT;
+	}
+	if (addr_in->in6.sin6_family == AF_INET6) {
+		if (addr_len < sizeof(struct sockaddr_in6)) {
+			hsk->error_msg = "ipv6 address too short";
+			return -EINVAL;
+		}
+		port = ntohs(addr_in->in6.sin6_port);
+	} else if (addr_in->in4.sin_family == AF_INET) {
+		if (addr_len < sizeof(struct sockaddr_in)) {
+			hsk->error_msg = "ipv4 address too short";
+			return -EINVAL;
+		}
+		port = ntohs(addr_in->in4.sin_port);
+	}
+	return homa_sock_bind(hsk->hnet, hsk, port);
+}
+
+/**
+ * homa_close() - Invoked when close system call is invoked on a Homa socket.
+ * @sk:      Socket being closed
+ * @timeout: ??
+ */
+void homa_close(struct sock *sk, long timeout)
+{
+	struct homa_sock *hsk = homa_sk(sk);
+
+	homa_sock_shutdown(hsk);
+	sk_common_release(sk);
+}
+
+/**
+ * homa_shutdown() - Implements the shutdown system call for Homa sockets.
+ * @sock:    Socket to shut down.
+ * @how:     Ignored: for other sockets, can independently shut down
+ *           sending and receiving, but for Homa any shutdown will
+ *           shut down everything.
+ *
+ * Return: 0 on success, otherwise a negative errno.
+ */
+int homa_shutdown(struct socket *sock, int how)
+{
+	homa_sock_shutdown(homa_sk(sock->sk));
+	return 0;
+}
+
+/**
+ * homa_ioc_info() - The top-level function that implements the
+ * HOMAIOCINFO ioctl for Homa sockets.
+ * @sock:  Socket for this request
+ * @arg:   The address in user space of the argument to ioctl, which
+ *          is a homa_info struct.
+ *
+ * Return:  0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *          on errors.
+ */
+int homa_ioc_info(struct socket *sock, unsigned long arg)
+{
+	struct homa_sock *hsk = homa_sk(sock->sk);
+	struct homa_rpc **rpcs = NULL;
+	struct homa_rpc_info rinfo;
+	struct homa_info hinfo;
+	struct homa_rpc *rpc;
+	int result = 0;
+	int bytes_avl;
+	int num_rpcs;
+	char *dst;
+	int i;
+
+	if (unlikely(copy_from_user(&hinfo, (void __user *)arg,
+				    sizeof(hinfo)))) {
+		hsk->error_msg = "invalid address for homa_info";
+		return -EFAULT;
+	}
+
+	if (!homa_protect_rpcs(hsk)) {
+		hsk->error_msg = "socket has been shut down";
+		return -ESHUTDOWN;
+	}
+	hinfo.bpool_avail_bytes = homa_pool_avail_bytes(hsk->buffer_pool);
+	hinfo.port = hsk->port;
+	dst = (char *)hinfo.rpc_info;
+	bytes_avl = hinfo.rpc_info_length;
+	hinfo.num_rpcs = 0;
+
+	/* This function is tricky because we need to hold an RCU lock
+	 * while scanning the RPCs of the socket, but we can't hold the
+	 * RCU lock while copying status information out to user space.
+	 * Thus, we first collect pointers to all the RPCs in a separate
+	 * array (while holding an RCU lock), acquire a reference on each
+	 * RPC, then release the RCU lock and copy out to user space.
+	 */
+	num_rpcs = 0;
+	rcu_read_lock();
+	list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links)
+		num_rpcs++;
+
+	if (num_rpcs > 0) {
+		/* Allocate an array and populate it with homa_rpc pointers.
+		 * Must release the RCU lock temporarily while allocating.
+		 */
+		rcu_read_unlock();
+		rpcs = kmalloc_objs(*rpcs, num_rpcs, GFP_KERNEL_ACCOUNT);
+		if (!rpcs) {
+			homa_unprotect_rpcs(hsk);
+			return -ENOMEM;
+		}
+		rcu_read_lock();
+		i = 0;
+		list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
+			homa_rpc_lock(rpc);
+			if (rpc->state != RPC_DEAD) {
+				rpcs[i] = rpc;
+				homa_rpc_hold(rpc);
+				i++;
+			}
+			homa_rpc_unlock(rpc);
+			if (i == num_rpcs)
+				break;
+		}
+		/* The number of RPCs could have changed between the first
+		 * pass and the second pass.
+		 */
+		num_rpcs = i;
+	}
+	rcu_read_unlock();
+	homa_unprotect_rpcs(hsk);
+
+	/* Now scan the array and copy information out to user space.  Note
+	 * that RPCs could have ended since we added them to the array.
+	 */
+	for (i = 0; i < num_rpcs; i++) {
+		rpc = rpcs[i];
+		homa_rpc_lock(rpc);
+		homa_rpc_put(rpc);
+		if (rpc->state == RPC_DEAD) {
+			homa_rpc_unlock(rpc);
+			continue;
+		}
+		homa_rpc_get_info(rpc, &rinfo);
+		homa_rpc_unlock(rpc);
+		if (dst && bytes_avl >= sizeof(rinfo) && result == 0) {
+			if (copy_to_user((void __user *)dst, &rinfo,
+					 sizeof(rinfo))) {
+				hsk->error_msg = "couldn't copy homa_rpc_info to user space: invalid or read-only address?";
+				result = -EFAULT;
+			}
+			dst += sizeof(rinfo);
+			bytes_avl -= sizeof(rinfo);
+		}
+		hinfo.num_rpcs++;
+	}
+	kfree(rpcs);
+
+	snprintf(hinfo.error_msg, HOMA_ERROR_MSG_SIZE, "%s", hsk->error_msg);
+
+	if (copy_to_user((void __user *)arg, &hinfo, sizeof(hinfo))) {
+		hsk->error_msg = "couldn't copy homa_info to user space: read-only address?";
+		return -EFAULT;
+	}
+	return result;
+}
+
+/**
+ * homa_ioctl() - Implements the ioctl system call for Homa sockets.
+ * @sock:  Socket on which the system call was invoked.
+ * @cmd:   Identifier for a particular ioctl operation.
+ * @arg:   Operation-specific argument; typically the address of a block
+ *         of data in user address space.
+ *
+ * Return: 0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *         on errors.
+ */
+int homa_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
+{
+	if (cmd == HOMAIOCINFO)
+		return homa_ioc_info(sock, arg);
+	homa_sk(sock->sk)->error_msg = "ioctl opcode isn't supported by Homa";
+	return -EINVAL;
+}
+
+/**
+ * homa_socket() - Implements the socket(2) system call for sockets.
+ * @sk:    Socket on which the system call was invoked. The non-Homa
+ *         parts have already been initialized.
+ *
+ * Return: always 0 (success).
+ */
+int homa_socket(struct sock *sk)
+{
+	return homa_sock_init(homa_sk(sk));
+}
+
+/**
+ * homa_setsockopt() - Implements the setsockopt system call for Homa sockets.
+ * @sk:      Socket on which the system call was invoked.
+ * @level:   Level at which the operation should be handled; will always
+ *           be IPPROTO_HOMA.
+ * @optname: Identifies a particular setsockopt operation.
+ * @optval:  Address in user space of information about the option.
+ * @optlen:  Number of bytes of data at @optval.
+ * Return:   0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *           on errors.
+ */
+int homa_setsockopt(struct sock *sk, int level, int optname,
+		    sockptr_t optval, unsigned int optlen)
+{
+	struct homa_sock *hsk = homa_sk(sk);
+	int ret;
+
+	if (level != IPPROTO_HOMA) {
+		hsk->error_msg = "homa_setsockopt invoked with level not IPPROTO_HOMA";
+		return -ENOPROTOOPT;
+	}
+
+	if (optname == SO_HOMA_RCVBUF) {
+		struct homa_rcvbuf_args args;
+
+		if (optlen != sizeof(struct homa_rcvbuf_args)) {
+			hsk->error_msg = "invalid optlen argument: must be sizeof(struct homa_rcvbuf_args)";
+			return -EINVAL;
+		}
+
+		if (copy_from_sockptr(&args, optval, optlen)) {
+			hsk->error_msg = "invalid address for homa_rcvbuf_args";
+			return -EFAULT;
+		}
+
+		/* Do a trivial test to make sure we can at least write the
+		 * first page of the region.
+		 */
+		if (copy_to_user(u64_to_user_ptr(args.start), &args,
+				 sizeof(args))) {
+			hsk->error_msg = "receive buffer region is not writable";
+			return -EFAULT;
+		}
+
+		ret = homa_pool_set_region(hsk, u64_to_user_ptr(args.start),
+					   args.length);
+	} else if (optname == SO_HOMA_SERVER) {
+		int arg;
+
+		if (optlen != sizeof(arg)) {
+			hsk->error_msg = "invalid optlen argument: must be sizeof(int)";
+			return -EINVAL;
+		}
+
+		if (copy_from_sockptr(&arg, optval, optlen)) {
+			hsk->error_msg = "invalid address for SO_HOMA_SERVER value";
+			return -EFAULT;
+		}
+
+		if (arg)
+			hsk->is_server = true;
+		else
+			hsk->is_server = false;
+		ret = 0;
+	} else {
+		hsk->error_msg = "setsockopt option not supported by Homa";
+		ret = -ENOPROTOOPT;
+	}
+	return ret;
+}
+
+/**
+ * homa_getsockopt() - Implements the getsockopt system call for Homa sockets.
+ * @sk:      Socket on which the system call was invoked.
+ * @level:   Selects level in the network stack to handle the request;
+ *           must be IPPROTO_HOMA.
+ * @optname: Identifies a particular setsockopt operation.
+ * @optval:  Address in user space where the option's value should be stored.
+ * @optlen:  Number of bytes available at optval; will be overwritten with
+ *           actual number of bytes stored.
+ * Return:   0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *           on errors.
+ */
+int homa_getsockopt(struct sock *sk, int level, int optname,
+		    char __user *optval, int __user *optlen)
+{
+	struct homa_sock *hsk = homa_sk(sk);
+	struct homa_rcvbuf_args rcvbuf_args;
+	int is_server;
+	void *result;
+	int len;
+
+	if (copy_from_sockptr(&len, USER_SOCKPTR(optlen), sizeof(int))) {
+		hsk->error_msg = "invalid address for optlen argument to getsockopt";
+		return -EFAULT;
+	}
+
+	if (level != IPPROTO_HOMA) {
+		hsk->error_msg = "homa_getsockopt invoked with level not IPPROTO_HOMA";
+		return -ENOPROTOOPT;
+	}
+	if (optname == SO_HOMA_RCVBUF) {
+		if (len < sizeof(rcvbuf_args)) {
+			hsk->error_msg = "invalid optlen argument: must be sizeof(struct homa_rcvbuf_args)";
+			return -EINVAL;
+		}
+
+		homa_sock_lock(hsk);
+		homa_pool_get_rcvbuf(hsk->buffer_pool, &rcvbuf_args);
+		homa_sock_unlock(hsk);
+		len = sizeof(rcvbuf_args);
+		result = &rcvbuf_args;
+	} else if (optname == SO_HOMA_SERVER) {
+		if (len < sizeof(is_server)) {
+			hsk->error_msg = "invalid optlen argument: must be sizeof(int)";
+			return -EINVAL;
+		}
+
+		is_server = hsk->is_server;
+		len = sizeof(is_server);
+		result = &is_server;
+	} else {
+		hsk->error_msg = "getsockopt option not supported by Homa";
+		return -ENOPROTOOPT;
+	}
+
+	if (copy_to_sockptr(USER_SOCKPTR(optlen), &len, sizeof(int))) {
+		hsk->error_msg = "couldn't update optlen argument to getsockopt: read-only?";
+		return -EFAULT;
+	}
+
+	if (copy_to_sockptr(USER_SOCKPTR(optval), result, len)) {
+		hsk->error_msg = "couldn't update optval argument to getsockopt: read-only?";
+		return -EFAULT;
+	}
+
+	return 0;
+}
+
+/**
+ * homa_sendmsg() - Send a request or response message on a Homa socket.
+ * @sk:     Socket on which the system call was invoked.
+ * @msg:    Structure describing the message to send; the msg_control
+ *          field points to additional information.
+ * @length: Number of bytes of the message.
+ * Return:  0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *          on errors.
+ */
+int homa_sendmsg(struct sock *sk, struct msghdr *msg, size_t length)
+{
+	DECLARE_SOCKADDR(union sockaddr_in_union *, addr, msg->msg_name);
+	struct homa_sock *hsk = homa_sk(sk);
+	struct homa_sendmsg_args args;
+	struct homa_rpc *rpc = NULL;
+	int result = 0;
+
+	if (!addr) {
+		hsk->error_msg = "no msg_name passed to sendmsg";
+		result = -EINVAL;
+		goto error;
+	}
+
+	if (unlikely(!msg->msg_control_is_user)) {
+		hsk->error_msg = "msg_control argument for sendmsg isn't in user space";
+		result = -EINVAL;
+		goto error;
+	}
+	if (unlikely(copy_from_user(&args, (void __user *)msg->msg_control,
+				    sizeof(args)))) {
+		hsk->error_msg = "invalid address for msg_control argument to sendmsg";
+		result = -EFAULT;
+		goto error;
+	}
+	if (args.flags & ~HOMA_SENDMSG_VALID_FLAGS ||
+	    args.reserved != 0) {
+		hsk->error_msg = "reserved fields in homa_sendmsg_args must be zero";
+		result = -EINVAL;
+		goto error;
+	}
+
+	if (!homa_sock_wmem_avl(hsk)) {
+		result = homa_sock_wait_wmem(hsk,
+					     msg->msg_flags & MSG_DONTWAIT);
+		if (result != 0)
+			goto error;
+	}
+
+	if (addr->sa.sa_family != sk->sk_family) {
+		hsk->error_msg = "address family in sendmsg address must match the socket";
+		result = -EAFNOSUPPORT;
+		goto error;
+	}
+	if (msg->msg_namelen < sizeof(struct sockaddr_in) ||
+	    (msg->msg_namelen < sizeof(struct sockaddr_in6) &&
+	     addr->in6.sin6_family == AF_INET6)) {
+		hsk->error_msg = "msg_namelen too short";
+		result = -EINVAL;
+		goto error;
+	}
+
+	if (unlikely(msg->msg_iter.count == 0)) {
+		hsk->error_msg = "message has length zero";
+		result = -EINVAL;
+		goto error;
+	}
+	if (unlikely(msg->msg_iter.count > HOMA_MAX_MESSAGE_LENGTH)) {
+		hsk->error_msg = "message length exceeded HOMA_MAX_MESSAGE_LENGTH";
+		result = -EINVAL;
+		goto error;
+	}
+
+	if (!args.id) {
+		/* This is a request message. */
+		rpc = homa_rpc_alloc_client(hsk, addr);
+		if (IS_ERR(rpc)) {
+			result = PTR_ERR(rpc);
+			rpc = NULL;
+			goto error;
+		}
+		homa_rpc_hold(rpc);
+		if (args.flags & HOMA_SENDMSG_PRIVATE)
+			set_bit(RPC_PRIVATE, &rpc->flags);
+		rpc->completion_cookie = args.completion_cookie;
+		result = homa_tx_copy_from_user(rpc, &msg->msg_iter, true);
+		if (result)
+			goto error;
+		args.id = rpc->id;
+		homa_rpc_unlock(rpc); /* Locked by homa_rpc_alloc_client. */
+
+		if (unlikely(copy_to_user((void __user *)msg->msg_control,
+					  &args, sizeof(args)))) {
+			homa_rpc_lock(rpc);
+			hsk->error_msg = "couldn't update homa_sendmsg_args argument to sendmsg: read-only?";
+			result = -EFAULT;
+			goto error;
+		}
+		homa_rpc_put(rpc);
+	} else {
+		/* This is a response message. */
+		struct in6_addr canonical_dest;
+
+		if (args.completion_cookie != 0) {
+			hsk->error_msg = "completion_cookie must be zero when sending responses";
+			result = -EINVAL;
+			goto error;
+		}
+		canonical_dest = canonical_ipv6_addr(addr);
+
+		rpc = homa_rpc_find_server(hsk, &canonical_dest, args.id);
+		if (!rpc) {
+			/* Return without an error if the RPC doesn't exist;
+			 * this could be totally valid (e.g. client is
+			 * no longer interested in it).
+			 */
+			return 0;
+		}
+		homa_rpc_hold(rpc);
+		if (rpc->error) {
+			hsk->error_msg = "RPC has failed, so can't send response";
+			result = rpc->error;
+			goto error;
+		}
+		if (rpc->state != RPC_IN_SERVICE) {
+			hsk->error_msg = "RPC is not in a state where a response can be sent";
+			result = -EINVAL;
+			goto error_dont_end_rpc;
+		}
+		rpc->state = RPC_OUTGOING;
+
+		result = homa_tx_copy_from_user(rpc, &msg->msg_iter, true);
+		if (result && rpc->state != RPC_DEAD) {
+			hsk->error_msg = "error copying response message data from user space";
+			goto error;
+		}
+		homa_rpc_put(rpc);
+		homa_rpc_unlock(rpc); /* Locked by homa_rpc_find_server. */
+	}
+	return 0;
+
+error:
+	if (rpc)
+		homa_rpc_end(rpc);
+
+error_dont_end_rpc:
+	if (rpc) {
+		homa_rpc_put(rpc);
+
+		/* Locked by homa_rpc_find_server or homa_rpc_alloc_client. */
+		homa_rpc_unlock(rpc);
+	}
+	return result;
+}
+
+/**
+ * homa_recvmsg() - Receive a message from a Homa socket.
+ * @sk:          Socket on which the system call was invoked.
+ * @msg:         Controlling information for the receive.
+ * @len:         Total bytes of space available in msg->msg_iov; not used.
+ * @flags:       Flags from system call; only MSG_DONTWAIT is used.
+ * Return:       The length of the message on success, otherwise a negative
+ *               errno. Sets hsk->error_msg on errors.
+ */
+int homa_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags)
+{
+	struct homa_sock *hsk = homa_sk(sk);
+	struct homa_recvmsg_args control;
+	struct homa_rpc *rpc = NULL;
+	int nonblocking;
+	int result;
+
+	if (unlikely(!msg->msg_control)) {
+		/* This test isn't strictly necessary, but it provides a
+		 * hook for testing kernel call times.
+		 */
+		hsk->error_msg = "no msg_control passed to recvmsg";
+		return -EINVAL;
+	}
+	if (msg->msg_controllen != sizeof(control)) {
+		hsk->error_msg = "invalid msg_controllen in recvmsg";
+		return -EINVAL;
+	}
+	if (unlikely(copy_from_user(&control, (void __user *)msg->msg_control,
+				    sizeof(control)))) {
+		hsk->error_msg = "invalid address for msg_control argument to recvmsg";
+		return -EFAULT;
+	}
+	control.completion_cookie = 0;
+
+	if (control.num_bpages > HOMA_MAX_BPAGES) {
+		hsk->error_msg = "num_pages exceeds HOMA_MAX_BPAGES";
+		result = -EINVAL;
+		goto done;
+	}
+	if (control.reserved != 0) {
+		hsk->error_msg = "reserved fields in homa_recvmsg_args must be zero";
+		result = -EINVAL;
+		goto done;
+	}
+	if (!hsk->buffer_pool) {
+		hsk->error_msg = "SO_HOMA_RECVBUF socket option has not been set";
+		result = -EINVAL;
+		goto done;
+	}
+	result = homa_pool_free_bufs(hsk->buffer_pool, control.num_bpages,
+				     control.bpage_offsets);
+	control.num_bpages = 0;
+	if (result != 0) {
+		hsk->error_msg = "error while releasing buffer pages";
+		goto done;
+	}
+
+	nonblocking = flags & MSG_DONTWAIT;
+	if (control.id != 0) {
+		rpc = homa_rpc_find_client(hsk, control.id); /* Locks RPC. */
+		if (!rpc) {
+			hsk->error_msg = "invalid RPC id passed to recvmsg";
+			result = -EINVAL;
+			goto done;
+		}
+		homa_rpc_hold(rpc);
+		result = homa_wait_private(rpc, nonblocking);
+		if (result != 0) {
+			hsk->error_msg = "error while waiting for private RPC to complete";
+			control.id = 0;
+			goto done;
+		}
+	} else {
+		rpc = homa_wait_shared(hsk, nonblocking);
+		if (IS_ERR(rpc)) {
+			/* If we get here, it means there was an error that
+			 * prevented us from finding an RPC to return. Errors
+			 * in the RPC itself are handled below.
+			 */
+			hsk->error_msg = "error while waiting for shared RPC to complete";
+			result = PTR_ERR(rpc);
+			rpc = NULL;
+			goto done;
+		}
+	}
+	if (rpc->error) {
+		hsk->error_msg = "RPC failed";
+		result = rpc->error;
+	} else {
+		result = rpc->msgin.length;
+	}
+
+	/* Collect result information. */
+	control.id = rpc->id;
+	control.completion_cookie = rpc->completion_cookie;
+	if (likely(result > 0)) {
+		control.num_bpages = rpc->msgin.num_bpages;
+		memcpy(control.bpage_offsets, rpc->msgin.bpage_offsets,
+		       sizeof(rpc->msgin.bpage_offsets));
+	}
+	if (msg->msg_name) {
+		if (sk->sk_family == AF_INET6) {
+			DECLARE_SOCKADDR(struct sockaddr_in6 *, in6,
+					 msg->msg_name);
+
+			in6->sin6_family = AF_INET6;
+			in6->sin6_port = htons(rpc->dport);
+			in6->sin6_addr = rpc->route->peer->addr;
+			msg->msg_namelen = sizeof(*in6);
+		} else {
+			DECLARE_SOCKADDR(struct sockaddr_in *, in4,
+					 msg->msg_name);
+
+			in4->sin_family = AF_INET;
+			in4->sin_port = htons(rpc->dport);
+			in4->sin_addr.s_addr = ipv6_to_ipv4(rpc->route->peer->addr);
+			msg->msg_namelen = sizeof(*in4);
+		}
+	}
+
+	if (result < 0) {
+		homa_rpc_end(rpc);
+	} else {
+		/* This indicates that the application now owns the buffers, so
+		 * they won't be freed in homa_rpc_end.
+		 */
+		rpc->msgin.num_bpages = 0;
+		if (homa_is_client(rpc->id)) {
+			homa_peer_add_ack(rpc);
+			homa_rpc_end(rpc);
+		} else {
+			rpc->state = RPC_IN_SERVICE;
+		}
+	}
+
+done:
+	/* Note: must release the RPC lock before calling homa_rpc_reap
+	 * or copying results to user space.
+	 */
+	if (rpc) {
+		homa_rpc_put(rpc);
+
+		/* Locked by homa_rpc_find_client or homa_wait_shared. */
+		homa_rpc_unlock(rpc);
+	}
+
+	while (test_bit(HOMA_SOCK_NOSPACE, &hsk->flags)) {
+		/* There are tasks waiting for tx memory, so reap
+		 * immediately.
+		 */
+		if (!homa_rpc_reap(hsk))
+			break;
+	}
+
+	if (unlikely(copy_to_user((__force void __user *)msg->msg_control,
+				  &control, sizeof(control)))) {
+		hsk->error_msg = "couldn't update homa_recvmsg_args argument to recvmsg: read-only?";
+		result = -EFAULT;
+	}
+
+	return result;
+}
+
+/**
+ * homa_hash() - Not needed for Homa.
+ * @sk:    Socket for the operation
+ * Return: ??
+ */
+int homa_hash(struct sock *sk)
+{
+	return 0;
+}
+
+/**
+ * homa_unhash() - Not needed for Homa.
+ * @sk:    Socket for the operation
+ */
+void homa_unhash(struct sock *sk)
+{
+}
+
+/**
+ * homa_softirq() - This function is invoked at SoftIRQ level to handle
+ * incoming packets.
+ * @skb:   The incoming packet.
+ * Return: Always 0
+ */
+int homa_softirq(struct sk_buff *skb)
+{
+	struct sk_buff *packets, *other_pkts, *next;
+	struct sk_buff **prev_link, **other_link;
+	enum skb_drop_reason reason;
+	struct homa_common_hdr *h;
+	int header_offset;
+
+	/* skb may actually contain many distinct packets, linked through
+	 * skb_shinfo(skb)->frag_list by the Homa GRO mechanism. Make a
+	 * pass through the list to process all of the short packets,
+	 * leaving the longer packets in the list. Also, perform various
+	 * prep/cleanup/error checking functions.
+	 */
+	skb->next = skb_shinfo(skb)->frag_list;
+	skb_shinfo(skb)->frag_list = NULL;
+	packets = skb;
+	prev_link = &packets;
+	for (skb = packets; skb; skb = next) {
+		next = skb->next;
+
+		/* Make the header available at skb->data, even if the packet
+		 * is fragmented. One complication: it's possible that the IP
+		 * header hasn't yet been removed (this happens for GRO packets
+		 * on the frag_list, since they aren't handled explicitly by IP.
+		 */
+		if (!homa_make_header_avl(skb)) {
+			reason = SKB_DROP_REASON_HDR_TRUNC;
+			goto discard;
+		}
+		header_offset = skb_transport_header(skb) - skb->data;
+		if (header_offset)
+			__skb_pull(skb, header_offset);
+
+		/* Reject packets that are too short or have bogus types. */
+		h = (struct homa_common_hdr *)skb->data;
+		if (unlikely(skb->len < sizeof(struct homa_common_hdr) ||
+			     h->type < DATA || h->type > MAX_OP ||
+			     skb->len < header_lengths[h->type - DATA])) {
+			reason = SKB_DROP_REASON_PKT_TOO_SMALL;
+			goto discard;
+		}
+
+		/* Process the packet now if it is a control packet or
+		 * if it contains an entire short message.
+		 */
+		if (h->type != DATA || ntohl(((struct homa_data_hdr *)h)
+				->message_length) < 1400) {
+			*prev_link = skb->next;
+			skb->next = NULL;
+			homa_dispatch_pkts(skb);
+		} else {
+			prev_link = &skb->next;
+		}
+		continue;
+
+discard:
+		*prev_link = skb->next;
+		kfree_skb_reason(skb, reason);
+	}
+
+	/* Now process the longer packets. Each iteration of this loop
+	 * collects all of the packets for a particular RPC and dispatches
+	 * them (batching the packets for an RPC allows more efficient
+	 * generation of grants).
+	 */
+	while (packets) {
+		struct in6_addr saddr, saddr2;
+		struct homa_common_hdr *h2;
+		struct sk_buff *skb2;
+
+		skb = packets;
+		prev_link = &skb->next;
+		saddr = skb_canonical_ipv6_saddr(skb);
+		other_pkts = NULL;
+		other_link = &other_pkts;
+		h = (struct homa_common_hdr *)skb->data;
+		for (skb2 = skb->next; skb2; skb2 = next) {
+			next = skb2->next;
+			h2 = (struct homa_common_hdr *)skb2->data;
+			if (h2->sender_id == h->sender_id) {
+				saddr2 = skb_canonical_ipv6_saddr(skb2);
+				if (ipv6_addr_equal(&saddr, &saddr2)) {
+					*prev_link = skb2;
+					prev_link = &skb2->next;
+					continue;
+				}
+			}
+			*other_link = skb2;
+			other_link = &skb2->next;
+		}
+		*prev_link = NULL;
+		*other_link = NULL;
+		homa_dispatch_pkts(packets);
+		packets = other_pkts;
+	}
+
+	return 0;
+}
+
+/**
+ * homa_err_handler_v4() - Invoked by IP to handle an incoming error
+ * packet, such as ICMP UNREACHABLE.
+ * @skb:    The incoming packet; skb->data points to the byte just after
+ *          the ICMP header (the first byte of the embedded packet IP header).
+ * @skb:   The incoming packet.
+ * @info:  Information about the error that occurred?
+ *
+ * Return: zero, or a negative errno if the error couldn't be handled here.
+ */
+int homa_err_handler_v4(struct sk_buff *skb, u32 info)
+{
+	struct homa *homa = homa_net(dev_net(skb->dev))->homa;
+	const struct icmphdr *icmp = icmp_hdr(skb);
+	struct in6_addr daddr;
+	int type = icmp->type;
+	int code = icmp->code;
+	struct iphdr *iph;
+	int error = 0;
+	int port = 0;
+
+	iph = (struct iphdr *)(skb->data);
+	ipv6_addr_set_v4mapped(iph->daddr, &daddr);
+	if (type == ICMP_DEST_UNREACH && code == ICMP_PORT_UNREACH) {
+		struct homa_common_hdr *h = (struct homa_common_hdr *)(skb->data
+				+ iph->ihl * 4);
+
+		port = ntohs(h->dport);
+		error = -ENOTCONN;
+	} else if (type == ICMP_DEST_UNREACH) {
+		if (code == ICMP_PROT_UNREACH)
+			error = -EPROTONOSUPPORT;
+		else
+			error = -EHOSTUNREACH;
+	} else {
+		pr_notice("%s invoked with info %x, ICMP type %d, ICMP code %d\n",
+			  __func__, info, type, code);
+	}
+	if (error != 0)
+		homa_abort_rpcs(homa, &daddr, port, error);
+	return 0;
+}
+
+/**
+ * homa_err_handler_v6() - Invoked by IP to handle an incoming error
+ * packet, such as ICMP UNREACHABLE.
+ * @skb:    The incoming packet; skb->data points to the byte just after
+ *          the ICMP header (the first byte of the embedded packet IP header).
+ * @opt:    Not used.
+ * @type:   Type of ICMP packet.
+ * @code:   Additional information about the error.
+ * @offset: Total length of IPv6 header, including any extension headers.
+ * @info:   Information about the error that occurred?
+ *
+ * Return: zero, or a negative errno if the error couldn't be handled here.
+ */
+int homa_err_handler_v6(struct sk_buff *skb, struct inet6_skb_parm *opt,
+			u8 type,  u8 code,  int offset,  __be32 info)
+{
+	const struct ipv6hdr *iph = (const struct ipv6hdr *)skb->data;
+	struct homa *homa = homa_net(dev_net(skb->dev))->homa;
+	int error = 0;
+	int port = 0;
+
+	if (type == ICMPV6_DEST_UNREACH && code == ICMPV6_PORT_UNREACH) {
+		const struct homa_common_hdr *h;
+
+		h = (struct homa_common_hdr *)(skb->data + offset);
+		port = ntohs(h->dport);
+		error = -ENOTCONN;
+	} else if (type == ICMPV6_DEST_UNREACH && code == ICMPV6_ADDR_UNREACH) {
+		error = -EHOSTUNREACH;
+	} else if (type == ICMPV6_PARAMPROB && code == ICMPV6_UNK_NEXTHDR) {
+		error = -EPROTONOSUPPORT;
+	}
+	if (error != 0)
+		homa_abort_rpcs(homa, &iph->daddr, port, error);
+	return 0;
+}
+
+/**
+ * homa_poll() - Invoked by Linux as part of implementing select, poll,
+ * epoll, etc.
+ * @file:  Open file that is participating in a poll, select, etc.
+ * @sock:  A Homa socket, associated with @file.
+ * @wait:  This table will be registered with the socket, so that it
+ *         is notified when the socket's ready state changes.
+ *
+ * Return: A mask of bits such as EPOLLIN, which indicate the current
+ *         state of the socket.
+ */
+__poll_t homa_poll(struct file *file, struct socket *sock,
+		   struct poll_table_struct *wait)
+{
+	struct homa_sock *hsk = homa_sk(sock->sk);
+	__poll_t mask;
+
+	mask = 0;
+	sock_poll_wait(file, sock, wait);
+	if (homa_sock_wmem_avl(hsk))
+		mask |= EPOLLOUT | EPOLLWRNORM;
+	else
+		set_bit(HOMA_SOCK_NOSPACE, &hsk->flags);
+
+	if (hsk->shutdown)
+		mask |= EPOLLIN;
+
+	if (!list_empty(&hsk->ready_rpcs))
+		mask |= EPOLLIN | EPOLLRDNORM;
+	return mask;
+}
+
+/**
+ * homa_hrtimer() - This function is invoked by the hrtimer mechanism to
+ * wake up the timer thread. Runs at IRQ level.
+ * @timer:   The timer that triggered; not used.
+ *
+ * Return:   Always HRTIMER_NORESTART.
+ */
+enum hrtimer_restart homa_hrtimer(struct hrtimer *timer)
+{
+	wake_up_process(timer_kthread);
+	return HRTIMER_NORESTART;
+}
+
+/**
+ * homa_timer_main() - Top-level function for the timer thread.
+ * @transport:  Pointer to struct homa.
+ *
+ * Return:         Always 0.
+ */
+int homa_timer_main(void *transport)
+{
+	struct homa *homa = (struct homa *)transport;
+	ktime_t tick_interval;
+	u64 nsec;
+
+	hrtimer_setup(&hrtimer, homa_hrtimer, CLOCK_MONOTONIC,
+		      HRTIMER_MODE_REL);
+	nsec = 1000000;                   /* 1 ms */
+	tick_interval = ns_to_ktime(nsec);
+	while (1) {
+		set_current_state(TASK_UNINTERRUPTIBLE);
+		if (!kthread_should_stop()) {
+			hrtimer_start(&hrtimer, tick_interval,
+				      HRTIMER_MODE_REL);
+			schedule();
+		}
+		__set_current_state(TASK_RUNNING);
+		if (kthread_should_stop())
+			break;
+		homa_timer(homa);
+	}
+	hrtimer_cancel(&hrtimer);
+	return 0;
+}
+
+MODULE_LICENSE("Dual BSD/GPL");
+MODULE_AUTHOR("John Ousterhout <ouster@cs.stanford.edu>");
+MODULE_DESCRIPTION("Homa transport protocol");
+MODULE_VERSION("1.0");
+
+/* Arrange for this module to be loaded automatically when a Homa socket is
+ * opened. Apparently symbols don't work in the macros below, so must use
+ * numeric values for IPPROTO_HOMA (146) and SOCK_DGRAM(2).
+ */
+MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET, 146, 2);
+MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET6, 146, 2);
diff --git a/net/homa/homa_pool.c b/net/homa/homa_pool.c
new file mode 100644
index 0000000000000..0aadfbc53ef1b
--- /dev/null
+++ b/net/homa/homa_pool.c
@@ -0,0 +1,553 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+#include "homa_impl.h"
+#include "homa_pool.h"
+
+/* This file contains functions that manage user-space buffer pools. */
+
+/* Used when determining how many bpages to consider for allocation. */
+#define MIN_EXTRA 4
+
+/**
+ * set_bpages_needed() - Set the bpages_needed field of @pool based
+ * on the length of the first RPC that's waiting for buffer space.
+ * The caller must own the lock for @pool->hsk.
+ * @pool: Pool to update.
+ */
+static void set_bpages_needed(struct homa_pool *pool)
+{
+	struct homa_rpc *rpc = list_first_entry(&pool->hsk->waiting_for_bufs,
+						struct homa_rpc, buf_links);
+
+	pool->bpages_needed = (rpc->msgin.length + HOMA_BPAGE_SIZE - 1) >>
+			      HOMA_BPAGE_SHIFT;
+}
+
+/**
+ * homa_pool_alloc() - Allocate and initialize a new homa_pool (it will have
+ * no region associated with it until homa_pool_set_region is invoked).
+ * @hsk:          Socket the pool will be associated with.
+ * Return: A pointer to the new pool or a negative errno.
+ */
+struct homa_pool *homa_pool_alloc(struct homa_sock *hsk)
+{
+	struct homa_pool *pool;
+
+	pool = kzalloc_obj(*pool, GFP_KERNEL_ACCOUNT);
+	if (!pool)
+		return ERR_PTR(-ENOMEM);
+	pool->hsk = hsk;
+	return pool;
+}
+
+/**
+ * homa_pool_set_region() - Associate a region of memory with a pool.
+ * @hsk:          Socket whose pool the region will be associated with.
+ *                Must not be locked, and the pool must not currently
+ *                have a region associated with it.
+ * @region:       First byte of the memory region for the pool, allocated
+ *                by the application; must be page-aligned.
+ * @region_size:  Total number of bytes available at @buf_region.
+ * Return: Either zero (for success) or a negative errno for failure.
+ */
+int homa_pool_set_region(struct homa_sock *hsk, void __user *region,
+			 u64 region_size)
+{
+	struct homa_pool_core __percpu *cores;
+	struct homa_bpage *descriptors;
+	int i, result, num_bpages;
+	struct homa_pool *pool;
+	u64 min_size;
+
+	if (((uintptr_t)region) & ~PAGE_MASK) {
+		hsk->error_msg = "buffer pool is not page aligned";
+		return -EINVAL;
+	}
+
+	/* The region must be large enough to hold a private bpage for
+	 * each core, plus enough additional space for a couple of
+	 * full-size messages. Otherwise we could deadlock over allocation
+	 * (no free pages available, so no attempt is made to steal back
+	 * private pages).
+	 */
+	min_size = nr_cpu_ids;
+	min_size = min_size * HOMA_BPAGE_SIZE + 2 * HOMA_MAX_MESSAGE_LENGTH;
+	if (region_size < min_size) {
+		hsk->error_msg = "buffer pool is not large enough";
+		return -EINVAL;
+	}
+
+	/* The region must not be so large that offsets into the region
+	 * overflow the 32-bit values used in bpage_offsets in
+	 * homa_recvmsg_args.
+	 */
+	if (region_size > 0x100000000ULL) {
+		hsk->error_msg = "buffer pool cannot be larger than 4 GB";
+		return -EINVAL;
+	}
+
+	/* Allocate memory before locking the socket, so we can allocate
+	 * without GFP_ATOMIC.
+	 */
+	num_bpages = region_size >> HOMA_BPAGE_SHIFT;
+	descriptors = kmalloc_array(num_bpages, sizeof(struct homa_bpage),
+				    GFP_KERNEL | __GFP_ZERO | __GFP_ACCOUNT);
+	if (!descriptors)
+		return -ENOMEM;
+	cores = alloc_percpu_gfp(struct homa_pool_core, __GFP_ZERO);
+	if (!cores) {
+		result = -ENOMEM;
+		goto error;
+	}
+
+	homa_sock_lock(hsk);
+	pool = hsk->buffer_pool;
+	if (pool->region) {
+		result = -EINVAL;
+		homa_sock_unlock(hsk);
+		goto error;
+	}
+
+	pool->num_bpages = num_bpages;
+	pool->descriptors = descriptors;
+	atomic_set(&pool->free_bpages, pool->num_bpages);
+	pool->bpages_needed = INT_MAX;
+	pool->cores = cores;
+	pool->check_waiting_invoked = 0;
+
+	for (i = 0; i < pool->num_bpages; i++) {
+		struct homa_bpage *bp = &pool->descriptors[i];
+
+		spin_lock_init(&bp->lock);
+		bp->owner = -1;
+	}
+
+	/* Barrier ensures that concurrent cores trying to access
+	 * newly-created region will see all the region's data.
+	 */
+	smp_store_release(&pool->region, (char __user *)region);
+	homa_sock_unlock(hsk);
+	return 0;
+
+error:
+	kfree(descriptors);
+	free_percpu(cores);
+	return result;
+}
+
+/**
+ * homa_pool_free() - Destructor for homa_pool. After this method
+ * returns, the object should not be used (it will be freed here).
+ * @pool: Pool to destroy.
+ */
+void homa_pool_free(struct homa_pool *pool)
+{
+	if (homa_pool_exists(pool)) {
+		kfree(pool->descriptors);
+		free_percpu(pool->cores);
+		pool->region = NULL;
+	}
+	kfree(pool);
+}
+
+/**
+ * homa_pool_get_rcvbuf() - Return information needed to handle getsockopt
+ * for HOMA_SO_RCVBUF.
+ * @pool:         Pool for which information is needed.
+ * @args:         Store info here.
+ */
+void homa_pool_get_rcvbuf(struct homa_pool *pool,
+			  struct homa_rcvbuf_args *args)
+{
+	args->start = (uintptr_t)pool->region;
+	args->length = (u64)pool->num_bpages << HOMA_BPAGE_SHIFT;
+}
+
+/**
+ * homa_bpage_available() - Check whether a bpage is available for use.
+ * @bpage:      Bpage to check
+ * @now:        Current time (homa_clock() units)
+ * Return:      True if the bpage is free or if it can be stolen, otherwise
+ *              false.
+ */
+bool homa_bpage_available(struct homa_bpage *bpage, u64 now)
+{
+	return bpage->refs == 0 || (bpage->refs == 1 && bpage->owner >= 0 &&
+				    bpage->expiration <= now);
+}
+
+/**
+ * homa_pool_get_pages() - Allocate one or more full pages from the pool.
+ * @pool:         Pool from which to allocate pages
+ * @num_pages:    Number of pages needed
+ * @pages:        The indices of the allocated pages are stored here; caller
+ *                must ensure this array is big enough. Reference counts have
+ *                been set to 1 on all of these pages (or 2 if set_owner
+ *                was specified).
+ * @set_owner:    If nonzero, the current core is marked as owner of all
+ *                of the allocated pages (and the expiration time is also
+ *                set). Otherwise the pages are left unowned.
+ * Return: 0 for success, -1 if there wasn't enough free space in the pool.
+ */
+int homa_pool_get_pages(struct homa_pool *pool, int num_pages, u32 *pages,
+			int set_owner)
+{
+	int core_num = smp_processor_id();
+	struct homa_pool_core *core;
+	u64 now = homa_clock();
+	int alloced = 0;
+	int limit = 0;
+	int free;
+
+	core = this_cpu_ptr(pool->cores);
+
+	/* Atomically check for available space and decrement the
+	 * free page counter.
+	 */
+	free = atomic_read_acquire(&pool->free_bpages);
+	while (1) {
+		if (free < num_pages)
+			return -1;
+		if (atomic_try_cmpxchg(&pool->free_bpages, &free,
+				       free - num_pages))
+			break;
+	}
+
+	/* Once we get to this point we know we will be able to find
+	 * enough free pages; now we just have to find them.
+	 */
+	while (alloced != num_pages) {
+		struct homa_bpage *bpage;
+		int cur;
+
+		/* If we don't need to use all of the bpages in the pool,
+		 * then try to use only the ones with low indexes. This
+		 * will reduce the cache footprint for the pool by reusing
+		 * a few bpages over and over. Specifically this code will
+		 * not consider any candidate page whose index is >= limit.
+		 * Limit is chosen to make sure there are a reasonable
+		 * number of free pages in the range, so we won't have to
+		 * check a huge number of pages.
+		 */
+		if (limit == 0) {
+			int extra;
+
+			limit = pool->num_bpages -
+				atomic_read(&pool->free_bpages);
+			extra = limit >> 2;
+			limit += (extra < MIN_EXTRA) ? MIN_EXTRA : extra;
+			if (limit > pool->num_bpages)
+				limit = pool->num_bpages;
+		}
+
+		cur = core->next_candidate;
+		core->next_candidate++;
+		if (cur >= limit) {
+			core->next_candidate = 0;
+
+			/* Must recompute the limit for each new loop through
+			 * the bpage array: we may need to consider a larger
+			 * range of pages because of concurrent allocations.
+			 */
+			limit = 0;
+			continue;
+		}
+		bpage = &pool->descriptors[cur];
+
+		/* Figure out whether this candidate is free (or can be
+		 * stolen). Do a quick check without locking the page, and
+		 * if the page looks promising, then lock it and check again
+		 * (must check again in case someone else snuck in and
+		 * grabbed the page).
+		 */
+		if (!homa_bpage_available(bpage, now))
+			continue;
+		if (!spin_trylock_bh(&bpage->lock))
+			/* Rather than wait for a locked page to become free,
+			 * just go on to the next page. If the page is locked,
+			 * it probably won't turn out to be available anyway.
+			 */
+			continue;
+		if (!homa_bpage_available(bpage, now)) {
+			spin_unlock_bh(&bpage->lock);
+			continue;
+		}
+		if (bpage->owner >= 0)
+			atomic_fetch_inc_release(&pool->free_bpages);
+		if (set_owner) {
+			bpage->refs = 2;
+			bpage->owner = core_num;
+			bpage->expiration = now +
+					    pool->hsk->homa->bpage_lease_cycles;
+		} else {
+			bpage->refs = 1;
+			bpage->owner = -1;
+		}
+		spin_unlock_bh(&bpage->lock);
+		pages[alloced] = cur;
+		alloced++;
+	}
+	return 0;
+}
+
+/**
+ * homa_pool_alloc_msg() - Allocate buffer space for an incoming message.
+ * @rpc:  RPC that needs space allocated for its incoming message (space must
+ *        not already have been allocated). The fields @msgin->num_buffers
+ *        and @msgin->buffers are filled in. Must be locked by caller.
+ * Return: The return value is normally 0, which means either buffer space
+ * was allocated or the @rpc was queued on @hsk->waiting. If a fatal error
+ * occurred, such as no buffer pool present, then a negative errno is
+ * returned.
+ */
+int homa_pool_alloc_msg(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_pool *pool = rpc->hsk->buffer_pool;
+	int full_pages, partial, i, core_id;
+	struct homa_pool_core *core;
+	u32 pages[HOMA_MAX_BPAGES];
+	struct homa_bpage *bpage;
+	struct homa_rpc *other;
+
+	if (!homa_pool_exists(pool))
+		return -ENOMEM;
+	if (rpc->state == RPC_DEAD)
+		return 0;
+
+	/* First allocate any full bpages that are needed. */
+	full_pages = rpc->msgin.length >> HOMA_BPAGE_SHIFT;
+	if (unlikely(full_pages)) {
+		if (homa_pool_get_pages(pool, full_pages, pages, 0) != 0)
+			goto out_of_space;
+		for (i = 0; i < full_pages; i++)
+			rpc->msgin.bpage_offsets[i] = pages[i] <<
+					HOMA_BPAGE_SHIFT;
+	}
+	rpc->msgin.num_bpages = full_pages;
+
+	/* The last chunk may be less than a full bpage; for this we use
+	 * the bpage that we own (and reuse it for multiple messages).
+	 */
+	partial = rpc->msgin.length & (HOMA_BPAGE_SIZE - 1);
+	if (unlikely(partial == 0))
+		goto success;
+	core_id = smp_processor_id();
+	core = this_cpu_ptr(pool->cores);
+	bpage = &pool->descriptors[core->page_hint];
+	spin_lock_bh(&bpage->lock);
+	if (bpage->owner != core_id) {
+		spin_unlock_bh(&bpage->lock);
+		goto new_page;
+	}
+	if ((core->allocated + partial) > HOMA_BPAGE_SIZE) {
+		if (bpage->refs == 1) {
+			/* Bpage is totally free, so we can reuse it. */
+			core->allocated = 0;
+		} else {
+			bpage->owner = -1;
+
+			/* We know the reference count can't reach zero here
+			 * because of check above, so we won't have to decrement
+			 * pool->free_bpages.
+			 */
+			bpage->refs--;
+			spin_unlock_bh(&bpage->lock);
+			goto new_page;
+		}
+	}
+	bpage->expiration = homa_clock() +
+			    pool->hsk->homa->bpage_lease_cycles;
+	bpage->refs++;
+	spin_unlock_bh(&bpage->lock);
+	goto allocate_partial;
+
+	/* Can't use the current page; get another one. */
+new_page:
+	if (homa_pool_get_pages(pool, 1, pages, 1) != 0) {
+		homa_pool_free_bufs(pool, rpc->msgin.num_bpages,
+				    rpc->msgin.bpage_offsets);
+		rpc->msgin.num_bpages = 0;
+		goto out_of_space;
+	}
+	core->page_hint = pages[0];
+	core->allocated = 0;
+
+allocate_partial:
+	rpc->msgin.bpage_offsets[rpc->msgin.num_bpages] = core->allocated
+			+ (core->page_hint << HOMA_BPAGE_SHIFT);
+	rpc->msgin.num_bpages++;
+	core->allocated += partial;
+
+success:
+	return 0;
+
+	/* We get here if there wasn't enough buffer space for this
+	 * message; add the RPC to hsk->waiting_for_bufs. The list is sorted
+	 * by RPC length in order to implement SRPT.
+	 */
+out_of_space:
+	homa_sock_lock(pool->hsk);
+	list_for_each_entry(other, &pool->hsk->waiting_for_bufs, buf_links) {
+		if (other->msgin.length > rpc->msgin.length) {
+			list_add_tail(&rpc->buf_links, &other->buf_links);
+			goto queued;
+		}
+	}
+	list_add_tail(&rpc->buf_links, &pool->hsk->waiting_for_bufs);
+
+queued:
+	set_bpages_needed(pool);
+	homa_sock_unlock(pool->hsk);
+	return 0;
+}
+
+/**
+ * homa_pool_get_buffer() - Given an RPC, figure out where to store incoming
+ * message data.
+ * @rpc:        RPC for which incoming message data is being processed; its
+ *              msgin must be properly initialized and buffer space must have
+ *              been allocated for the message.
+ * @offset:     Offset within @rpc's incoming message.
+ * @available:  Will be filled in with the number of bytes of space available
+ *              at the returned address (could be zero if offset is
+ *              (erroneously) past the end of the message).
+ * Return:      The application's virtual address for buffer space corresponding
+ *              to @offset in the incoming message for @rpc.
+ */
+void __user *homa_pool_get_buffer(struct homa_rpc *rpc, int offset,
+				  int *available)
+{
+	int bpage_index, bpage_offset;
+
+	bpage_index = offset >> HOMA_BPAGE_SHIFT;
+	if (offset >= rpc->msgin.length) {
+		WARN_ONCE(true, "%s got offset %d >= message length %d\n",
+			  __func__, offset, rpc->msgin.length);
+		*available = 0;
+		return NULL;
+	}
+	bpage_offset = offset & (HOMA_BPAGE_SIZE - 1);
+	*available = (bpage_index < (rpc->msgin.num_bpages - 1))
+			? HOMA_BPAGE_SIZE - bpage_offset
+			: rpc->msgin.length - offset;
+	return rpc->hsk->buffer_pool->region +
+			rpc->msgin.bpage_offsets[bpage_index] + bpage_offset;
+}
+
+/**
+ * homa_pool_free_bufs() - Release buffer space so that it can be
+ * reused.
+ * @pool:         Pool that the buffer space belongs to. Doesn't need to
+ *                be locked.
+ * @num_buffers:  How many buffers to release.
+ * @buffers:      Points to @num_buffers values, each of which is an offset
+ *                from the start of the pool to the buffer to be released.
+ * Return:        0 for success, otherwise a negative errno.
+ */
+int homa_pool_free_bufs(struct homa_pool *pool, int num_buffers, u32 *buffers)
+{
+	int i;
+
+	if (!homa_pool_exists(pool))
+		return -EINVAL;
+	for (i = 0; i < num_buffers; i++) {
+		u32 bpage_index = buffers[i] >> HOMA_BPAGE_SHIFT;
+		struct homa_bpage *bpage;
+
+		if (bpage_index >= pool->num_bpages)
+			return -EINVAL;
+		bpage = &pool->descriptors[bpage_index];
+
+		spin_lock_bh(&bpage->lock);
+		if (bpage->refs == 0 || (bpage->refs == 1 &&
+					 bpage->owner >= 0)) {
+			/* This bpage is already free; looks like the app
+			 * has misbehaved and freed an offset multiple times.
+			 */
+			spin_unlock_bh(&bpage->lock);
+			return -EINVAL;
+		}
+		bpage->refs--;
+		if (bpage->refs == 0)
+			atomic_fetch_inc(&pool->free_bpages);
+		spin_unlock_bh(&bpage->lock);
+	}
+	return 0;
+}
+
+/**
+ * homa_pool_check_waiting() - Checks to see if there are enough free
+ * bpages to wake up any RPCs that were blocked. Whenever
+ * homa_pool_free_bufs is invoked, this function must be invoked later,
+ * at a point when the caller holds no locks (homa_pool_free_bufs may
+ * be invoked with locks held, so it can't safely invoke this function).
+ * This is regrettably tricky, but I can't think of a better solution.
+ * @pool:         Information about the buffer pool.
+ */
+void homa_pool_check_waiting(struct homa_pool *pool)
+{
+	if (!homa_pool_exists(pool))
+		return;
+	while (atomic_read_acquire(&pool->free_bpages) >= pool->bpages_needed) {
+		struct homa_rpc *rpc;
+
+		homa_sock_lock(pool->hsk);
+		if (list_empty(&pool->hsk->waiting_for_bufs)) {
+			pool->bpages_needed = INT_MAX;
+			homa_sock_unlock(pool->hsk);
+			break;
+		}
+		rpc = list_first_entry(&pool->hsk->waiting_for_bufs,
+				       struct homa_rpc, buf_links);
+		if (!homa_rpc_try_lock(rpc)) {
+			/* Can't just spin on the RPC lock because we're
+			 * holding the socket lock and the lock order is
+			 * rpc-then-socket (see "Homa Locking Strategy" in
+			 * homa_impl.h). Instead, release the socket lock
+			 * and try the entire operation again.
+			 */
+			homa_sock_unlock(pool->hsk);
+			cpu_relax();
+			continue;
+		}
+		list_del_init(&rpc->buf_links);
+		if (list_empty(&pool->hsk->waiting_for_bufs))
+			pool->bpages_needed = INT_MAX;
+		else
+			set_bpages_needed(pool);
+		homa_sock_unlock(pool->hsk);
+		homa_pool_alloc_msg(rpc);
+		homa_rpc_unlock(rpc);
+	}
+}
+
+/**
+ * homa_pool_avail_bytes() - Return a count of the number of bytes currently
+ * unused and available for allocation in a pool.
+ * @pool:    Pool of interest.
+ * Return:    See above.
+ */
+u64 homa_pool_avail_bytes(struct homa_pool *pool)
+{
+	struct homa_pool_core *core;
+	struct homa_bpage *bpage;
+	u64 avail;
+	int cpu;
+
+	if (!homa_pool_exists(pool))
+		return 0;
+	avail = atomic_read(&pool->free_bpages);
+	avail *= HOMA_BPAGE_SIZE;
+	for (cpu = 0; cpu < nr_cpu_ids; cpu++) {
+		core = per_cpu_ptr(pool->cores, cpu);
+		bpage = &pool->descriptors[core->page_hint];
+		if (bpage->owner == cpu) {
+			if (bpage->refs > 1)
+				avail += HOMA_BPAGE_SIZE - core->allocated;
+			else
+				avail += HOMA_BPAGE_SIZE;
+		}
+	}
+	return avail;
+}
diff --git a/net/homa/homa_pool.h b/net/homa/homa_pool.h
new file mode 100644
index 0000000000000..80b14475d0be2
--- /dev/null
+++ b/net/homa/homa_pool.h
@@ -0,0 +1,184 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file contains definitions used to manage user-space buffer pools.
+ */
+
+#ifndef _HOMA_POOL_H
+#define _HOMA_POOL_H
+
+#include <linux/percpu.h>
+
+#include "homa_rpc.h"
+
+/**
+ * struct homa_bpage - Contains information about a single page in
+ * a buffer pool.
+ */
+struct homa_bpage {
+	/** @lock: to synchronize shared access. */
+	spinlock_t lock;
+
+	/**
+	 * @refs: Counts number of distinct uses of this
+	 * bpage (1 tick for each message that is using
+	 * this page, plus an additional tick if the @owner
+	 * field is set).
+	 */
+	int refs;
+
+	/**
+	 * @owner: kernel core that currently owns this page
+	 * (< 0 if none).
+	 */
+	int owner;
+
+	/**
+	 * @expiration: homa_clock() time after which it's OK to steal this
+	 * page from its current owner (if @refs is 1).
+	 */
+	u64 expiration;
+} ____cacheline_aligned_in_smp;
+
+/**
+ * struct homa_pool_core - Holds core-specific data for a homa_pool (a bpage
+ * out of which that core is allocating small chunks).
+ */
+struct homa_pool_core {
+	/**
+	 * @page_hint: Index of bpage in pool->descriptors,
+	 * which may be owned by this core. If so, we'll use it
+	 * for allocating partial pages.
+	 */
+	int page_hint;
+
+	/**
+	 * @allocated: if the page given by @page_hint is
+	 * owned by this core, this variable gives the number of
+	 * (initial) bytes that have already been allocated
+	 * from the page.
+	 */
+	int allocated;
+
+	/**
+	 * @next_candidate: when searching for free bpages,
+	 * check this index next.
+	 */
+	int next_candidate;
+};
+
+/**
+ * struct homa_pool - Describes a pool of buffer space for incoming
+ * messages for a particular socket; managed by homa_pool.c. The pool is
+ * divided up into "bpages", which are a multiple of the hardware page size.
+ * A bpage may be owned by a particular core so that it can more efficiently
+ * allocate space for small messages.
+ */
+struct homa_pool {
+	/**
+	 * @hsk: the socket that this pool belongs to.
+	 */
+	struct homa_sock *hsk;
+
+	/**
+	 * @region: beginning of the pool's region (in the app's virtual
+	 * memory). Divided into bpages. 0 means the pool hasn't yet been
+	 * initialized. This pointer is used for lock-free synchronization
+	 * between a core creating the region and other cores attempting
+	 * to use it.
+	 */
+	char __user *region;
+
+	/** @num_bpages: total number of bpages in the pool. */
+	int num_bpages;
+
+	/** @descriptors: kmalloced area containing one entry for each bpage. */
+	struct homa_bpage *descriptors;
+
+	/**
+	 * @free_bpages: the number of pages still available for allocation
+	 * by homa_pool_get_pages. This equals the number of pages with zero
+	 * reference counts, minus the number of pages that have been claimed
+	 * by homa_pool_get_pages but not yet allocated.
+	 */
+	atomic_t free_bpages;
+
+	/**
+	 * @bpages_needed: the number of free bpages required to satisfy the
+	 * needs of the first RPC on @hsk->waiting_for_bufs, or INT_MAX if
+	 * that queue is empty.
+	 */
+	int bpages_needed;
+
+	/** @cores: core-specific info; dynamically allocated. */
+	struct homa_pool_core __percpu *cores;
+
+	/**
+	 * @check_waiting_invoked: incremented during unit tests when
+	 * homa_pool_check_waiting is invoked.
+	 */
+	int check_waiting_invoked;
+};
+
+bool     homa_bpage_available(struct homa_bpage *bpage, u64 now);
+struct   homa_pool *homa_pool_alloc(struct homa_sock *hsk);
+int      homa_pool_alloc_msg(struct homa_rpc *rpc);
+u64      homa_pool_avail_bytes(struct homa_pool *pool);
+void     homa_pool_check_waiting(struct homa_pool *pool);
+void     homa_pool_free(struct homa_pool *pool);
+void __user *homa_pool_get_buffer(struct homa_rpc *rpc, int offset,
+				  int *available);
+int      homa_pool_get_pages(struct homa_pool *pool, int num_pages,
+			     u32 *pages, int leave_locked);
+void     homa_pool_get_rcvbuf(struct homa_pool *pool,
+			      struct homa_rcvbuf_args *args);
+int      homa_pool_free_bufs(struct homa_pool *pool, int num_buffers,
+			     u32 *buffers);
+int      homa_pool_set_region(struct homa_sock *hsk, void __user *region,
+			      u64 region_size);
+
+/**
+ * homa_pool_unlink() - Remove an RPC from any lists related to buffer
+ * pool memory, so the RPC will not be accessed by this module again.
+ * @rpc:     RPC to unlink. Must be locked, and the rpc's socket must
+ *           also be locked.
+ */
+static inline void homa_pool_unlink(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+	__must_hold(rpc->hsk->lock)
+{
+	list_del_init(&rpc->buf_links);
+}
+
+/**
+ * homa_pool_release() - Invoked when RPCs are being reaped: releases
+ * pool space owned by the RPC.
+ * @rpc:        RPC to clean up. Caller must ensure that no-one else can
+ *              access the RPC concurrently (e.g., it is being reaped).
+ */
+static inline void homa_pool_release(struct homa_rpc *rpc)
+{
+	if (rpc->msgin.num_bpages > 0) {
+		homa_pool_free_bufs(rpc->hsk->buffer_pool,
+				    rpc->msgin.num_bpages,
+				    rpc->msgin.bpage_offsets);
+		rpc->msgin.num_bpages = 0;
+	}
+}
+
+/**
+ * homa_pool_exists() - Determine whether a pool has been fully initialized
+ * with a memory region.
+ * @pool:     Pool to check.
+ * Return:    True if there is a memory region associated with the pool,
+ *            false if SO_HOMA_RCVBUF hasn't been invoked for the socket.
+ */
+static inline bool homa_pool_exists(struct homa_pool *pool)
+{
+	/* This barrier allows lockless concurrent allocation of the pool:
+	 * it ensures that if the pool exists we'll see all of the initialized
+	 * values related to the pool.
+	 */
+	return smp_load_acquire(&pool->region) != NULL;
+}
+
+#endif /* _HOMA_POOL_H */
diff --git a/net/homa/homa_rpc.c b/net/homa/homa_rpc.c
new file mode 100644
index 0000000000000..3c94489641c21
--- /dev/null
+++ b/net/homa/homa_rpc.c
@@ -0,0 +1,735 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file contains functions for managing homa_rpc structs. */
+
+#include "homa_impl.h"
+#include "homa_interest.h"
+#include "homa_peer.h"
+#include "homa_pool.h"
+#include "homa_tx_pool.h"
+
+/**
+ * homa_rpc_alloc_client() - Allocate and initialize a client RPC (one that
+ * is used to issue an outgoing request). Doesn't send any packets. Invoked
+ * with no locks held.
+ * @hsk:      Socket to which the RPC belongs.
+ * @dest:     Address of host (ip and port) to which the RPC will be sent.
+ *
+ * Return:    A pointer to the newly allocated object, or a negative
+ *            errno if an error occurred. The RPC will be locked; the
+ *            caller must eventually unlock it. Sets hsk->error_msg on errors.
+ */
+struct homa_rpc *homa_rpc_alloc_client(struct homa_sock *hsk,
+				       const union sockaddr_in_union *dest)
+	__cond_acquires(nonnull, crpc->bucket->lock)
+{
+	struct in6_addr dest_addr_as_ipv6 = canonical_ipv6_addr(dest);
+	struct homa_rpc_bucket *bucket;
+	struct homa_rpc *crpc;
+	int err;
+
+	crpc = kzalloc_obj(*crpc, GFP_KERNEL_ACCOUNT);
+	if (unlikely(!crpc)) {
+		hsk->error_msg = "couldn't allocate memory for client RPC";
+		return ERR_PTR(-ENOMEM);
+	}
+
+	/* Initialize fields that don't require the socket lock. */
+	crpc->hsk = hsk;
+	crpc->id = atomic64_fetch_add(2, &hsk->homa->next_outgoing_id);
+	bucket = homa_client_rpc_bucket(hsk, crpc->id);
+	crpc->bucket = bucket;
+	crpc->state = RPC_OUTGOING;
+	refcount_set(&crpc->refs, 1);
+	crpc->route = homa_route_get(hsk, &dest_addr_as_ipv6);
+	if (IS_ERR(crpc->route)) {
+		err = PTR_ERR(crpc->route);
+		crpc->route = NULL;
+		goto error;
+	}
+	crpc->dport = ntohs(dest->in6.sin6_port);
+	crpc->msgin.length = -1;
+	crpc->msgout.length = -1;
+	INIT_LIST_HEAD(&crpc->ready_links);
+	INIT_LIST_HEAD(&crpc->buf_links);
+	INIT_LIST_HEAD(&crpc->dead_links);
+	crpc->resend_timer_ticks = hsk->homa->timer_ticks;
+	crpc->magic = HOMA_RPC_MAGIC;
+	crpc->start_time = homa_clock();
+
+	/* Initialize fields that require locking. This allows the most
+	 * expensive work, such as copying in the message from user space,
+	 * to be performed without holding locks. Also, can't hold spin
+	 * locks while doing things that could block, such as memory allocation.
+	 */
+	homa_bucket_lock(bucket, crpc->id);
+	homa_sock_lock(hsk);
+	if (hsk->shutdown) {
+		homa_sock_unlock(hsk);
+		homa_rpc_unlock(crpc);
+		hsk->error_msg = "socket has been shut down";
+		err = -ESHUTDOWN;
+		goto error;
+	}
+	hlist_add_head(&crpc->hash_links, &bucket->rpcs);
+	rcu_read_lock();
+	list_add_tail_rcu(&crpc->active_links, &hsk->active_rpcs);
+	rcu_read_unlock();
+	homa_sock_unlock(hsk);
+
+	return crpc;
+
+error:
+	if (crpc->route)
+		homa_route_release(crpc->route);
+	kfree(crpc);
+	return ERR_PTR(err);
+}
+
+/**
+ * homa_rpc_alloc_server() - Allocate and initialize a server RPC (one that is
+ * used to manage an incoming request). If appropriate, the RPC will also
+ * be handed off (we do it here, while we have the socket locked, to avoid
+ * acquiring the socket lock a second time later for the handoff).
+ * @hsk:      Socket that owns this RPC.
+ * @source:   IP address (network byte order) of the RPC's client.
+ * @h:        Header for the first data packet received for this RPC; used
+ *            to initialize the RPC.
+ *
+ * Return:  A pointer to a new RPC, which is locked, or a negative errno
+ *          if an error occurred. If there is already an RPC corresponding
+ *          to h, then it is returned instead of creating a new RPC.
+ */
+struct homa_rpc *homa_rpc_alloc_server(struct homa_sock *hsk,
+				       const struct in6_addr *source,
+				       struct homa_data_hdr *h)
+	__cond_acquires(nonnull, srpc->bucket->lock)
+{
+	u64 id = homa_local_id(h->common.sender_id);
+	struct homa_rpc_bucket *bucket;
+	struct homa_rpc *srpc = NULL;
+	int err;
+
+	if (!hsk->buffer_pool)
+		return ERR_PTR(-ENOMEM);
+
+	/* Lock the bucket, and make sure no-one else has already created
+	 * the desired RPC.
+	 */
+	bucket = homa_server_rpc_bucket(hsk, id);
+	homa_bucket_lock(bucket, id);
+	hlist_for_each_entry(srpc, &bucket->rpcs, hash_links) {
+		if (srpc->id == id &&
+		    srpc->dport == ntohs(h->common.sport) &&
+		    ipv6_addr_equal(&srpc->route->peer->addr, source)) {
+			/* RPC already exists; just return it instead
+			 * of creating a new RPC.
+			 */
+			return srpc;
+		}
+	}
+
+	/* Initialize fields that don't require the socket lock. */
+	if (hsk->sock.sk_memcg) {
+		struct mem_cgroup *old = set_active_memcg(hsk->sock.sk_memcg);
+
+		srpc = kzalloc_obj(*srpc, GFP_ATOMIC | __GFP_ACCOUNT);
+		set_active_memcg(old);
+	} else {
+		srpc = kzalloc_obj(*srpc, GFP_ATOMIC);
+	}
+	if (!srpc) {
+		err = -ENOMEM;
+		goto error;
+	}
+
+	/* Must be initialized before any errors can occur in this function. */
+	INIT_LIST_HEAD(&srpc->buf_links);
+
+	srpc->hsk = hsk;
+	srpc->bucket = bucket;
+	srpc->state = RPC_INCOMING;
+	refcount_set(&srpc->refs, 1);
+	srpc->route = homa_route_get(hsk, source);
+	if (IS_ERR(srpc->route)) {
+		err = PTR_ERR(srpc->route);
+		srpc->route = NULL;
+		goto error;
+	}
+	srpc->dport = ntohs(h->common.sport);
+	srpc->id = id;
+	srpc->msgin.length = -1;
+	srpc->msgout.length = -1;
+	INIT_LIST_HEAD(&srpc->ready_links);
+	INIT_LIST_HEAD(&srpc->dead_links);
+	srpc->resend_timer_ticks = hsk->homa->timer_ticks;
+	srpc->magic = HOMA_RPC_MAGIC;
+	srpc->start_time = homa_clock();
+	err = homa_message_in_init(srpc, ntohl(h->message_length));
+	if (err != 0)
+		goto error;
+
+	/* Initialize fields that require socket to be locked. */
+	homa_sock_lock(hsk);
+	if (hsk->shutdown) {
+		homa_sock_unlock(hsk);
+		err = -ESHUTDOWN;
+		goto error;
+	}
+	hlist_add_head(&srpc->hash_links, &bucket->rpcs);
+	list_add_tail_rcu(&srpc->active_links, &hsk->active_rpcs);
+	homa_sock_unlock(hsk);
+	if (ntohl(h->seg.offset) == 0 && srpc->msgin.num_bpages > 0) {
+		set_bit(RPC_PKTS_READY, &srpc->flags);
+		homa_rpc_handoff(srpc);
+	}
+	return srpc;
+
+error:
+	if (srpc) {
+		homa_pool_release(srpc);
+		if (srpc->route)
+			homa_route_release(srpc->route);
+	}
+	homa_bucket_unlock(bucket, id);
+	kfree(srpc);
+	return ERR_PTR(err);
+}
+
+/**
+ * homa_rpc_ack() - Handle one or more acknowledgments for RPCs.
+ * @hsk:      Socket on which the ack(s) were received. Can sometimes be used
+ *            to avoid a socket lookup.
+ * @rpc:      RPC for which caller holds lock (NULL if none).
+ * @saddr:    Source address from which the ack was received (the client
+ *            node for the RPC)
+ * @num_acks: Number of acknowledgments in @acks
+ * @acks:     Information about one or more RPCs from @saddr that may now be
+ *            deleted safely.
+ */
+void homa_rpc_ack(struct homa_sock *hsk, struct homa_rpc *rpc,
+		  const struct in6_addr *saddr, int num_acks,
+		  struct homa_ack *acks)
+{
+	struct homa_sock *hsk2;
+	struct homa_rpc *rpc2;
+	u16 server_port;
+	u64 id;
+	int i;
+
+	if (rpc)
+		homa_rpc_unlock(rpc);
+	for (i = 0; i < num_acks; i++) {
+		struct homa_ack *ack = &acks[i];
+
+		server_port = ntohs(ack->server_port);
+		id = homa_local_id(ack->client_id);
+		if (hsk->port != server_port) {
+			/* Without RCU, sockets other than hsk can be deleted
+			 * out from under us.
+			 */
+			hsk2 = homa_sock_find(hsk->hnet, server_port);
+			if (!hsk2)
+				continue;
+		} else {
+			hsk2 = hsk;
+		}
+		rpc2 = homa_rpc_find_server(hsk2, saddr, id);
+		if (rpc2) {
+			homa_rpc_end(rpc2);
+			homa_rpc_unlock(rpc2); /* Locked by homa_rpc_find_server. */
+		}
+		if (hsk2 != hsk)
+			sock_put(&hsk2->sock);
+	}
+	if (rpc)
+		homa_rpc_lock(rpc);
+}
+
+/**
+ * homa_rpc_end() - Stop all activity on an RPC and begin the process of
+ * releasing its resources; this process will continue in the background
+ * until homa_rpc_reap eventually completes it.
+ * @rpc:  Structure to clean up, or NULL. Must be locked. Its socket must
+ *        not be locked. The RPC may still be used after this function returns
+ *        (there are many places where the RPC lock is temporarily released,
+ *        and it would add too much complexity to put checks for death
+ *        every time the lock is reacquired). However, any code that could
+ *        make the RPC visible again must check rpc->state; if the RPC is
+ *        dead then that code must no-op itself.
+ */
+void homa_rpc_end(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	/* The goal for this function is to make the RPC inaccessible,
+	 * so that no other code will ever access it again. However, don't
+	 * actually release resources or tear down the internal structure
+	 * of the RPC; leave that to homa_rpc_reap, which runs later. There
+	 * are two reasons for this. First, releasing resources may be
+	 * expensive, so we don't want to keep the caller waiting; homa_rpc_reap
+	 * will run in situations where there is time to spare. Second, there
+	 * may be other code that currently has pointers to this RPC but
+	 * temporarily released the lock (e.g. to copy data to/from user space).
+	 * It isn't safe to clean up until that code has finished its work and
+	 * released any pointers to the RPC (homa_rpc_reap will ensure that
+	 * this has happened). So, this function should only make changes
+	 * needed to make the RPC inaccessible.
+	 */
+	if (!rpc || rpc->state == RPC_DEAD)
+		return;
+	rpc->state = RPC_DEAD;
+	rpc->error = -EINVAL;
+
+	/* Unlink from all lists, so no-one will ever find this RPC again. */
+	homa_sock_lock(rpc->hsk);
+	__hlist_del(&rpc->hash_links);
+	list_del_rcu(&rpc->active_links);
+	list_add_tail(&rpc->dead_links, &rpc->hsk->dead_rpcs);
+	__list_del_entry(&rpc->ready_links);
+	homa_pool_unlink(rpc);
+	homa_interest_notify_private(rpc);
+
+	rpc->hsk->dead_frags += rpc->msgout.num_frags + 1;
+	if (rpc->hsk->dead_frags > rpc->hsk->homa->max_dead_frags)
+		/* This update isn't thread-safe; it's just a
+		 * statistic so it's OK if updates occasionally get
+		 * missed.
+		 */
+		rpc->hsk->homa->max_dead_frags = rpc->hsk->dead_frags;
+
+	homa_sock_unlock(rpc->hsk);
+}
+
+/**
+ * homa_rpc_abort() - Terminate an RPC.
+ * @rpc:     RPC to be terminated.  Must be locked by caller.
+ * @error:   A negative errno value indicating the error that caused the abort.
+ *           If this is a client RPC, the error will be returned to the
+ *           application; if it's a server RPC, the error is ignored and
+ *           we just free the RPC.
+ */
+void homa_rpc_abort(struct homa_rpc *rpc, int error)
+	__must_hold(rpc->bucket->lock)
+{
+	if (!homa_is_client(rpc->id)) {
+		homa_rpc_end(rpc);
+		return;
+	}
+	rpc->error = error;
+	homa_rpc_handoff(rpc);
+}
+
+/**
+ * homa_abort_rpcs() - Abort all RPCs to/from a particular peer.
+ * @homa:    Overall data about the Homa protocol implementation.
+ * @addr:    Address (network order) of the destination whose RPCs are
+ *           to be aborted.
+ * @port:    If nonzero, then RPCs will only be aborted if they were
+ *	     targeted at this server port.
+ * @error:   Negative errno value indicating the reason for the abort.
+ */
+void homa_abort_rpcs(struct homa *homa, const struct in6_addr *addr,
+		     int port, int error)
+{
+	struct homa_socktab_scan scan;
+	struct homa_sock *hsk;
+	struct homa_rpc *rpc;
+
+	for (hsk = homa_socktab_start_scan(homa->socktab, &scan); hsk;
+	     hsk = homa_socktab_next(&scan)) {
+		/* Skip the (expensive) lock acquisition if there's no
+		 * work to do.
+		 */
+		if (list_empty(&hsk->active_rpcs))
+			continue;
+		if (!homa_protect_rpcs(hsk))
+			continue;
+		rcu_read_lock();
+		list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
+			if (!ipv6_addr_equal(&rpc->route->peer->addr, addr))
+				continue;
+			if (port && rpc->dport != port)
+				continue;
+			homa_rpc_lock(rpc);
+			if (rpc->state != RPC_DEAD)
+				homa_rpc_abort(rpc, error);
+			homa_rpc_unlock(rpc);
+		}
+		rcu_read_unlock();
+		homa_unprotect_rpcs(hsk);
+	}
+	homa_socktab_end_scan(&scan);
+}
+
+/**
+ * homa_rpc_reap() - Invoked to release resources associated with dead
+ * RPCs for a given socket. Each call will do a small amount of work; there
+ * may still be unreaped RPCs on return.
+ * @hsk:      Homa socket that may contain dead RPCs. Must not be locked by the
+ *            caller; this function will lock and release.
+ *
+ * Return: A return value of 0 means that we ran out of work to do; calling
+ *         again may not do any work (there could be unreaped RPCs, but if so,
+ *         they cannot currently be reaped).  A value greater than zero means
+ *         there is still more reaping work to be done.
+ */
+int homa_rpc_reap(struct homa_sock *hsk)
+{
+	/* RPC Reaping Strategy:
+	 *
+	 * (Note: there are references to this comment elsewhere in the
+	 * Homa code)
+	 *
+	 * This function is separate from homa_rpc_end for two reasons.
+	 * First, there may be outstanding references to an RPC when
+	 * homa_rpc_end is invoked; the storage for the RPC cannot be
+	 * freed until all of those references have been released.
+	 * Second, reaping an RPC is potentially expensive (if it owns a
+	 * lot of buffer memory) and homa_rpc_end could be invoked in
+	 * homa_softirq when there are short messages waiting to be processed.
+	 * Taking time to reap a long RPC could result in delays for
+	 * subsequent short RPCs. This second reason is less important
+	 * now than it used to be (in earlier versions of Homa skbs for both
+	 * inbound and outbound messages were retained until the RPC was
+	 * reaped, and freeing the skbs was relatively expensive; now no
+	 * skbs are retained; there are only pages of tx message memory to
+	 * return to homa_tx_pool).
+	 *
+	 * Thus Homa doesn't reap immediately in homa_rpc_end. Instead, dead
+	 * RPCs are queued up and reaping occurs in this function, which is
+	 * invoked later. The challenge is to do this so that (a) we don't allow
+	 * large numbers of dead RPCs to accumulate and (b) we minimize the
+	 * impact of reaping on latency of unrelated messages.
+	 *
+	 * The primary place where homa_rpc_reap is invoked is when threads
+	 * are waiting for incoming messages. The thread has nothing else to
+	 * do (it may even be polling for input), so reaping can be performed
+	 * with no latency impact on the application.  However, if a machine
+	 * is overloaded then it may never wait, so this mechanism isn't always
+	 * sufficient.
+	 *
+	 * Homa now reaps in two other places, if reaping while waiting for
+	 * messages isn't adequate:
+	 * 1. If too many dead RPCs accumulate, then homa_timer will call
+	 *    homa_rpc_reap.
+	 * 2. If the timer thread cannot keep up with all the reaping to be
+	 *    done then as a last resort homa_dispatch_pkts will reap in small
+	 *    increments (a few sk_buffs or RPCs) for every incoming batch
+	 *    of packets. This is undesirable because it will impact Homa's
+	 *    latency.
+	 *
+	 * During the introduction of homa_pools for managing input
+	 * buffers, freeing of packets for incoming messages was moved to
+	 * homa_copy_to_user under the assumption that this code wouldn't be
+	 * on the critical path. However, there is evidence that with
+	 * fast networks (e.g. 100 Gbps) copying to user space is the
+	 * bottleneck for incoming messages, and packet freeing takes about
+	 * 20-25% of the total time in homa_copy_to_user. So, it may eventually
+	 * be desirable to move packet freeing out of homa_copy_to_user.
+	 */
+#define BATCH_MAX_RPCS 5
+#define BATCH_MAX_FRAGS 30
+	struct homa_rpc *rpcs[BATCH_MAX_RPCS];
+	int checked_all_rpcs;
+	int total_dead_frags;
+	struct homa_rpc *rpc;
+	struct homa_rpc *tmp;
+	int i, num_rpcs;
+
+	/* Each iteration through the following loop will reap
+	 * up to BATCH_MAX_RPCS RPCs.
+	 */
+	checked_all_rpcs = list_empty(&hsk->dead_rpcs);
+	if (checked_all_rpcs)
+		return 0;
+	num_rpcs = 0;
+	total_dead_frags = 0;
+
+	homa_sock_lock(hsk);
+	if (atomic_read(&hsk->protect_count)) {
+		homa_sock_unlock(hsk);
+		return 0;
+	}
+
+	/* Collect freeable RPCs. */
+	list_for_each_entry_safe(rpc, tmp, &hsk->dead_rpcs, dead_links) {
+		int refs;
+
+		if (num_rpcs >= BATCH_MAX_RPCS ||
+		    total_dead_frags >= BATCH_MAX_FRAGS)
+			goto release;
+
+		/* Make sure that all outstanding uses of the RPC have
+		 * completed. We can read the reference count safely
+		 * only when we're holding the lock. Note: it isn't
+		 * safe to block while locking the RPC here, since we
+		 * hold the socket lock.
+		 */
+		if (homa_rpc_try_lock(rpc)) {
+			refs = refcount_read(&rpc->refs);
+			homa_rpc_unlock(rpc);
+		} else {
+			refs = 2;
+		}
+		if (refs > 1)
+			continue;
+
+		rpcs[num_rpcs] = rpc;
+		num_rpcs++;
+		list_del(&rpc->dead_links);
+		hsk->dead_frags -= (rpc->msgout.num_frags + 1);
+		total_dead_frags += rpc->msgout.num_frags;
+	}
+	checked_all_rpcs = true;
+
+	/* Free all of the collected resources; release the socket lock
+	 * while doing this.
+	 */
+release:
+	homa_sock_unlock(hsk);
+	for (i = 0; i < num_rpcs; i++) {
+		rpc = rpcs[i];
+
+		/* Free any unconsumed input packets and gaps (there
+		 * shouldn't usually be any of either).
+		 */
+		if (rpc->msgin.length >= 0) {
+			struct sk_buff *skb;
+
+			for (skb = __skb_dequeue(&rpc->msgin.packets); skb;
+			     skb = __skb_dequeue(&rpc->msgin.packets))
+				consume_skb(skb);
+			while (1) {
+				struct homa_gap *gap;
+
+				gap = list_first_entry_or_null(&rpc->msgin.gaps,
+							       struct homa_gap,
+							       links);
+				if (!gap)
+					break;
+				list_del(&gap->links);
+				kfree(gap);
+			}
+		}
+
+		if (rpc->route) {
+			homa_route_release(rpc->route);
+			rpc->route = NULL;
+		}
+		homa_pool_release(rpc);
+		homa_tx_pool_free(hsk->homa, rpc->msgout.num_frags,
+				  rpc->msgout.frags);
+		WARN_ON(refcount_sub_and_test(rpc->msgout.frag_bytes,
+					      &hsk->sock.sk_wmem_alloc));
+		if (rpc->msgout.frags != &rpc->msgout.frag)
+			kfree(rpc->msgout.frags);
+		rpc->state = 0;
+		rpc->magic = 0;
+		kfree(rpc);
+	}
+	homa_sock_wakeup_wmem(hsk);
+	if (hsk->buffer_pool)
+		homa_pool_check_waiting(hsk->buffer_pool);
+	return !checked_all_rpcs;
+}
+
+/**
+ * homa_abort_sock_rpcs() - Abort all outgoing (client-side) RPCs on a given
+ * socket.
+ * @hsk:         Socket whose RPCs should be aborted.
+ * @error:       Zero means that the aborted RPCs should be freed immediately.
+ *               A nonzero value means that the RPCs should be marked
+ *               complete, so that they can be returned to the application;
+ *               this value (a negative errno) will be returned from
+ *               recvmsg.
+ */
+void homa_abort_sock_rpcs(struct homa_sock *hsk, int error)
+{
+	struct homa_rpc *rpc;
+
+	if (list_empty(&hsk->active_rpcs))
+		return;
+	if (!homa_protect_rpcs(hsk))
+		return;
+	rcu_read_lock();
+	list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
+		if (!homa_is_client(rpc->id))
+			continue;
+		homa_rpc_lock(rpc);
+		if (rpc->state == RPC_DEAD) {
+			homa_rpc_unlock(rpc);
+			continue;
+		}
+		if (error)
+			homa_rpc_abort(rpc, error);
+		else
+			homa_rpc_end(rpc);
+		homa_rpc_unlock(rpc);
+	}
+	rcu_read_unlock();
+	homa_unprotect_rpcs(hsk);
+}
+
+/**
+ * homa_rpc_find_client() - Locate client-side information about the RPC that
+ * a packet belongs to, if there is any. Thread-safe without socket lock.
+ * @hsk:      Socket via which packet was received.
+ * @id:       Unique identifier for the RPC.
+ *
+ * Return:    A pointer to the homa_rpc for this id, or NULL if none.
+ *            The RPC will be locked; the caller must eventually unlock it
+ *            by invoking homa_rpc_unlock.
+ */
+struct homa_rpc *homa_rpc_find_client(struct homa_sock *hsk, u64 id)
+	__cond_acquires(nonnull, crpc->bucket->lock)
+{
+	struct homa_rpc_bucket *bucket = homa_client_rpc_bucket(hsk, id);
+	struct homa_rpc *crpc;
+
+	homa_bucket_lock(bucket, id);
+	hlist_for_each_entry(crpc, &bucket->rpcs, hash_links) {
+		if (crpc->id == id)
+			return crpc;
+	}
+	homa_bucket_unlock(bucket, id);
+	return NULL;
+}
+
+/**
+ * homa_rpc_find_server() - Locate server-side information about the RPC that
+ * a packet belongs to, if there is any. Thread-safe without socket lock.
+ * @hsk:      Socket via which packet was received.
+ * @saddr:    Address from which the packet was sent.
+ * @id:       Unique identifier for the RPC (must have server bit set).
+ *
+ * Return:    A pointer to the homa_rpc matching the arguments, or NULL
+ *            if none. The RPC will be locked; the caller must eventually
+ *            unlock it by invoking homa_rpc_unlock.
+ */
+struct homa_rpc *homa_rpc_find_server(struct homa_sock *hsk,
+				      const struct in6_addr *saddr, u64 id)
+	__cond_acquires(nonnull, srpc->bucket->lock)
+{
+	struct homa_rpc_bucket *bucket = homa_server_rpc_bucket(hsk, id);
+	struct homa_rpc *srpc;
+
+	homa_bucket_lock(bucket, id);
+	hlist_for_each_entry(srpc, &bucket->rpcs, hash_links) {
+		if (srpc->id == id && ipv6_addr_equal(&srpc->route->peer->addr,
+						      saddr))
+			return srpc;
+	}
+	homa_bucket_unlock(bucket, id);
+	return NULL;
+}
+
+/**
+ * homa_rpc_find_from_skb() - Given an skb for a Homa packet, find the homa_rpc
+ * associated with the packet and lock it.
+ * @skb:        Packet buffer; must contain a Homa packet that is "fully
+ *              populated" (e.g. the dev field and IP header are initialized).
+ * @incoming:   True means this is an incoming packet, false means outgoing.
+ * Return:      Pointer an RPC that has been locked; the caller is responsible
+ *              for unlocking it. If no RPC could be found, NULL is returned.
+ */
+struct homa_rpc *homa_rpc_find_from_skb(struct sk_buff *skb, bool incoming)
+{
+	struct homa_common_hdr *h;
+	struct homa_sock *hsk;
+	struct homa_net *hnet;
+	struct homa_rpc *rpc;
+	int port;
+	u64 id;
+
+	/* Find the appropriate socket.*/
+	h = (struct homa_common_hdr *)skb_transport_header(skb);
+	id = be64_to_cpu(h->sender_id);
+	if (incoming) {
+		port = ntohs(h->dport);
+		id ^= 1;
+	} else {
+		port = ntohs(h->sport);
+	}
+	hnet = homa_net(dev_net(skb->dev));
+	hsk = homa_sock_find(hnet, port);
+	if (!hsk)
+		return NULL;
+
+	/* Look up the RPC (client and server RPCs are handled differently) */
+	if (homa_is_client(id)) {
+		rpc = homa_rpc_find_client(hsk, id);
+	} else {
+		if (skb_is_ipv6(skb)) {
+			struct in6_addr *addr;
+
+			addr = (incoming) ? &ipv6_hdr(skb)->saddr :
+					&ipv6_hdr(skb)->daddr;
+			rpc = homa_rpc_find_server(hsk, addr, id);
+		} else {
+			struct in6_addr addr;
+
+			if (incoming)
+				ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
+						       &addr);
+			else
+				ipv6_addr_set_v4mapped(ip_hdr(skb)->daddr,
+						       &addr);
+			rpc = homa_rpc_find_server(hsk, &addr, id);
+		}
+	}
+	sock_put(&hsk->sock);
+	return rpc;
+}
+
+/**
+ * homa_rpc_get_info() - Extract information from an RPC for returning to
+ * an application via the HOMAIOCINFO ioctl.
+ * @rpc:   RPC for which information is desired.
+ * @info:  Structure in which to store the information.
+ */
+void homa_rpc_get_info(struct homa_rpc *rpc, struct homa_rpc_info *info)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_gap *gap;
+
+	memset(info, 0, sizeof(*info));
+	info->id = rpc->id;
+	if (rpc->hsk->inet.sk.sk_family == AF_INET6) {
+		info->peer.in6.sin6_family = AF_INET6;
+		info->peer.in6.sin6_addr = rpc->route->peer->addr;
+		info->peer.in6.sin6_port = htons(rpc->dport);
+	} else {
+		info->peer.in6.sin6_family = AF_INET;
+		info->peer.in4.sin_addr.s_addr = ipv6_to_ipv4(rpc->route->peer->addr);
+		info->peer.in4.sin_port = htons(rpc->dport);
+	}
+	info->completion_cookie = rpc->completion_cookie;
+	if (rpc->msgout.length >= 0) {
+		info->tx_length = rpc->msgout.length;
+		info->tx_sent = rpc->msgout.next_xmit_offset;
+		info->tx_granted = rpc->msgout.length;
+	} else {
+		info->tx_length = -1;
+	}
+	if (rpc->msgin.length >= 0) {
+		info->rx_length = rpc->msgin.length;
+		info->rx_remaining = rpc->msgin.bytes_remaining;
+		list_for_each_entry(gap, &rpc->msgin.gaps, links) {
+			info->rx_gaps++;
+			info->rx_gap_bytes += gap->end - gap->start;
+		}
+		info->rx_granted = rpc->msgin.length;
+		if (skb_queue_len(&rpc->msgin.packets) > 0)
+			info->flags |= HOMA_RPC_RX_COPY;
+	} else {
+		info->rx_length = -1;
+	}
+	if (!list_empty(&rpc->buf_links))
+		info->flags |= HOMA_RPC_BUF_STALL;
+	if (!list_empty(&rpc->ready_links) &&
+	    rpc->msgin.bytes_remaining == 0 &&
+	    skb_queue_len(&rpc->msgin.packets) == 0)
+		info->flags |= HOMA_RPC_RX_READY;
+	if (rpc->flags & RPC_PRIVATE)
+		info->flags |= HOMA_RPC_PRIVATE;
+}
diff --git a/net/homa/homa_rpc.h b/net/homa/homa_rpc.h
new file mode 100644
index 0000000000000..fa082d229740a
--- /dev/null
+++ b/net/homa/homa_rpc.h
@@ -0,0 +1,545 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file defines homa_rpc and related structs.  */
+
+#ifndef _HOMA_RPC_H
+#define _HOMA_RPC_H
+
+#include <linux/percpu-defs.h>
+#include <linux/skbuff.h>
+#include <linux/types.h>
+
+#include "homa_sock.h"
+#include "homa_wire.h"
+
+/* Forward references. */
+struct homa_ack;
+
+/**
+ * struct homa_message_out - Describes a message (either request or response)
+ * for which this machine is the sender.
+ */
+struct homa_message_out {
+	/**
+	 * @length: Total bytes in message (excluding headers).  A value
+	 * less than 0 means this structure is uninitialized and therefore
+	 * not in use (all other fields will be zero in this case).
+	 */
+	int length;
+
+	/**
+	 * @frags: Array of fragments that hold the tx message in a ready-
+	 * to-transmit form, consisting of segments, each with a
+	 * homa_seg_hdr followed by the data for that segment. These
+	 * fragments will be incorporated into skb's to transmit the message.
+	 * If this doesn't point to @frag below then it is dynamically
+	 * allocated and must be freed.
+	 */
+	skb_frag_t *frags;
+
+	/** @num_frags: Number of fragments at @frags. */
+	int num_frags;
+
+	/**
+	 * @frag_bytes: Total amount of memory in all of @frags; this is
+	 * included in sk_wmem_alloc.
+	 */
+	int frag_bytes;
+
+	/**
+	 * @frag: @frags will point here if the message data all fits in a
+	 * single fragment (avoid alloc/free overhead).
+	 */
+	skb_frag_t frag;
+
+	/**
+	 * @max_seg_data: Maximum amount of message data to include in each
+	 * segment of tx packets.
+	 */
+	int max_seg_data;
+
+	/**
+	 * @max_gso_segs: Maximum number of segments that can be present in a
+	 * single GSO packet.
+	 */
+	int max_gso_segs;
+
+	/**
+	 * @max_gso_data: Maximum amount of message data in a GSO frame
+	 * (@max_seg_data * @max_gso_segs).
+	 */
+	int max_gso_data;
+
+	/**
+	 * @copied_from_user: Number of bytes of the message that have
+	 * been copied from user space into @frags. Used for lockless
+	 * communication between one core copying in data and another
+	 * core transmitting the data in skbs.
+	 */
+	int copied_from_user;
+
+	/**
+	 * @next_xmit_offset: All bytes in the message, up to but not
+	 * including this one, have been passed to ip_queue_xmit or
+	 * ip6_xmit at least once.
+	 */
+	int next_xmit_offset;
+
+	/**
+	 * @init_time: homa_clock() time when this structure was initialized.
+	 * Used to find the oldest outgoing message.
+	 */
+	u64 init_time;
+};
+
+/**
+ * struct homa_gap - Represents a range of bytes within a message that have
+ * not yet been received.
+ */
+struct homa_gap {
+	/** @start: offset of first byte in this gap. */
+	int start;
+
+	/** @end: offset of byte just after last one in this gap. */
+	int end;
+
+	/**
+	 * @time: homa_clock() time when the gap was first detected.
+	 * As of 7/2024 this isn't used for anything.
+	 */
+	u64 time;
+
+	/** @links: for linking into list in homa_message_in. */
+	struct list_head links;
+};
+
+/**
+ * struct homa_message_in - Holds the state of a message received by
+ * this machine; used for both requests and responses.
+ */
+struct homa_message_in {
+	/**
+	 * @length: Payload size in bytes. -1 means this structure is
+	 * uninitialized and therefore not in use.
+	 */
+	int length;
+
+	/**
+	 * @packets: DATA packets for this message that have been received but
+	 * not yet copied to user space (ordered by increasing offset). The
+	 * lock in this structure is not used (the RPC lock is used instead).
+	 */
+	struct sk_buff_head packets;
+
+	/**
+	 * @recv_end: Offset of the byte just after the highest one that
+	 * has been received so far.
+	 */
+	int recv_end;
+
+	/**
+	 * @gaps: List of homa_gaps describing all of the bytes with
+	 * offsets less than @recv_end that have not yet been received.
+	 */
+	struct list_head gaps;
+
+	/**
+	 * @bytes_remaining: Amount of data for this message that has
+	 * not yet been received; will determine the message's priority.
+	 */
+	int bytes_remaining;
+
+	/**
+	 * @num_bpages: The number of entries in @bpage_offsets used for this
+	 * message (0 means buffers not allocated yet or the buffers have
+	 * been handed off to the application).
+	 */
+	u32 num_bpages;
+
+	/**
+	 * @bpage_offsets: Describes buffer space allocated for this message.
+	 * Each entry is an offset from the start of the buffer region.
+	 * All but the last pointer refer to areas of size HOMA_BPAGE_SIZE.
+	 */
+	u32 bpage_offsets[HOMA_MAX_BPAGES];
+
+};
+
+/**
+ * struct homa_rpc - One of these structures exists for each active
+ * RPC. The same structure is used to manage both outgoing RPCs on
+ * clients and incoming RPCs on servers.
+ */
+struct homa_rpc {
+	/** @hsk:  Socket that owns the RPC. */
+	struct homa_sock *hsk;
+
+	/**
+	 * @bucket: Pointer to the bucket in hsk->client_rpc_buckets or
+	 * hsk->server_rpc_buckets where this RPC is linked. Used primarily
+	 * for locking the RPC (which is done by locking its bucket).
+	 */
+	struct homa_rpc_bucket *bucket;
+
+	/**
+	 * @state: The current state of this RPC:
+	 *
+	 * @RPC_OUTGOING:     The RPC is waiting for @msgout to be transmitted
+	 *                    to the peer.
+	 * @RPC_INCOMING:     The RPC is waiting for data @msgin to be received
+	 *                    from the peer; at least one packet has already
+	 *                    been received.
+	 * @RPC_IN_SERVICE:   Used only for server RPCs: the request message
+	 *                    has been read from the socket, but the response
+	 *                    message has not yet been presented to the kernel.
+	 * @RPC_DEAD:         The RPC has been killed and is waiting to be
+	 *                    reaped. The RPC may continue to be used in this
+	 *                    state using references that existed when
+	 *                    homa_rpc_end was invoked, but it can no longer
+	 *                    be discovered and no code may make it
+	 *                    discoverable.
+	 *
+	 * Client RPCs pass through states in the following order:
+	 * RPC_OUTGOING, RPC_INCOMING, RPC_DEAD.
+	 *
+	 * Server RPCs pass through states in the following order:
+	 * RPC_INCOMING, RPC_IN_SERVICE, RPC_OUTGOING, RPC_DEAD.
+	 */
+	enum {
+		RPC_OUTGOING            = 5,
+		RPC_INCOMING            = 6,
+		RPC_IN_SERVICE          = 8,
+		RPC_DEAD                = 9
+	} state;
+
+	/**
+	 * @flags: Additional state information: an OR'ed combination of
+	 * various single-bit flags. See below for definitions. Must be
+	 * manipulated with atomic operations because some of the manipulations
+	 * occur without holding the RPC lock.
+	 */
+	unsigned long flags;
+
+	/* Valid bit numbers for @flags:
+	 * RPC_PKTS_READY -        The RPC has input packets ready to be
+	 *                         copied to user space.
+	 * APP_NEEDS_LOCK -        Means that code in the application thread
+	 *                         needs the RPC lock (e.g. so it can start
+	 *                         copying data to user space) so others
+	 *                         (e.g. SoftIRQ processing) should relinquish
+	 *                         the lock ASAP. Without this, SoftIRQ can
+	 *                         lock out the application for a long time,
+	 *                         preventing data copies to user space from
+	 *                         starting (and they limit throughput at
+	 *                         high network speeds).
+	 * RPC_PRIVATE -           This RPC will be waited on in "private" mode,
+	 *                         where the app explicitly requests the
+	 *                         response from this particular RPC.
+	 * RPC_GRANTABLE -         1 means this RPC needs help from the grant
+	 *                         mechanism to receive its incoming message. 0
+	 *                         means either it is entirely unscheduled or
+	 *                         the message has been completely received.
+	 *                         This bit gets set at most once in the life
+	 *                         of an RPC; once cleared, it never gets set
+	 *                         again.
+	 * RPC_GRANT_MANAGED -     1 means this RPC has been inserted in the
+	 *                         grant management data structures. This
+	 *                         doesn't happen until the first time
+	 *                         homa_grant_check_rpc is called, so it is
+	 *                         possible for RPC_GRANTABLE to be set but
+	 *                         not RPC_GRANT_MANAGED.
+	 */
+#define RPC_PKTS_READY        0
+#define APP_NEEDS_LOCK        1
+#define RPC_PRIVATE           2
+#define RPC_GRANTABLE         3
+#define RPC_GRANT_MANAGED     4
+
+	/**
+	 * @refs: Number of references to this RPC, including one for each
+	 * unmatched call to homa_rpc_hold plus one for the socket's reference
+	 * in either active_rpcs or dead_rpcs. References are acquired at
+	 * "top level", such as homa_dispatch_pkts or homa_recvmsg. If a
+	 * function receives a locked RPC as parameter, it can assume
+	 * that the caller is also holding a reference to it.
+	 */
+	refcount_t refs;
+
+	/**
+	 * @route: Holds a dst_entry that can be used to route to the peer;
+	 * also provides indirect access to a homa_peer for the peer. This
+	 * value can change due to route invalidations, if RPC lock not held.
+	 */
+	struct homa_route *route;
+
+	/** @dport: Port number on @peer that will handle packets. */
+	u16 dport;
+
+	/**
+	 * @id: Unique identifier for the RPC among all those issued
+	 * from its port. The low-order bit indicates whether we are
+	 * server (1) or client (0) for this RPC.
+	 */
+	u64 id;
+
+	/**
+	 * @completion_cookie: Only used on clients. Contains identifying
+	 * information about the RPC provided by the application; returned to
+	 * the application with the RPC's result.
+	 */
+	u64 completion_cookie;
+
+	/**
+	 * @error: Only used on clients. If nonzero, then the RPC has
+	 * failed and the value is a negative errno that describes the
+	 * problem.
+	 */
+	int error;
+
+	/**
+	 * @msgin: Information about the message we receive for this RPC
+	 * (for server RPCs this is the request, for client RPCs this is the
+	 * response).
+	 */
+	struct homa_message_in msgin;
+
+	/**
+	 * @msgout: Information about the message we send for this RPC
+	 * (for client RPCs this is the request, for server RPCs this is the
+	 * response).
+	 */
+	struct homa_message_out msgout;
+
+	/**
+	 * @hash_links: Used to link this object into a hash bucket for
+	 * either @hsk->client_rpc_buckets (for a client RPC), or
+	 * @hsk->server_rpc_buckets (for a server RPC).
+	 */
+	struct hlist_node hash_links;
+
+	/**
+	 * @ready_links: Used to link this object into @hsk->ready_rpcs.
+	 */
+	struct list_head ready_links;
+
+	/**
+	 * @buf_links: Used to link this RPC into @hsk->waiting_for_bufs.
+	 * If the RPC isn't on @hsk->waiting_for_bufs, this is an empty
+	 * list pointing to itself.
+	 */
+	struct list_head buf_links;
+
+	/**
+	 * @active_links: For linking this object into @hsk->active_rpcs.
+	 * The next field will be LIST_POISON1 if this RPC hasn't yet been
+	 * linked into @hsk->active_rpcs. Access with RCU.
+	 */
+	struct list_head active_links;
+
+	/** @dead_links: For linking this object into @hsk->dead_rpcs. */
+	struct list_head dead_links;
+
+	/**
+	 * @private_interest: If there is a thread waiting for this RPC in
+	 * homa_wait_private, then this points to that thread's interest.
+	 */
+	struct homa_interest *private_interest;
+
+	/**
+	 * @silent_ticks: Number of times homa_timer has been invoked
+	 * since the last time a packet indicating progress was received
+	 * for this RPC, so we don't need to send a resend for a while.
+	 */
+	int silent_ticks;
+
+	/**
+	 * @resend_timer_ticks: Value of homa->timer_ticks the last time
+	 * we sent a RESEND for this RPC.
+	 */
+	u32 resend_timer_ticks;
+
+	/**
+	 * @done_timer_ticks: The value of homa->timer_ticks the first
+	 * time we noticed that this (server) RPC is done (all response
+	 * packets have been transmitted), so we're ready for an ack.
+	 * Zero means we haven't reached that point yet.
+	 */
+	u32 done_timer_ticks;
+
+	/**
+	 * @magic: when the RPC is alive, this holds a distinct value that
+	 * is unlikely to occur naturally. The value is cleared when the
+	 * RPC is reaped, so we can detect accidental use of an RPC after
+	 * it has been reaped.
+	 */
+#define HOMA_RPC_MAGIC 0xdeadbeef
+	int magic;
+
+	/**
+	 * @start_time: homa_clock() time when this RPC was created. Used
+	 * occasionally for testing.
+	 */
+	u64 start_time;
+};
+
+void     homa_abort_rpcs(struct homa *homa, const struct in6_addr *addr,
+			 int port, int error);
+void     homa_abort_sock_rpcs(struct homa_sock *hsk, int error);
+void     homa_rpc_abort(struct homa_rpc *crpc, int error);
+void     homa_rpc_ack(struct homa_sock *hsk, struct homa_rpc *rpc,
+		      const struct in6_addr *saddr, int num_acks,
+		      struct homa_ack *acks);
+struct homa_rpc
+	*homa_rpc_alloc_client(struct homa_sock *hsk,
+			       const union sockaddr_in_union *dest);
+struct homa_rpc
+	*homa_rpc_alloc_server(struct homa_sock *hsk,
+			       const struct in6_addr *source,
+			       struct homa_data_hdr *h);
+void     homa_rpc_end(struct homa_rpc *rpc);
+struct homa_rpc
+	*homa_rpc_find_client(struct homa_sock *hsk, u64 id);
+struct homa_rpc
+	*homa_rpc_find_from_skb(struct sk_buff *skb, bool incoming);
+struct homa_rpc
+	*homa_rpc_find_server(struct homa_sock *hsk,
+			      const struct in6_addr *saddr, u64 id);
+void     homa_rpc_get_info(struct homa_rpc *rpc, struct homa_rpc_info *info);
+int      homa_rpc_reap(struct homa_sock *hsk);
+
+/**
+ * homa_rpc_lock() - Acquire the lock for an RPC.
+ * @rpc:    RPC to lock.
+ */
+static inline void homa_rpc_lock(struct homa_rpc *rpc)
+	__acquires(rpc->bucket->lock)
+{
+	homa_bucket_lock(rpc->bucket, rpc->id);
+}
+
+/**
+ * homa_rpc_try_lock() - Acquire the lock for an RPC if it is available.
+ * @rpc:       RPC to lock.
+ * Return:     Nonzero if lock was successfully acquired, zero if it is
+ *             currently owned by someone else.
+ */
+static inline int homa_rpc_try_lock(struct homa_rpc *rpc)
+	__cond_acquires(nonzero, rpc->bucket->lock)
+{
+	if (!spin_trylock_bh(&rpc->bucket->lock))
+		return 0;
+	return 1;
+}
+
+/**
+ * homa_rpc_lock_preempt() - Same as homa_rpc_lock, except sets the
+ * APP_NEEDS_LOCK flags while waiting to encourage the existing lock
+ * owner to relinquish the lock.
+ * @rpc:   RPC to lock.
+ */
+static inline void homa_rpc_lock_preempt(struct homa_rpc *rpc)
+	__acquires(rpc->bucket->lock)
+{
+	set_bit(APP_NEEDS_LOCK, &rpc->flags);
+	homa_bucket_lock(rpc->bucket, rpc->id);
+	clear_bit(APP_NEEDS_LOCK, &rpc->flags);
+}
+
+/**
+ * homa_rpc_unlock() - Release the lock for an RPC.
+ * @rpc:   RPC to unlock.
+ */
+static inline void homa_rpc_unlock(struct homa_rpc *rpc)
+	__releases(rpc->bucket->lock)
+{
+	homa_bucket_unlock(rpc->bucket, rpc->id);
+}
+
+/**
+ * homa_protect_rpcs() - Ensures that no RPCs will be reaped for a given
+ * socket until homa_unprotect_rpcs is called. Typically used by functions
+ * that want to scan the active RPCs for a socket without holding the socket
+ * lock.  Multiple calls to this function may be in effect at once. See
+ * "Homa Locking Strategy" in homa_impl.h for more info on why this function
+ * is needed.
+ * @hsk:    Socket whose RPCs should be protected. Must not be locked
+ *          by the caller; will be locked here.
+ *
+ * Return:  1 for success, 0 if the socket has been shutdown, in which
+ *          case its RPCs cannot be protected.
+ */
+static inline int homa_protect_rpcs(struct homa_sock *hsk)
+{
+	int result;
+
+	homa_sock_lock(hsk);
+	result = !hsk->shutdown;
+	if (result)
+		atomic_inc(&hsk->protect_count);
+	homa_sock_unlock(hsk);
+	return result;
+}
+
+/**
+ * homa_unprotect_rpcs() - Cancel the effect of a previous call to
+ * homa_protect_rpcs(), so that RPCs can once again be reaped.
+ * @hsk:    Socket whose RPCs should be unprotected.
+ */
+static inline void homa_unprotect_rpcs(struct homa_sock *hsk)
+{
+	atomic_dec(&hsk->protect_count);
+}
+
+/**
+ * homa_rpc_hold() - Increment the reference count on an RPC, which will
+ * prevent it from being freed until homa_rpc_put() is called. References
+ * are taken in two situations:
+ * 1. An RPC is going to be manipulated by a collection of functions. In
+ *    this case the top-most function that identifies the RPC takes the
+ *    reference; any function that receives an RPC as an argument can
+ *    assume that a reference has been taken on the RPC by some higher
+ *    function on the call stack.
+ * 2. A pointer to an RPC is stored in an object for use later, such as
+ *    an interest. A reference must be held as long as the pointer remains
+ *    accessible in the object.
+ * @rpc:      RPC on which to take a reference.
+ */
+static inline void homa_rpc_hold(struct homa_rpc *rpc)
+{
+	refcount_inc(&rpc->refs);
+}
+
+/**
+ * homa_rpc_put() - Release a reference on an RPC (cancels the effect of
+ * a previous call to homa_rpc_hold).
+ * @rpc:      RPC to release.
+ */
+static inline void homa_rpc_put(struct homa_rpc *rpc)
+{
+	refcount_dec(&rpc->refs);
+}
+
+/**
+ * homa_is_client(): returns true if we are the client for a particular RPC,
+ * false if we are the server.
+ * @id:  Id of the RPC in question.
+ * Return: true if we are the client for RPC id, false otherwise
+ */
+static inline bool homa_is_client(u64 id)
+{
+	return (id & 1) == 0;
+}
+
+/**
+ * homa_rpc_needs_attention() - Returns true if @rpc has failed or if
+ * its incoming message is ready for attention by an application thread
+ * (e.g., packets are ready to copy to user space).
+ * @rpc: RPC to check.
+ * Return: See above
+ */
+static inline bool homa_rpc_needs_attention(struct homa_rpc *rpc)
+{
+	return (rpc->error != 0 || test_bit(RPC_PKTS_READY, &rpc->flags));
+}
+
+#endif /* _HOMA_RPC_H */
diff --git a/net/homa/homa_sock.c b/net/homa/homa_sock.c
new file mode 100644
index 0000000000000..a5fd321bacf23
--- /dev/null
+++ b/net/homa/homa_sock.c
@@ -0,0 +1,544 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file manages homa_sock and homa_socktab objects. */
+
+#include "homa_impl.h"
+#include "homa_interest.h"
+#include "homa_peer.h"
+#include "homa_pool.h"
+
+/**
+ * homa_socktab_init() - Constructor for homa_socktabs.
+ * @socktab:  The object to initialize; previous contents are discarded.
+ */
+void homa_socktab_init(struct homa_socktab *socktab)
+{
+	int i;
+
+	spin_lock_init(&socktab->write_lock);
+	socktab->next_sequence = 1;
+	for (i = 0; i < HOMA_SOCKTAB_BUCKETS; i++)
+		INIT_HLIST_HEAD(&socktab->buckets[i]);
+}
+
+/**
+ * homa_socktab_destroy() - Destructor for homa_socktabs: deletes all
+ * existing sockets.
+ * @socktab:  The object to destroy.
+ * @hnet:     If non-NULL, only sockets for this namespace are deleted.
+ */
+void homa_socktab_destroy(struct homa_socktab *socktab, struct homa_net *hnet)
+{
+	struct homa_socktab_scan scan;
+	struct homa_sock *hsk;
+
+	for (hsk = homa_socktab_start_scan(socktab, &scan); hsk;
+			hsk = homa_socktab_next(&scan)) {
+		if (hnet && hnet != hsk->hnet)
+			continue;
+
+		/* In actual use there should be no sockets left when this
+		 * function is invoked, so the code below will never be
+		 * invoked. However, it is useful during unit tests.
+		 */
+		homa_sock_shutdown(hsk);
+		homa_sock_destroy(&hsk->sock);
+	}
+	homa_socktab_end_scan(&scan);
+}
+
+/**
+ * homa_socktab_start_scan() - Begin an iteration over all of the sockets
+ * in a socktab.
+ * @socktab:   Socktab to scan.
+ * @scan:      Will hold the current state of the scan; any existing
+ *             contents are discarded. The caller must eventually pass this
+ *             to homa_socktab_end_scan.
+ *
+ * Return:     The first socket in the table, or NULL if the table is
+ *             empty. If non-NULL, a reference is held on the socket to
+ *             prevent its deletion.
+ *
+ * Each call to homa_socktab_next will return the next socket in the table.
+ * All sockets that are present in the table at the time this function is
+ * invoked will eventually be returned, as long as they are not removed
+ * from the table. It is safe to remove sockets from the table while the
+ * scan is in progress. If a socket is removed from the table during the scan,
+ * it may or may not be returned by homa_socktab_next. New entries added
+ * during the scan may or may not be returned.
+ */
+struct homa_sock *homa_socktab_start_scan(struct homa_socktab *socktab,
+					  struct homa_socktab_scan *scan)
+{
+	scan->socktab = socktab;
+	scan->hsk = NULL;
+	scan->current_bucket = 0;
+	scan->avail = 0;
+	scan->sequence = U64_MAX;
+
+	return homa_socktab_next(scan);
+}
+
+/**
+ * homa_socktab_fill_scan() - Refill the @socks array for a homa_socktab_scan.
+ * On return, if its @avail member is zero it means all of the sockets in
+ * the socktab have been scanned.
+ * @scan:      State of the scan. Normally the @avail member will be zero,
+ *             but this is not necessary.
+ */
+void homa_socktab_fill_scan(struct homa_socktab_scan *scan)
+{
+	struct homa_sock_link *slink;
+	struct hlist_head *bucket;
+	struct hlist_node *next;
+
+	rcu_read_lock();
+	bucket = &scan->socktab->buckets[scan->current_bucket];
+	next = rcu_dereference(hlist_first_rcu(bucket));
+	while (scan->avail < HOMA_MAX_SCANNED_SOCKS) {
+		if (!next) {
+			if (scan->current_bucket >= HOMA_SOCKTAB_BUCKETS - 1)
+				break;
+			scan->current_bucket++;
+			scan->sequence = U64_MAX;
+			bucket = &scan->socktab->buckets[scan->current_bucket];
+			next = rcu_dereference(hlist_first_rcu(bucket));
+			continue;
+		}
+		slink = hlist_entry(next, struct homa_sock_link, links);
+		next = rcu_dereference(hlist_next_rcu(next));
+		if (slink->sequence < scan->sequence) {
+			scan->sequence = slink->sequence;
+			scan->socks[scan->avail] = slink->hsk;
+			if (refcount_inc_not_zero(&slink->hsk->sock.sk_refcnt))
+				scan->avail++;
+		}
+	}
+	rcu_read_unlock();
+}
+
+/**
+ * homa_socktab_next() - Return the next socket in an iteration over a socktab.
+ * @scan:      State of the scan.
+ *
+ * Return:     The next socket in the table, or NULL if the iteration has
+ *             returned all of the sockets in the table.  If non-NULL, a
+ *             reference is held on the socket to prevent its deletion (this
+ *             module will release the reference in the next call to
+ *             homa_socktab_next or homa_socktab_end). Sockets are not returned
+ *             in any particular order. It's possible that the returned socket
+ *             has been shutdown.
+ */
+struct homa_sock *homa_socktab_next(struct homa_socktab_scan *scan)
+{
+	if (scan->hsk) {
+		sock_put(&scan->hsk->sock);
+		scan->hsk = NULL;
+	}
+
+	if (scan->avail == 0) {
+		homa_socktab_fill_scan(scan);
+		if (scan->avail == 0)
+			return NULL;
+	}
+
+	scan->hsk = scan->socks[scan->avail - 1];
+	scan->avail--;
+	return scan->hsk;
+}
+
+/**
+ * homa_socktab_end_scan() - Must be invoked on completion of each scan
+ * to clean up state associated with the scan.
+ * @scan:      State of the scan.
+ */
+void homa_socktab_end_scan(struct homa_socktab_scan *scan)
+{
+	if (scan->hsk) {
+		sock_put(&scan->hsk->sock);
+		scan->hsk = NULL;
+	}
+	while (scan->avail > 0) {
+		sock_put(&scan->socks[scan->avail - 1]->sock);
+		scan->avail--;
+	}
+}
+
+/**
+ * homa_sock_init() - Constructor for homa_sock objects. This function
+ * handles Homa-specific initialization.
+ * @hsk:    Object to initialize. The Homa-specific parts must have been
+ *          initialized to zeroes by the caller.
+ *
+ * Return:  0 for success, otherwise a negative errno.
+ */
+int homa_sock_init(struct homa_sock *hsk)
+{
+	struct homa_pool *buffer_pool;
+	struct homa_socktab *socktab;
+	struct homa_sock *other;
+	struct homa_net *hnet;
+	struct homa *homa;
+	int starting_port;
+	int result = 0;
+	int i;
+
+	hnet = (struct homa_net *)net_generic(sock_net(&hsk->sock),
+					      homa_net_id);
+	homa = hnet->homa;
+	socktab = homa->socktab;
+
+	/* Do things requiring memory allocation before locking the socket,
+	 * so that GFP_ATOMIC is not needed.
+	 */
+	buffer_pool = homa_pool_alloc(hsk);
+	if (IS_ERR(buffer_pool))
+		return PTR_ERR(buffer_pool);
+
+	/* Initialize the fields private to Homa. We can initialize
+	 * everything except the port and hash table links without acquiring
+	 * the socket table lock.
+	 */
+	hsk->homa = homa;
+	hsk->hnet = hnet;
+	hsk->buffer_pool = buffer_pool;
+
+	hsk->is_server = false;
+	hsk->shutdown = false;
+	hsk->ip_header_length = (hsk->inet.sk.sk_family == AF_INET) ?
+				sizeof(struct iphdr) : sizeof(struct ipv6hdr);
+	hsk->error_msg = "no error";
+	spin_lock_init(&hsk->lock);
+	atomic_set(&hsk->protect_count, 0);
+	INIT_LIST_HEAD(&hsk->active_rpcs);
+	INIT_LIST_HEAD(&hsk->dead_rpcs);
+	INIT_LIST_HEAD(&hsk->waiting_for_bufs);
+	INIT_LIST_HEAD(&hsk->ready_rpcs);
+	INIT_LIST_HEAD(&hsk->interests);
+	for (i = 0; i < HOMA_CLIENT_RPC_BUCKETS; i++) {
+		struct homa_rpc_bucket *bucket = &hsk->client_rpc_buckets[i];
+
+		spin_lock_init(&bucket->lock);
+		bucket->id = i;
+		INIT_HLIST_HEAD(&bucket->rpcs);
+	}
+	for (i = 0; i < HOMA_SERVER_RPC_BUCKETS; i++) {
+		struct homa_rpc_bucket *bucket = &hsk->server_rpc_buckets[i];
+
+		spin_lock_init(&bucket->lock);
+		bucket->id = i + 1000000;
+		INIT_HLIST_HEAD(&bucket->rpcs);
+	}
+
+	/* Initialize fields outside the Homa part. */
+	hsk->sock.sk_sndbuf = homa->wmem_max;
+	sock_set_flag(&hsk->inet.sk, SOCK_RCU_FREE);
+
+	/* This is needed to prevent blocking when allocating memory in
+	 * functions like ip_route_output_flow, which could be invoked
+	 * while atomic.
+	 */
+	hsk->sock.sk_allocation = GFP_ATOMIC;
+
+	/* Pick a default port. Must keep the socktab locked from now
+	 * until the new socket is added to the socktab, to ensure that
+	 * no other socket chooses the same port.
+	 */
+	spin_lock_bh(&socktab->write_lock);
+	starting_port = hnet->prev_default_port;
+	while (1) {
+		hnet->prev_default_port++;
+		if (hnet->prev_default_port < HOMA_MIN_DEFAULT_PORT)
+			hnet->prev_default_port = HOMA_MIN_DEFAULT_PORT;
+		other = homa_sock_find(hnet, hnet->prev_default_port);
+		if (!other)
+			break;
+		sock_put(&other->sock);
+		if (hnet->prev_default_port == starting_port) {
+			spin_unlock_bh(&socktab->write_lock);
+			result = -EADDRNOTAVAIL;
+			goto error;
+		}
+		spin_unlock_bh(&socktab->write_lock);
+		cond_resched();
+		spin_lock_bh(&socktab->write_lock);
+	}
+	result = homa_sock_link(hsk, hnet->prev_default_port);
+	spin_unlock_bh(&socktab->write_lock);
+	if (result == 0)
+		return result;
+
+error:
+	hsk->shutdown = true;
+	hsk->homa = NULL;
+	homa_pool_free(buffer_pool);
+	return result;
+}
+
+/**
+ * homa_sock_link() - Add a socket to the hash table for its socktab,
+ * so that it will be discoverable through homa_sock_find. If the socket
+ * is already linked, the current link will be removed.
+ * @hsk:    Socket to link in; hsk->port will be used to determine
+ *          where the socket is linked in it socktab. Caller must hold
+ *          the lock for the socket's socktab.
+ * @port:   Port to use for the socket; if this function succeeds, this
+ *          number will be stored in hsk.
+ *
+ * Return:  0 for success, otherwise a negative errno.
+ */
+int homa_sock_link(struct homa_sock *hsk, int port)
+	__must_hold(hsk->homa->socktab->write_lock)
+{
+	struct homa_socktab *socktab = hsk->homa->socktab;
+	struct homa_sock_link *slink;
+
+	slink = kmalloc_obj(*slink, GFP_ATOMIC | __GFP_ACCOUNT);
+	if (!slink)
+		return -ENOMEM;
+	homa_sock_unlink(hsk);
+	slink->hsk = hsk;
+	slink->sequence = socktab->next_sequence;
+	socktab->next_sequence++;
+	hlist_add_head_rcu(&slink->links,
+			   &socktab->buckets[homa_socktab_bucket(hsk->hnet,
+								 port)]);
+	hsk->port = port;
+	hsk->inet.inet_num = port;
+	hsk->inet.inet_sport = htons(port);
+	hsk->slink = slink;
+	return 0;
+}
+
+/*
+ * homa_sock_unlink() - Unlinks a socket from its socktab. Once this method
+ * returns, the socket will not be discoverable through the socktab.
+ * @hsk:  Socket to unlink. Caller must hold the lock for the socket's
+ *        socktab.
+ */
+void homa_sock_unlink(struct homa_sock *hsk)
+	__must_hold(hsk->homa->socktab->write_lock)
+{
+	struct homa_sock_link *slink;
+
+	slink = hsk->slink;
+	if (!slink)
+		return;
+	hsk->slink = NULL;
+	hlist_del_rcu(&slink->links);
+	kfree_rcu(slink, rcu_head);
+}
+
+/**
+ * homa_sock_shutdown() - Disable a socket so that it can no longer
+ * be used for either sending or receiving messages. Any system calls
+ * currently waiting to send or receive messages will be aborted. This
+ * function will terminate any existing use of the socket, but it does
+ * not free up socket resources: that happens in homa_sock_destroy.
+ * @hsk:       Socket to shut down.
+ */
+void homa_sock_shutdown(struct homa_sock *hsk)
+{
+	struct homa_socktab *socktab;
+	struct homa_rpc *rpc;
+
+	homa_sock_lock(hsk);
+	if (hsk->shutdown || !hsk->homa) {
+		homa_sock_unlock(hsk);
+		return;
+	}
+
+	/* The order of cleanup is very important, because there could be
+	 * active operations that hold RPC locks but not the socket lock.
+	 * 1. Set @shutdown; this ensures that no new RPCs will be created for
+	 *    this socket (though some creations might already be in progress)
+	 *    and incoming packets will be dropped.
+	 * 2. Remove the socket from its socktab, so no-one will ever find
+	 *    it again.
+	 * 3. Go through all of the RPCs and delete them; this will
+	 *    synchronize with any operations in progress.
+	 * 4. Perform other socket cleanup: at this point we know that
+	 *    there will be no concurrent activities on individual RPCs.
+	 * 5. Don't delete the buffer pool until after all of the RPCs
+	 *    have been reaped.
+	 * See "Homa Locking Strategy" in homa_impl.h for additional information
+	 * about locking.
+	 */
+	hsk->shutdown = true;
+
+	/* This protects against RPC deletions during the RCU scan of
+	 * active_rpcs below.
+	 */
+	atomic_inc(&hsk->protect_count);
+	homa_sock_unlock(hsk);
+
+	socktab = hsk->homa->socktab;
+	spin_lock_bh(&socktab->write_lock);
+	homa_sock_unlink(hsk);
+	spin_unlock_bh(&socktab->write_lock);
+
+	rcu_read_lock();
+	list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
+		homa_rpc_lock(rpc);
+		homa_rpc_end(rpc);
+		homa_rpc_unlock(rpc);
+	}
+	wake_up_interruptible_poll(sk_sleep(&hsk->sock), EPOLLOUT);
+	rcu_read_unlock();
+	homa_unprotect_rpcs(hsk);
+
+	homa_sock_lock(hsk);
+	while (!list_empty(&hsk->interests))
+		homa_interest_notify_shared(hsk, NULL);
+	homa_sock_unlock(hsk);
+}
+
+/**
+ * homa_sock_destroy() - Release all of the internal resources associated
+ * with a socket; is invoked at time when that is safe (i.e., all references
+ * on the socket have been dropped).
+ * @sk:       Socket to destroy.
+ */
+void homa_sock_destroy(struct sock *sk)
+{
+	struct homa_sock *hsk = homa_sk(sk);
+
+	if (!hsk->homa)
+		return;
+
+	while (!list_empty(&hsk->dead_rpcs))
+		homa_rpc_reap(hsk);
+
+	WARN_ON_ONCE(refcount_read(&hsk->sock.sk_wmem_alloc) != 1);
+
+	if (hsk->buffer_pool) {
+		homa_pool_free(hsk->buffer_pool);
+		hsk->buffer_pool = NULL;
+	}
+}
+
+/**
+ * homa_sock_bind() - Associates a server port with a socket; if there
+ * was a previous server port assignment for @hsk, it is abandoned.
+ * @hnet:      Network namespace with which port is associated.
+ * @hsk:       Homa socket.
+ * @port:      Desired server port for @hsk. If 0, then this call
+ *             becomes a no-op: the socket will continue to use
+ *             its randomly assigned client port.
+ *
+ * Return:  0 for success, otherwise a negative errno. If an error is
+ *          returned, hsk->error_msg is set.
+ */
+int homa_sock_bind(struct homa_net *hnet, struct homa_sock *hsk,
+		   u16 port)
+{
+	struct homa_socktab *socktab = hnet->homa->socktab;
+	struct homa_sock *owner;
+	int result = 0;
+
+	if (port == 0)
+		return result;
+	if (port >= HOMA_MIN_DEFAULT_PORT) {
+		hsk->error_msg = "port number invalid: in the automatically assigned range";
+		return -EINVAL;
+	}
+	homa_sock_lock(hsk);
+	spin_lock_bh(&socktab->write_lock);
+	if (hsk->shutdown) {
+		hsk->error_msg = "socket has been shut down";
+		result = -ESHUTDOWN;
+		goto done;
+	}
+
+	owner = homa_sock_find(hnet, port);
+	if (owner) {
+		sock_put(&owner->sock);
+		if (owner != hsk) {
+			hsk->error_msg = "requested port number is already in use";
+			result = -EADDRINUSE;
+		}
+		goto done;
+	}
+	result = homa_sock_link(hsk, port);
+	if (result == 0)
+		hsk->is_server = true;
+done:
+	spin_unlock_bh(&socktab->write_lock);
+	homa_sock_unlock(hsk);
+	return result;
+}
+
+/**
+ * homa_sock_find() - Returns the socket associated with a given port.
+ * @hnet:       Network namespace where the socket will be used.
+ * @port:       The port of interest.
+ * Return:      The socket that owns @port, or NULL if none. If non-NULL
+ *              then this method has taken a reference on the socket and
+ *              the caller must call sock_put to release it.
+ */
+struct homa_sock *homa_sock_find(struct homa_net *hnet, u16 port)
+{
+	int bucket = homa_socktab_bucket(hnet, port);
+	struct homa_sock *result = NULL;
+	struct homa_sock_link *slink;
+	struct homa_sock *hsk;
+
+	rcu_read_lock();
+	hlist_for_each_entry_rcu(slink, &hnet->homa->socktab->buckets[bucket],
+				 links) {
+		hsk = slink->hsk;
+		if (hsk && hsk->port == port && hsk->hnet == hnet &&
+		    !hsk->shutdown &&
+		    refcount_inc_not_zero(&hsk->sock.sk_refcnt)) {
+			result = hsk;
+			break;
+		}
+	}
+	rcu_read_unlock();
+	return result;
+}
+
+/**
+ * homa_sock_wait_wmem() - Block the thread until @hsk's usage of tx
+ * packet memory drops below the socket's limit.
+ * @hsk:          Socket of interest.
+ * @nonblocking:  If there's not enough memory, return -EWOLDBLOCK instead
+ *                of blocking.
+ * Return: 0 for success, otherwise a negative errno.
+ */
+int homa_sock_wait_wmem(struct homa_sock *hsk, int nonblocking)
+{
+	long timeo = hsk->sock.sk_sndtimeo;
+	int result;
+
+	/* Note: we can't use sock_wait_for_wmem because that function
+	 * is not available to modules (as of August 2025 it's static).
+	 */
+	if (nonblocking)
+		timeo = 0;
+	set_bit(HOMA_SOCK_NOSPACE, &hsk->flags);
+
+	/* Must wakeup if either memory becomes available or HOMA_SOCK_NOSPACE
+	 * gets cleared. The wmem_avl check is needed to handle a race where
+	 * memory gets freed just before HOMA_SOCK_NOSPACE is set above. The
+	 * HOMA_SOCK_NOSPACE check is needed to handle a race where multiple
+	 * threads wakeup and one thread consumes enough memory that the
+	 * wmem_avl check fails for the other. This approach means that we may
+	 * exceed the memory limit if multiple threads wake up at once, but
+	 * it prevents thread starvation that could occur if the second
+	 * thread were to go back to sleep.
+	 */
+	result = wait_event_interruptible_timeout(*sk_sleep(&hsk->sock),
+						  homa_sock_wmem_avl(hsk) ||
+						  hsk->shutdown ||
+						  !test_bit(HOMA_SOCK_NOSPACE,
+							    &hsk->flags),
+						  timeo);
+	if (hsk->shutdown)
+		return -ESHUTDOWN;
+	if (signal_pending(current))
+		return -EINTR;
+	if (result == 0)
+		return -EWOULDBLOCK;
+	return 0;
+}
diff --git a/net/homa/homa_sock.h b/net/homa/homa_sock.h
new file mode 100644
index 0000000000000..21a7802a999c0
--- /dev/null
+++ b/net/homa/homa_sock.h
@@ -0,0 +1,513 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file defines structs and other things related to Homa sockets.  */
+
+#ifndef _HOMA_SOCK_H
+#define _HOMA_SOCK_H
+
+/* Forward declarations. */
+struct homa;
+struct homa_pool;
+struct homa_sock;
+
+/* Number of hash buckets in a homa_socktab. Must be a power of 2. */
+#define HOMA_SOCKTAB_BUCKET_BITS 10
+#define HOMA_SOCKTAB_BUCKETS BIT(HOMA_SOCKTAB_BUCKET_BITS)
+
+/**
+ * struct homa_socktab - A hash table that maps from port numbers (either
+ * client or server) to homa_sock objects.
+ *
+ * This table is managed exclusively by homa_socktab.c, using RCU to
+ * minimize synchronization during lookups.
+ */
+struct homa_socktab {
+	/**
+	 * @write_lock: Controls all modifications to this object; not needed
+	 * for socket lookups (RCU is used instead). Also used to
+	 * synchronize port allocation.
+	 */
+	spinlock_t write_lock;
+
+	/**
+	 * @next_sequence: Next sequence number to assign for a
+	 * homa_sock_link.
+	 */
+	u64 next_sequence;
+
+	/**
+	 * @buckets: Heads of chains for hash table buckets. Chains
+	 * consist of homa_sock_link objects, in decreasing order of
+	 * sequence number.
+	 */
+	struct hlist_head buckets[HOMA_SOCKTAB_BUCKETS];
+};
+
+/**
+ * struct homa_sock_link - Used to link a socket into a list associated
+ * with a bucket in a homa_socktab. This is a separate dynamically
+ * allocated object because a socket may need to change its position in
+ * the homa_socktab (because its port number changes); during the
+ * transition, multiple of these objects may exist for a socket so that
+ * socktab scans are not disrupted by the change in position. The lifetime
+ * of these objects is managed with RCU.
+ */
+struct homa_sock_link {
+	/** @hsk: The socket associated with this link. */
+	struct homa_sock *hsk;
+
+	/**
+	 * @sequence: Unique sequence number for this struct among all structs
+	 * in a socktab (smaller means older).
+	 */
+	u64 sequence;
+
+	/**
+	 * @links: Links this object into the chain for a bucket in a
+	 * homa_socktab.
+	 */
+	struct hlist_node links;
+
+	/** @rcu_head: Used for RCU-based freeing of this object. */
+	struct rcu_head rcu_head;
+};
+
+/**
+ * struct homa_socktab_scan - Records the state of an iteration over all
+ * the entries in a homa_socktab, in a way that is safe against concurrent
+ * reclamation of sockets.
+ */
+struct homa_socktab_scan {
+	/** @socktab: The table that is being scanned. */
+	struct homa_socktab *socktab;
+
+	/**
+	 * @hsk: Points to the current socket in the iteration, or NULL if
+	 * we're at the beginning of the iteration or have reached the end of
+	 * the current bucket. If non-NULL then we are holding a reference
+	 * to this socket.
+	 */
+	struct homa_sock *hsk;
+
+	/**
+	 * @current_bucket: The index of the bucket in socktab->buckets
+	 * currently being scanned.
+	 */
+	int current_bucket;
+
+	/**
+	 * @avail: The first @avail entries in @links are valid and
+	 * available for homa_sock_next to return.
+	 */
+	int avail;
+
+	/**
+	 * @socks: Used to collect a bunch of sockets by scanning hash table
+	 * bucket chains. Sockets are then returned from here by
+	 * homa_socktab_next. We own a reference for each of these sockets.
+	 */
+#define HOMA_MAX_SCANNED_SOCKS 5
+	struct homa_sock *socks[HOMA_MAX_SCANNED_SOCKS];
+
+	/**
+	 * @sequence: All homa_sock_links with @sequence numbers >= this
+	 * have already been scanned from @current_bucket.
+	 */
+	u64 sequence;
+};
+
+/**
+ * struct homa_rpc_bucket - One bucket in a hash table of RPCs.
+ */
+
+struct homa_rpc_bucket {
+	/**
+	 * @lock: serves as a lock both for this bucket (e.g., when
+	 * adding and removing RPCs) and also for all of the RPCs in
+	 * the bucket. Must be held whenever looking up an RPC in
+	 * this bucket or manipulating an RPC in the bucket. This approach
+	 * has the following properties:
+	 * 1. An RPC can be looked up and locked (a common operation) with
+	 *    a single lock acquisition.
+	 * 2. Looking up and locking are atomic: there is no window of
+	 *    vulnerability where someone else could delete an RPC after
+	 *    it has been looked up and before it has been locked.
+	 * 3. The lookup mechanism does not use RCU.  This is important because
+	 *    RPCs are created rapidly and typically live only a few tens of
+	 *    microseconds.  As of May 2025 RCU introduces a lag of about
+	 *    25 ms before objects can be deleted; for RPCs this would result
+	 *    in hundreds or thousands of RPCs accumulating before RCU allows
+	 *    them to be deleted.
+	 * This approach has the disadvantage that RPCs within a bucket share
+	 * locks and thus may not be able to work concurrently, but there are
+	 * enough buckets in the table to make such colllisions rare.
+	 *
+	 * See "Homa Locking Strategy" in homa_impl.h for more info about
+	 * locking.
+	 */
+	spinlock_t lock;
+
+	/**
+	 * @id: identifier for this bucket, used in error messages etc.
+	 * It's the index of the bucket within its hash table bucket
+	 * array, with an additional offset to separate server and
+	 * client RPCs.
+	 */
+	int id;
+
+	/** @rpcs: list of RPCs that hash to this bucket. */
+	struct hlist_head rpcs;
+};
+
+/**
+ * define HOMA_CLIENT_RPC_BUCKETS - Number of buckets in hash tables for
+ * client RPCs. Must be a power of 2.
+ */
+#define HOMA_CLIENT_RPC_BUCKETS 1024
+
+/**
+ * define HOMA_SERVER_RPC_BUCKETS - Number of buckets in hash tables for
+ * server RPCs. Must be a power of 2.
+ */
+#define HOMA_SERVER_RPC_BUCKETS 1024
+
+/**
+ * struct homa_sock - Information about an open socket.
+ */
+struct homa_sock {
+	/* Info for other network layers. Note: IPv6 info (struct ipv6_pinfo
+	 * comes at the very end of the struct, *after* Homa's data, if this
+	 * socket uses IPv6).
+	 */
+	union {
+		/** @sock: generic socket data; must be the first field. */
+		struct sock sock;
+
+		/**
+		 * @inet: generic Internet socket data; must also be the
+		 first field (contains sock as its first member).
+		 */
+		struct inet_sock inet;
+	};
+
+	/**
+	 * @homa: Overall state about the Homa implementation. NULL
+	 * means this socket was never initialized or has been deleted.
+	 */
+	struct homa *homa;
+
+	/**
+	 * @hnet: Overall state specific to the network namespace for
+	 * this socket.
+	 */
+	struct homa_net *hnet;
+
+	/**
+	 * @buffer_pool: used to allocate buffer space for incoming messages.
+	 * Storage is dynamically allocated.
+	 */
+	struct homa_pool *buffer_pool;
+
+	/**
+	 * @port: Port number: identifies this socket uniquely among all
+	 * those on this node.
+	 */
+	u16 port;
+
+	/**
+	 * @is_server: True means that this socket can act as both client
+	 * and server; false means the socket is client-only.
+	 */
+	bool is_server;
+
+	/**
+	 * @shutdown: True means the socket is no longer usable (either
+	 * shutdown has already been invoked, or the socket was never
+	 * properly initialized). Note: can't use the SOCK_DEAD flag for
+	 * this because that flag doesn't get set until much later in the
+	 * process of closing a socket.
+	 */
+	bool shutdown;
+
+	/**
+	 * @ip_header_length: Length of IP headers for this socket (depends
+	 * on IPv4 vs. IPv6).
+	 */
+	int ip_header_length;
+
+	/** @slink: Links this socket into a homa_socktab bucket. */
+	struct homa_sock_link *slink;
+
+	/**
+	 * @error_msg: Static string giving human-readable information about
+	 * the reason for the last error returned by a Homa kernel call.
+	 * Applications can fetch this with the HOMAIOCINFO ioctl to figure
+	 * out why a call failed.
+	 */
+	char *error_msg;
+
+	/* Information above is (almost) never modified; start a new
+	 * cache line below for info that is modified frequently.
+	 */
+
+	/**
+	 * @lock: Must be held when modifying fields such as interests
+	 * and lists of RPCs. This lock is used in place of sk->sk_lock
+	 * because it's used differently (it's always used as a simple
+	 * spin lock).  See "Homa Locking Strategy" in homa_impl.h
+	 * for more on Homa's synchronization strategy.
+	 */
+	spinlock_t lock ____cacheline_aligned_in_smp;
+
+	/**
+	 * @protect_count: counts the number of calls to homa_protect_rpcs
+	 * for which there have not yet been calls to homa_unprotect_rpcs.
+	 */
+	atomic_t protect_count;
+
+	/**
+	 * @flags: Additional state information: an OR'ed combination of
+	 * various single-bit flags. See below for definitions. Must be
+	 * manipulated with test_bit etc. because some of the manipulations
+	 * occur without holding @lock.
+	 */
+	unsigned long flags;
+
+	/* Valid bit numbers for @flags:
+	 * HOMA_SOCK_NOSPACE -     Nonzero means that the socket has hit its
+	 *                         limit on tx buffer space and threads are
+	 *                         blocked waiting for skbs to be released. Used
+	 *                         instead of the SOCK_NOSPACE flag in
+	 *                         @sock.sk_socket->flags. This is because
+	 *                         @sock.sk_socket can become NULL unexpectedly
+	 *                         (especially since Homa never acquires the
+	 *                         Linux socket lock). Thus code using sk_socket
+	 *                         requires tricky synchronization and is
+	 *                         error-prone.
+	 */
+#define HOMA_SOCK_NOSPACE        0
+
+	/**
+	 * @active_rpcs: List of all existing RPCs related to this socket,
+	 * including both client and server RPCs. This list isn't strictly
+	 * needed, since RPCs are already in one of the hash tables below,
+	 * but it's more efficient for homa_timer to have this list
+	 * (so it doesn't have to scan large numbers of hash buckets).
+	 * The list is sorted, with the oldest RPC first. Manipulate with
+	 * RCU so timer can access without locking.
+	 */
+	struct list_head active_rpcs;
+
+	/**
+	 * @dead_rpcs: Contains RPCs for which homa_rpc_end has been
+	 * called, but which have not yet been reaped by homa_rpc_reap.
+	 */
+	struct list_head dead_rpcs;
+
+	/**
+	 * @dead_frags: An estimate of the amount of memory tied up in
+	 * RPCs that are dead but have not yet been reaped. The sum of
+	 * rpc->msgout.num_frags + 1 for all of the dead RPCs (the 1 accounts
+	 * for the RPC itself). Used to detect when the reaper is lagging
+	 * behind. See "RPC Reaping Strategy" in homa_rpc_reap code for
+	 * deetails.
+	 */
+	u64 dead_frags;
+
+	/**
+	 * @waiting_for_bufs: Contains RPCs that are blocked because there
+	 * wasn't enough space in the buffer pool region for their incoming
+	 * messages. Sorted in increasing order of message length.
+	 */
+	struct list_head waiting_for_bufs;
+
+	/**
+	 * @ready_rpcs: List of all RPCs that are ready for attention from
+	 * an application thread.
+	 */
+	struct list_head ready_rpcs;
+
+	/**
+	 * @interests: List of threads that are currently waiting for
+	 * incoming messages via homa_wait_shared.
+	 */
+	struct list_head interests;
+
+	/**
+	 * @client_rpc_buckets: Hash table for fast lookup of client RPCs.
+	 * Modifications are synchronized with bucket locks, not
+	 * the socket lock.
+	 */
+	struct homa_rpc_bucket client_rpc_buckets[HOMA_CLIENT_RPC_BUCKETS];
+
+	/**
+	 * @server_rpc_buckets: Hash table for fast lookup of server RPCs.
+	 * Modifications are synchronized with bucket locks, not
+	 * the socket lock.
+	 */
+	struct homa_rpc_bucket server_rpc_buckets[HOMA_SERVER_RPC_BUCKETS];
+};
+
+/**
+ * struct homa_v6_sock - For IPv6, additional IPv6-specific information
+ * is present in the socket struct after Homa-specific information.
+ */
+struct homa_v6_sock {
+	/** @homa: All socket info except for IPv6-specific stuff. */
+	struct homa_sock homa;
+
+	/** @inet6: Socket info specific to IPv6. */
+	struct ipv6_pinfo inet6;
+};
+
+int                homa_sock_bind(struct homa_net *hnet, struct homa_sock *hsk,
+				  u16 port);
+void               homa_sock_destroy(struct sock *sk);
+void               homa_socktab_fill_scan(struct homa_socktab_scan *scan);
+struct homa_sock  *homa_sock_find(struct homa_net *hnet, u16 port);
+int                homa_sock_init(struct homa_sock *hsk);
+int                homa_sock_link(struct homa_sock *hsk, int port);
+void               homa_sock_shutdown(struct homa_sock *hsk);
+void               homa_sock_unlink(struct homa_sock *hsk);
+int                homa_sock_wait_wmem(struct homa_sock *hsk, int nonblocking);
+void               homa_socktab_destroy(struct homa_socktab *socktab,
+					struct homa_net *hnet);
+void               homa_socktab_end_scan(struct homa_socktab_scan *scan);
+void               homa_socktab_init(struct homa_socktab *socktab);
+struct homa_sock  *homa_socktab_next(struct homa_socktab_scan *scan);
+struct homa_sock  *homa_socktab_start_scan(struct homa_socktab *socktab,
+					   struct homa_socktab_scan *scan);
+
+/**
+ * homa_sock_lock() - Acquire the lock for a socket.
+ * @hsk:     Socket to lock.
+ */
+static inline void homa_sock_lock(struct homa_sock *hsk)
+	__acquires(hsk->lock)
+{
+	spin_lock_bh(&hsk->lock);
+}
+
+/**
+ * homa_sock_unlock() - Release the lock for a socket.
+ * @hsk:   Socket to lock.
+ */
+static inline void homa_sock_unlock(struct homa_sock *hsk)
+	__releases(hsk->lock)
+{
+	spin_unlock_bh(&hsk->lock);
+}
+
+/**
+ * homa_socktab_bucket() - Compute the bucket number in a homa_socktab
+ * that will contain a particular socket.
+ * @hnet:   Network namespace of the desired socket.
+ * @port:   Port number of the socket.
+ *
+ * Return:  The index of the bucket in which a socket matching @hnet and
+ *          @port will be found (if it exists).
+ */
+static inline int homa_socktab_bucket(struct homa_net *hnet, u16 port)
+{
+	return hash_32((uintptr_t)hnet ^ port, HOMA_SOCKTAB_BUCKET_BITS);
+}
+
+/**
+ * homa_client_rpc_bucket() - Find the bucket containing a given
+ * client RPC.
+ * @hsk:      Socket associated with the RPC.
+ * @id:       Id of the desired RPC.
+ *
+ * Return:    The bucket in which this RPC will appear, if the RPC exists.
+ */
+static inline struct homa_rpc_bucket
+		*homa_client_rpc_bucket(struct homa_sock *hsk, u64 id)
+{
+	/* We can use a really simple hash function here because RPC ids
+	 * are allocated sequentially.
+	 */
+	return &hsk->client_rpc_buckets[(id >> 1) &
+	       (HOMA_CLIENT_RPC_BUCKETS - 1)];
+}
+
+/**
+ * homa_server_rpc_bucket() - Find the bucket containing a given
+ * server RPC.
+ * @hsk:         Socket associated with the RPC.
+ * @id:          Id of the desired RPC.
+ *
+ * Return:    The bucket in which this RPC will appear, if the RPC exists.
+ */
+static inline struct homa_rpc_bucket
+		*homa_server_rpc_bucket(struct homa_sock *hsk, u64 id)
+{
+	/* Each client allocates RPC ids sequentially, so they will
+	 * naturally distribute themselves across the hash space.
+	 * Thus we can use the id directly as hash.
+	 */
+	return &hsk->server_rpc_buckets[(id >> 1)
+			& (HOMA_SERVER_RPC_BUCKETS - 1)];
+}
+
+/**
+ * homa_bucket_lock() - Acquire the lock for an RPC hash table bucket.
+ * @bucket:    Bucket to lock.
+ * @id:        Id of the RPC on whose behalf the bucket is being locked.
+ *             Used only for metrics.
+ */
+static inline void homa_bucket_lock(struct homa_rpc_bucket *bucket, u64 id)
+	__acquires(bucket->lock)
+{
+	spin_lock_bh(&bucket->lock);
+}
+
+/**
+ * homa_bucket_unlock() - Release the lock for an RPC hash table bucket.
+ * @bucket:   Bucket to unlock.
+ * @id:       ID of the RPC that was using the lock.
+ */
+static inline void homa_bucket_unlock(struct homa_rpc_bucket *bucket, u64 id)
+	__releases(bucket->lock)
+{
+	spin_unlock_bh(&bucket->lock);
+}
+
+static inline struct homa_sock *homa_sk(const struct sock *sk)
+{
+	return (struct homa_sock *)sk;
+}
+
+/**
+ * homa_sock_wmem_avl() - Returns true if the socket is within its limit
+ * for output memory usage. False means that no new messages should be sent
+ * until memory is freed.
+ * @hsk:   Socket of interest.
+ * Return: See above.
+ */
+static inline bool homa_sock_wmem_avl(struct homa_sock *hsk)
+{
+	return refcount_read(&hsk->sock.sk_wmem_alloc) < hsk->sock.sk_sndbuf;
+}
+
+/**
+ * homa_sock_wakeup_wmem() - Invoked when tx packet memory has been freed;
+ * if memory usage is below the limit and there are tasks waiting for memory,
+ * wake them up.
+ * @hsk:   Socket of interest.
+ */
+static inline void homa_sock_wakeup_wmem(struct homa_sock *hsk)
+{
+	/* Note: can't use sk_stream_write_space for this functionality
+	 * because it uses a different test to determine whether enough
+	 * memory is available.
+	 */
+	if (test_bit(HOMA_SOCK_NOSPACE, &hsk->flags) &&
+	    homa_sock_wmem_avl(hsk)) {
+		clear_bit(HOMA_SOCK_NOSPACE, &hsk->flags);
+		rcu_read_lock();
+		wake_up_interruptible_poll(sk_sleep(&hsk->sock), EPOLLOUT);
+		rcu_read_unlock();
+	}
+}
+
+#endif /* _HOMA_SOCK_H */
diff --git a/net/homa/homa_timer.c b/net/homa/homa_timer.c
new file mode 100644
index 0000000000000..2fa86f523088d
--- /dev/null
+++ b/net/homa/homa_timer.c
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file handles timing-related functions for Homa, such as retries
+ * and timeouts.
+ */
+
+#include "homa_impl.h"
+#include "homa_peer.h"
+#include "homa_rpc.h"
+#include "homa_tx_pool.h"
+
+/**
+ * homa_timer_check_rpc() -  Invoked for each RPC during each timer pass; does
+ * most of the work of checking for time-related actions such as sending
+ * resends, aborting RPCs for which there is no response, and sending
+ * requests for acks. It is separate from homa_timer because homa_timer
+ * got too long and deeply indented.
+ * @rpc:     RPC to check; must be locked by the caller.
+ */
+void homa_timer_check_rpc(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa *homa = rpc->hsk->homa;
+	int tx_end = homa_rpc_tx_end(rpc);
+
+	/* See if we need to request an ack for this RPC. */
+	if (!homa_is_client(rpc->id) && rpc->state == RPC_OUTGOING &&
+	    tx_end == rpc->msgout.length) {
+		if (rpc->done_timer_ticks == 0) {
+			rpc->done_timer_ticks = homa->timer_ticks;
+		} else {
+			/* >= comparison that handles tick wrap-around. */
+			if ((rpc->done_timer_ticks + homa->request_ack_ticks
+					- 1 - homa->timer_ticks) & 1 << 31) {
+				struct homa_need_ack_hdr h;
+
+				homa_xmit_control(NEED_ACK, &h, sizeof(h), rpc);
+			}
+		}
+	}
+
+	if (rpc->state == RPC_INCOMING) {
+		if (rpc->msgin.num_bpages == 0) {
+			/* Waiting for buffer space, so no problem. */
+			rpc->silent_ticks = 0;
+			return;
+		}
+	} else if (!homa_is_client(rpc->id)) {
+		/* We're the server and we've received the input message;
+		 * no need to worry about retries.
+		 */
+		rpc->silent_ticks = 0;
+		return;
+	}
+
+	if (rpc->state == RPC_OUTGOING) {
+		if (tx_end < rpc->msgout.length) {
+			/* There are granted bytes that we haven't transmitted,
+			 * so no need to be concerned; the ball is in our court.
+			 */
+			rpc->silent_ticks = 0;
+			return;
+		}
+	}
+
+	if (rpc->silent_ticks < homa->resend_ticks)
+		return;
+	if (rpc->silent_ticks >= homa->timeout_ticks) {
+		homa_rpc_abort(rpc, -ETIMEDOUT);
+		return;
+	}
+	if (((rpc->silent_ticks - homa->resend_ticks) % homa->resend_interval)
+			== 0)
+		homa_request_retrans(rpc);
+}
+
+/**
+ * homa_timer() - This function is invoked at regular intervals ("ticks")
+ * to implement retries and aborts for Homa.
+ * @homa:    Overall data about the Homa protocol implementation.
+ */
+void homa_timer(struct homa *homa)
+{
+	struct homa_socktab_scan scan;
+	struct homa_sock *hsk;
+	struct homa_rpc *rpc;
+	int rpc_count = 0;
+
+	homa->timer_ticks++;
+
+	/* Scan all existing RPCs in all sockets. */
+	for (hsk = homa_socktab_start_scan(homa->socktab, &scan);
+			hsk; hsk = homa_socktab_next(&scan)) {
+		while (hsk->dead_frags > homa->dead_frags_limit)
+			/* If we get here, it means that Homa isn't keeping
+			 * up with RPC reaping, so we'll help out.  See
+			 * "RPC Reaping Strategy" in homa_rpc_reap code for
+			 * details.
+			 */
+			if (homa_rpc_reap(hsk) == 0)
+				break;
+
+		if (list_empty(&hsk->active_rpcs) || hsk->shutdown)
+			continue;
+
+		if (!homa_protect_rpcs(hsk))
+			continue;
+		rcu_read_lock();
+		list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
+			homa_rpc_lock(rpc);
+			if (rpc->state == RPC_IN_SERVICE) {
+				rpc->silent_ticks = 0;
+				homa_rpc_unlock(rpc);
+				continue;
+			}
+			rpc->silent_ticks++;
+			homa_timer_check_rpc(rpc);
+			homa_rpc_unlock(rpc);
+			rpc_count++;
+			if (rpc_count >= 10) {
+				/* Give other kernel threads a chance to run
+				 * on this core.
+				 */
+				rcu_read_unlock();
+				schedule();
+				rcu_read_lock();
+				rpc_count = 0;
+			}
+		}
+		rcu_read_unlock();
+		homa_unprotect_rpcs(hsk);
+	}
+	homa_socktab_end_scan(&scan);
+	homa_tx_pool_gc(homa);
+	homa_route_gc(homa->peertab);
+}
diff --git a/net/homa/homa_tx_pool.c b/net/homa/homa_tx_pool.c
new file mode 100644
index 0000000000000..c6420ffe2d19c
--- /dev/null
+++ b/net/homa/homa_tx_pool.c
@@ -0,0 +1,527 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file manages a reusable pools of pages (one per NUMA node), that
+ * are used to hold the data of outgoing Homa messages. Homa uses these
+ * custom pools rather than, say, page_pools because Homa can free pages
+ * from its pools more aggressively than in page_pool. And, this module
+ * also implements a one-page cache page per core to use for allocating
+ * smaller chunks of tx memory.
+ */
+
+#include "homa_impl.h"
+#include "homa_tx_pool.h"
+
+DEFINE_PER_CPU(struct homa_tx_pool_core, homa_tx_pool_core);
+
+static void frag_page_set(skb_frag_t *frag, struct page *page)
+{
+	frag->netmem = page_to_netmem(page);
+}
+
+/**
+ * homa_tx_pool_init() - Invoked when a struct homa is created; initializes
+ * information related to this module.
+ * @homa:        Shared information about the Homa transport; pool-related
+ *               fields are assumed to have been initialized to zero.
+ * Return:       0 for success, negative errno on error
+ */
+int homa_tx_pool_init(struct homa *homa)
+{
+	u64 min_kb;
+	int i;
+
+	homa->tx_page_pool_min_kb = 1000;
+	min_kb = 3 * HOMA_MAX_MESSAGE_LENGTH;
+	do_div(min_kb, 1000);
+	homa->tx_page_pool_min_kb = min_kb;
+
+	/* Initialize NUMA-specfific page pools. */
+	homa->max_numa = -1;
+	for (i = 0; i < nr_cpu_ids; i++) {
+		struct homa_tx_pool_core *tx_core;
+		int numa = cpu_to_node(i);
+
+		BUG_ON(numa >= MAX_NUMNODES);
+		if (numa > homa->max_numa)
+			homa->max_numa = numa;
+		if (!homa->tx_pools[numa]) {
+			struct homa_tx_pool *pool;
+
+			pool = kzalloc_obj(*pool, GFP_ATOMIC);
+			if (!pool)
+				goto error;
+			homa->tx_pools[numa] = pool;
+		}
+		tx_core = &per_cpu(homa_tx_pool_core, i);
+		tx_core->pool = homa->tx_pools[numa];
+	}
+	pr_notice("%s found max NUMA node %d\n", __func__, homa->max_numa);
+	return 0;
+
+error:
+	homa_tx_pool_cleanup(homa);
+	return -ENOMEM;
+}
+
+/**
+ * homa_tx_pool_cleanup() - Invoked when a struct homa is deleted; cleans
+ * up information related to this module.
+ * @homa:  Overall information about the Homa transport.
+ */
+void homa_tx_pool_cleanup(struct homa *homa)
+{
+	int i, j;
+
+	for (i = 0; i < nr_cpu_ids; i++) {
+		struct homa_tx_pool_core *tx_core;
+
+		tx_core = &per_cpu(homa_tx_pool_core, i);
+		if (!tx_core)
+			continue;
+		if (tx_core->page) {
+			put_page(tx_core->page);
+			tx_core->page = NULL;
+			tx_core->page_size = 0;
+			tx_core->allocated = 0;
+		}
+		tx_core->pool = NULL;
+	}
+
+	for (i = 0; i < MAX_NUMNODES; i++) {
+		struct homa_tx_pool *pool = homa->tx_pools[i];
+
+		if (!pool)
+			continue;
+		for (j = pool->avail - 1; j >= 0; j--)
+			put_page(pool->pages[j]);
+		pool->avail = 0;
+		kfree(pool);
+		homa->tx_pools[i] = NULL;
+	}
+
+	kfree(homa->tx_pages_to_free);
+	homa->tx_pages_to_free = NULL;
+	homa->tx_pages_to_free_slots = 0;
+}
+
+/**
+ * homa_tx_pool_alloc() - Allocate a block of memory in one or more
+ * fragments.
+ * @homa:        Shared information about the Homa transport.
+ * @length:       Total number of bytes to allocate.
+ * @num_frags:   Number of fragments of storage initially available at **frags;
+ *               modified to hold the total number of fragments
+ *               allocated.
+ * @frags:       Pointer to pointer to space in which to store fragments;
+ *               if this initial space is insufficient to hold all of the
+ *               fragments needed, will be overwritten with a dynamically
+ *               allocated block.
+ * Return:       0 for success, negative errno on error.
+ */
+int homa_tx_pool_alloc(struct homa *homa, int length, int *num_frags,
+		       skb_frag_t **frags)
+{
+	struct homa_tx_pool_core *tx_core;
+	skb_frag_t *cur_frags = *frags;
+	int max_frags = *num_frags;
+	int bytes_left = length;
+	int frags_allocated = 0;
+	skb_frag_t *frag;
+	int err;
+
+	/* Asssure atomicity with respect to SoftIRQ invocations or
+	 * task preemption (so we can access per-core info without races).
+	 */
+	local_bh_disable();
+	tx_core = &per_cpu(homa_tx_pool_core, smp_processor_id());
+
+	while (bytes_left  > 0) {
+		/* Expand the frag array if needed. */
+		if (frags_allocated == max_frags) {
+			skb_frag_t *new_frags;
+			int num_new;
+
+			num_new = ((bytes_left + HOMA_TX_PAGE_SIZE - 1) >>
+				   (PAGE_SHIFT + HOMA_TX_PAGE_ORDER)) +
+				  frags_allocated;
+			new_frags = kvmalloc_array(num_new, sizeof(*new_frags),
+						   GFP_ATOMIC);
+			if (!new_frags) {
+				err = -ENOMEM;
+				goto error;
+			}
+			memcpy(new_frags, cur_frags,
+			       frags_allocated * sizeof(*new_frags));
+			if (cur_frags != *frags)
+				kfree(cur_frags);
+			cur_frags = new_frags;
+			max_frags = num_new;
+		}
+
+		frag = &cur_frags[frags_allocated];
+		err = __homa_tx_pool_alloc_frag(tx_core, bytes_left, frag);
+		if (err != 0)
+			goto error;
+		frags_allocated++;
+		bytes_left -= skb_frag_size(frag);
+	}
+	local_bh_enable();
+	*frags  = cur_frags;
+	*num_frags = frags_allocated;
+	return 0;
+
+error:
+	homa_tx_pool_free(homa, frags_allocated, cur_frags);
+	if (cur_frags != *frags)
+		kfree(cur_frags);
+	*num_frags = 0;
+	local_bh_enable();
+	return err;
+}
+
+/**
+ * __homa_tx_pool_alloc_frag() - Allocate space for a single fragment.
+ * Caller must have disabled interrupts.
+ * @tx_core:   Core-specific information to use for the allocation.
+ * @length:    Desired length: actual length of fragment may be less
+ *             than this.
+ * @frag:      Store information about the allocated fragment here. Its
+ *             length may be less than @length. A reference will be taken
+ *             on its page.
+ * Return:     0 for success, otherwise a negative errno.
+ */
+int __homa_tx_pool_alloc_frag(struct homa_tx_pool_core *tx_core, int length,
+			      skb_frag_t *frag)
+{
+	struct page *page;
+	int page_size;
+
+	/* See if the allocation can be handled with the core's cached page. */
+	if (tx_core->page_size - tx_core->allocated >= length) {
+		get_page(tx_core->page);
+		frag_page_set(frag, tx_core->page);
+		frag->offset = tx_core->allocated;
+		skb_frag_size_set(frag, length);
+		tx_core->allocated += length;
+		if (tx_core->allocated == tx_core->page_size) {
+			put_page(tx_core->page);
+			tx_core->page = NULL;
+			tx_core->page_size = 0;
+			tx_core->allocated = 0;
+		}
+		return 0;
+	}
+
+	/* Must allocate a new page. */
+	page = homa_tx_pool_alloc_page(tx_core, &page_size);
+	if (!page)
+		return -ENOMEM;
+	frag_page_set(frag, page);
+	frag->offset = 0;
+	skb_frag_size_set(frag, min(page_size, length));
+
+	/* Retain the leftover part of the page as the core's cached page,
+	 * if it has more space available than the current cached page.
+	 */
+	if (!tx_core->page || (tx_core->page_size - tx_core->allocated) <
+			       (page_size - skb_frag_size(frag))) {
+		if (tx_core->page)
+			put_page(tx_core->page);
+		get_page(page);
+		tx_core->page = page;
+		tx_core->page_size = page_size;
+		tx_core->allocated = skb_frag_size(frag);
+	}
+	return 0;
+}
+
+/**
+ * homa_tx_pool_alloc_frag() - Allocate space for a single fragment.
+ * @homa:      Overall information about the Homa transport.
+ * @length:    Desired length: actual length of fragment may be less
+ *             than this.
+ * @frag:      Store information about the allocated fragment here. Its
+ *             length may be less than @length. A reference will be taken
+ *             on its page.
+ * Return:     0 for success, otherwise a negative errno.
+ */
+int homa_tx_pool_alloc_frag(struct homa *homa, int length, skb_frag_t *frag)
+{
+	struct homa_tx_pool_core *tx_core;
+	int result;
+
+	tx_core = &per_cpu(homa_tx_pool_core, smp_processor_id());
+	local_bh_disable();
+	result = __homa_tx_pool_alloc_frag(tx_core, length, frag);
+	local_bh_enable();
+	return result;
+}
+
+/**
+ * homa_tx_pool_alloc_page() - Allocate a new page for skb allocation for a
+ * given core. Any existing page is released.
+ * @tx_core:    Core-specific info; the page will be allocated in this core.
+ * @length:     The length of the allocated page (if any) will be stored here.
+ * Return:      The allocated page (with reference count 1) or NULL if
+ *              no page could be allocated.
+ */
+struct page *homa_tx_pool_alloc_page(struct homa_tx_pool_core *tx_core,
+				     int *length)
+{
+	struct homa_tx_pool *pool;
+	struct page *page;
+
+	/* Step 1: can we reuse the core's cached page? */
+	page = tx_core->page;
+	if (page && page_ref_count(page) == 1) {
+		*length = tx_core->page_size;
+		tx_core->page = NULL;
+		tx_core->page_size = 0;
+		tx_core->allocated = 0;
+		return page;
+	}
+
+	/* Step 2: can we retrieve a page from the pool for this NUMA node? */
+	pool = tx_core->pool;
+	if (pool->avail) {
+		spin_lock_bh(&pool->mutex);
+
+		/* Must recheck: could have changed before locked. */
+		if (pool->avail) {
+			pool->avail--;
+			if (pool->avail < pool->low_mark)
+				pool->low_mark = pool->avail;
+			page = pool->pages[pool->avail];
+			spin_unlock_bh(&pool->mutex);
+			*length = HOMA_TX_PAGE_SIZE;
+			return page;
+		}
+		spin_unlock_bh(&pool->mutex);
+	}
+
+	/* Step 3: can we allocate a big page? */
+	page = alloc_pages(GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN |
+			   __GFP_NORETRY, HOMA_TX_PAGE_ORDER);
+	if (likely(page)) {
+		*length = HOMA_TX_PAGE_SIZE;
+		return page;
+	}
+
+	/* Step 4: can we allocate a normal page? */
+	page = alloc_page(GFP_ATOMIC);
+	if (likely(page)) {
+		*length = PAGE_SIZE;
+		return page;
+	}
+	return NULL;
+}
+
+/**
+ * homa_tx_pool_free() - Release one or more fragments previously allocated
+ * by homa_tx_pool_alloc.
+ * @homa:        Shared information about the Homa transport.
+ * @num_frags:   Number of fragments at *frags.
+ * @frags:       Pointer to array of fragments to free; must not be used
+ *               after this function returns.
+ */
+void homa_tx_pool_free(struct homa *homa, int num_frags, skb_frag_t *frags)
+{
+	struct homa_tx_pool *pool;
+	int i;
+
+	if (num_frags <= 0)
+		return;
+
+	pool = homa->tx_pools[page_to_nid(skb_frag_page(&frags[0]))];
+	spin_lock_bh(&pool->mutex);
+	for (i = 0; i < num_frags; i++) {
+		struct page *page = skb_frag_page(&frags[i]);
+
+		if (compound_order(page) == HOMA_TX_PAGE_ORDER &&
+		    page_ref_count(page) == 1 &&
+		    pool->avail < HOMA_TX_POOL_LIMIT) {
+			pool->pages[pool->avail] = page;
+			pool->avail++;
+		} else {
+			put_page(page);
+		}
+	}
+	spin_unlock_bh(&pool->mutex);
+}
+
+/**
+ * homa_tx_pool_gc() - This function is invoked occasionally; its
+ * job is to gradually release pages from the page pools back to
+ * Linux, based on sysctl parameters such as tx_page_frees_per_sec.
+ * @homa:  Overall information about the Homa transport.
+ */
+void homa_tx_pool_gc(struct homa *homa)
+{
+	int i, max_low_mark, min_pages, release, release_max;
+	struct homa_tx_pool *max_pool;
+	u64 now = homa_clock();
+
+	if (now < homa->tx_page_free_time)
+		return;
+
+	/* Free pages every 0.5 second. */
+	homa->tx_page_free_time = now + (500 * homa_clock_khz());
+
+	/* Make sure we have space in which to collect pages to free. */
+	release_max = homa->tx_page_frees_per_sec / 2;
+	if (homa->tx_pages_to_free_slots < release_max) {
+		struct page **old = homa->tx_pages_to_free;
+
+		homa->tx_pages_to_free = kmalloc_array(release_max,
+						       sizeof(struct page *),
+						       GFP_ATOMIC);
+		if (homa->tx_pages_to_free) {
+			kfree(old);
+			homa->tx_pages_to_free_slots = release_max;
+		} else {
+			/* Couldn't allocate space; reuse existing space
+			 * and reduce how many pages we'll free.
+			 */
+			homa->tx_pages_to_free = old;
+			release_max = homa->tx_pages_to_free_slots;
+		}
+	}
+
+	/* Find the pool with the largest number of pages that haven't
+	 * been used recently.
+	 */
+	max_low_mark = -1;
+	for (i = 0; i <= homa->max_numa; i++) {
+		struct homa_tx_pool *pool = homa->tx_pools[i];
+
+		if (!pool)
+			continue;
+		spin_lock_bh(&pool->mutex);
+		if (pool->low_mark > max_low_mark) {
+			max_low_mark = pool->low_mark;
+			max_pool = pool;
+		}
+		pool->low_mark = pool->avail;
+		spin_unlock_bh(&pool->mutex);
+	}
+
+	/* Collect pages to free (but don't free them until after
+	 * releasing the lock, since freeing is expensive).
+	 */
+	spin_lock_bh(&max_pool->mutex);
+	min_pages = ((homa->tx_page_pool_min_kb * 1000)
+			+ (HOMA_TX_PAGE_SIZE - 1)) >> HOMA_TX_PAGE_SHIFT;
+
+	/* Note: may need to adjust max_low_mark to reflect changes made
+	 * while lock wasn't held.
+	 */
+	if (max_low_mark > max_pool->low_mark)
+		max_low_mark = max_pool->low_mark;
+	release = max_low_mark - min_pages;
+	if (release > release_max)
+		release = release_max;
+	for (i = 0; i < release; i++) {
+		max_pool->avail--;
+		homa->tx_pages_to_free[i] = max_pool->pages[max_pool->avail];
+	}
+	max_pool->low_mark = max_pool->avail;
+	spin_unlock_bh(&max_pool->mutex);
+
+	/* Free the pages that were collected. */
+	for (i = 0; i < release; i++) {
+		struct page *page = homa->tx_pages_to_free[i];
+
+		put_page(page);
+	}
+}
+
+/**
+ * homa_copy_to_frags() - Copy a block of data into an array of fragments.
+ * @filler:    Describes the current position in the array of fragments;
+ *             will be updated to reflect the copied data.
+ * @src:       Copy bytes from here into the fragments.
+ * @num_bytes: Number of bytes to copy.
+ * Return:     0 for success; -EINVAL if there isn't enough room in the
+ *             fragments for the new bytes.
+ */
+int homa_copy_to_frags(struct homa_frag_filler *filler, void *src,
+		       int num_bytes)
+{
+	int p_off, copied, p_len;
+	int bytes_this_frag;
+	struct page *p;
+	u8 *src_cur;
+
+	src_cur = src;
+	while (num_bytes > 0) {
+		if (filler->offset >= skb_frag_size(filler->frag)) {
+			filler->frag++;
+			filler->num_frags--;
+			if (filler->num_frags <= 0)
+				return -EINVAL;
+			filler->offset = 0;
+		}
+		bytes_this_frag = min(num_bytes,
+				      skb_frag_size(filler->frag) -
+				      filler->offset);
+		skb_frag_foreach_page(filler->frag,
+				      skb_frag_off(filler->frag) +
+				      filler->offset, bytes_this_frag, p,
+				      p_off, p_len, copied) {
+			u8 *vaddr = kmap_local_page(p);
+
+			memcpy(vaddr + p_off, src_cur, p_len);
+			kunmap_local(vaddr);
+			src_cur += p_len;
+		}
+		filler->offset += bytes_this_frag;
+		num_bytes -= bytes_this_frag;
+	}
+	return 0;
+}
+
+/**
+ * homa_copy_iter_to_frags() - Copy data from an iterator (presumably
+ * referring to user-space data) into an array of fragments.
+ * @filler:    Describes the current position in the array of fragments;
+ *             will be updated to reflect the copied data.
+ * @iter:      Copy bytes from here into the fragments.
+ * @num_bytes: Number of bytesto copy.
+ * Return:     0 for success; -EINVAL if there isn't enough room in the
+ *             fragments for the new bytes.
+ */
+int homa_copy_iter_to_frags(struct homa_frag_filler *filler,
+			    struct iov_iter *iter, int num_bytes)
+{
+	int p_off, copied, p_len;
+	int bytes_this_frag;
+	struct page *p;
+
+	while (num_bytes > 0) {
+		if (filler->offset >= skb_frag_size(filler->frag)) {
+			filler->frag++;
+			filler->num_frags--;
+			if (filler->num_frags <= 0)
+				return -EINVAL;
+			filler->offset = 0;
+		}
+		bytes_this_frag = min(num_bytes,
+				      skb_frag_size(filler->frag) -
+				      filler->offset);
+		skb_frag_foreach_page(filler->frag,
+				      skb_frag_off(filler->frag) +
+				      filler->offset, bytes_this_frag, p,
+				      p_off, p_len, copied) {
+			int result;
+			void *vaddr = kmap_local_page(p);
+
+			result = copy_from_iter(vaddr + p_off, p_len, iter);
+			kunmap_local(vaddr);
+			if (result != p_len)
+				return -EFAULT;
+		}
+		filler->offset += bytes_this_frag;
+		num_bytes -= bytes_this_frag;
+	}
+	return 0;
+}
diff --git a/net/homa/homa_tx_pool.h b/net/homa/homa_tx_pool.h
new file mode 100644
index 0000000000000..aca47f9a3184a
--- /dev/null
+++ b/net/homa/homa_tx_pool.h
@@ -0,0 +1,139 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This module manages a pool of memory pages used for outgoing sk_buffs. */
+
+#ifndef _HOMA_TX_POOL_H
+#define _HOMA_TX_POOL_H
+
+#include <linux/percpu-defs.h>
+
+/**
+ * define HOMA_TX_PAGE_ORDER - exponent (power of two) determining how
+ * many pages to allocate in a high-order page for skb pages (e.g.,
+ * 2 means allocate in units of 4 pages).
+ */
+#define HOMA_TX_PAGE_ORDER 4
+
+/**
+ * define HOMA_TX_PAGE_SIZE - number of bytes corresponding to HOMA_PAGE_ORDER.
+ */
+#define HOMA_TX_PAGE_SIZE (PAGE_SIZE << HOMA_TX_PAGE_ORDER)
+
+/**
+ * define HOMA_TX_PAGE_SHIFT: HOMA_PAGE_SIZE == 1 << HOMA_TX_PAGE_SHIFT
+ */
+#define HOMA_TX_PAGE_SHIFT (PAGE_SHIFT + HOMA_TX_PAGE_ORDER)
+
+/**
+ * struct homa_tx_pool - A cache of free pages available for use.
+ * Each page is of size HOMA_TX_PAGE_SIZE, and a given pool is dedicated for
+ * use by a single NUMA node.
+ */
+struct homa_tx_pool {
+	/** @mutex: Used to synchronize access to the fields in this struct. */
+	spinlock_t mutex;
+
+	/** @avail: Number of free pages currently in the pool. */
+	int avail;
+
+	/**
+	 * @low_mark: Low water mark: smallest value of avail since the
+	 * last time homa_tx_pool_gc reset it.
+	 */
+	int low_mark;
+
+#define HOMA_TX_POOL_LIMIT 1000
+
+	/**
+	 * @pages: Pointers to pages that are currently free; the ref count
+	 * is 1 in each of these pages.
+	 */
+	struct page *pages[HOMA_TX_POOL_LIMIT];
+};
+
+/**
+ * struct homa_tx_pool_core - Stores core-specific information related to
+ * tx memory allocation. All values are assumed to be zero initially.
+ */
+struct homa_tx_pool_core {
+	/**
+	 * @pool: NUMA-specific page pool from which to allocate skb pages
+	 * for this core.
+	 */
+	struct homa_tx_pool *pool;
+
+	/**
+	 * @page: a page of data that is "owned" by this core and used for
+	 * allocation on this core (or NULL). This pointer is included in
+	 * the page's reference count.
+	 */
+	struct page *page;
+
+	/**
+	 * @page_size: total number of bytes in @page (including any
+	 * already allocated).
+	 */
+	int page_size;
+
+	/**
+	 * @allocated: number of (initial) bytes in @page that have already
+	 * been allocated for use.
+	 */
+	int allocated;
+};
+DECLARE_PER_CPU(struct homa_tx_pool_core, homa_tx_pool_core);
+
+/**
+ * struct homa_frag_filler - Used to iterate over an array of skb_frag_t's
+ * to copy data into them.
+ */
+struct homa_frag_filler {
+	/** @frag: Fragment currently being filled (in an array of frags). */
+	skb_frag_t *frag;
+
+	/**
+	 * @offset: Offset within @frag where the next byte of data should be
+	 * stored.
+	 */
+	int offset;
+
+	/**
+	 * @num_frags: Number of fragments in the array including @frag:
+	 * if this reaches zero then we have run out of space.
+	 */
+	int num_frags;
+};
+
+/**
+ * homa_frag_filler_init() - Initialize a frag filler.
+ * @filler:     Struct to initialize.
+ * @num_frags:  Number of fragments available to fill.
+ * @frags:      First in array of @num_frags fragments.
+ */
+static inline void homa_frag_filler_init(struct homa_frag_filler *filler,
+					 int num_frags, skb_frag_t *frags)
+{
+	filler->frag = frags;
+	filler->offset = 0;
+	filler->num_frags = num_frags;
+}
+
+int          homa_copy_iter_to_frags(struct homa_frag_filler *filler,
+				     struct iov_iter *iter, int num_bytes);
+int          homa_copy_to_frags(struct homa_frag_filler *filler, void *src,
+				int num_bytes);
+int          homa_tx_pool_alloc(struct homa *homa, int length, int *num_frags,
+				skb_frag_t **frags);
+int          __homa_tx_pool_alloc_frag(struct homa_tx_pool_core *tx_core,
+				       int length, skb_frag_t *frag);
+int          homa_tx_pool_alloc_frag(struct homa *homa, int length,
+				     skb_frag_t *frag);
+struct page *homa_tx_pool_alloc_page(struct homa_tx_pool_core *tx_core,
+				     int *length);
+void         homa_tx_pool_cleanup(struct homa *homa);
+void         homa_tx_pool_free(struct homa *homa, int num_frags,
+			       skb_frag_t *frags);
+void         homa_tx_pool_gc(struct homa *homa);
+int          homa_tx_pool_init(struct homa *homa);
+
+#endif /* _HOMA_TX_POOL_H */
diff --git a/net/homa/homa_utils.c b/net/homa/homa_utils.c
new file mode 100644
index 0000000000000..94799976a8ab4
--- /dev/null
+++ b/net/homa/homa_utils.c
@@ -0,0 +1,119 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file contains miscellaneous utility functions for Homa, such
+ * as initializing and destroying homa structs.
+ */
+
+#include "homa_impl.h"
+#include "homa_peer.h"
+#include "homa_rpc.h"
+#include "homa_tx_pool.h"
+
+/**
+ * homa_init() - Constructor for homa objects.
+ * @homa:   Object to initialize.
+ *
+ * Return:  0 on success, or a negative errno if there was an error.
+ */
+int homa_init(struct homa *homa)
+{
+	int err;
+
+	memset(homa, 0, sizeof(*homa));
+
+	atomic64_set(&homa->next_outgoing_id, 2);
+	homa->link_mbps = 25000;
+	homa->peertab = homa_peer_alloc_peertab();
+	if (IS_ERR(homa->peertab)) {
+		err = PTR_ERR(homa->peertab);
+		homa->peertab = NULL;
+		goto error;
+	}
+	homa->socktab = kmalloc(sizeof(*homa->socktab), GFP_KERNEL);
+	if (!homa->socktab) {
+		err = -ENOMEM;
+		goto error;
+	}
+	homa_socktab_init(homa->socktab);
+	err = homa_tx_pool_init(homa);
+	if (err) {
+		pr_err("Couldn't initialize homa_tx_pool (errno %d)\n",
+		       -err);
+		goto error;
+	}
+
+	/* Wild guesses to initialize configuration values... */
+	homa->resend_ticks = 5;
+	homa->resend_interval = 5;
+	homa->timeout_ticks = 100;
+	homa->timeout_resends = 5;
+	homa->request_ack_ticks = 2;
+	homa->dead_frags_limit = 100;
+	homa->max_gso_size = 1000;
+	homa->wmem_max = 100000000;
+	homa->bpage_lease_usecs = 10000;
+	homa->bpage_lease_cycles = homa->bpage_lease_usecs  * 2500;
+	return 0;
+
+error:
+	homa_destroy(homa);
+	return err;
+}
+
+/**
+ * homa_destroy() -  Destructor for homa objects.
+ * @homa:      Object to destroy. It is safe if this object has already
+ *             been previously destroyed.
+ */
+void homa_destroy(struct homa *homa)
+{
+	/* The order of the following cleanups matters! */
+	if (homa->socktab) {
+		homa_socktab_destroy(homa->socktab, NULL);
+		kfree(homa->socktab);
+		homa->socktab = NULL;
+	}
+	if (homa->peertab) {
+		homa_peer_free_peertab(homa->peertab);
+		homa->peertab = NULL;
+	}
+	homa_tx_pool_cleanup(homa);
+}
+
+/**
+ * homa_net_init() - Initialize a new struct homa_net.
+ * @hnet:    Struct to initialize.
+ * @homa:    The main Homa data structure to use for the net.
+ * Return:  0 on success, otherwise a negative errno.
+ */
+int homa_net_init(struct homa_net *hnet, struct homa *homa)
+{
+	memset(hnet, 0, sizeof(*hnet));
+	hnet->homa = homa;
+	hnet->prev_default_port = HOMA_MIN_DEFAULT_PORT - 1;
+	return 0;
+}
+
+/**
+ * homa_net_destroy() - Release any resources associated with a homa_net.
+ * @hnet:    Object to destroy; must not be used again after this function
+ *           returns.
+ */
+void homa_net_destroy(struct homa_net *hnet)
+{
+	homa_socktab_destroy(hnet->homa->socktab, hnet);
+	homa_peer_free_net(hnet);
+}
+
+/**
+ * homa_spin() - Delay (without sleeping) for a given time interval.
+ * @ns:   How long to delay (in nanoseconds)
+ */
+void homa_spin(int ns)
+{
+	u64 end;
+
+	end = homa_clock() + homa_ns_to_cycles(ns);
+	while (homa_clock() < end)
+		cpu_relax();
+}
diff --git a/net/homa/homa_wire.h b/net/homa/homa_wire.h
new file mode 100644
index 0000000000000..5bc4a25ec9200
--- /dev/null
+++ b/net/homa/homa_wire.h
@@ -0,0 +1,346 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file defines the on-the-wire format of Homa packets. */
+
+#ifndef _HOMA_WIRE_H
+#define _HOMA_WIRE_H
+
+#include <linux/skbuff.h>
+#include <net/tcp.h>
+
+/* Defines the possible types of Homa packets.
+ *
+ * See the xxx_header structs below for more information about each type.
+ */
+enum homa_packet_type {
+	DATA               = 0x10,
+	RESEND             = 0x12,
+	RPC_UNKNOWN        = 0x13,
+	BUSY               = 0x14,
+	NEED_ACK           = 0x17,
+	ACK                = 0x18,
+	MAX_OP             = 0x18,
+	/* If you add a new type here, you must also do the following:
+	 * 1. Change MAX_OP so it is the highest valid opcode
+	 * 2. Add support for the new opcode in homa_print_packet,
+	 *    homa_print_packet_short, homa_symbol_for_type, and mock_skb_alloc.
+	 * 3. Add the header length to header_lengths in homa_plumbing.c.
+	 */
+};
+
+/**
+ * define HOMA_SKB_EXTRA - How many bytes of additional space to allow at the
+ * beginning of each sk_buff, before the Homa header. This includes room for
+ * either an IPV4 or IPV6 header, Ethernet header, VLAN header, etc. This is
+ * a bit of an overestimate, since it also includes space for a TCP header.
+ */
+#define HOMA_SKB_EXTRA MAX_TCP_HEADER
+
+/**
+ * define HOMA_ETH_FRAME_OVERHEAD - Additional overhead bytes for each
+ * Ethernet packet that are not included in the packet header (preamble,
+ * start frame delimiter, CRC, and inter-packet gap).
+ */
+#define HOMA_ETH_FRAME_OVERHEAD 24
+
+/**
+ * define HOMA_ETH_OVERHEAD - Number of bytes per Ethernet packet for Ethernet
+ * header, CRC, preamble, and inter-packet gap.
+ */
+#define HOMA_ETH_OVERHEAD (18 + HOMA_ETH_FRAME_OVERHEAD)
+
+/**
+ * define HOMA_MIN_PKT_LENGTH - Every Homa packet must be padded to at least
+ * this length to meet Ethernet frame size limitations. This number includes
+ * Homa headers and data, but not IP or Ethernet headers.
+ */
+#define HOMA_MIN_PKT_LENGTH 26
+
+/**
+ * define HOMA_MAX_HEADER - Number of bytes in the largest Homa header.
+ */
+#define HOMA_MAX_HEADER 90
+
+/**
+ * struct homa_common_hdr - Wire format for the first bytes in every Homa
+ * packet. This must (mostly) match the format of a TCP header to enable
+ * Homa packets to actually be transmitted as TCP packets (and thereby
+ * take advantage of TSO and other features).
+ */
+struct homa_common_hdr {
+	/**
+	 * @sport: Port on source machine from which packet was sent.
+	 * Must be in the same position as in a TCP header.
+	 */
+	__be16 sport;
+
+	/**
+	 * @dport: Port on destination that is to receive packet. Must be
+	 * in the same position as in a TCP header.
+	 */
+	__be16 dport;
+
+	/**
+	 * @sequence: corresponds to the sequence number field in TCP headers;
+	 * not used by Homa (may be auto-incremented by TSO).
+	 */
+	__be32 sequence;
+
+	/**
+	 * @ack: Corresponds to the high-order bits of the acknowledgment
+	 * field in TCP headers; not used by Homa.
+	 */
+	char ack[3];
+
+	/**
+	 * @type: Homa packet type (one of the values of the homa_packet_type
+	 * enum). Corresponds to the low-order byte of the ack in TCP.
+	 */
+	u8 type;
+
+	/**
+	 * @doff: High order 4 bits correspond to the Data Offset field of a
+	 * TCP header. In DATA packets they hold the number of 4-byte chunks
+	 * in a homa_data_hdr; used by TSO to determine where the replicated
+	 * header portion ends. For other packets the offset is always 5
+	 * (standard TCP header length); other values may cause some NICs
+	 * (such as Intel E810-C) to drop outgoing data packets when TCP
+	 * hijacking is enabled. The low-order bits are always 0.
+	 */
+	u8 doff;
+
+	/** @reserved1: Not used (corresponds to TCP flags). */
+	u8 reserved1;
+
+	/**
+	 * @window: Corresponds to the window field in TCP headers. Not used
+	 * by HOMA.
+	 */
+	__be16 window;
+
+	/**
+	 * @checksum: occupies the same bytes as the checksum in a TCP
+	 * header. Set by Homa only during TCP hijacking.
+	 */
+	__be16 checksum;
+
+	/** @reserved2: Not used (corresponds to TCP urgent field). */
+	__be16 reserved2;
+
+	/**
+	 * @sender_id: the identifier of this RPC as used on the sender (i.e.,
+	 * if the low-order bit is set, then the sender is the server for
+	 * this RPC).
+	 */
+	__be64 sender_id;
+} __packed;
+
+/**
+ * struct homa_ack - Identifies an RPC that can be safely deleted by its
+ * server. After sending the response for an RPC, the server must retain its
+ * state for the RPC until it knows that the client has successfully
+ * received the entire response. An ack indicates this. Clients will
+ * piggyback acks on future data packets, but if a client doesn't send
+ * any data to the server, the server will eventually request an ack
+ * explicitly with a NEED_ACK packet, in which case the client will
+ * return an explicit ACK.
+ */
+struct homa_ack {
+	/**
+	 * @client_id: The client's identifier for the RPC. 0 means this ack
+	 * is invalid.
+	 */
+	__be64 client_id;
+
+	/** @server_port: The server-side port for the RPC. */
+	__be16 server_port;
+} __packed;
+
+/* struct homa_data_hdr - Contains data for part or all of a Homa message.
+ * An incoming packet consists of a homa_data_hdr followed by message data.
+ * An outgoing packet can have this simple format as well, or it can be
+ * structured as a GSO packet with the following format:
+ *
+ *    |-----------------------|
+ *    |                       |
+ *    |     data_header       |
+ *    |                       |
+ *    |---------------------- |
+ *    |                       |
+ *    |                       |
+ *    |     segment data      |
+ *    |                       |
+ *    |                       |
+ *    |-----------------------|
+ *    |      seg_header       |
+ *    |-----------------------|
+ *    |                       |
+ *    |                       |
+ *    |     segment data      |
+ *    |                       |
+ *    |                       |
+ *    |-----------------------|
+ *    |      seg_header       |
+ *    |-----------------------|
+ *    |                       |
+ *    |                       |
+ *    |     segment data      |
+ *    |                       |
+ *    |                       |
+ *    |-----------------------|
+ *
+ * TSO may not adjust @homa_common_hdr.sequence in the segments, so Homa
+ * sprinkles correct offsets (in homa_seg_hdrs) throughout the segment data;
+ * TSO/GSO will include a different homa_seg_hdr in each generated packet.
+ */
+
+struct homa_seg_hdr {
+	/**
+	 * @offset: Offset within message of the first byte of data in
+	 * this segment.
+	 */
+	__be32 offset;
+} __packed;
+
+struct homa_data_hdr {
+	struct homa_common_hdr common;
+
+	/** @message_length: Total #bytes in the message. */
+	__be32 message_length;
+
+	__be32 reserved1;
+
+	/** @ack: If the @client_id field of this is nonzero, provides info
+	 * about an RPC that the recipient can now safely free. Note: in
+	 * TSO packets this will get duplicated in each of the segments;
+	 * in order to avoid repeated attempts to ack the same RPC,
+	 * homa_gro_receive will clear this field in all segments but the
+	 * first.
+	 */
+	struct homa_ack ack;
+
+	__be16 reserved2;
+
+	/**
+	 * @retransmit: 1 means this packet was sent in response to a RESEND
+	 * (it has already been sent previously).
+	 */
+	u8 retransmit;
+
+	char pad[3];
+
+	/** @seg: First of possibly many segments. */
+	struct homa_seg_hdr seg;
+} __packed;
+
+/**
+ * homa_data_len() - Returns the total number of bytes in a DATA packet
+ * after the homa_data_hdr. Note: if the packet is a GSO packet, the result
+ * may include metadata as well as packet data.
+ * @skb:   Incoming data packet
+ * Return: see above
+ */
+static inline u32 homa_data_len(struct sk_buff *skb)
+{
+	return skb->len - skb_transport_offset(skb) -
+			sizeof(struct homa_data_hdr);
+}
+
+/**
+ * struct homa_resend_hdr - Wire format for RESEND packets.
+ *
+ * A RESEND is sent by the receiver when it believes that message data may
+ * have been lost in transmission (or if it is concerned that the sender may
+ * have crashed). The receiver should resend the specified portion of the
+ * message, even if it already sent it previously.
+ */
+struct homa_resend_hdr {
+	/** @common: Fields common to all packet types. */
+	struct homa_common_hdr common;
+
+	/**
+	 * @offset: Offset within the message of the first byte of data that
+	 * should be retransmitted.
+	 */
+	__be32 offset;
+
+	/**
+	 * @length: Number of bytes of data to retransmit. -1 means no data
+	 * has been received for the message, so everything sent previously
+	 * should be retransmitted.
+	 */
+	__be32 length;
+
+} __packed;
+
+/**
+ * struct homa_rpc_unknown_hdr - Wire format for RPC_UNKNOWN packets.
+ *
+ * An RPC_UNKNOWN packet is sent by either server or client when it receives a
+ * packet for an RPC that is unknown to it. When a client receives an
+ * RPC_UNKNOWN packet it will typically restart the RPC from the beginning;
+ * when a server receives an RPC_UNKNOWN packet it will typically discard its
+ * state for the RPC.
+ */
+struct homa_rpc_unknown_hdr {
+	/** @common: Fields common to all packet types. */
+	struct homa_common_hdr common;
+} __packed;
+
+/**
+ * struct homa_busy_hdr - Wire format for BUSY packets.
+ *
+ * These packets tell the recipient that the sender is still alive (even if
+ * it isn't sending data expected by the recipient).
+ */
+struct homa_busy_hdr {
+	/** @common: Fields common to all packet types. */
+	struct homa_common_hdr common;
+} __packed;
+
+/**
+ * struct homa_need_ack_hdr - Wire format for NEED_ACK packets.
+ *
+ * These packets ask the recipient (a client) to return an ACK message if
+ * the packet's RPC is no longer active.
+ */
+struct homa_need_ack_hdr {
+	/** @common: Fields common to all packet types. */
+	struct homa_common_hdr common;
+} __packed;
+
+/**
+ * struct homa_ack_hdr - Wire format for ACK packets.
+ *
+ * These packets are sent from a client to a server to indicate that
+ * a set of RPCs is no longer active on the client, so the server can
+ * free any state it may have for them.
+ */
+struct homa_ack_hdr {
+	/** @common: Fields common to all packet types. */
+	struct homa_common_hdr common;
+
+	/** @num_acks: Number of (leading) elements in @acks that are valid. */
+	__be16 num_acks;
+
+#define HOMA_MAX_ACKS_PER_PKT 5
+	/** @acks: Info about RPCs that are no longer active. */
+	struct homa_ack acks[HOMA_MAX_ACKS_PER_PKT];
+} __packed;
+
+/**
+ * homa_local_id(): given an RPC identifier from an input packet (which
+ * is network-encoded), return the decoded id we should use for that
+ * RPC on this machine.
+ * @sender_id:  RPC id from an incoming packet, such as h->common.sender_id
+ * Return: see above
+ */
+static inline u64 homa_local_id(__be64 sender_id)
+{
+	/* If the client bit was set on the sender side, it needs to be
+	 * removed here, and conversely.
+	 */
+	return be64_to_cpu(sender_id) ^ 1;
+}
+
+#endif /* _HOMA_WIRE_H */

3/2 2026/09/15 00:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 114043
							output: 26
							thoughts: 827
						

Thoughts:
**Evaluating the Homa Kernel Patch: A Utilitarian Perspective**

Okay, let's break this down from a purely benefit-driven angle, without getting bogged down in specifics initially. The user wants an assessment of this kernel patch, focusing on its potential good or harm. My initial thought? This is a *massive* addition – a completely new network transport protocol, Homa, being integrated into the Linux kernel. It's a whole new socket family, with all the associated complexities: `setsockopt`, `getsockopt`, `ioctl`, the works. We're talking RPC state machines, concurrency primitives (spinlocks, waitqueues), memory management, and user-kernel data transfers. It's a lot of code, a lot of potential attack surface.

The first question that pops into my head is, "Is this worth investigating for fuzzing purposes?" The answer, without hesitation, is a resounding YES. Any new code path, especially one exposed to both privileged and unprivileged users through standard sockets, is prime real estate for fuzzing. The potential benefits are huge: discovering kernel bugs, memory corruptions, race conditions, use-after-frees, information leaks – all of these could have far-reaching security and stability implications. From a utilitarian standpoint, finding these flaws and mitigating them would be of immense value.

Now, let's dig into the details a bit. I need to understand the dependencies and how easily this code can be enabled. A quick look at `net/homa/Kconfig` tells me that `CONFIG_HOMA` depends on `CONFIG_IPV6`, which is manageable. It seems like enabling HOMA is as simple as enabling both `HOMA` and `IPV6`. I'll need to check if there are other, hidden dependencies, perhaps in the Makefiles or through `#ifdef CONFIG_` directives scattered throughout the `net/homa` directory. So I will search for additional configuration options in that directory using `grepper`.



4/2 2026/09/15 00:56 tool grepper
0m Args:
{
  "Expression": "CONFIG_",
  "PathPrefix": "net/homa"
}

Results:
{
  "Output": "net/homa/Makefile-4-\nnet/homa/Makefile:5:obj-$(CONFIG_HOMA) += homa.o\nnet/homa/Makefile-6-homa-y:=        homa_incoming.o \\\n"
}

5/2 2026/09/15 00:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 115377
							output: 295
							thoughts: 1468
						

Thoughts:
**Homa Configuration and Fuzzing Rationale**

Alright, let's break this down. First, `CONFIG_HOMA` depends on `IPV6`, which I've confirmed by checking the dependencies in `net/Kconfig`. I'll make sure `EnableConfigs` reflects that, likely including both `HOMA` and `IPV6`, or just `HOMA` with `IPV6` since the dependency is implied.

Now, the important part: identifying the right symbols for FocusSymbols. I need to pinpoint specific entry points and core logic, avoiding ubiquitous functions like general allocators. Based on the files `homa_plumbing.c`, `homa_incoming.c`, `homa_outgoing.c`, `homa_pool.c`, and `homa_rpc.c`, the following are key:

*   **Entrypoints and Socket API:** `homa_sendmsg`, `homa_recvmsg`, `homa_setsockopt`, `homa_getsockopt`, `homa_ioctl`, `homa_ioc_info`, `homa_bind`, `homa_socket`.
*   **Protocol Handling:** `homa_softirq`, `homa_dispatch_pkts`, `homa_rpc_reap`, `homa_rpc_alloc_client`, `homa_rpc_alloc_server`, `homa_pool_set_region`.

I've made sure to pick functions which are *not* static, so that they're visible to the fuzzer. I double-checked the list against the code, to ensure that the functions are, in fact, non-static.

Now, considering the fuzzing goals, this is straightforward. The patch introduces the Homa datacenter transport protocol, implementing the full socket API (socket creation, binding, sendmsg, recvmsg, setsockopt, getsockopt, ioctls) along with packet reception via softirq and buffer pool management. The key thing is that this code is *directly reachable* from userspace in standard virtual environments via the socket syscalls. That makes fuzzing absolutely essential. It's the only way to effectively test memory safety, the protocol state transitions, the concurrency/locking, and buffer management aspects. It's a clear case of WorthFuzzing = true.

With this rationale, I'm ready to `set-results`.



6/2 2026/09/15 00:56 tool set-results
0m Args:
{
  "EnableConfigs": [
    "HOMA",
    "IPV6"
  ],
  "FocusSymbols": [
    "homa_sendmsg",
    "homa_recvmsg",
    "homa_setsockopt",
    "homa_getsockopt",
    "homa_ioctl",
    "homa_ioc_info",
    "homa_bind",
    "homa_socket",
    "homa_softirq",
    "homa_dispatch_pkts",
    "homa_pool_set_region",
    "homa_rpc_reap",
    "homa_rpc_alloc_client",
    "homa_rpc_alloc_server",
    "homa_tx_copy_from_user"
  ],
  "Reasoning": "The patch series introduces the implementation of the Homa transport protocol (IPPROTO_HOMA) in the Linux kernel networking stack. It adds support for AF_INET and AF_INET6 Homa sockets, including sendmsg/recvmsg message passing, user buffer pools, setsockopt/getsockopt, HOMAIOCINFO ioctl, softirq packet dispatching, RPC state management, and custom memory pools. This new protocol is directly reachable from user space in standard virtualized environments and contains complex concurrency, locking, and packet processing logic that warrants thorough fuzzing.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "HOMA",
    "IPV6"
  ],
  "FocusSymbols": [
    "homa_sendmsg",
    "homa_recvmsg",
    "homa_setsockopt",
    "homa_getsockopt",
    "homa_ioctl",
    "homa_ioc_info",
    "homa_bind",
    "homa_socket",
    "homa_softirq",
    "homa_dispatch_pkts",
    "homa_pool_set_region",
    "homa_rpc_reap",
    "homa_rpc_alloc_client",
    "homa_rpc_alloc_server",
    "homa_tx_copy_from_user"
  ],
  "Reasoning": "The patch series introduces the implementation of the Homa transport protocol (IPPROTO_HOMA) in the Linux kernel networking stack. It adds support for AF_INET and AF_INET6 Homa sockets, including sendmsg/recvmsg message passing, user buffer pools, setsockopt/getsockopt, HOMAIOCINFO ioctl, softirq packet dispatching, RPC state management, and custom memory pools. This new protocol is directly reachable from user space in standard virtualized environments and contains complex concurrency, locking, and packet processing logic that warrants thorough fuzzing.",
  "WorthFuzzing": true
}

7/1 2026/09/15 00:56 action If
2m Args:
{
  "WorthFuzzing": true
}

Results:
null

8/2 2026/09/15 00:56 agent kmsan-evaluator
2m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch introduces the Homa transport protocol implementation, which includes a kernel-to-user memory information leak in `homa_recvmsg()`:\n\n1. In `homa_recvmsg()` (`net/homa/homa_plumbing.c`), when `msg-\u003emsg_name` is provided (which points to an uninitialized `struct sockaddr_storage addr` on the kernel stack in `____sys_recvmsg()` in `net/socket.c`):\n   - For `AF_INET` sockets, only `sin_family`, `sin_port`, and `sin_addr.s_addr` are populated in `struct sockaddr_in *in4`. The trailing 8-byte `sin_zero` padding array is left uninitialized, and `msg-\u003emsg_namelen` is set to `sizeof(*in4)` (16 bytes).\n   - For `AF_INET6` sockets, only `sin6_family`, `sin6_port`, and `sin6_addr` are set in `struct sockaddr_in6 *in6`. The `sin6_flowinfo` (4 bytes) and `sin6_scope_id` (4 bytes) fields are left uninitialized, and `msg-\u003emsg_namelen` is set to `sizeof(*in6)` (28 bytes).\n2. Upon return from `homa_recvmsg()`, `____sys_recvmsg()` invokes `move_addr_to_user(\u0026addr, msg_sys-\u003emsg_namelen, uaddr, uaddr_len)`, which copies the uninitialized kernel stack bytes from `addr` directly to userspace memory.\n\nKASAN, LOCKDEP, and UB sanitizers cannot detect this vulnerability because `addr` resides within the valid bounds of the caller's kernel stack frame and no out-of-bounds or use-after-free memory access occurs. KMSAN specifically tracks shadow initialization bits and detects kernel-to-user information leaks of uninitialized memory. Therefore, a dedicated KMSAN fuzzing session is justified.",
  "NeedsKMSAN": true
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 5dfb61235ce9a7847572ab2527dd1855871d9ab9
Author: syz-cluster <triage@syzkaller.com>
Date:   Tue Sep 15 00:56:16 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst
index 2fc53093752d1..c6cb82ff627e2 100644
--- a/Documentation/userspace-api/ioctl/ioctl-number.rst
+++ b/Documentation/userspace-api/ioctl/ioctl-number.rst
@@ -255,6 +255,7 @@ Code  Seq#    Include File                                             Comments
                                                                        <mailto:zapman@interlan.net>
 'h'   00-1F  linux/hpet.h                                              conflict!
 'h'   80-8F  fs/hfsplus/ioctl.c
+'h'   90-9F  uapi/linux/homa.h
 'i'   00-3F  linux/i2o-dev.h                                           conflict!
 'i'   0B-1F  linux/ipmi.h                                              conflict!
 'i'   80-8F  linux/i8k.h
diff --git a/MAINTAINERS b/MAINTAINERS
index 0e04d92d1b098..56e7651d01716 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -11938,6 +11938,13 @@ F:	lib/test_hmm*
 F:	mm/hmm*
 F:	tools/testing/selftests/mm/*hmm*
 
+HOMA TRANSPORT PROTOCOL
+M:	John Ousterhout <ouster@cs.stanford.edu>
+S:	Maintained
+W:	https://homa-transport.atlassian.net/wiki/spaces/HOMA
+F:	include/uapi/linux/homa.h
+F:	net/homa/
+
 HONEYWELL ABP2030PA PRESSURE SENSOR SERIES IIO DRIVER
 M:	Petre Rodan <petre.rodan@subdimension.ro>
 L:	linux-iio@vger.kernel.org
diff --git a/include/uapi/linux/homa.h b/include/uapi/linux/homa.h
new file mode 100644
index 0000000000000..deeca70f944a1
--- /dev/null
+++ b/include/uapi/linux/homa.h
@@ -0,0 +1,290 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ WITH Linux-syscall-note */
+
+/* This file defines the kernel call interface for the Homa
+ * transport protocol.
+ */
+
+#ifndef _UAPI_LINUX_HOMA_H
+#define _UAPI_LINUX_HOMA_H
+
+#include <linux/in.h>
+#include <linux/in6.h>
+#include <linux/socket.h>
+#include <linux/types.h>
+
+/* IANA-assigned Internet Protocol number for Homa. */
+#define IPPROTO_HOMA 146
+
+/**
+ * define HOMA_MAX_MESSAGE_LENGTH - Maximum bytes of payload in a Homa
+ * request or response message.
+ */
+#define HOMA_MAX_MESSAGE_LENGTH 1000000
+
+/**
+ * define HOMA_BPAGE_SIZE - Number of bytes in pages used for receive
+ * buffers. Must be power of two.
+ */
+#define HOMA_BPAGE_SIZE (1 << HOMA_BPAGE_SHIFT)
+#define HOMA_BPAGE_SHIFT 16
+
+/**
+ * define HOMA_MAX_BPAGES - The largest number of bpages that will be required
+ * to store an incoming message.
+ */
+#define HOMA_MAX_BPAGES ((HOMA_MAX_MESSAGE_LENGTH + HOMA_BPAGE_SIZE - 1) >> \
+		HOMA_BPAGE_SHIFT)
+
+/**
+ * define HOMA_MIN_DEFAULT_PORT - The 16 bit port space is divided into
+ * two nonoverlapping regions. Ports 1-32767 are reserved exclusively
+ * for well-defined server ports. The remaining ports are used for client
+ * ports; these are allocated automatically by Homa. Port 0 is reserved.
+ */
+#define HOMA_MIN_DEFAULT_PORT 0x8000
+
+/**
+ * struct homa_sendmsg_args - Provides information needed by Homa's
+ * sendmsg; passed to sendmsg using the msg_control field.
+ */
+struct homa_sendmsg_args {
+	/**
+	 * @id: (in/out) An initial value of 0 means a new request is
+	 * being sent; nonzero means the message is a reply to the given
+	 * id. If the message is a request, then the value is modified to
+	 * hold the id of the new RPC.
+	 */
+	__u64 id;
+
+	/**
+	 * @completion_cookie: (in) Used only for request messages; will be
+	 * returned by recvmsg when the RPC completes. Typically used to
+	 * locate app-specific info about the RPC.
+	 */
+	__u64 completion_cookie;
+
+	/**
+	 * @flags: (in) OR-ed combination of bits that control the operation.
+	 * See below for values.
+	 */
+	__u32 flags;
+
+	/** @reserved: Not currently used, must be 0. */
+	__u32 reserved;
+};
+
+/* Flag bits for homa_sendmsg_args.flags (see man page for documentation):
+ */
+#define HOMA_SENDMSG_PRIVATE       0x01
+#define HOMA_SENDMSG_VALID_FLAGS   0x01
+
+/**
+ * struct homa_recvmsg_args - Provides information needed by Homa's
+ * recvmsg; passed to recvmsg using the msg_control field.
+ */
+struct homa_recvmsg_args {
+	/**
+	 * @id: (in/out) Initial value is 0 to wait for any shared RPC;
+	 * nonzero means wait for that specific (private) RPC. Returns
+	 * the id of the RPC received.
+	 */
+	__u64 id;
+
+	/**
+	 * @completion_cookie: (out) If the incoming message is a response,
+	 * this will return the completion cookie specified when the
+	 * request was sent. For requests this will always be zero.
+	 */
+	__u64 completion_cookie;
+
+	/**
+	 * @num_bpages: (in/out) Number of valid entries in @bpage_offsets.
+	 * Passes in bpages from previous messages that can now be
+	 * recycled; returns bpages from the new message.
+	 */
+	__u32 num_bpages;
+
+	/** @reserved: Not currently used, must be 0. */
+	__u32 reserved;
+
+	/**
+	 * @bpage_offsets: (in/out) Each entry is an offset into the buffer
+	 * region for the socket pool. When returned from recvmsg, the
+	 * offsets indicate where fragments of the new message are stored. All
+	 * entries but the last refer to full buffer pages (HOMA_BPAGE_SIZE
+	 * bytes) and are bpage-aligned. The last entry may refer to a bpage
+	 * fragment and is not necessarily aligned. The application now owns
+	 * these bpages and must eventually return them to Homa, using
+	 * bpage_offsets in a future recvmsg invocation.
+	 */
+	__u32 bpage_offsets[HOMA_MAX_BPAGES];
+};
+
+/** define SO_HOMA_RCVBUF: setsockopt option for specifying buffer region. */
+#define SO_HOMA_RCVBUF 10
+
+/**
+ * define SO_HOMA_SERVER: setsockopt option for specifying whether a
+ * socket will act as server.
+ */
+#define SO_HOMA_SERVER 11
+
+/** struct homa_rcvbuf_args - setsockopt argument for SO_HOMA_RCVBUF. */
+struct homa_rcvbuf_args {
+	/** @start: Address of first byte of buffer region in user space. */
+	__u64 start;
+
+	/** @length: Total number of bytes available at @start. */
+	__u64 length;
+};
+
+/**
+ * struct homa_rpc_info - Used by HOMAIOCINFO to return information about
+ * a specific RPC.
+ */
+struct homa_rpc_info {
+	/**
+	 * @id: Identifier for the RPC, unique among all RPCs sent by the
+	 * client node. If the low-order bit is 1, this node is the server
+	 * for the RPC; 0 means we are the client.
+	 */
+	__u64 id;
+
+	/** @peer: Address of the peer socket for this RPC. */
+	union {
+		struct __kernel_sockaddr_storage storage;
+		struct sockaddr_in in4;
+		struct sockaddr_in6 in6;
+	} peer;
+
+	/**
+	 * @completion_cookie: For client-side RPCs this gives the completion
+	 * cookie specified when the RPC was initiated. For server-side RPCs
+	 * this is zero.
+	 */
+	__u64 completion_cookie;
+
+	/**
+	 * @tx_length: Length of the outgoing message in bytes, or -1 if
+	 * the sendmsg hasn't yet been called.
+	 */
+	__s32 tx_length;
+
+	/**
+	 * @tx_sent: Number of bytes of the outgoing message that have been
+	 * transmitted at least once.
+	 */
+	__u32 tx_sent;
+
+	/**
+	 * @tx_granted: Number of bytes of the outgoing message that the
+	 * receiver has authorized us to transmit (includes unscheduled
+	 * bytes).
+	 */
+	__u32 tx_granted;
+
+	/** @reserved: Reserved for future use. */
+	__u32 reserved;
+
+	/**
+	 * @rx_length: Length of the incoming message, in bytes. -1 means
+	 * the length is not yet known (this is a client-side RPC and
+	 * no packets have been received).
+	 */
+	__s32 rx_length;
+
+	/**
+	 * @rx_remaining: Number of bytes in the incoming message that have
+	 * not yet been received.
+	 */
+	__u32 rx_remaining;
+
+	/**
+	 * @rx_gaps: The number of gaps in the incoming message. A gap is
+	 * a range of bytes that have not been received yet, but bytes after
+	 * the gap have been received.
+	 */
+	__u32 rx_gaps;
+
+	/**
+	 * @rx_gap_bytes: The total number of bytes in gaps in the incoming
+	 * message.
+	 */
+	__u32 rx_gap_bytes;
+
+	/**
+	 * @rx_granted: The number of bytes in the message that the sender
+	 * is authorized to transmit (includes unscheduled bytes).
+	 */
+	__u32 rx_granted;
+
+	/**
+	 * @flags: Various single-bit values associated with the RPC:
+	 * HOMA_RPC_BUF_STALL:  The incoming message is currently stalled
+	 *                      because there is insufficient receiver buffer
+	 *                      space.
+	 * HOMA_RPC_PRIVATE:    The RPC has been created as "private"; set
+	 *                      only on the client side.
+	 * HOMA_RPC_RX_READY:   The incoming message is complete and has
+	 *                      been queued waiting for a thread to call
+	 *                      recvmsg.
+	 * HOMA_RPC_RX_COPY:    There are packets that have been received,
+	 *                      whose data has not yet been copied from
+	 *                      packet buffers to user space.
+	 */
+	__u16 flags;
+#define HOMA_RPC_BUF_STALL    1
+#define HOMA_RPC_PRIVATE      2
+#define HOMA_RPC_RX_READY     4
+#define HOMA_RPC_RX_COPY      8
+};
+
+/**
+ * struct homa_info - In/out argument passed to HOMAIOCINFO. Fields labeled
+ * as "in" must be set by the application; other fields are returned to the
+ * application from the kernel.
+ */
+struct homa_info {
+	/**
+	 * @rpc_info: (in) Address of memory region in which to store
+	 * information about individual RPCs. Actual type is
+	 * "struct homa_rpc_info *".
+	 */
+	__u64 rpc_info;
+
+	/**
+	 * @rpc_info_length: (in) Number of bytes of storage available at
+	 * rpc_info.
+	 */
+	__u64 rpc_info_length;
+
+	/**
+	 * @bpool_avail_bytes: Number of bytes in the buffer pool for incoming
+	 * messages that is currently available for new messages.
+	 */
+	__u64 bpool_avail_bytes;
+
+	/** @port: Port number handled by this socket. */
+	__u32 port;
+
+	/**
+	 * @num_rpcs: Total number of active RPCs (both server and client) for
+	 * this socket. The number stored at @rpc_info will be less than this
+	 * if @rpc_info_length is too small.
+	 */
+	__u32 num_rpcs;
+
+	/**
+	 * @error_msg: Provides additional information about the last error
+	 * returned by a Homa-related kernel call such as sendmsg, recvmsg,
+	 * or ioctl. Not updated for some obvious return values such as EINTR
+	 * or EWOULDBLOCK.
+	 */
+#define HOMA_ERROR_MSG_SIZE 104
+	char error_msg[HOMA_ERROR_MSG_SIZE];
+};
+
+/* I/O control calls on Homa sockets.*/
+#define HOMAIOCINFO  _IOWR('h', 0x90, struct homa_info)
+
+#endif /* _UAPI_LINUX_HOMA_H */
diff --git a/net/Kconfig b/net/Kconfig
index e384773935515..6780fee341a08 100644
--- a/net/Kconfig
+++ b/net/Kconfig
@@ -252,6 +252,7 @@ source "net/bridge/netfilter/Kconfig"
 endif # if NETFILTER
 
 source "net/sctp/Kconfig"
+source "net/homa/Kconfig"
 source "net/rds/Kconfig"
 source "net/tipc/Kconfig"
 source "net/atm/Kconfig"
diff --git a/net/Makefile b/net/Makefile
index 5b2dd7f07a85e..f9a3c966a83b2 100644
--- a/net/Makefile
+++ b/net/Makefile
@@ -40,6 +40,7 @@ ifneq ($(CONFIG_VLAN_8021Q),)
 obj-y				+= 8021q/
 endif
 obj-$(CONFIG_IP_SCTP)		+= sctp/
+obj-$(CONFIG_HOMA)		+= homa/
 obj-$(CONFIG_RDS)		+= rds/
 obj-$(CONFIG_WIRELESS)		+= wireless/
 obj-$(CONFIG_MAC80211)		+= mac80211/
diff --git a/net/homa/Kconfig b/net/homa/Kconfig
new file mode 100644
index 0000000000000..a420ea18b6c19
--- /dev/null
+++ b/net/homa/Kconfig
@@ -0,0 +1,20 @@
+# SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+#
+# Homa transport protocol
+#
+
+config HOMA
+	tristate "The Homa transport protocol"
+	depends on IPV6
+
+	help
+	  Homa is a network transport protocol for communication within
+	  a datacenter. It provides significantly lower latency than TCP,
+	  particularly for workloads containing a mixture of large and small
+	  messages operating at high network utilization. At present, Homa
+	  has been only partially upstreamed; this version provides bare-bones
+	  functionality but is not performant. For more information see the
+	  homa(7) man page or checkout the Homa Wiki at
+	  https://homa-transport.atlassian.net/wiki/spaces/HOMA/overview.
+
+	  If unsure, say N.
diff --git a/net/homa/Makefile b/net/homa/Makefile
new file mode 100644
index 0000000000000..b36e7fca19b59
--- /dev/null
+++ b/net/homa/Makefile
@@ -0,0 +1,16 @@
+# SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+#
+# Makefile for the Linux implementation of the Homa transport protocol.
+
+obj-$(CONFIG_HOMA) += homa.o
+homa-y:=        homa_incoming.o \
+		homa_interest.o \
+		homa_outgoing.o \
+		homa_peer.o \
+		homa_plumbing.o \
+		homa_pool.o \
+		homa_rpc.o \
+		homa_sock.o \
+		homa_timer.o \
+		homa_tx_pool.o \
+		homa_utils.o
diff --git a/net/homa/homa_impl.h b/net/homa/homa_impl.h
new file mode 100644
index 0000000000000..6172902e5d8c5
--- /dev/null
+++ b/net/homa/homa_impl.h
@@ -0,0 +1,593 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file contains definitions that are shared across the files
+ * that implement Homa for Linux.
+ */
+
+#ifndef _HOMA_IMPL_H
+#define _HOMA_IMPL_H
+
+#include <linux/bug.h>
+
+#include <linux/audit.h>
+#include <linux/icmp.h>
+#include <linux/init.h>
+#include <linux/list.h>
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/kthread.h>
+#include <linux/completion.h>
+#include <linux/proc_fs.h>
+#include <linux/sched/signal.h>
+#include <linux/skbuff.h>
+#include <linux/socket.h>
+#include <linux/vmalloc.h>
+#include <net/icmp.h>
+#include <net/ip.h>
+#include <net/netns/generic.h>
+#include <net/protocol.h>
+#include <net/inet_common.h>
+#include <net/gro.h>
+#include <net/rps.h>
+
+#include <linux/homa.h>
+#include "homa_wire.h"
+
+/* Forward declarations. */
+struct homa;
+struct homa_peer;
+struct homa_rpc;
+struct homa_route;
+struct homa_sock;
+
+/**
+ * union sockaddr_in_union - Holds either an IPv4 or IPv6 address (smaller
+ * and easier to use than sockaddr_storage).
+ */
+union sockaddr_in_union {
+	/** @sa: Used to access as a generic sockaddr. */
+	struct sockaddr sa;
+
+	/** @in4: Used to access as IPv4 socket. */
+	struct sockaddr_in in4;
+
+	/** @in6: Used to access as IPv6 socket.  */
+	struct sockaddr_in6 in6;
+};
+
+/**
+ * struct homa - Stores overall information about the Homa transport, which
+ * is shared across all Homa sockets and all network namespaces.
+ */
+struct homa {
+	/**
+	 * @next_outgoing_id: Id to use for next outgoing RPC request.
+	 * This is always even: it's used only to generate client-side ids.
+	 * Accessed without locks. Note: RPC ids are unique within a
+	 * single client machine.
+	 */
+	atomic64_t next_outgoing_id;
+
+	/**
+	 * @peertab: Info about all the other hosts we have communicated with;
+	 * includes peers from all network namespaces.
+	 */
+	struct homa_peertab *peertab;
+
+	/**
+	 * @socktab: Information about all open sockets. Dynamically
+	 * allocated; must be kfreed.
+	 */
+	struct homa_socktab *socktab;
+
+	/**
+	 * @tx_pools: One tx_page_pool for each NUMA node on the machine.
+	 * If there are no cores for a node, then its value is NULL.
+	 */
+	struct homa_tx_pool *tx_pools[MAX_NUMNODES];
+
+	/** @max_numa: Highest NUMA node id in use by any core. */
+	int max_numa;
+
+	/**
+	 * @tx_page_frees_per_sec: Rate at which to return pages from
+	 * homa_tx_page_pools back to Linux. This is the total rate across
+	 * all pools. Set externally via sysctl.
+	 */
+	int tx_page_frees_per_sec;
+
+	/**
+	 * @tx_pages_to_free: Space in which to collect pages that are
+	 * about to be released. Dynamically allocated.
+	 */
+	struct page **tx_pages_to_free;
+
+	/**
+	 * @tx_pages_to_free_slots: Maximum number of pages that can be
+	 * stored in tx_pages_to_free;
+	 */
+	int tx_pages_to_free_slots;
+
+	/**
+	 * @tx_page_free_time: homa_clock() time when the next tx
+	 * page should be freed. Could be in the past.
+	 */
+	u64 tx_page_free_time;
+
+	/**
+	 * @tx_page_pool_min_kb: A floor on the amount of space for Homa to
+	 * retain in a pool, specified in Kbytes. Set externally via
+	 * sysctl.
+	 */
+	int tx_page_pool_min_kb;
+
+	/**
+	 * @link_mbps: The raw bandwidth of the network uplink, in
+	 * units of 1e06 bits per second.  Set externally via sysctl.
+	 */
+	int link_mbps;
+
+	/**
+	 * @resend_ticks: When an RPC's @silent_ticks reaches this value,
+	 * start sending RESEND requests.
+	 */
+	int resend_ticks;
+
+	/**
+	 * @resend_interval: minimum number of homa timer ticks between
+	 * RESENDs for the same RPC.
+	 */
+	int resend_interval;
+
+	/**
+	 * @timeout_ticks: abort an RPC if its silent_ticks reaches this value.
+	 */
+	int timeout_ticks;
+
+	/**
+	 * @timeout_resends: Assume that a server is dead if it has not
+	 * responded after this many RESENDs have been sent to it.
+	 */
+	int timeout_resends;
+
+	/**
+	 * @request_ack_ticks: How many timer ticks we'll wait for the
+	 * client to ack an RPC before explicitly requesting an ack.
+	 * Set externally via sysctl.
+	 */
+	int request_ack_ticks;
+
+	/**
+	 * @dead_frags_limit: If hsk->dead_frags is less than this number
+	 * for a socket, then Homa reaps RPCs in a way that minimizes impact
+	 * on performance but may permit dead RPCs to accumulate. If
+	 * dead_frags exceeds this value, then Homa switches to a more
+	 * aggressive approach to reaping RPCs. Set externally via sysctl.
+	 */
+	int dead_frags_limit;
+
+	/**
+	 * @max_dead_frags: The largest value of hsk->dead_frags that has
+	 * existed so far for any socket.  Readable via sysctl, and may be
+	 * reset via sysctl to begin recalculating.
+	 */
+	int max_dead_frags;
+
+	/**
+	 * @max_gso_size: Maximum number of bytes that will be included
+	 * in a single output packet that Homa passes to Linux. Can be set
+	 * externally via sysctl to lower the limit already enforced by Linux.
+	 */
+	int max_gso_size;
+
+	/**
+	 * @wmem_max: Limit on the value of sk_sndbuf for any socket. Set
+	 * externally via sysctl.
+	 */
+	int wmem_max;
+
+	/**
+	 * @timer_ticks: number of times that homa_timer has been invoked
+	 * (may wraparound, which is safe).
+	 */
+	u32 timer_ticks;
+
+	/**
+	 * @bpage_lease_usecs: how long a core can own a bpage (microseconds)
+	 * before its ownership can be revoked to reclaim the page.
+	 */
+	int bpage_lease_usecs;
+
+	/**
+	 * @bpage_lease_cycles: same as bpage_lease_usecs except in
+	 * homa_clock() units.
+	 */
+	int bpage_lease_cycles;
+
+	/**
+	 * @next_id: Set via sysctl; causes next_outgoing_id to be set to
+	 * this value; always reads as zero. Typically used while debugging to
+	 * ensure that different nodes use different ranges of ids.
+	 */
+	int next_id;
+
+	/**
+	 * @destroyed: True means that this structure is being destroyed
+	 * so everyone should clean up.
+	 */
+	bool destroyed;
+
+};
+
+/**
+ * struct homa_net - Contains Homa information that is specific to a
+ * particular network namespace.
+ */
+struct homa_net {
+	/** @homa: Global Homa information. */
+	struct homa *homa;
+
+	/**
+	 * @prev_default_port: The most recent port number assigned from
+	 * the range of default ports.
+	 */
+	u16 prev_default_port;
+
+	/**
+	 * @num_routes: The total number of struct homa_peers that exist
+	 * for this namespace. Managed by homa_peer.c under the peertab lock.
+	 */
+	int num_routes;
+};
+
+/**
+ * struct homa_skb_info - Additional information needed by Homa for each
+ * outbound DATA packet. Space is allocated for this at the very end of the
+ * linear part of the skb.
+ */
+struct homa_skb_info {
+	/**
+	 * @data_bytes: total bytes of message data across all of the
+	 * segments in this packet.
+	 */
+	int data_bytes;
+
+	/**
+	 * @dont_defer: True means that homa_qdisc_enqueue should pass this
+	 * packet along without considering NIC congestion. This flag is set
+	 * by the pacer when it retransmits packets after deferral.
+	 */
+	bool dont_defer;
+};
+
+/**
+ * homa_get_skb_info() - Return the address of Homa's private information
+ * for an sk_buff.
+ * @skb:     Socket buffer whose info is needed.
+ * Return: address of Homa's private information for @skb.
+ */
+static inline struct homa_skb_info *homa_get_skb_info(struct sk_buff *skb)
+{
+	return (struct homa_skb_info *)(skb_end_pointer(skb)) - 1;
+}
+
+/**
+ * homa_set_doff() - Fills in the doff TCP header field for a packet.
+ * @skb:   Packet whose doff field is to be set.
+ * @size:  Size of the "header" in bytes (must be a multiple of 4). This is
+ *         needed for two reasons. First, for TSO to work it must indicate
+ *         the number of bytes that should be replicated in each segment.
+ *         The bytes after this will be distributed among segments. Second,
+ *         for TCP hijacking to work it must have a valid value (20 is a
+ *         good choice if the packet isn't a TSO frame).
+ */
+static inline void homa_set_doff(struct sk_buff *skb, int size)
+{
+	tcp_hdr(skb)->doff = size >> 2;
+}
+
+/** skb_is_ipv6() - Return true if the packet is encapsulated with IPv6,
+ *  false otherwise (presumably it's IPv4).
+ */
+static inline bool skb_is_ipv6(const struct sk_buff *skb)
+{
+	return ipv6_hdr(skb)->version == 6;
+}
+
+/**
+ * ipv6_to_ipv4() - Given an IPv6 address produced by ipv4_to_ipv6, return
+ * the original IPv4 address (in network byte order).
+ * @ip6:  IPv6 address; assumed to be a mapped IPv4 address.
+ * Return: IPv4 address stored in @ip6.
+ */
+static inline __be32 ipv6_to_ipv4(const struct in6_addr ip6)
+{
+	return ip6.in6_u.u6_addr32[3];
+}
+
+/**
+ * canonical_ipv6_addr() - Convert a socket address to the "standard"
+ * form used in Homa, which is always an IPv6 address; if the original address
+ * was IPv4, convert it to an IPv4-mapped IPv6 address.
+ * @addr:   Address to canonicalize (if NULL, "any" is returned).
+ * Return: IPv6 address corresponding to @addr.
+ */
+static inline struct in6_addr canonical_ipv6_addr(const union sockaddr_in_union
+						  *addr)
+{
+	struct in6_addr mapped;
+
+	if (addr) {
+		if (addr->sa.sa_family == AF_INET6)
+			return addr->in6.sin6_addr;
+		ipv6_addr_set_v4mapped(addr->in4.sin_addr.s_addr, &mapped);
+		return mapped;
+	}
+	return in6addr_any;
+}
+
+/**
+ * skb_canonical_ipv6_saddr() - Given a packet buffer, return its source
+ * address in the "standard" form used in Homa, which is always an IPv6
+ * address; if the original address was IPv4, convert it to an IPv4-mapped
+ * IPv6 address.
+ * @skb:   The source address will be extracted from this packet buffer.
+ * Return: IPv6 address for @skb's source machine.
+ */
+static inline struct in6_addr skb_canonical_ipv6_saddr(struct sk_buff *skb)
+{
+	struct in6_addr mapped;
+
+	if (skb_is_ipv6(skb))
+		return ipv6_hdr(skb)->saddr;
+	ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr, &mapped);
+	return mapped;
+}
+
+/**
+ * homa_make_header_avl() - Invokes pskb_may_pull to make sure that all the
+ * Homa header information for a packet is in the linear part of the skb
+ * where it can be addressed using skb_transport_header.
+ * @skb:     Packet for which header is needed.
+ * Return:   The result of pskb_may_pull (true for success)
+ */
+static inline bool homa_make_header_avl(struct sk_buff *skb)
+{
+	int pull_length;
+
+	pull_length = skb_transport_header(skb) - skb->data + HOMA_MAX_HEADER;
+	if (pull_length > skb->len)
+		pull_length = skb->len;
+	return pskb_may_pull(skb, pull_length);
+}
+
+extern unsigned int homa_net_id;
+
+void     homa_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,
+		      struct homa_rpc *rpc);
+enum skb_drop_reason homa_add_packet(struct homa_rpc *rpc, struct sk_buff *skb);
+int      homa_bind(struct socket *sk, struct sockaddr_unsized *addr,
+		   int addr_len);
+void     homa_close(struct sock *sock, long timeout);
+int      homa_copy_to_user(struct homa_rpc *rpc);
+void     homa_data_pkt(struct sk_buff *skb, struct homa_rpc *rpc);
+void     homa_destroy(struct homa *homa);
+void     homa_dispatch_pkts(struct sk_buff *skb);
+int      homa_err_handler_v4(struct sk_buff *skb, u32 info);
+int      homa_err_handler_v6(struct sk_buff *skb,
+			     struct inet6_skb_parm *opt, u8 type,  u8 code,
+			     int offset, __be32 info);
+struct homa_gap *homa_gap_alloc(struct list_head *next, int start, int end);
+int      homa_getsockopt(struct sock *sk, int level, int optname,
+			 char __user *optval, int __user *optlen);
+int      homa_hash(struct sock *sk);
+enum hrtimer_restart homa_hrtimer(struct hrtimer *timer);
+int      homa_init(struct homa *homa);
+int      homa_ioc_info(struct socket *sock, unsigned long arg);
+int      homa_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg);
+int      homa_load(void);
+void     homa_message_out_init(struct homa_rpc *rpc, int length);
+void     homa_need_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,
+			   struct homa_rpc *rpc);
+void     homa_net_destroy(struct homa_net *hnet);
+void     homa_net_exit(struct net *net);
+int      homa_net_init(struct homa_net *hnet, struct homa *homa);
+int      homa_net_start(struct net *net);
+__poll_t homa_poll(struct file *file, struct socket *sock,
+		   struct poll_table_struct *wait);
+int      homa_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
+		      int flags);
+void     homa_request_retrans(struct homa_rpc *rpc);
+int      homa_resend_data(struct homa_rpc *rpc, int start, int end);
+void     homa_resend_pkt(struct sk_buff *skb, struct homa_rpc *rpc,
+			 struct homa_sock *hsk);
+void     homa_rpc_handoff(struct homa_rpc *rpc);
+int      homa_rpc_tx_end(struct homa_rpc *rpc);
+int      homa_sendmsg(struct sock *sk, struct msghdr *msg, size_t len);
+int      homa_setsockopt(struct sock *sk, int level, int optname,
+			 sockptr_t optval, unsigned int optlen);
+int      homa_shutdown(struct socket *sock, int how);
+struct sk_buff *__homa_skb_alloc(int length);
+int      homa_socket(struct sock *sk);
+int      homa_softirq(struct sk_buff *skb);
+void     homa_spin(int ns);
+void     homa_timer(struct homa *homa);
+void     homa_timer_check_rpc(struct homa_rpc *rpc);
+int      homa_timer_main(void *transport);
+int      homa_tx_copy_from_user(struct homa_rpc *rpc, struct iov_iter *iter,
+				bool xmit);
+struct sk_buff *homa_tx_skb_alloc(struct homa_rpc *rpc, u32 offset, u32 *end);
+int      homa_tx_skb_send(struct homa_rpc *rpc, u32 offset, u32 *end);
+void     homa_unhash(struct sock *sk);
+void     homa_rpc_unknown_pkt(struct sk_buff *skb, struct homa_rpc *rpc);
+void     homa_unload(void);
+int      homa_wait_private(struct homa_rpc *rpc, int nonblocking);
+struct homa_rpc *homa_wait_shared(struct homa_sock *hsk, int nonblocking);
+int      homa_xmit_control(enum homa_packet_type type, void *contents,
+			   size_t length, struct homa_rpc *rpc);
+int      __homa_xmit_control(void *contents, size_t length,
+			     struct homa_route *route, struct homa_sock *hsk);
+void     homa_xmit_data(struct homa_rpc *rpc);
+void     homa_xmit_unknown(struct sk_buff *skb, struct homa_sock *hsk);
+
+int      homa_message_in_init(struct homa_rpc *rpc, int length);
+
+/**
+ * homa_net() - Return the struct homa_net associated with a particular
+ * struct net.
+ * @net:     Get the Homa data for this net namespace.
+ * Return:   see above.
+ */
+static inline struct homa_net *homa_net(struct net *net)
+{
+	return (struct homa_net *)net_generic(net, homa_net_id);
+}
+
+/**
+ * homa_clock() - Return a fine-grain clock value that is monotonic and
+ * consistent across cores.
+ * Return: see above.
+ */
+static inline u64 homa_clock(void)
+{
+	/* This function exists to make it easy to switch time sources
+	 * if/when new or better sources become available.
+	 */
+	return ktime_get_ns();
+}
+
+/**
+ * homa_clock_khz() - Return the frequency of the values returned by
+ * homa_clock, in units of KHz.
+ * Return: see above.
+ */
+static inline u64 homa_clock_khz(void)
+{
+	return 1000000;
+}
+
+/**
+ * homa_ns_to_cycles() - Convert from units of nanoseconds to units of
+ * homa_clock().
+ * @ns:      A time measurement in nanoseconds
+ * Return:   The time in homa_clock() units corresponding to @ns.
+ */
+static inline u64 homa_ns_to_cycles(u64 ns)
+{
+	u64 tmp;
+
+	tmp = ns * homa_clock_khz();
+	do_div(tmp, 1000000);
+	return tmp;
+}
+
+/* Homa Locking Strategy:
+ *
+ * (Note: this documentation is referenced in several other places in the
+ * Homa code)
+ *
+ * In the Linux TCP/IP stack the primary locking mechanism is a sleep-lock
+ * per socket. However, per-socket locks aren't adequate for Homa, because
+ * sockets are "larger" in Homa. In TCP, a socket corresponds to a single
+ * connection between two peers; an application can have hundreds or
+ * thousands of sockets open at once, so per-socket locks leave lots of
+ * opportunities for concurrency. With Homa, a single socket can be used for
+ * communicating with any number of peers, so there will typically be just
+ * one socket per thread. As a result, a single Homa socket must support many
+ * concurrent RPCs efficiently, and a per-socket lock would create a bottleneck
+ * (Homa tried this approach initially).
+ *
+ * Thus, the primary locks used in Homa spinlocks at RPC granularity. This
+ * allows operations on different RPCs for the same socket to proceed
+ * concurrently. Homa also has socket locks (which are spinlocks different
+ * from the official socket sleep-locks) but these are used much less
+ * frequently than RPC locks.
+ *
+ * Lock Ordering:
+ *
+ * There are several other locks in Homa besides RPC locks, all of which
+ * are spinlocks. When multiple locks are held, they must be acquired in a
+ * consistent order in order to prevent deadlock. Here are the rules for Homa:
+ * 1. Except for RPC locks, socket locks, and the grant lock, all locks
+ *    should be considered "leaf" locks: don't acquire other locks while
+ *    holding them.
+ * 2. The lock order is:
+ *    * Grant lock
+ *    * RPC lock
+ *    * Socket lock
+ *    * Other lock
+ *
+ * It may seem surprising that RPC locks are acquired *before* socket locks,
+ * but this is essential for high performance. Homa has been designed so that
+ * many common operations (such as processing input packets) can be performed
+ * while holding only an RPC lock; this allows operations on different RPCs
+ * to proceed in parallel. Only a few operations, such as handing off an
+ * incoming message to a waiting thread, require the socket lock. If socket
+ * locks had to be acquired first, any operation that might eventually need
+ * the socket lock would have to acquire it before the RPC lock, which would
+ * severely restrict concurrency.
+ *
+ * Socket Shutdown:
+ *
+ * It is possible for socket shutdown to begin while operations are underway
+ * that hold RPC locks but not the socket lock. For example, a new RPC
+ * creation might be underway when a socket is shut down. The RPC creation
+ * will eventually acquire the socket lock and add the new RPC to those
+ * for the socket; it would be very bad if this were to happen after
+ * homa_sock_shutdown thinks it has deleted all RPCs for the socket.
+ * In general, any operation that acquires a socket lock must check
+ * hsk->shutdown after acquiring the lock and abort if hsk->shutdown is set.
+ *
+ * Spinlock Implications:
+ *
+ * Homa uses spinlocks exclusively; this is needed because locks typically
+ * need to be acquired at atomic level, such as in SoftIRQ code.
+ *
+ * Operations that can block, such as memory allocation and copying data
+ * to/from user space, are not permitted while holding spinlocks (spinlocks
+ * disable interrupts, so the holder must not block. This results in awkward
+ * code in several places to move restricted operations outside locked
+ * regions. Such code typically looks like this:
+ *   - Acquire a reference on an object such as an RPC, in order to prevent
+ *     the object from being deleted.
+ *   - Release the object's lock.
+ *   - Perform the restricted operation.
+ *   - Re-acquire the lock.
+ *   - Release the reference.
+ * It is possible that the object may have been modified by some other party
+ * while it was unlocked, so additional checks may be needed after reacquiring
+ * the lock. As one example, an RPC may have been terminated, in which case
+ * any operation in progress on that RPC should be aborted after reacquiring
+ * the lock.
+ *
+ * Lists of RPCs:
+ *
+ * There are a few places where Homa needs to process all of the RPCs
+ * associated with a socket, such as the timer. Such code must first lock
+ * the socket (to protect access to the link pointers) then lock
+ * individual RPCs on the list. However, this violates the rules for locking
+ * order. It isn't safe to unlock the socket before locking the individual RPCs,
+ * because RPCs could be deleted and their memory recycled between the unlock
+ * of the socket lock and the lock of the RPC; this could result in corruption.
+ * Homa uses two different approaches to handle this situation:
+ * 1. Use ``homa_protect_rpcs`` to prevent RPC reaping for a socket. RPCs can
+ *    still be terminated, but their memory won't go away until
+ *    homa_unprotect_rpcs is invoked. This allows the socket lock to be
+ *    released before acquiring RPC locks; after acquiring each RPC lock,
+ *    the RPC must be checked to see if it has been terminated; if so, skip it.
+ * 2. Use ``spin_trylock_bh`` to acquire the RPC lock while still holding the
+ *    socket lock. If this fails, then release the socket lock and retry
+ *    both the socket lock and the RPC lock. Of course, the state of both
+ *    socket and RPC could change before the locks are finally acquired.
+ *
+ * Locks and Packet Transmission:
+ *
+ * Homa must not hold locks while transmitting packets (e.g. by calling
+ * ip_queue_xmit or ip6_xmit). This is because homa_qdisc could be invoked
+ * during the transmission process, and it may need to acquire locks under
+ * some conditions (such as an RPC lock). Homa_qdisc is invoked with the
+ * qdisc lock held, so invoking ip*xmit with a lock held can result in
+ * AB-BA deadlocks.
+ */
+
+#endif /* _HOMA_IMPL_H */
diff --git a/net/homa/homa_incoming.c b/net/homa/homa_incoming.c
new file mode 100644
index 0000000000000..d85dd325de4d1
--- /dev/null
+++ b/net/homa/homa_incoming.c
@@ -0,0 +1,886 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file contains functions that handle incoming Homa messages. */
+
+#include "homa_impl.h"
+#include "homa_interest.h"
+#include "homa_peer.h"
+#include "homa_pool.h"
+
+/**
+ * homa_message_in_init() - Constructor for homa_message_in.
+ * @rpc:          RPC whose msgin structure should be initialized. The
+ *                msgin struct is assumed to be zeroes.
+ * @length:       Total number of bytes in message.
+ * Return:        Zero for successful initialization, or a negative errno
+ *                if rpc->msgin could not be initialized.
+ */
+int homa_message_in_init(struct homa_rpc *rpc, int length)
+	__must_hold(rpc->bucket->lock)
+{
+	int err;
+
+	if (((unsigned int)length) > HOMA_MAX_MESSAGE_LENGTH)
+		return -EINVAL;
+
+	rpc->msgin.length = length;
+	__skb_queue_head_init(&rpc->msgin.packets);
+	INIT_LIST_HEAD(&rpc->msgin.gaps);
+	rpc->msgin.bytes_remaining = length;
+	err = homa_pool_alloc_msg(rpc);
+	if (err != 0) {
+		rpc->msgin.length = -1;
+		return err;
+	}
+	return 0;
+}
+
+/**
+ * homa_gap_alloc() - Allocate a new gap and add it to a gap list.
+ * @next:   Add the new gap just before this list element.
+ * @start:  Offset of first byte covered by the gap.
+ * @end:    Offset of byte just after the last one covered by the gap.
+ * Return:  Pointer to the new gap, or NULL if memory couldn't be allocated
+ *          for the gap object.
+ */
+struct homa_gap *homa_gap_alloc(struct list_head *next, int start, int end)
+{
+	struct homa_gap *gap;
+
+	gap = kmalloc_obj(*gap, GFP_ATOMIC);
+	if (!gap)
+		return NULL;
+	gap->start = start;
+	gap->end = end;
+	gap->time = homa_clock();
+	list_add_tail(&gap->links, next);
+	return gap;
+}
+
+/**
+ * homa_request_retrans() - The function is invoked when it appears that
+ * data packets for a message have been lost. It issues RESEND requests
+ * as appropriate and may modify the state of the RPC.
+ * @rpc:     RPC for which incoming data is delinquent; must be locked by
+ *           caller.
+ */
+void homa_request_retrans(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_resend_hdr *resends;
+	struct homa_resend_hdr resend;
+	struct homa_gap *gap;
+	int offset, length;
+	int num_gaps, i;
+
+	if (rpc->msgin.length >= 0) {
+		/* Issue RESENDS for any gaps in incoming data.  Must
+		 * pre-allocate space for all of the packet headers because
+		 * so we don't have to release the RPC lock while iterating
+		 * the gap list.
+		 */
+		num_gaps = list_count_nodes(&rpc->msgin.gaps);
+		resends = kzalloc_objs(*resends, num_gaps, GFP_ATOMIC);
+		if (!resends)
+			return;
+		i = 0;
+		list_for_each_entry(gap, &rpc->msgin.gaps, links) {
+			resends[i].offset = htonl(gap->start);
+			resends[i].length = htonl(gap->end - gap->start);
+			i++;
+		}
+		for (i = 0; i < num_gaps; i++)
+			homa_xmit_control(RESEND, &resends[i],
+					  sizeof(resends[i]), rpc);
+		kfree(resends);
+
+		/* Issue a RESEND for any granted data after the last gap. */
+		offset = rpc->msgin.recv_end;
+		length = rpc->msgin.length - rpc->msgin.recv_end;
+		if (length <= 0)
+			return;
+	} else {
+		/* No data has been received for the RPC. Ask the sender to
+		 * resend everything it has sent so far.
+		 */
+		offset = 0;
+		length = -1;
+	}
+
+	memset(&resend, 0, sizeof(resend));
+	resend.offset = htonl(offset);
+	resend.length = htonl(length);
+	homa_xmit_control(RESEND, &resend, sizeof(resend), rpc);
+}
+
+/**
+ * homa_add_packet() - Add an incoming packet to the contents of a
+ * partially received message.
+ * @rpc:   Add the packet to the msgin for this RPC.
+ * @skb:   The new packet. If the packet is linked into rpc then an additional
+ *         reference will be taken on it.
+ * Return: 0 if the packet was successfully linked into rpc, otherwise the
+ *         reason why the packet was not linked in.
+ */
+enum skb_drop_reason homa_add_packet(struct homa_rpc *rpc, struct sk_buff *skb)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_data_hdr *h = (struct homa_data_hdr *)skb->data;
+	struct homa_gap *gap, *dummy, *gap2;
+	u32 start = ntohl(h->seg.offset);
+	u32 length = homa_data_len(skb);
+	enum skb_drop_reason reason = 0;
+	u32 end = start + length;
+
+	if (start >= rpc->msgin.length ||
+	    length > (rpc->msgin.length - start)) {
+		reason = SKB_DROP_REASON_PKT_TOO_BIG;
+		goto ignore;
+	}
+
+	if (start == rpc->msgin.recv_end) {
+		/* Common case: packet is sequential. */
+		rpc->msgin.recv_end += length;
+		goto keep;
+	}
+
+	if (start > rpc->msgin.recv_end) {
+		/* Packet creates a new gap. */
+		if (!homa_gap_alloc(&rpc->msgin.gaps,
+				    rpc->msgin.recv_end, start)) {
+			reason = SKB_DROP_REASON_NOMEM;
+			goto ignore;
+		}
+		rpc->msgin.recv_end = end;
+		goto keep;
+	}
+
+	/* Must now check to see if the packet fills in part or all of
+	 * an existing gap.
+	 */
+	list_for_each_entry_safe(gap, dummy, &rpc->msgin.gaps, links) {
+		/* Is packet at the start of this gap? */
+		if (start <= gap->start) {
+			if (end <= gap->start)
+				continue;
+			if (start < gap->start) {
+				reason = SKB_DROP_REASON_DUP_FRAG;
+				goto ignore;
+			}
+			if (end > gap->end) {
+				reason = SKB_DROP_REASON_DUP_FRAG;
+				goto ignore;
+			}
+			gap->start = end;
+			if (gap->start >= gap->end) {
+				list_del(&gap->links);
+				kfree(gap);
+			}
+			goto keep;
+		}
+
+		/* Is packet at the end of this gap? BTW, at this point we know
+		 * the packet can't cover the entire gap.
+		 */
+		if (end >= gap->end) {
+			if (start >= gap->end)
+				continue;
+			if (end > gap->end) {
+				reason = SKB_DROP_REASON_DUP_FRAG;
+				goto ignore;
+			}
+			gap->end = start;
+			goto keep;
+		}
+
+		/* Packet is in the middle of the gap; must split the gap. */
+		gap2 = homa_gap_alloc(&gap->links, gap->start, start);
+		if (!gap2) {
+			reason = SKB_DROP_REASON_NOMEM;
+			goto ignore;
+		}
+		gap2->time = gap->time;
+		gap->start = end;
+		goto keep;
+	}
+	/* Packet doesn't overlap any gap, so it is a duplicate. */
+	reason = SKB_DROP_REASON_DUP_FRAG;
+
+ignore:
+	return reason;
+
+keep:
+	__skb_queue_tail(&rpc->msgin.packets, skb);
+	skb_get(skb);
+	rpc->msgin.bytes_remaining -= length;
+	return 0;
+}
+
+/**
+ * homa_copy_to_user() - Copy as much data as possible from incoming
+ * packet buffers to buffers in user space.
+ * @rpc:     RPC for which data should be copied. Must be locked by caller.
+ * Return:   Zero for success or a negative errno if there is an error.
+ *           It is possible for the RPC to be freed while this function
+ *           executes (it releases and reacquires the RPC lock). If that
+ *           happens, -EINVAL will be returned and the state of @rpc
+ *           will be RPC_DEAD. Clears the RPC_PKTS_READY bit in @rpc->flags
+ *           if all available packets have been copied out.
+ */
+int homa_copy_to_user(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+#define MAX_SKBS 20
+	struct sk_buff *skbs[MAX_SKBS];
+	int error = 0;
+	int n = 0;             /* Number of filled entries in skbs. */
+	int i;
+
+	/* Tricky note: we can't hold the RPC lock while we're actually
+	 * copying to user space, because (a) it's illegal to hold a spinlock
+	 * while copying to user space and (b) we'd like for homa_softirq
+	 * to add more packets to the RPC while we're copying these out.
+	 * So, collect a bunch of packets to copy, then release the lock,
+	 * copy them, and reacquire the lock.
+	 */
+	while (true) {
+		struct sk_buff *skb;
+
+		if (rpc->state == RPC_DEAD) {
+			error = -EINVAL;
+			break;
+		}
+
+		skb = __skb_dequeue(&rpc->msgin.packets);
+		if (skb) {
+			skbs[n] = skb;
+			n++;
+			if (n < MAX_SKBS)
+				continue;
+		}
+		if (n == 0) {
+			clear_bit(RPC_PKTS_READY, &rpc->flags);
+			break;
+		}
+
+		/* At this point we've collected a batch of packets (or
+		 * run out of packets); copy any available packets out to
+		 * user space.
+		 */
+		homa_rpc_unlock(rpc);
+
+		/* Each iteration of this loop copies out one skb. */
+		for (i = 0; i < n; i++) {
+			struct homa_data_hdr *h = (struct homa_data_hdr *)
+					skbs[i]->data;
+			int pkt_length = homa_data_len(skbs[i]);
+			int offset = ntohl(h->seg.offset);
+			int buf_bytes, chunk_size;
+			struct iov_iter iter;
+			int copied = 0;
+			char __user *dst;
+
+			/* Each iteration of this loop copies to one
+			 * user buffer.
+			 */
+			while (copied < pkt_length) {
+				chunk_size = pkt_length - copied;
+				dst = homa_pool_get_buffer(rpc, offset + copied,
+							   &buf_bytes);
+				if (buf_bytes < chunk_size) {
+					if (buf_bytes == 0) {
+						/* skb has data beyond message
+						 * end?
+						 */
+						break;
+					}
+					chunk_size = buf_bytes;
+				}
+				error = import_ubuf(READ, dst, chunk_size,
+						    &iter);
+				if (error)
+					goto free_skbs;
+				error = skb_copy_datagram_iter(skbs[i],
+							       sizeof(*h) +
+							       copied,  &iter,
+							       chunk_size);
+				if (error)
+					goto free_skbs;
+				copied += chunk_size;
+			}
+		}
+
+free_skbs:
+		for (i = 0; i < n; i++)
+			consume_skb(skbs[i]);
+		n = 0;
+		homa_rpc_lock_preempt(rpc);
+		if (error)
+			break;
+	}
+	return error;
+}
+
+/**
+ * homa_dispatch_pkts() - Top-level function that processes a batch of packets,
+ * all related to the same RPC.
+ * @skb:       First packet in the batch, linked through skb->next.
+ */
+void homa_dispatch_pkts(struct sk_buff *skb)
+{
+	const struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);
+	struct homa_data_hdr *h = (struct homa_data_hdr *)skb->data;
+	u64 id = homa_local_id(h->common.sender_id);
+	int dport = ntohs(h->common.dport);
+	struct homa_rpc *rpc = NULL;
+	struct homa_sock *hsk;
+	struct homa_net *hnet;
+	struct sk_buff *next;
+
+	/* Find the appropriate socket.*/
+	hnet = homa_net(dev_net(skb->dev));
+	hsk = homa_sock_find(hnet, dport);
+	if (!hsk || (!homa_is_client(id) && !hsk->is_server)) {
+		if (skb_is_ipv6(skb))
+			icmp6_send(skb, ICMPV6_DEST_UNREACH,
+				   ICMPV6_PORT_UNREACH, 0, NULL, IP6CB(skb));
+		else
+			icmp_send(skb, ICMP_DEST_UNREACH,
+				  ICMP_PORT_UNREACH, 0);
+		while (skb) {
+			next = skb->next;
+			kfree_skb(skb);
+			skb = next;
+		}
+		if (hsk)
+			sock_put(&hsk->sock);
+		return;
+	}
+
+	/* Each iteration through the following loop processes one packet. */
+	for (; skb; skb = next) {
+		h = (struct homa_data_hdr *)skb->data;
+		next = skb->next;
+
+		/* Relinquish the RPC lock temporarily if it's needed
+		 * elsewhere.
+		 */
+		if (rpc) {
+			if (test_bit(APP_NEEDS_LOCK, &rpc->flags)) {
+				homa_rpc_unlock(rpc);
+
+				/* This short spin is needed to ensure that the
+				 * other thread gets the lock before this thread
+				 * grabs it again below (the need for this
+				 * was confirmed experimentally in 2/2025;
+				 * without it, the handoff fails 20-25% of the
+				 * time). Furthermore, the call to homa_spin
+				 * seems to allow the other thread to acquire
+				 * the lock more quickly.
+				 */
+				homa_spin(100);
+				homa_rpc_lock(rpc);
+			}
+		}
+
+		/* If we don't already have an RPC, find it, lock it,
+		 * and create a reference on it.
+		 */
+		if (!rpc) {
+			if (!homa_is_client(id)) {
+				/* We are the server for this RPC. */
+				if (h->common.type == DATA) {
+					/* Create a new RPC if one doesn't
+					 * already exist.
+					 */
+					rpc = homa_rpc_alloc_server(hsk, &saddr,
+								    h);
+					if (IS_ERR(rpc)) {
+						rpc = NULL;
+						goto discard;
+					}
+				} else {
+					rpc = homa_rpc_find_server(hsk, &saddr,
+								   id);
+				}
+			} else {
+				rpc = homa_rpc_find_client(hsk, id);
+			}
+			if (rpc)
+				homa_rpc_hold(rpc);
+		}
+		if (unlikely(!rpc)) {
+			if (h->common.type != NEED_ACK &&
+			    h->common.type != ACK &&
+			    h->common.type != RESEND)
+				goto discard;
+		} else {
+			if (h->common.type == DATA ||
+			    h->common.type == BUSY)
+				rpc->silent_ticks = 0;
+		}
+
+		switch (h->common.type) {
+		case DATA:
+			homa_data_pkt(skb, rpc);
+			break;
+		case RESEND:
+			homa_resend_pkt(skb, rpc, hsk);
+			break;
+		case RPC_UNKNOWN:
+			homa_rpc_unknown_pkt(skb, rpc);
+			break;
+		case BUSY:
+			/* Nothing to do for these packets except reset
+			 * silent_ticks, which happened above.
+			 */
+			goto discard;
+		case NEED_ACK:
+			homa_need_ack_pkt(skb, hsk, rpc);
+			break;
+		case ACK:
+			homa_ack_pkt(skb, hsk, rpc);
+			break;
+		default:
+			goto discard;
+		}
+		continue;
+
+discard:
+		kfree_skb(skb);
+	}
+	if (rpc) {
+		homa_rpc_put(rpc);
+		homa_rpc_unlock(rpc);
+	}
+
+	/* We need to reap dead RPCs here under two conditions:
+	 * 1. The socket has hit its limit on tx buffer space and threads are
+	 *    blocked waiting for skbs to be released.
+	 * 2. A large number of dead RPCs have accumulated, and it seems
+	 *    that the reaper isn't keeping up when invoked only at
+	 *    "convenient" times (see "RPC Reaping Strategy" in homa_rpc_reap
+	 *    code for details).
+	 */
+	if (hsk->dead_frags > 0) {
+		while (test_bit(HOMA_SOCK_NOSPACE, &hsk->flags) ||
+		       hsk->dead_frags >= 2 * hsk->homa->dead_frags_limit) {
+			int more;
+
+			more = homa_rpc_reap(hsk);
+			if (!more)
+				break;
+		}
+	}
+	sock_put(&hsk->sock);
+}
+
+/**
+ * homa_data_pkt() - Handler for incoming DATA packets
+ * @skb:     Incoming packet; size known to be large enough for the header.
+ *           This function now owns the packet.
+ * @rpc:     Information about the RPC corresponding to this packet.
+ *           Must be locked by the caller.
+ */
+void homa_data_pkt(struct sk_buff *skb, struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	enum skb_drop_reason drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
+	struct homa_data_hdr *h = (struct homa_data_hdr *)skb->data;
+
+	if (rpc->state != RPC_INCOMING && homa_is_client(rpc->id)) {
+		if (unlikely(rpc->state != RPC_OUTGOING))
+			goto handle_ack;
+		rpc->state = RPC_INCOMING;
+		if (homa_message_in_init(rpc, ntohl(h->message_length)) != 0) {
+			drop_reason = SKB_DROP_REASON_NOMEM;
+			goto handle_ack;
+		}
+	} else if (rpc->state != RPC_INCOMING) {
+		/* Must be server; note that homa_rpc_alloc_server already
+		 * initialized msgin and allocated buffers.
+		 */
+		if (unlikely(rpc->msgin.length >= 0))
+			goto handle_ack;
+	}
+
+	if (rpc->msgin.num_bpages == 0) {
+		/* Drop packets that arrive when we can't allocate buffer
+		 * space. If we keep them around, packet buffer usage can
+		 * exceed available cache space, resulting in poor
+		 * performance.
+		 */
+		drop_reason = SKB_DROP_REASON_NOMEM;
+		goto handle_ack;
+	}
+
+	drop_reason = homa_add_packet(rpc, skb);
+
+	if (skb_queue_len(&rpc->msgin.packets) != 0 &&
+	    !test_bit(RPC_PKTS_READY, &rpc->flags)) {
+		set_bit(RPC_PKTS_READY, &rpc->flags);
+		homa_rpc_handoff(rpc);
+	}
+
+handle_ack:
+	/* It's important to handle acks *after* calling homa_add_packet.
+	 * Otherwise we can end up with extraneous handoffs: we have to release
+	 * the RPC lock to handle acks, but that could allow some other thread
+	 * to receive a previous handoff made by homa_rpc_alloc_server, even
+	 * though the packet hasn't been added to the RPC. If this happens
+	 * the call to homa_rpc_handoff above will have to make an additional
+	 * handoff.
+	 */
+	if (h->ack.client_id) {
+		const struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);
+
+		homa_rpc_ack(rpc->hsk, rpc, &saddr, 1, &h->ack);
+	}
+	kfree_skb_reason(skb, drop_reason);
+}
+
+/**
+ * homa_resend_pkt() - Handler for incoming RESEND packets
+ * @skb:     Incoming packet; size already verified large enough for header.
+ *           This function now owns the packet.
+ * @rpc:     Information about the RPC corresponding to this packet; must
+ *           be locked by caller, but may be NULL if there is no RPC matching
+ *           this packet
+ * @hsk:     Socket on which the packet was received.
+ */
+void homa_resend_pkt(struct sk_buff *skb, struct homa_rpc *rpc,
+		     struct homa_sock *hsk)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_resend_hdr *h = (struct homa_resend_hdr *)skb->data;
+	int offset = ntohl(h->offset);
+	int length = ntohl(h->length);
+	int end = offset + length;
+	struct homa_busy_hdr busy;
+	int tx_end;
+
+	if (!rpc) {
+		homa_xmit_unknown(skb, hsk);
+		goto done;
+	}
+
+	tx_end = homa_rpc_tx_end(rpc);
+	if (!homa_is_client(rpc->id) && rpc->state != RPC_OUTGOING) {
+		/* We are the server for this RPC and don't yet have a
+		 * response message, so send BUSY to keep the client
+		 * waiting.
+		 */
+		homa_xmit_control(BUSY, &busy, sizeof(busy), rpc);
+		goto done;
+	}
+
+	if (length == -1)
+		end = tx_end;
+
+	/* Don't retransmit data that we haven't transmitted for the first
+	 * time: we're not ready to send that data yet (we'll send a BUSY
+	 * packet below if needed).
+	 */
+	homa_resend_data(rpc, offset, (end > tx_end) ? tx_end : end);
+	if (rpc->state == RPC_DEAD)
+		goto done;
+
+	if (offset >= tx_end) {
+		/* We have chosen not to transmit any of the requested data;
+		 * send BUSY so the receiver knows we are alive.
+		 */
+		homa_xmit_control(BUSY, &busy, sizeof(busy), rpc);
+		goto done;
+	}
+
+done:
+	consume_skb(skb);
+}
+
+/**
+ * homa_rpc_unknown_pkt() - Handler for incoming RPC_UNKNOWN packets.
+ * @skb:     Incoming packet; size known to be large enough for the header.
+ *           This function now owns the packet.
+ * @rpc:     Information about the RPC corresponding to this packet. Must
+ *           be locked by caller.
+ */
+void homa_rpc_unknown_pkt(struct sk_buff *skb, struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	if (homa_is_client(rpc->id)) {
+		if (rpc->state == RPC_OUTGOING) {
+			int tx_end = homa_rpc_tx_end(rpc);
+
+			/* It appears that everything we've already transmitted
+			 * has been lost; retransmit it.
+			 */
+			homa_resend_data(rpc, 0, tx_end);
+			goto done;
+		}
+	} else {
+		homa_rpc_end(rpc);
+	}
+done:
+	consume_skb(skb);
+}
+
+/**
+ * homa_need_ack_pkt() - Handler for incoming NEED_ACK packets
+ * @skb:     Incoming packet; size already verified large enough for header.
+ *           This function now owns the packet.
+ * @hsk:     Socket on which the packet was received.
+ * @rpc:     The RPC named in the packet header, or NULL if no such
+ *           RPC exists. The RPC must have been locked by the caller.
+ */
+void homa_need_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,
+		       struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_common_hdr *h = (struct homa_common_hdr *)skb->data;
+	const struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);
+	u64 id = homa_local_id(h->sender_id);
+	struct homa_route *route;
+	struct homa_ack_hdr ack;
+
+	/* Don't ack if it's not safe for the peer to purge its state
+	 * for this RPC (the RPC still exists and we haven't received
+	 * the entire response), or if we can't find peer info.
+	 */
+	if (rpc && (rpc->state != RPC_INCOMING ||
+		    rpc->msgin.bytes_remaining)) {
+		homa_request_retrans(rpc);
+		goto done;
+	}
+	route = homa_route_get(hsk, &saddr);
+	if (IS_ERR(route))
+		goto done;
+
+	/* Send an ACK for this RPC. At the same time, include all of the
+	 * other acks available for the peer. Note: can't use rpc below,
+	 * since it may be NULL.
+	 */
+	memset(&ack, 0, sizeof(ack));
+	ack.common.type = ACK;
+	ack.common.sport = h->dport;
+	ack.common.dport = h->sport;
+	ack.common.sender_id = cpu_to_be64(id);
+	ack.num_acks = htons(homa_peer_get_acks(route->peer,
+						HOMA_MAX_ACKS_PER_PKT,
+						ack.acks));
+	if (rpc)
+		homa_rpc_unlock(rpc);
+	__homa_xmit_control(&ack, sizeof(ack), route, hsk);
+	if (rpc)
+		homa_rpc_lock(rpc);
+	homa_route_release(route);
+
+done:
+	consume_skb(skb);
+}
+
+/**
+ * homa_ack_pkt() - Handler for incoming ACK packets
+ * @skb:     Incoming packet; size already verified large enough for header.
+ *           This function now owns the packet.
+ * @hsk:     Socket on which the packet was received.
+ * @rpc:     The RPC named in the packet header, or NULL if no such
+ *           RPC exists. The RPC must be locked by the caller.
+ */
+void homa_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,
+		  struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	const struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);
+	struct homa_ack_hdr *h = (struct homa_ack_hdr *)skb->data;
+	int count;
+
+	if (rpc)
+		homa_rpc_end(rpc);
+
+	count = ntohs(h->num_acks);
+	if (count > HOMA_MAX_ACKS_PER_PKT)
+		count = HOMA_MAX_ACKS_PER_PKT;
+	if (count > 0)
+		homa_rpc_ack(hsk, rpc, &saddr, count, h->acks);
+	consume_skb(skb);
+}
+
+/**
+ * homa_wait_private() - Waits until the response has been received for
+ * a specific RPC or the RPC has failed with an error.
+ * @rpc:          RPC to wait for; an error will be returned if the RPC is
+ *                not a client RPC or not private. Must be locked by caller.
+ * @nonblocking:  Nonzero means return immediately if @rpc not ready.
+ * Return:        0 means that @rpc is ready for attention: either its response
+ *                has been received or it has an unrecoverable error such as
+ *                ETIMEDOUT (in rpc->error). Nonzero means some other error
+ *                (such as EINTR or EINVAL) occurred before @rpc became ready
+ *                for attention; in this case the return value is a negative
+ *                errno.
+ */
+int homa_wait_private(struct homa_rpc *rpc, int nonblocking)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_interest interest;
+	int result;
+
+	if (!test_bit(RPC_PRIVATE, &rpc->flags))
+		return -EINVAL;
+
+	/* Each iteration through this loop waits until rpc needs attention
+	 * in some way (e.g. packets have arrived), then deals with that need
+	 * (e.g. copy to user space). It may take many iterations until the
+	 * RPC is ready for the application.
+	 */
+	while (1) {
+		result = 0;
+		if (!rpc->error)
+			rpc->error = homa_copy_to_user(rpc);
+		if (rpc->error)
+			break;
+		if (rpc->msgin.length >= 0 &&
+		    rpc->msgin.bytes_remaining == 0 &&
+		    skb_queue_len(&rpc->msgin.packets) == 0)
+			break;
+
+		if (nonblocking) {
+			result = -EAGAIN;
+			break;
+		}
+
+		result = homa_interest_init_private(&interest, rpc);
+		if (result != 0)
+			break;
+
+		homa_rpc_unlock(rpc);
+		result = homa_interest_wait(&interest);
+
+		homa_rpc_lock_preempt(rpc);
+		homa_interest_unlink_private(&interest);
+		if (result != 0)
+			break;
+	}
+
+	return result;
+}
+
+/**
+ * homa_wait_shared() - Wait for the completion of any non-private
+ * incoming message on a socket.
+ * @hsk:          Socket on which to wait. Must not be locked.
+ * @nonblocking:  Nonzero means return immediately if no RPC is ready.
+ *
+ * Return:    Pointer to an RPC with a complete incoming message or nonzero
+ *            error field, or a negative errno (usually -EINTR). If an RPC
+ *            is returned it will be locked and referenced; the caller
+ *            must release the lock and the reference.
+ */
+struct homa_rpc *homa_wait_shared(struct homa_sock *hsk, int nonblocking)
+	__cond_acquires(nonnull, rpc->bucket->lock)
+{
+	struct homa_interest interest;
+	struct homa_rpc *rpc;
+	int result;
+
+	/* Each iteration through this loop waits until an RPC needs attention
+	 * in some way (e.g. packets have arrived), then deals with that need
+	 * (e.g. copy to user space). It may take many iterations until an
+	 * RPC is ready for the application.
+	 */
+	while (1) {
+		homa_sock_lock(hsk);
+		if (hsk->shutdown) {
+			rpc = ERR_PTR(-ESHUTDOWN);
+			homa_sock_unlock(hsk);
+			goto done;
+		}
+		if (!list_empty(&hsk->ready_rpcs)) {
+			rpc = list_first_entry(&hsk->ready_rpcs,
+					       struct homa_rpc,
+					       ready_links);
+			homa_rpc_hold(rpc);
+			list_del_init(&rpc->ready_links);
+			if (!list_empty(&hsk->ready_rpcs)) {
+				/* There are still more RPCs available, so
+				 * let Linux know.
+				 */
+				hsk->sock.sk_data_ready(&hsk->sock);
+			}
+			homa_sock_unlock(hsk);
+		} else if (nonblocking) {
+			rpc = ERR_PTR(-EAGAIN);
+			homa_sock_unlock(hsk);
+
+			/* This is a good time to cleanup dead RPCS. */
+			homa_rpc_reap(hsk);
+			goto done;
+		} else {
+			homa_interest_init_shared(&interest, hsk);
+			homa_sock_unlock(hsk);
+			result = homa_interest_wait(&interest);
+
+			if (result != 0) {
+				rpc = ERR_PTR(result);
+				goto done;
+			}
+
+			rpc = interest.rpc;
+			if (!rpc) {
+				rpc = ERR_PTR(-ESHUTDOWN);
+				goto done;
+			}
+		}
+
+		homa_rpc_lock_preempt(rpc);
+		if (!rpc->error)
+			rpc->error = homa_copy_to_user(rpc);
+		if (rpc->error) {
+			if (rpc->state != RPC_DEAD)
+				break;
+		} else if (rpc->msgin.bytes_remaining == 0 &&
+		    skb_queue_len(&rpc->msgin.packets) == 0)
+			break;
+		homa_rpc_put(rpc);
+		homa_rpc_unlock(rpc);
+	}
+
+done:
+	return rpc;
+}
+
+/**
+ * homa_rpc_handoff() - This function is called when the input message for
+ * an RPC is ready for attention from a user thread. It notifies a waiting
+ * reader and/or queues the RPC, as appropriate.
+ * @rpc:                RPC to handoff; must be locked.
+ */
+void homa_rpc_handoff(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_sock *hsk = rpc->hsk;
+
+	if (rpc->state == RPC_DEAD)
+		return;
+
+	if (test_bit(RPC_PRIVATE, &rpc->flags)) {
+		homa_interest_notify_private(rpc);
+		return;
+	}
+
+	/* Shared RPC; if there is a waiting thread, hand off the RPC;
+	 * otherwise enqueue it.
+	 */
+	homa_sock_lock(hsk);
+	if (hsk->shutdown) {
+		homa_sock_unlock(hsk);
+		return;
+	}
+	if (!list_empty(&hsk->interests)) {
+		homa_rpc_hold(rpc);
+		homa_interest_notify_shared(hsk, rpc);
+	} else if (list_empty(&rpc->ready_links)) {
+		list_add_tail(&rpc->ready_links, &hsk->ready_rpcs);
+		hsk->sock.sk_data_ready(&hsk->sock);
+	}
+	homa_sock_unlock(hsk);
+}
diff --git a/net/homa/homa_interest.c b/net/homa/homa_interest.c
new file mode 100644
index 0000000000000..66ea429aac274
--- /dev/null
+++ b/net/homa/homa_interest.c
@@ -0,0 +1,192 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file contains functions for managing homa_interest structs. */
+
+#include "homa_impl.h"
+#include "homa_interest.h"
+#include "homa_rpc.h"
+#include "homa_sock.h"
+
+/* DESIGN NOTES:
+ * The key idea behind the design of the interest mechanism is to reduce usage
+ * of socket locks while handing off ready RPCs to application threads. Private
+ * handoffs do not require the socket lock to be acquired at all. Shared
+ * handoffs must acquire the socket lock to select one thread from a pool of
+ * waiting threads. But in the normal case the thread receiving the ready RPC
+ * does not need to acquire the socket lock again after the RPC has been
+ * handed off to it. The HOMA_INTEREST_HANDOFF_ACTIVE mechanism eliminates
+ * races that would otherwise be present in the absence of locking.
+ */
+
+/**
+ * homa_interest_init_shared() - Initialize an interest and queue it up on
+ * a socket.
+ * @interest:  Interest to initialize
+ * @hsk:       Socket on which the interests should be queued. Must be locked
+ *             by caller.
+ */
+void homa_interest_init_shared(struct homa_interest *interest,
+			       struct homa_sock *hsk)
+	__must_hold(hsk->lock)
+{
+	interest->rpc = NULL;
+	atomic_set(&interest->state, 0);
+	interest->blocked = 0;
+	init_waitqueue_head(&interest->wait_queue);
+	interest->hsk = hsk;
+	list_add(&interest->links, &hsk->interests);
+}
+
+/**
+ * homa_interest_init_private() - Initialize an interest that will wait
+ * on a particular (private) RPC, and link it to that RPC.
+ * @interest:   Interest to initialize.
+ * @rpc:        RPC to associate with the interest. Must be private, and
+ *              caller must have locked it.
+ *
+ * Return:      0 for success, otherwise a negative errno.
+ */
+int homa_interest_init_private(struct homa_interest *interest,
+			       struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	if (rpc->private_interest)
+		return -EINVAL;
+
+	interest->rpc = rpc;
+	atomic_set(&interest->state, 0);
+	interest->blocked = 0;
+	init_waitqueue_head(&interest->wait_queue);
+	interest->hsk = rpc->hsk;
+	INIT_LIST_HEAD(&interest->links);
+	rpc->private_interest = interest;
+	return 0;
+}
+
+/**
+ * homa_interest_wait() - Wait for an interest to have an actionable RPC,
+ * or for an error to occur.
+ * @interest:     Interest to wait for; must previously have been initialized
+ *                and linked to a socket or RPC. On return, the interest
+ *                will have been unlinked if it is shared and its ready flag
+ *                is set; otherwise it may still be linked.
+ *
+ * Return: 0 for success (the ready flag is set in the interest), or -EINTR
+ * if the thread received an interrupt. When this function returns, the
+ * interest will no longer be linked to a socket (if it ever was).
+ */
+int homa_interest_wait(struct homa_interest *interest)
+{
+	struct homa_sock *hsk = interest->hsk;
+	int result = 0;
+	int iteration;
+	int wait_err;
+
+	interest->blocked = 0;
+
+	/* This loop iterates in order to poll and/or reap dead RPCS. */
+	for (iteration = 0; ; iteration++) {
+		if (iteration != 0)
+			/* Give NAPI/SoftIRQ tasks a chance to run. */
+			schedule();
+
+		if (atomic_read_acquire(&interest->state) & HOMA_INTEREST_READY)
+			goto done;
+
+		if (signal_pending(current)) {
+			wait_err = -ERESTARTSYS;
+			goto check_err;
+		}
+
+		/* See if we can cleanup dead RPCs while waiting. */
+		if (homa_rpc_reap(hsk) != 0)
+			continue;
+
+		break;
+	}
+
+	interest->blocked = 1;
+	wait_err = wait_event_interruptible_exclusive(interest->wait_queue,
+						      atomic_read_acquire(&interest->state) &
+						      HOMA_INTEREST_READY);
+
+check_err:
+	if (wait_err == -ERESTARTSYS) {
+		int ready;
+
+		/* An interrupt occurred. We have to do two things.  First,
+		 * unlink the interest from the socket (if it was linked).
+		 * Second, check to see if in the meantime the interest
+		 * received a handoff. If so, ignore the interrupt. Must hold
+		 * the socket lock while checking, in order to eliminate races
+		 * with homa_rpc_handoff. Technically these are only needed
+		 * for shared interests, but it's harmless to do them for
+		 * private interests as well.
+		 */
+		homa_sock_lock(hsk);
+		list_del_init(&interest->links);
+		ready = atomic_read_acquire(&interest->state) &
+			HOMA_INTEREST_READY;
+		homa_sock_unlock(hsk);
+		if (ready == 0)
+			result = -EINTR;
+	}
+
+done:
+	/* Make sure that the handing off thread has completely finished
+	 * accessing the interest, so that it's safe for our caller to
+	 * reuse the interest's memory.
+	 */
+	while (atomic_read(&interest->state) & HOMA_INTEREST_HANDOFF_ACTIVE)
+		cpu_relax();
+	return result;
+}
+
+/**
+ * homa_interest_notify_private() - If a thread is waiting on the private
+ * interest for an RPC, wake it up.
+ * @rpc:      RPC that may (potentially) have a private interest. Must be
+ *            locked by the caller.
+ */
+void homa_interest_notify_private(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	if (rpc->private_interest) {
+		/* See comment in homa_interest_notify_shared. */
+		atomic_set_release(&rpc->private_interest->state,
+				   HOMA_INTEREST_READY |
+				   HOMA_INTEREST_HANDOFF_ACTIVE);
+		wake_up(&rpc->private_interest->wait_queue);
+		atomic_set_release(&rpc->private_interest->state,
+				   HOMA_INTEREST_READY);
+	}
+}
+
+/**
+ * homa_interest_notify_shared() - Hand an RPC off to one of the interests
+ * available for a socket.
+ * @hsk:      Socket for the handoff; must have at least one interest.
+ *            Must be locked by caller.
+ * @rpc:      RPC to handoff; can be NULL to indicate that the socket
+ *            has been shutdown. Caller must have taken a reference.
+ */
+void homa_interest_notify_shared(struct homa_sock *hsk, struct homa_rpc *rpc)
+	__must_hold(hsk->lock)
+{
+	struct homa_interest *interest;
+
+	interest = list_first_entry(&hsk->interests,
+				    struct homa_interest, links);
+	list_del_init(&interest->links);
+	interest->rpc = rpc;
+
+	/* The dance below eliminates two race conditions: (a) a waking up
+	 * thread doesn't see the change to state and (b) a waking up thread
+	 * recycles the memory of the interest before we have finished
+	 * accessing it in wake_up.
+	 */
+	atomic_set_release(&interest->state,
+			   HOMA_INTEREST_READY | HOMA_INTEREST_HANDOFF_ACTIVE);
+	wake_up(&interest->wait_queue);
+	atomic_set_release(&interest->state, HOMA_INTEREST_READY);
+}
diff --git a/net/homa/homa_interest.h b/net/homa/homa_interest.h
new file mode 100644
index 0000000000000..cb0b3f0d4f183
--- /dev/null
+++ b/net/homa/homa_interest.h
@@ -0,0 +1,92 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file defines struct homa_interest and related functions.  */
+
+#ifndef _HOMA_INTEREST_H
+#define _HOMA_INTEREST_H
+
+#include "homa_rpc.h"
+#include "homa_sock.h"
+
+/**
+ * struct homa_interest - Holds info that allows applications to wait for
+ * incoming RPC messages. An interest can be either private, in which case
+ * the application is waiting for a single specific RPC response and the
+ * interest is referenced by an rpc->private_interest, or shared, in which
+ * case the application is waiting for any incoming message that isn't
+ * private and the interest is present on hsk->interests.
+ */
+struct homa_interest {
+	/**
+	 * @rpc: If ready is set, then this holds an RPC that needs
+	 * attention, or NULL if this is a shared interest and hsk has
+	 * been shutdown. If ready is not set, this will be NULL if the
+	 * interest is shared; if it's private, it holds the RPC the
+	 * interest is associated with. If non-NULL, a reference has been
+	 * taken on the RPC.
+	 */
+	struct homa_rpc *rpc;
+
+	/**
+	 * @state: Used to manage the process of handing off an RPC.  Consists
+	 * of the following bits:
+	 * HOMA_INTEREST_READY:
+	 *     Nonzero means the interest is ready for attention: either there
+	 *     is an RPC that needs attention or @hsk has been shutdown.
+	 * HOMA_INTEREST_HANDOFF_ACTIVE:
+	 *     Nonzero means a handing-off thread is still accessing the
+	 *     interest. Used to ensure that the handing-off thread is
+	 *     completely finished before homa_interest_wait returns (so
+	 *     that the interest can safely be deleted).
+	 */
+#define HOMA_INTEREST_READY           1
+#define HOMA_INTEREST_HANDOFF_ACTIVE  2
+	atomic_t state;
+
+	/**
+	 * @blocked: Zero means a handoff was received without the thread
+	 * needing to block; nonzero means the thread blocked.
+	 */
+	int blocked;
+
+	/**
+	 * @wait_queue: Used to block the thread while waiting (will never
+	 * have more than one queued thread).
+	 */
+	struct wait_queue_head wait_queue;
+
+	/** @hsk: Socket that the interest is associated with. */
+	struct homa_sock *hsk;
+
+	/**
+	 * @links: If the interest is shared, used to link this object into
+	 * @hsk->interests.
+	 */
+	struct list_head links;
+};
+
+/**
+ * homa_interest_unlink_private() - Detach a private interest from its
+ * RPC. Note: this can race with homa_rpc_handoff, so on return it's
+ * possible that the interest is ready.
+ * @interest:    Interest to remove. Must have been initialized with
+ *               homa_interest_init_private. Its RPC must be locked by
+ *               the caller.
+ */
+static inline void homa_interest_unlink_private(struct homa_interest *interest)
+	__must_hold(interest->rpc->bucket->lock)
+{
+	if (interest == interest->rpc->private_interest)
+		interest->rpc->private_interest = NULL;
+}
+
+void     homa_interest_init_shared(struct homa_interest *interest,
+				   struct homa_sock *hsk);
+int      homa_interest_init_private(struct homa_interest *interest,
+				    struct homa_rpc *rpc);
+void     homa_interest_notify_private(struct homa_rpc *rpc);
+void     homa_interest_notify_shared(struct homa_sock *hsk,
+				     struct homa_rpc *rpc);
+int      homa_interest_wait(struct homa_interest *interest);
+
+#endif /* _HOMA_INTEREST_H */
diff --git a/net/homa/homa_outgoing.c b/net/homa/homa_outgoing.c
new file mode 100644
index 0000000000000..afc7c034d1453
--- /dev/null
+++ b/net/homa/homa_outgoing.c
@@ -0,0 +1,537 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file contains functions related to the sender side of message
+ * transmission. It also contains utility functions for sending packets.
+ */
+
+#include "homa_impl.h"
+#include "homa_peer.h"
+#include "homa_rpc.h"
+#include "homa_tx_pool.h"
+#include "homa_wire.h"
+
+/**
+ * homa_message_out_init() - Initialize rpc->msgout. This function doesn't
+ * read data from user space or create sk_buffs, but it sets up information
+ * such as the message geometry.
+ * @rpc:       RPC whose output message should be initialized. Must be
+ *             locked by caller. Fields in rpc->msgout should have been
+ *             zeroed by the caller.
+ * @length:    Number of bytes that will eventually be in rpc->msgout.
+ */
+void homa_message_out_init(struct homa_rpc *rpc, int length)
+	__must_hold(rpc->bucket->lock)
+{
+	struct dst_entry *dst;
+	u64 max_segs;
+	int mtu;
+
+	memset(&rpc->msgout, 0, sizeof(rpc->msgout));
+	rpc->msgout.length = length;
+	rpc->msgout.init_time = homa_clock();
+
+	/* Compute the geometry of packets. */
+	rcu_read_lock();
+	dst = rcu_dereference(rpc->route->dst);
+	mtu = dst_mtu(dst);
+	rpc->msgout.max_seg_data = mtu - rpc->hsk->ip_header_length -
+				   sizeof(struct homa_data_hdr);
+	max_segs = min_t(u32, rpc->hsk->homa->max_gso_size,
+			 dst->dev->gso_max_size) -
+		   (sizeof(struct homa_data_hdr) + HOMA_SKB_EXTRA);
+	do_div(max_segs, rpc->msgout.max_seg_data +
+			 sizeof(struct homa_seg_hdr));
+	if (max_segs > dst->dev->gso_max_segs)
+		max_segs = dst->dev->gso_max_segs;
+	if (max_segs < 1)
+		max_segs = 1;
+	rpc->msgout.max_gso_segs = max_segs;
+	rpc->msgout.max_gso_data = max_segs * rpc->msgout.max_seg_data;
+	rcu_read_unlock();
+}
+
+/**
+ * homa_tx_copy_from_user() - Copy outbound message data for an RPC from
+ * user space into kernel memory and (possibly) start transmitting packets.
+ * @rpc:      RPC whose tx message is to be copied.
+ * @iter:     Describes the location in user space of the message
+ *            data.
+ * @xmit:     True means this function should also start transmitting packets.
+ *            False means only copy data; don't transmit packets.
+ * Return:    Zero for success, otherwise a negative errno.
+ */
+int homa_tx_copy_from_user(struct homa_rpc *rpc, struct iov_iter *iter,
+			   bool xmit)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_frag_filler filler;
+	int err, hdr_space;
+	u64 num_segs;
+	int offset;
+
+	homa_message_out_init(rpc, iter->count);
+
+	/* Allocate kernel memory to hold the message data (note that we
+	 * need to allocate extra space for homa_seg_hdrs).
+	 */
+	num_segs = rpc->msgout.length + rpc->msgout.max_seg_data - 1;
+	do_div(num_segs, rpc->msgout.max_seg_data);
+	hdr_space = num_segs * sizeof(struct homa_seg_hdr);
+	rpc->msgout.frags = &rpc->msgout.frag;
+	rpc->msgout.num_frags = 1;
+	err = homa_tx_pool_alloc(rpc->hsk->homa, rpc->msgout.length + hdr_space,
+				 &rpc->msgout.num_frags, &rpc->msgout.frags);
+	if (err != 0)
+		return err;
+	rpc->msgout.frag_bytes = rpc->msgout.length + hdr_space;
+	refcount_add(rpc->msgout.frag_bytes, &rpc->hsk->sock.sk_wmem_alloc);
+
+	/* Copy the data in from user space, preceding each segment of data
+	 * with its homa_seg_hdr.
+	 */
+	homa_rpc_unlock(rpc);
+	homa_frag_filler_init(&filler, rpc->msgout.num_frags,
+			      rpc->msgout.frags);
+	offset = 0;
+	while (offset < rpc->msgout.length) {
+		int seg_size = min(rpc->msgout.length - offset,
+				   rpc->msgout.max_seg_data);
+		struct homa_seg_hdr seg_hdr;
+
+		seg_hdr.offset = htonl(offset);
+		err = homa_copy_to_frags(&filler, &seg_hdr, sizeof(seg_hdr));
+		if (unlikely(err != 0))
+			goto done;
+		err = homa_copy_iter_to_frags(&filler, iter, seg_size);
+		if (unlikely(err != 0))
+			goto done;
+		offset += seg_size;
+
+		/* Make sure that anyone seeing a change in copied_from_user
+		 * also sees related changes to rpc->msgout.
+		 */
+		smp_store_release(&rpc->msgout.copied_from_user, offset);
+	}
+
+done:
+	homa_rpc_lock(rpc);
+	if (xmit && err == 0)
+		homa_xmit_data(rpc);
+	return err;
+}
+
+/**
+ * __homa_skb_alloc() - Allocate a new (empty) sk_buff for use in transmitting
+ * data or control info.
+ * @length:       Number of bytes of data that the caller would like to
+ *                have available in the linear part of the sk_buff for
+ *                the Homa header and additional data beyond that. This
+ *                function will allocate additional space for IP and
+ *                Ethernet headers, as well as for the homa_skb_info.
+ * Return:        New sk_buff, or NULL if there was insufficient memory.
+ *                The sk_buff will be configured so that the next
+ *                skb_put will be for the transport (Homa) header. The
+ *                homa_skb_info is not initialized.
+ */
+struct sk_buff *__homa_skb_alloc(int length)
+{
+	struct sk_buff *skb;
+
+	skb = alloc_skb(HOMA_SKB_EXTRA + sizeof(struct homa_skb_info) + length,
+			GFP_ATOMIC);
+	if (likely(skb)) {
+		skb_reserve(skb, HOMA_SKB_EXTRA);
+		skb_reset_transport_header(skb);
+	}
+	return skb;
+}
+
+/**
+ * homa_tx_skb_alloc() - Create an outgoing data packet for a Homa message.
+ * @rpc:      RPC for the message. Its @msgout must have been initialized
+ *            (e.g. the packet geometry will be determined by information
+ *            in @rpc->msgout).
+ * @offset:   Offset within the message of the first byte of data for
+ *            this packet.
+ * @end:      Offset within the message of the byte just after the last
+ *            one to include in this packet. The skb may actually end either
+ *            before or after this offset; this value is modified to hold
+ *            the actual end.
+ * Return:    A pointer to the sk_buff, or a negative errno for error.
+ */
+struct sk_buff *homa_tx_skb_alloc(struct homa_rpc *rpc, u32 offset, u32 *end)
+	__must_hold(rpc->bucket->lock)
+{
+	int msg_frags_left, bytes_left, bytes_to_skip, rem;
+	struct homa_sock *hsk = rpc->hsk;
+	struct homa_skb_info *homa_info;
+	skb_frag_t *msg_frag, *skb_frag;
+	struct skb_shared_info *shinfo;
+	u64 seg_index, num_segs;
+	struct homa_data_hdr *h;
+	struct sk_buff *skb;
+	int err;
+
+	if (offset >= rpc->msgout.length)
+		return ERR_PTR(-EINVAL);
+	if (*end > rpc->msgout.length)
+		*end = rpc->msgout.length;
+
+	/* Find the location within rpc->msgin.frags of the data for the
+	 * first segment to output (skipping its homa_seg_hdr, since that
+	 * will be in the linear part of the skb). Also, round offset down
+	 * to the start of its segment.
+	 */
+	seg_index = offset;
+	rem = do_div(seg_index, rpc->msgout.max_seg_data);
+	offset -= rem;
+	bytes_to_skip = seg_index * (rpc->msgout.max_seg_data +
+				     sizeof(struct homa_seg_hdr)) +
+			sizeof(struct homa_seg_hdr);
+	for (msg_frags_left = rpc->msgout.num_frags,
+	     msg_frag = rpc->msgout.frags; ; msg_frags_left--, msg_frag++) {
+		if (bytes_to_skip < skb_frag_size(msg_frag))
+			break;
+		bytes_to_skip -= skb_frag_size(msg_frag);
+	}
+
+	/* Compute how much data from rpc->msgout.frags to include in the
+	 * packet.
+	 */
+	num_segs = *end - offset + rpc->msgout.max_seg_data - 1;
+	do_div(num_segs, rpc->msgout.max_seg_data);
+	if (num_segs > rpc->msgout.max_gso_segs)
+		num_segs = rpc->msgout.max_gso_segs;
+	bytes_left = num_segs * (rpc->msgout.max_seg_data +
+				 sizeof(struct homa_seg_hdr)) -
+		     sizeof(struct homa_seg_hdr);
+
+	skb = __homa_skb_alloc(sizeof(struct homa_data_hdr));
+	if (unlikely(!skb))
+		return ERR_PTR(-ENOMEM);
+	skb->ooo_okay = 1;
+	shinfo = skb_shinfo(skb);
+
+	/* Fill in the Homa header (which will be replicated in every
+	 * segment by GSO). The header in the linear portion contains the
+	 * homa_seg_hdr for the first fragment.
+	 */
+	h = (struct homa_data_hdr *)skb_put(skb, sizeof(struct homa_data_hdr));
+	memset(h, 0, sizeof(*h));
+	h->common.sport = htons(hsk->port);
+	h->common.dport = htons(rpc->dport);
+	h->common.type = DATA;
+	homa_set_doff(skb, sizeof(struct homa_data_hdr) -
+			   sizeof(struct homa_seg_hdr));
+	h->common.sender_id = cpu_to_be64(rpc->id);
+	h->message_length = htonl(rpc->msgout.length);
+	homa_peer_get_acks(rpc->route->peer, 1, &h->ack);
+	if (offset < rpc->msgout.next_xmit_offset)
+		h->retransmit = 1;
+	h->seg.offset = htonl(offset);
+
+	/* Virtually copy data from rpc->msgout.frags to the skb; each
+	 * iteration of the following loop copies one frag.
+	 */
+	while (bytes_left > 0 && shinfo->nr_frags < MAX_SKB_FRAGS &&
+	       msg_frags_left > 0) {
+		skb_frag_t *skb_frag = &shinfo->frags[shinfo->nr_frags];
+		struct page *page;
+		int frag_bytes;
+
+		frag_bytes = min(skb_frag_size(msg_frag) - bytes_to_skip,
+				 bytes_left);
+		page = skb_frag_page(msg_frag);
+		get_page(page);
+		skb_frag->netmem = page_to_netmem(page);
+		skb_frag->offset = msg_frag->offset + bytes_to_skip;
+		skb_frag_size_set(skb_frag, frag_bytes);
+		skb_len_add(skb, frag_bytes);
+
+		bytes_left -= frag_bytes;
+		bytes_to_skip = 0;
+		msg_frag++;
+		msg_frags_left--;
+		shinfo->nr_frags++;
+	}
+
+	if (bytes_left > 0 && msg_frags_left > 0 &&
+	    shinfo->nr_frags >= MAX_SKB_FRAGS) {
+		/* There wasn't enough fragment space in skb to store all the
+		 * desired segments. Round the skb back to the nearest segment
+		 * boundary.
+		 */
+		while (bytes_left > 0) {
+			bytes_left -= rpc->msgout.max_seg_data +
+				      sizeof(struct homa_seg_hdr);
+			num_segs--;
+		}
+		if (num_segs == 0) {
+			err = -EINVAL;
+			goto error;
+		}
+		while (bytes_left < 0) {
+			skb_frag = &shinfo->frags[shinfo->nr_frags - 1];
+			if (-bytes_left < skb_frag_size(skb_frag)) {
+				skb_frag_size_sub(skb_frag, -bytes_left);
+				skb_len_add(skb, bytes_left);
+				break;
+			}
+			bytes_left += skb_frag_size(skb_frag);
+			skb_len_add(skb, -skb_frag_size(skb_frag));
+			put_page(skb_frag_page(skb_frag));
+			shinfo->nr_frags--;
+		}
+	}
+	*end = min_t(u32, offset + num_segs * rpc->msgout.max_seg_data,
+		     rpc->msgout.length);
+
+	/* Fill in fields in shinfo. */
+	if (num_segs > 1) {
+		shinfo->gso_segs = num_segs;
+		shinfo->gso_size = rpc->msgout.max_seg_data +
+				   sizeof(struct homa_seg_hdr);
+		shinfo->gso_type = (hsk->inet.sk.sk_family ==
+				    AF_INET6) ? SKB_GSO_TCPV6 :
+				    SKB_GSO_TCPV4;
+	}
+
+	/* Initialize homa_skb_info for the packet. */
+	homa_info = homa_get_skb_info(skb);
+	memset(homa_info, 0, sizeof(*homa_info));
+	homa_info->data_bytes = *end - offset;
+	homa_info->dont_defer = false;
+	return skb;
+
+error:
+	kfree_skb_reason(skb, SKB_DROP_REASON_NOT_SPECIFIED);
+	return ERR_PTR(err);
+}
+
+/**
+ * homa_tx_skb_send() - Create and send one (GSO) data packet for an RPC. The
+ * dimensions of the packet transmitted may change from those specified
+ * in the argument depending on factors such as availability of GSO,
+ * MTU, etc.
+ * @rpc:         RPC for which to send the packet. This function releases
+ *               and then re-requires rpc's lock, so the RPC could be
+ *               dead when this function returns.
+ * @offset:      The packet must contain this offset.
+ * @end:         Offset of the message byte just after the last one
+ *               the caller would like included in the packet. Modified
+ *               to hold the offset just after the last byte actually
+ *               included in the packet.
+ * Return:       0 for success, otherwise a negative errno.
+ */
+int homa_tx_skb_send(struct homa_rpc *rpc, u32 offset, u32 *end)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_route *route;
+	struct sk_buff *skb;
+	int err;
+
+	skb = homa_tx_skb_alloc(rpc, offset, end);
+	if (IS_ERR(skb))
+		return PTR_ERR(skb);
+
+	/* Note: must update next_xmit_offset here, before releasing the
+	 * RPC lock below; otherwise some other thread might decide to
+	 * transmit the same bytes.
+	 */
+	if (*end > rpc->msgout.next_xmit_offset)
+		rpc->msgout.next_xmit_offset = *end;
+
+	err = homa_route_validate(rpc);
+	if (err != 0) {
+		kfree_skb_reason(skb, SKB_DROP_REASON_IP_OUTNOROUTES);
+		return err;
+	}
+	route = rpc->route;
+
+	/* Take a reference on the route so we can safely use it even after
+	 * the RPC lock has been released (rpc->route may change, but not
+	 * route).
+	 */
+	homa_route_hold(route);
+	homa_rpc_unlock(rpc);
+	err = homa_route_xmit(skb, rpc->hsk, route, 0);
+	homa_route_release(route);
+	homa_rpc_lock(rpc);
+	return err;
+}
+
+/**
+ * homa_xmit_control() - Send a control packet to the other end of an RPC.
+ * @type:      Packet type, such as DATA.
+ * @contents:  Address of buffer containing the contents of the packet.
+ *             Only information after the common header must be valid;
+ *             the common header will be filled in by this function.
+ * @length:    Length of @contents (including the common header).
+ * @rpc:       The packet will go to the socket that handles the other end
+ *             of this RPC. Addressing info for the packet, including all of
+ *             the fields of homa_common_hdr except type, will be set from this.
+ *
+ * Return:     Either zero (for success), or a negative errno value if there
+ *             was a problem.
+ */
+int homa_xmit_control(enum homa_packet_type type, void *contents,
+		      size_t length, struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_common_hdr *h = contents;
+	struct homa_route *route;
+	int err;
+
+	memset(h, 0, sizeof(*h));
+	h->type = type;
+	h->sport = htons(rpc->hsk->port);
+	h->dport = htons(rpc->dport);
+	h->sender_id = cpu_to_be64(rpc->id);
+	err = homa_route_validate(rpc);
+	if (err != 0)
+		return err;
+	route = rpc->route;
+
+	/* Must take a reference on route to ensure it persists through
+	 * packet transmission (rpc->route could get replaced once we
+	 * release the RPC lock).
+	 */
+	homa_route_hold(route);
+	homa_rpc_unlock(rpc);
+	err = __homa_xmit_control(contents, length, route, rpc->hsk);
+	homa_route_release(route);
+	homa_rpc_lock(rpc);
+	return err;
+}
+
+/**
+ * __homa_xmit_control() - Lower-level version of homa_xmit_control: sends
+ * a control packet.
+ * @contents:  Address of buffer containing the contents of the packet.
+ *             The caller must have filled in all of the information,
+ *             including the common header.
+ * @length:    Length of @contents.
+ * @route:     Route via which to send packet (includes destination).
+ * @hsk:       Socket via which the packet will be sent.
+ *
+ * Return:     Either zero (for success), or a negative errno value if there
+ *             was a problem.
+ */
+int __homa_xmit_control(void *contents, size_t length, struct homa_route *route,
+			struct homa_sock *hsk)
+{
+	struct homa_common_hdr *h;
+	struct sk_buff *skb;
+	int extra_bytes;
+	int err;
+
+	skb = __homa_skb_alloc(HOMA_MAX_HEADER);
+	if (unlikely(!skb))
+		return -ENOBUFS;
+
+	h = skb_put(skb, length);
+	memcpy(h, contents, length);
+	extra_bytes = HOMA_MIN_PKT_LENGTH - length;
+	if (extra_bytes > 0)
+		memset(skb_put(skb, extra_bytes), 0, extra_bytes);
+	skb->ooo_okay = 1;
+	homa_set_doff(skb, 20);
+	err = homa_route_xmit(skb, hsk, route, 0);
+	return err;
+}
+
+/**
+ * homa_xmit_unknown() - Send an RPC_UNKNOWN packet to a peer.
+ * @skb:         Buffer containing an incoming packet; identifies the peer to
+ *               which the RPC_UNKNOWN packet should be sent.
+ * @hsk:         Socket that should be used to send the RPC_UNKNOWN packet.
+ */
+void homa_xmit_unknown(struct sk_buff *skb, struct homa_sock *hsk)
+{
+	struct homa_common_hdr *h = (struct homa_common_hdr *)skb->data;
+	struct in6_addr saddr = skb_canonical_ipv6_saddr(skb);
+	struct homa_rpc_unknown_hdr unknown;
+	struct homa_route *route;
+
+	memset(&unknown, 0, sizeof(unknown));
+	unknown.common.sport = h->dport;
+	unknown.common.dport = h->sport;
+	unknown.common.type = RPC_UNKNOWN;
+	unknown.common.sender_id = cpu_to_be64(homa_local_id(h->sender_id));
+	route = homa_route_get(hsk, &saddr);
+	if (!IS_ERR(route)) {
+		__homa_xmit_control(&unknown, sizeof(unknown), route, hsk);
+		homa_route_release(route);
+	}
+}
+
+/**
+ * homa_xmit_data() - If an RPC has outbound data packets that are permitted
+ * to be transmitted according to the scheduling mechanism, arrange for
+ * them to be sent.
+ * @rpc:       RPC to check for transmittable packets. Must be locked by
+ *             caller.
+ */
+void homa_xmit_data(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	u32 xmit_offset, end;
+
+	while (rpc->state != RPC_DEAD) {
+		xmit_offset = rpc->msgout.next_xmit_offset;
+
+		/* Don't transmit unless enough data has been copied from user
+		 * space for a maximum-size packet.
+		 */
+		if (xmit_offset + rpc->msgout.max_gso_data >
+		    rpc->msgout.copied_from_user &&
+		    rpc->msgout.copied_from_user < rpc->msgout.length)
+			break;
+
+		if (xmit_offset >= rpc->msgout.length)
+			break;
+		end = rpc->msgout.length;
+		homa_tx_skb_send(rpc, xmit_offset, &end);
+	}
+}
+
+/**
+ * homa_resend_data() - This function is invoked as part of handling RESEND
+ * requests. It retransmits the packet(s) containing a given range of bytes
+ * from a message.
+ * @rpc:      RPC for which data should be resent. Must be locked by caller.
+ * @start:    Offset within @rpc->msgout of the first byte to retransmit.
+ * @end:      Offset within @rpc->msgout of the byte just after the last one
+ *            to retransmit.
+ * Return:    0 for success, otherwise a negative errno.
+ */
+int homa_resend_data(struct homa_rpc *rpc, int start, int end)
+	__must_hold(rpc->bucket->lock)
+{
+	u32 offset, pkt_end;
+	int err = 0;
+
+	for (offset = start; offset < end; offset = pkt_end) {
+		pkt_end = end;
+		err = homa_tx_skb_send(rpc, offset, &pkt_end);
+		if (err != 0)
+			break;
+		if (rpc->state == RPC_DEAD)
+			break;
+	}
+	return err;
+}
+
+/**
+ * homa_rpc_tx_end() - Return the offset of the first byte in an
+ * RPC's outgoing message that has not (with high probability) been
+ * passed to the NIC (i.e. offsets beyond this point have not been
+ * passed to ip*xmit or are deferred in homa_qdisc).
+ * @rpc:    RPC to check
+ * Return:  See above. If the message has been fully transmitted then
+ *          rpc->msgout.length is returned.
+ */
+int homa_rpc_tx_end(struct homa_rpc *rpc)
+{
+	return rpc->msgout.next_xmit_offset;
+}
diff --git a/net/homa/homa_peer.c b/net/homa/homa_peer.c
new file mode 100644
index 0000000000000..e387a399299bd
--- /dev/null
+++ b/net/homa/homa_peer.c
@@ -0,0 +1,669 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file provides functions related to homa_peer, homa_route, and
+ * homa_peertab objects.
+ */
+
+#include "homa_impl.h"
+#include "homa_peer.h"
+#include "homa_rpc.h"
+
+#include <linux/xxhash.h>
+
+/* Wrapper to allow xxhash to be used as rhashtable hash function. */
+static u32 xxh32_hash(const void *data, u32 len, u32 seed)
+{
+	return xxh32(data, len, seed);
+}
+
+const struct rhashtable_params peer_ht_params = {
+	.key_len     = sizeof(struct homa_peer_key),
+	.key_offset  = offsetof(struct homa_peer, ht_key),
+	.head_offset = offsetof(struct homa_peer, ht_linkage),
+	.nelem_hint = 10000,
+	.hashfn = xxh32_hash,
+	.obj_cmpfn = homa_peer_compare
+};
+
+const struct rhashtable_params route_ht_params = {
+	.key_len     = sizeof(struct homa_route_key),
+	.key_offset  = offsetof(struct homa_route, key),
+	.head_offset = offsetof(struct homa_route, ht_linkage),
+	.nelem_hint = 10000,
+	.hashfn = xxh32_hash
+};
+
+/**
+ * homa_peer_alloc_peertab() - Allocate and initialize a homa_peertab.
+ *
+ * Return:    A pointer to the new homa_peertab, or ERR_PTR(-errno) if there
+ *            was a problem.
+ */
+struct homa_peertab *homa_peer_alloc_peertab(void)
+{
+	struct homa_peertab *peertab;
+	int err;
+
+	peertab = kzalloc_obj(*peertab, GFP_KERNEL);
+	if (!peertab)
+		return ERR_PTR(-ENOMEM);
+
+	spin_lock_init(&peertab->lock);
+	err = rhashtable_init(&peertab->peer_ht, &peer_ht_params);
+	if (err)
+		goto error;
+	err = rhashtable_init(&peertab->route_ht, &route_ht_params);
+	if (err) {
+		rhashtable_destroy(&peertab->peer_ht);
+		goto error;
+	}
+	peertab->route_ht_valid = true;
+	rhashtable_walk_enter(&peertab->route_ht, &peertab->route_ht_iter);
+	peertab->gc_threshold = 5000;
+	peertab->net_max = 10000;
+	peertab->idle_secs_min = 10;
+	peertab->idle_secs_max = 120;
+
+	homa_peer_update_sysctl_deps(peertab);
+	return peertab;
+
+error:
+	homa_peer_free_peertab(peertab);
+	return ERR_PTR(err);
+}
+
+/**
+ * homa_peer_free_net() - Garbage collect all of the peer information
+ * associated with a particular network namespace.
+ * @hnet:    Network namespace whose peers should be freed. There must not
+ *           be any active sockets or RPCs for this namespace.
+ */
+void homa_peer_free_net(struct homa_net *hnet)
+{
+	struct homa_peertab *peertab = hnet->homa->peertab;
+	struct rhashtable_iter iter;
+	struct homa_route *route;
+
+	spin_lock_bh(&peertab->lock);
+	rhashtable_walk_enter(&peertab->route_ht, &iter);
+	rhashtable_walk_start(&iter);
+	while (1) {
+		route = rhashtable_walk_next(&iter);
+		if (!route)
+			break;
+		if (IS_ERR(route))
+			continue;
+		if (route->key.hnet != hnet)
+			continue;
+		if (rhashtable_remove_fast(&peertab->route_ht,
+					   &route->ht_linkage,
+					   route_ht_params) == 0) {
+			homa_route_release(route);
+			hnet->num_routes--;
+			peertab->num_routes--;
+		}
+	}
+	rhashtable_walk_stop(&iter);
+	rhashtable_walk_exit(&iter);
+	WARN(hnet->num_routes != 0, "%s ended up with hnet->num_routes %d",
+	     __func__, hnet->num_routes);
+	spin_unlock_bh(&peertab->lock);
+}
+
+/**
+ * homa_route_delete_fn() - This function is invoked for each entry in
+ * the route_ht hash table by the rhashtable code when the table is being
+ * deleted. It frees its argument.
+ * @object:     homa_peer to free.
+ * @dummy:      Not used.
+ */
+void homa_route_delete_fn(void *object, void *dummy)
+	__must_hold(((struct homa_route *)object)->key.hnet->homa->peertab->lock)
+{
+	struct homa_route *route = object;
+
+	/* Must unlink from the peer here (peertab is going away so
+	 * it won't be safe to do it later, if the reference count doesn't
+	 * drop to zero here).
+	 */
+	homa_peer_unlink(route);
+	homa_route_release(route);
+}
+
+/**
+ * homa_peer_free_peertab() - Destructor for homa_peertabs.
+ * @peertab:  The table to destroy. Caller must ensure that it will never
+ *            be accessed again.
+ */
+void homa_peer_free_peertab(struct homa_peertab *peertab)
+{
+	if (peertab->route_ht_valid) {
+		rhashtable_walk_exit(&peertab->route_ht_iter);
+		rhashtable_free_and_destroy(&peertab->route_ht,
+					    homa_route_delete_fn,
+					    NULL);
+		rcu_barrier();
+		rhashtable_destroy(&peertab->peer_ht);
+		peertab->route_ht_valid = false;
+	}
+	kfree(peertab);
+}
+
+/**
+ * homa_peer_alloc() - Allocate and initialize a new homa_peer object.
+ * @hsk:        Socket for which the peer will be used.
+ * @addr:       Address of the desired host: IPv4 addresses are represented
+ *              as IPv4-mapped IPv6 addresses.
+ * Return:      The peer associated with @addr, or a negative errno if an
+ *              error occurred. On a successful return the reference count
+ *              will be incremented for the returned peer. Sets hsk->error_msg
+ *              on errors.
+ */
+struct homa_peer *homa_peer_alloc(struct homa_sock *hsk,
+				  const struct in6_addr *addr)
+{
+	struct homa_peer *peer;
+
+	peer = kzalloc_obj(*peer, GFP_ATOMIC);
+	if (!peer) {
+		hsk->error_msg = "couldn't allocate memory for homa_peer";
+		return (struct homa_peer *)ERR_PTR(-ENOMEM);
+	}
+	peer->ht_key.addr = *addr;
+	peer->ht_key.hnet = hsk->hnet;
+	refcount_set(&peer->refs, 1);
+	spin_lock_init(&peer->lock);
+
+	return peer;
+}
+
+/**
+ * homa_peer_free() - Release any resources in a peer and free the homa_peer
+ * struct.
+ * @peer:   Peer to free. The @refs field must be zero (this also implies
+ *          for example, that the peer is not on any lists and
+ *          peer->grantable_rpcs is empty).
+ */
+void homa_peer_free(struct homa_peer *peer)
+{
+	kfree(peer);
+}
+
+/**
+ * homa_peer_get() - Returns the peer associated with a given host; creates
+ * a new homa_peer if one doesn't already exist.
+ * @hsk:        Socket where the peer will be used.
+ * @addr:       Address of the desired host: IPv4 addresses are represented
+ *              as IPv4-mapped IPv6 addresses.
+ *
+ * Return:      The peer associated with @addr, or a negative errno if an
+ *              error occurred. On a successful return the reference count
+ *              will be incremented for the returned peer. The caller must
+ *              eventually call homa_peer_release to release the reference.
+ */
+struct homa_peer *homa_peer_get(struct homa_sock *hsk,
+				const struct in6_addr *addr)
+	__must_hold(hsk->homa->peertab->lock)
+{
+	struct homa_peertab *peertab = hsk->homa->peertab;
+	struct homa_peer_key key;
+	struct homa_peer *peer;
+	int status;
+
+	key.addr = *addr;
+	key.hnet = hsk->hnet;
+
+	/* Fast path: use existing entry if it exists. */
+	peer = rhashtable_lookup(&peertab->peer_ht, &key, peer_ht_params);
+	if (peer) {
+		refcount_inc(&peer->refs);
+		return peer;
+	}
+
+	/* No existing entry, so we have to create a new one. */
+	peer = homa_peer_alloc(hsk, addr);
+	if (IS_ERR(peer))
+		return peer;
+	status = rhashtable_lookup_insert_fast(&peertab->peer_ht,
+					       &peer->ht_linkage,
+					       peer_ht_params);
+	if (status != 0) {
+		pr_err("homa_peer_get received unexpected error return from rhashtable_lookup_insert_fast");
+		hsk->error_msg = "unexpected error return from rhashtable_lookup_insert_fast";
+		homa_peer_free(peer);
+		return ERR_PTR(status);
+	}
+	return peer;
+}
+
+/**
+ * homa_route_alloc() - Allocate and initialize a new homa_route.
+ * object.
+ * @hsk:       Socket for which the homa_route will be used.
+ * @key:       Key that will be used for this entry in peertab->route_ht.
+ *             Contains the destination address and other information needed
+ *             to create a flowi and a dst_entry.
+ * Return:     A new homa_route corresdponding to @hsk and @key, or a
+ *             negative errno if an error occurred. Sets hsk->error_msg on
+ *             errors. On success, all fields have been initialized except
+ *             @peer; the route has not been inserted in route_ht and its
+ *             reference count will be one.
+ */
+struct homa_route *homa_route_alloc(struct homa_sock *hsk,
+				    const struct homa_route_key *key)
+{
+	struct homa_route *route;
+	struct dst_entry *dst;
+	int err;
+
+	route = kzalloc_obj(*route, GFP_ATOMIC);
+	if (!route) {
+		hsk->error_msg = "couldn't allocate memory for homa_route";
+		return ERR_PTR(-ENOMEM);
+	}
+	spin_lock_init(&route->lock);
+	refcount_set(&route->refs, 1);
+	route->access_jiffies = jiffies;
+	route->key = *key;
+
+	/* Find a dst_entry to use for this route. */
+	route->flow.flowi_secid = key->secid;
+	if (ipv6_addr_v4mapped(&route->key.daddr)) {
+		struct rtable *rt;
+
+		flowi4_init_output(&route->flow.u.ip4, key->bound_dev_if,
+				   key->mark, 0, RT_SCOPE_UNIVERSE,
+				   IPPROTO_HOMA, 0,
+				   ipv6_to_ipv4(route->key.daddr),
+				   ipv6_to_ipv4(route->key.saddr), 0, 0,
+				   key->uid);
+		rt = ip_route_output_flow(sock_net(&hsk->sock),
+					  &route->flow.u.ip4, &hsk->sock);
+		if (IS_ERR(rt)) {
+			err = PTR_ERR(rt);
+			goto error;
+		}
+		rcu_assign_pointer(route->dst, &rt->dst);
+	} else {
+		/* This code is derived from code in tcp_v6_connect. */
+		route->flow.u.ip6.flowi6_proto = IPPROTO_HOMA;
+		route->flow.u.ip6.daddr = route->key.daddr;
+		route->flow.u.ip6.saddr = route->key.saddr;
+		route->flow.u.ip6.flowlabel = ip6_make_flowinfo(0, 0);
+		route->flow.u.ip6.flowi6_oif = key->bound_dev_if;
+		route->flow.u.ip6.flowi6_mark = key->mark;
+		route->flow.u.ip6.fl6_dport = 0;
+		route->flow.u.ip6.fl6_sport = 0;
+		route->flow.u.ip6.flowi6_uid = key->uid;
+		dst = ip6_dst_lookup_flow(sock_net(&hsk->sock), &hsk->sock,
+						   &route->flow.u.ip6, NULL);
+		rcu_assign_pointer(route->dst, dst);
+
+		if (IS_ERR(route->dst)) {
+			err = PTR_ERR(route->dst);
+			goto error;
+		}
+		route->dst_cookie = rt6_get_cookie(dst_rt6_info(dst));
+	}
+	return route;
+error:
+	hsk->error_msg = "couldn't find route for peer";
+	kfree(route);
+	return ERR_PTR(err);
+}
+
+/**
+ * homa_route_free() - Release any resources in a homa_route and
+ * free the object's memory. May be invoked either as an RCU callback
+ * or directly (if invoked directly, caller must ensure exclusive
+ * access to the object, e.g. it was never actually published in
+ * route_ht).
+ * @head:     @rcu_head field  in the route to free.
+ */
+void homa_route_free(struct rcu_head *head)
+{
+	struct homa_route *route;
+
+	route = container_of(head, struct homa_route, rcu_head);
+	dst_release(rcu_dereference_protected(route->dst, 1));
+	spin_lock_bh(&route->key.hnet->homa->peertab->lock);
+	homa_peer_unlink(route);
+	spin_unlock_bh(&route->key.hnet->homa->peertab->lock);
+	kfree(route);
+}
+
+/**
+ * homa_route_get() - Returns a homa_route object that can be
+ * used to communicate with a given host over a given socket. Indirectly
+ * provides access to a homa_peer object for @addr.
+ * @hsk:        Socket where the peer will be used.
+ * @addr:       Address of the desired host: IPv4 addresses are represented
+ *              as IPv4-mapped IPv6 addresses.
+ *
+ * Return:      The homa_route associated with @addr, or a negative
+ *              errno if an error occurred. On a successful return the
+ *              reference count will be incremented for the returned object.
+ *              The caller must eventually call homa_peer_route_release to
+ *              release the reference.
+ */
+struct homa_route *homa_route_get(struct homa_sock *hsk,
+				  const struct in6_addr *addr)
+{
+	struct homa_peertab *peertab = hsk->homa->peertab;
+	struct homa_route *route, *other;
+	struct homa_route_key route_key;
+	struct homa_peer *peer;
+
+	/* See if we already have a suitable route cached. */
+	rcu_read_lock();
+	homa_route_key_init(&route_key, hsk, addr);
+	route = rhashtable_lookup(&peertab->route_ht, &route_key,
+				  route_ht_params);
+	if (route && refcount_inc_not_zero(&route->refs)) {
+		route->access_jiffies = jiffies;
+		rcu_read_unlock();
+		return route;
+	}
+
+	/* No existing entry, so we have to create a new one. Switch from
+	 * RCU to real locking for this.
+	 */
+	rcu_read_unlock();
+	route = homa_route_alloc(hsk, &route_key);
+	if (IS_ERR(route))
+		return route;
+
+	spin_lock_bh(&peertab->lock);
+	peer = homa_peer_get(hsk, addr);
+	if (IS_ERR(peer)) {
+		spin_unlock_bh(&peertab->lock);
+		homa_route_free(&route->rcu_head);
+		route = ERR_PTR(PTR_ERR(peer));
+		return route;
+	}
+	route->peer = peer;
+
+	/* Insert the new entry in the flow table. It's possible that
+	 * someone else already created the entry concurrently.
+	 */
+	other = rhashtable_lookup_get_insert_fast(&peertab->route_ht,
+						  &route->ht_linkage,
+						  route_ht_params);
+	if (IS_ERR(other)) {
+		/* Couldn't insert; return the error info. */
+		hsk->error_msg = "rhashtable_lookup_get_insert_key failed in homa_route_get";
+		spin_unlock_bh(&peertab->lock);
+		homa_route_free(&route->rcu_head);
+		route = other;
+	} else if (other) {
+		/* Someone else already created the desired object; use that
+		 * one instead of ours.
+		 */
+		refcount_inc(&other->refs);
+		spin_unlock_bh(&peertab->lock);
+		homa_route_free(&route->rcu_head);
+		route = other;
+		route->access_jiffies = jiffies;
+	} else {
+		/* The new object was inserted in the hash table. */
+		refcount_inc(&route->refs);
+		peertab->num_routes++;
+		route_key.hnet->num_routes++;
+		spin_unlock_bh(&peertab->lock);
+	}
+	return route;
+}
+
+/**
+ * homa_route_validate() - Check to be sure that the information in the
+ * route for an RPC is still valid; if not, try to allocate a new route
+ * for the RPC.
+ * @rpc:    RPC whose routing information should be checked.
+ * Return:  Zero for success, or a negative errno if the route was invalid
+ *          and no new route could be created.
+ */
+int homa_route_validate(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_route *route, *old;
+	struct dst_entry *dst;
+
+	old = rpc->route;
+	rcu_read_lock();
+	dst = rcu_dereference_protected(old->dst, 1);
+	rcu_read_unlock();
+	if (!dst_check(dst, rpc->route->dst_cookie)) {
+		struct homa_peertab *peertab = rpc->hsk->homa->peertab;
+
+		/* Existing route is no longer valid; remove it from
+		 * the hash table and try to create a new one.
+		 */
+		spin_lock_bh(&peertab->lock);
+		if (rhashtable_remove_fast(&peertab->route_ht, &old->ht_linkage,
+					   route_ht_params) == 0) {
+			homa_route_release(old);
+			peertab->num_routes--;
+			old->key.hnet->num_routes--;
+		}
+		spin_unlock_bh(&peertab->lock);
+		route = homa_route_get(rpc->hsk, &rpc->route->peer->addr);
+		if (IS_ERR(route))
+			return PTR_ERR(route);
+		old = xchg(&rpc->route, route);
+		homa_route_release(old);
+	}
+	return 0;
+}
+
+/**
+ * homa_route_gc() - This function is invoked by Homa at regular intervals;
+ * its job is to ensure that the number of routes stays within limits. If
+ * the number grows too large, it selectively deletes routes (and peers)
+ * to get back under the limit.
+ * @peertab:   Structure to garbage-collect.
+ */
+void homa_route_gc(struct homa_peertab *peertab)
+{
+#define EVICT_BATCH_SIZE 5
+	struct homa_route *victims[EVICT_BATCH_SIZE];
+	int num_victims;
+	int i;
+
+	spin_lock_bh(&peertab->lock);
+	if (peertab->num_routes < peertab->gc_threshold)
+		goto done;
+	num_victims = homa_route_pick_victims(peertab, victims,
+					      EVICT_BATCH_SIZE);
+	if (num_victims == 0)
+		goto done;
+
+	for (i = 0; i < num_victims; i++) {
+		struct homa_route *route = victims[i];
+
+		if (rhashtable_remove_fast(&peertab->route_ht,
+					   &route->ht_linkage,
+					   route_ht_params) == 0) {
+			peertab->num_routes--;
+			route->key.hnet->num_routes--;
+			homa_route_release(route);
+		}
+	}
+done:
+	spin_unlock_bh(&peertab->lock);
+}
+
+/**
+ * homa_route_pick_victims() - Select a few routes that can be freed.
+ * @peertab:      Choose routes that are stored here.
+ * @victims:      Return addresses of victims here.
+ * @max_victims:  Limit on how many victims to choose (and size of @victims
+ *                array).
+ * Return:        The number of routes stored in @victims; may be zero.
+ */
+int homa_route_pick_victims(struct homa_peertab *peertab,
+			    struct homa_route *victims[], int max_victims)
+{
+	struct homa_route *route;
+	int num_victims = 0;
+	int to_scan;
+	int i, idle;
+
+	/* Scan 2 routes for every potential victim and keep the "best"
+	 * routes for removal.
+	 */
+	rhashtable_walk_start(&peertab->route_ht_iter);
+	for (to_scan = 2 * max_victims; to_scan > 0; to_scan--) {
+		route = rhashtable_walk_next(&peertab->route_ht_iter);
+		if (!route) {
+			/* Reached the end of the table; restart at
+			 * the beginning.
+			 */
+			rhashtable_walk_stop(&peertab->route_ht_iter);
+			rhashtable_walk_exit(&peertab->route_ht_iter);
+			rhashtable_walk_enter(&peertab->peer_ht,
+					      &peertab->route_ht_iter);
+			rhashtable_walk_start(&peertab->route_ht_iter);
+			route = rhashtable_walk_next(&peertab->route_ht_iter);
+			if (!route)
+				break;
+		}
+		if (IS_ERR(route)) {
+			/* rhashtable decided to restart the search at the
+			 * beginning.
+			 */
+			route = rhashtable_walk_next(&peertab->route_ht_iter);
+			if (!route || IS_ERR(route))
+				break;
+		}
+
+		/* Has this route been idle long enough to be candidate for
+		 * eviction?
+		 */
+		idle = jiffies - route->access_jiffies;
+		if (idle < peertab->idle_jiffies_min)
+			continue;
+		if (idle < peertab->idle_jiffies_max &&
+		    route->key.hnet->num_routes <= peertab->net_max)
+			continue;
+
+		/* Sort the candidate into the existing list of victims. */
+		for (i = 0; i < num_victims; i++) {
+			if (route == victims[i]) {
+				/* This can happen if there aren't very many
+				 * routes and we wrapped around in the hash
+				 * table.
+				 */
+				route = NULL;
+				break;
+			}
+			if (homa_route_prefer_evict(peertab, route, victims[i]))
+				swap(route, victims[i]);
+		}
+
+		if (num_victims < max_victims && route) {
+			victims[num_victims] = route;
+			num_victims++;
+		}
+	}
+	rhashtable_walk_stop(&peertab->route_ht_iter);
+	return num_victims;
+}
+
+/**
+ * homa_route_prefer_evict() - Given two routes, determine which one is
+ * a better candidate for eviction.
+ * @peertab:    Overall information used to manage routes.
+ * @route1:     First route.
+ * @route2:     Second route.
+ * Return:      True if @route1 is a better candidate for eviction than @route2.
+ */
+int homa_route_prefer_evict(struct homa_peertab *peertab,
+			    struct homa_route *route1,
+			    struct homa_route *route2)
+{
+	/* Prefer a route whose homa_net is over its limit; if both are either
+	 * over or under, then prefer the route with the longest idle time.
+	 */
+	if (route1->key.hnet->num_routes > peertab->net_max) {
+		if (route2->key.hnet->num_routes <= peertab->net_max)
+			return true;
+		else
+			return time_before(route1->access_jiffies,
+					   route2->access_jiffies);
+	}
+	if (route2->key.hnet->num_routes > peertab->net_max)
+		return false;
+	else
+		return time_before(route1->access_jiffies,
+				   route2->access_jiffies);
+}
+
+/**
+ * homa_peer_add_ack() - Add a given RPC to the list of unacked
+ * RPCs for its server. Once this method has been invoked, it's safe
+ * to delete the RPC, since it will eventually be acked to the server.
+ * @rpc:    Client RPC that has now completed. Must be locked by caller.
+ */
+void homa_peer_add_ack(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_peer *peer = rpc->route->peer;
+	struct homa_ack_hdr ack;
+
+	homa_peer_lock(peer);
+	if (peer->num_acks < HOMA_MAX_ACKS_PER_PKT) {
+		peer->acks[peer->num_acks].client_id = cpu_to_be64(rpc->id);
+		peer->acks[peer->num_acks].server_port = htons(rpc->dport);
+		peer->num_acks++;
+		homa_peer_unlock(peer);
+		return;
+	}
+
+	/* The peer has filled up; send an ACK message to empty it. The
+	 * RPC in the message header will also be considered ACKed.
+	 */
+	memcpy(ack.acks, peer->acks, sizeof(peer->acks));
+	ack.num_acks = htons(peer->num_acks);
+	peer->num_acks = 0;
+	homa_peer_unlock(peer);
+	homa_xmit_control(ACK, &ack, sizeof(ack), rpc);
+}
+
+/**
+ * homa_peer_get_acks() - Copy acks out of a peer, and remove them from the
+ * peer.
+ * @peer:    Peer to check for possible unacked RPCs.
+ * @count:   Maximum number of acks to return.
+ * @dst:     The acks are copied to this location.
+ *
+ * Return:   The number of acks extracted from the peer (<= count).
+ */
+int homa_peer_get_acks(struct homa_peer *peer, int count, struct homa_ack *dst)
+{
+	/* Don't waste time acquiring the lock if there are no ids available. */
+	if (peer->num_acks == 0)
+		return 0;
+
+	homa_peer_lock(peer);
+
+	if (count > peer->num_acks)
+		count = peer->num_acks;
+	memcpy(dst, &peer->acks[peer->num_acks - count],
+	       count * sizeof(peer->acks[0]));
+	peer->num_acks -= count;
+
+	homa_peer_unlock(peer);
+	return count;
+}
+
+/**
+ * homa_peer_update_sysctl_deps() - Update any peertab fields that depend
+ * on values set by sysctl. This function is invoked anytime a peer sysctl
+ * value is updated.
+ * @peertab:   Struct to update.
+ */
+void homa_peer_update_sysctl_deps(struct homa_peertab *peertab)
+{
+	peertab->idle_jiffies_min = peertab->idle_secs_min * HZ;
+	peertab->idle_jiffies_max = peertab->idle_secs_max * HZ;
+}
diff --git a/net/homa/homa_peer.h b/net/homa/homa_peer.h
new file mode 100644
index 0000000000000..a0c80997ce199
--- /dev/null
+++ b/net/homa/homa_peer.h
@@ -0,0 +1,457 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file contains definitions related to managing peers and routes
+ * (homa_peer, homa_route, homa_peertab).
+ */
+
+#ifndef _HOMA_PEER_H
+#define _HOMA_PEER_H
+
+#include "homa_wire.h"
+#include "homa_sock.h"
+
+#include <linux/rhashtable.h>
+
+struct homa_rpc;
+
+/**
+ * struct homa_peertab - Stores homa_peer and homa_route objects. There is
+ * one of these per struct homa.
+ */
+struct homa_peertab {
+	/**
+	 * @lock: Used to synchronize updates to @peer_ht, @route_ht, as well
+	 * as other operations on this object.
+	 */
+	spinlock_t lock;
+
+	/** @peer_ht: Hash table that stores struct peers. */
+	struct rhashtable peer_ht;
+
+	/**
+	 * @route_ht:  Hash table that stores homa_peer_flow objects.
+	 * There can be multiple entries in this table for each peer.
+	 */
+	struct rhashtable route_ht;
+
+	/**
+	 * @route_ht_iter: Used to scan route_ht to find routes to garbage
+	 * collect.
+	 */
+	struct rhashtable_iter route_ht_iter;
+
+	/** @num_routes: Total number of objects currently in @route_ht. */
+	int num_routes;
+
+	/**
+	 * @route_ht_valid: True means route_ht has been initialized and must
+	 * eventually be destroyed (it also means peer_ht has been initialized).
+	 */
+	bool route_ht_valid;
+
+	/**
+	 * @gc_stop_count: Nonzero means that route garbage collection
+	 * should not be performed (conflicting state changes are underway).
+	 */
+	int gc_stop_count;
+
+	/**
+	 * @gc_threshold: If @num_routes is less than this, don't bother
+	 * doing any peer garbage collection. Set externally via sysctl.
+	 */
+	int gc_threshold;
+
+	/**
+	 * @net_max: If the number of peers for a homa_net exceeds this number,
+	 * work aggressively to reclaim peers for that homa_net. Set
+	 * externally via sysctl.
+	 */
+	int net_max;
+
+	/**
+	 * @idle_secs_min: A peer will not be considered for garbage collection
+	 * under any circumstances if it has been idle less than this many
+	 * seconds. Set externally via sysctl.
+	 */
+	int idle_secs_min;
+
+	/**
+	 * @idle_jiffies_min: Same as idle_secs_min except in units
+	 * of jiffies.
+	 */
+	int idle_jiffies_min;
+
+	/**
+	 * @idle_secs_max: A peer that has been idle for less than
+	 * this many seconds will not be considered for garbage collection
+	 * unless its homa_net has more than @net_threshold peers. Set
+	 * externally via sysctl.
+	 */
+	int idle_secs_max;
+
+	/**
+	 * @idle_jiffies_max: Same as idle_secs_max except in units
+	 * of jiffies.
+	 */
+	int idle_jiffies_max;
+
+	/** @rcu_head: Holds state of a pending call_rcu invocation. */
+	struct rcu_head rcu_head;
+};
+
+/**
+ * struct homa_peer_key - Used to look up homa_peer structs in homa_peertab->peer_ht.
+ */
+struct homa_peer_key {
+	/**
+	 * @addr: Address of the desired host. IPv4 addresses are represented
+	 * with IPv4-mapped IPv6 addresses. Must be the first variable in
+	 * the struct, because of union in homa_peer.
+	 */
+	struct in6_addr addr;
+
+	/** @hnet: The network namespace in which this peer is valid. */
+	struct homa_net *hnet;
+};
+
+/**
+ * struct homa_peer - One of these objects exists for each machine that we
+ * have communicated with (either as client or server). This struct contains
+ * information that is common to all uses of the peer.
+ */
+struct homa_peer {
+	union {
+		/**
+		 * @addr: IPv6 address for the machine (IPv4 addresses are
+		 * stored as IPv4-mapped IPv6 addresses).
+		 */
+		struct in6_addr addr;
+
+		/** @ht_key: The hash table key for this peer in peertab->peer_ht. */
+		struct homa_peer_key ht_key;
+	};
+
+	/**
+	 * @refs: Number of outstanding references to this peer. Does *not*
+	 * include a reference for the entry in peertab->peer_ht. The peer
+	 * can be freed when this value becomes zero.
+	 */
+	refcount_t refs;
+
+	/**
+	 * @ht_linkage: Used by rashtable implement to link this peer into
+	 * peertab->peer_ht.
+	 */
+	struct rhash_head ht_linkage;
+
+	/**
+	 * @lock: used to synchronize access to fields in this struct, such
+	 * as @num_acks, @acks, @dst, and @dst_cookie.
+	 */
+	spinlock_t lock ____cacheline_aligned_in_smp;
+
+	/**
+	 * @num_acks: the number of (initial) entries in @acks that
+	 * currently hold valid information.
+	 */
+	int num_acks;
+
+	/**
+	 * @acks: info about client RPCs whose results have been completely
+	 * received.
+	 */
+	struct homa_ack acks[HOMA_MAX_ACKS_PER_PKT];
+
+};
+
+/**
+ * struct homa_route_key - Used to look up homa_route structs in
+ * homa_peertab_route_ht. These fields represent all of the information
+ * that could impact the choice of a particular struct dst_entry.
+ */
+struct homa_route_key {
+	/**
+	 * @saddr: Source network address. IPv4 addresses are represented
+	 * with IPv4-mapped IPv6 addresses.
+	 */
+	struct in6_addr saddr;
+	/**
+	 * @daddr: Destination network address. IPv4 addresses are represented
+	 * with IPv4-mapped IPv6 addresses.
+	 */
+	struct in6_addr daddr;
+
+	/**
+	 * @hnet: The network namespace in which this route is valid. This
+	 * needs to be a homa_hnet pointer, not just struct net, in order
+	 * to access homa_hnet->num_routes.
+	 */
+	struct homa_net *hnet;
+
+	/**
+	 * @sk_policy_out: sk->sk_policy[XFRM_POLICY_OUT]: uniquely
+	 * determines IPsec policy, if any.
+	 */
+	struct xfrm_policy *sk_policy_out;
+
+	/** @uid: sock->sk_sk_uid */
+	kuid_t uid;
+
+	/** @mark: sock->sk_mark */
+	u32 mark;
+
+	/** @secid: flowic.secid produced by security_sk_classify_flow. */
+	u32 secid;
+
+	/** @bound_dev_if: sock->sk_bound_dev_if */
+	int bound_dev_if;
+};
+
+/**
+ * struct homa_route - Holds a dst_entry for communicating with a
+ * particular peer, as well as information needed to cache the dst_entry
+ * and share it for multiple RPCs. There can be more than one of these
+ * objects per peer, which have different homa_route_keys.
+ */
+struct homa_route {
+	/**
+	 * @lock: used to synchronize uypdates to this struct.
+	 */
+	spinlock_t lock;
+
+	/**
+	 * @refs: Number of outstanding references to this object. Includes
+	 * one reference for the entry in peertab->route_ht, plus one for each
+	 * call to homa_route_get that has not been canceled by a call to
+	 * homa_peer_route_release; the object will be freed (via RCU) when
+	 * this count becomes zero.
+	 */
+	refcount_t refs;
+
+	/**
+	 * @access_jiffies: Time in jiffies of most recent access to this
+	 * object; used for garbage collection.
+	 */
+	unsigned long access_jiffies;
+
+	/** @key: Identifies this entry in peertab->route_ht. */
+	struct homa_route_key key;
+
+	/**
+	 * @peer: Peer with which this route is associated. This object holds a
+	 * reference on the peer.
+	 */
+	struct homa_peer *peer;
+
+	/**
+	 * @dst: Used to route packets to this peer; this object owns a
+	 * reference that must eventually be released.
+	 */
+	struct dst_entry __rcu *dst;
+
+	/**
+	 * @dst_cookie: Used to check whether dst is still valid. This is
+	 * accessed without synchronization, which is racy, but the worst
+	 * that can happen is using an obsolete dst.
+	 */
+	u32 dst_cookie;
+
+	/**
+	 * @flow: Contains parameters used to generate @dst; must be
+	 * retained and passed to ip*xmit.
+	 */
+	struct flowi flow;
+
+	/**
+	 * @ht_linkage: Used by rashtable to link this object into
+	 * peertab->route_ht.
+	 */
+	struct rhash_head ht_linkage;
+
+	/** @rcu_head: Holds state of a pending call_rcu invocation. */
+	struct rcu_head rcu_head;
+};
+
+void     homa_dst_refresh(struct homa_peertab *peertab,
+			  struct homa_peer *peer, struct homa_sock *hsk);
+void     homa_peer_add_ack(struct homa_rpc *rpc);
+struct homa_peer
+	*homa_peer_alloc(struct homa_sock *hsk, const struct in6_addr *addr);
+struct homa_peertab
+	*homa_peer_alloc_peertab(void);
+int      homa_peer_dointvec(const struct ctl_table *table, int write,
+			    void *buffer, size_t *lenp, loff_t *ppos);
+void     homa_peer_free(struct homa_peer *peer);
+void     homa_peer_free_net(struct homa_net *hnet);
+void     homa_peer_free_peertab(struct homa_peertab *peertab);
+struct homa_peer
+	*homa_peer_get(struct homa_sock *hsk, const struct in6_addr *addr);
+int      homa_peer_get_acks(struct homa_peer *peer, int count,
+			    struct homa_ack *dst);
+void     homa_peer_lock_slow(struct homa_peer *peer);
+void     homa_peer_release_fn(void *object, void *dummy);
+void     homa_peer_update_sysctl_deps(struct homa_peertab *peertab);
+void     homa_peer_set_cutoffs(struct homa_peer *peer, int c0, int c1,
+			       int c2, int c3, int c4, int c5, int c6, int c7);
+struct homa_route
+	*homa_route_alloc(struct homa_sock *hsk,
+			  const struct homa_route_key *key);
+void     homa_route_delete_fn(void *object, void *dummy);
+void     homa_route_free(struct rcu_head *head);
+void     homa_route_gc(struct homa_peertab *peertab);
+struct homa_route
+	*homa_route_get(struct homa_sock *hsk,
+				    const struct in6_addr *addr);
+u32      homa_route_hash(const void *data, u32 len, u32 seed);
+int      homa_route_pick_victims(struct homa_peertab *peertab,
+				 struct homa_route *victims[], int max_victims);
+int      homa_route_prefer_evict(struct homa_peertab *peertab,
+				 struct homa_route *route1,
+				 struct homa_route *route2);
+int      homa_route_validate(struct homa_rpc *rpc);
+
+extern const struct rhashtable_params peer_ht_params;
+extern const struct rhashtable_params route_ht_params;
+
+/**
+ * homa_peer_lock() - Acquire the lock for a peer.
+ * @peer:    Peer to lock.
+ */
+static inline void homa_peer_lock(struct homa_peer *peer)
+	__acquires(peer->lock)
+{
+	spin_lock_bh(&peer->lock);
+}
+
+/**
+ * homa_peer_unlock() - Release the lock for a peer.
+ * @peer:   Peer to lock.
+ */
+static inline void homa_peer_unlock(struct homa_peer *peer)
+	__releases(peer->lock)
+{
+	spin_unlock_bh(&peer->lock);
+}
+
+/**
+ * homa_route_hold() - Increment the reference count on a route.
+ * Caller must eventually invoke homa_route_release to decrement the
+ * reference count again.
+ * @route:   Route whose reference count should be incremented. Caller must
+ *           already hold a reference to this.
+ */
+static inline void homa_route_hold(struct homa_route *route)
+{
+	refcount_inc(&route->refs);
+}
+
+/**
+ * homa_route_release() - Release a reference on a route (cancels the effect of
+ * a previous call to homa_route_hold). If the reference count becomes zero
+ * then the route may be deleted at any time.
+ * @route:      Object to release.
+ */
+static inline void homa_route_release(struct homa_route *route)
+{
+	if (refcount_dec_and_test(&route->refs))
+		call_rcu(&route->rcu_head, homa_route_free);
+}
+
+/**
+ * homa_peer_compare() - Comparison function for entries in @peertab->peer_ht.
+ * @arg:   Contains one of the keys to compare.
+ * @obj:   homa_peer object containing the other key to compare.
+ * Return: 0 means the keys match, 1 means mismatch.
+ */
+static inline int homa_peer_compare(struct rhashtable_compare_arg *arg,
+				    const void *obj)
+{
+	const struct homa_peer_key *key = arg->key;
+	const struct homa_peer *peer = obj;
+
+	return !(ipv6_addr_equal(&key->addr, &peer->ht_key.addr) &&
+		 peer->ht_key.hnet == key->hnet);
+}
+
+/**
+ * homa_route_xmit() - Transmit a packet according to a given route.
+ * @skb:      Packet to transmit.
+ * @hsk:      Socket on which to transmit packet.
+ * @route:    Route to use to transmit packet.
+ * @priority: Priority for packet.
+ * Return:    0 for success, otherwise a negative errno.
+ */
+static inline int homa_route_xmit(struct sk_buff *skb, struct homa_sock *hsk,
+				  struct homa_route *route, int priority)
+{
+	rcu_read_lock();
+	dst_hold(rcu_dereference(route->dst));
+	skb_dst_set(skb, rcu_dereference(route->dst));
+	rcu_read_unlock();
+	if (ipv6_addr_v4mapped(&route->peer->addr)) {
+		hsk->inet.tos = priority << 5;
+		return ip_queue_xmit(&hsk->inet.sk, skb, &route->flow);
+	}
+	return ip6_xmit(&hsk->inet.sk, skb, &route->flow.u.ip6, 0,
+			NULL, priority << 5, 0);
+}
+
+/**
+ * homa_peer_unlink() - Remove the connection between a route and its peer,
+ * potentially freeing the peer in the process.
+ * @route:    Route to disconnect.
+ */
+static inline void homa_peer_unlink(struct homa_route *route)
+	__must_hold(route->hnet->homa->peertab->lock)
+{
+	struct homa_peertab *peertab;
+
+	if (!route->peer)
+		return;
+
+	/* Note: we don't need to use RCU for freeing peers because we have
+	 * already used RCU for freeing routes, so we know there are no
+	 * outstanding uses. By holding the peertab lock we have locked
+	 * out calls to homa_peer_get.
+	 */
+	peertab = route->key.hnet->homa->peertab;
+	if (refcount_dec_and_test(&route->peer->refs)) {
+		rhashtable_remove_fast(&peertab->peer_ht,
+				       &route->peer->ht_linkage,
+				       peer_ht_params);
+		homa_peer_free(route->peer);
+	}
+	route->peer = NULL;
+}
+
+/**
+ * homa_route_key_init() - Initialize the fields of a key for
+ * peertab->route_ht. Note: caller must hold an RCU read lock.
+ * @key:      Key to initialize
+ * @hsk:      Socket from which to pull fields for the key other than
+ *            daddr.
+ * @daddr:    Destination address for the key.
+ */
+static inline void homa_route_key_init(struct homa_route_key *key,
+				       const struct homa_sock *hsk,
+				       const struct in6_addr *daddr)
+{
+	struct flowi_common flowic;
+
+	memset(key, 0, sizeof(*key));
+	if (hsk->sock.sk_family == AF_INET)
+		ipv6_addr_set_v4mapped(hsk->inet.inet_saddr, &key->saddr);
+	else
+		key->saddr = hsk->inet.pinet6->saddr;
+	key->daddr = *daddr;
+	key->hnet = hsk->hnet;
+	key->sk_policy_out = rcu_dereference(hsk->sock.sk_policy[XFRM_POLICY_OUT]);
+	key->uid = hsk->sock.sk_uid;
+	key->mark = hsk->sock.sk_mark;
+	flowic.flowic_secid = 0;
+	security_sk_classify_flow(&hsk->sock, &flowic);
+	key->secid = flowic.flowic_secid;
+	key->bound_dev_if = hsk->sock.sk_bound_dev_if;
+}
+
+#endif /* _HOMA_PEER_H */
diff --git a/net/homa/homa_plumbing.c b/net/homa/homa_plumbing.c
new file mode 100644
index 0000000000000..de3483b21d489
--- /dev/null
+++ b/net/homa/homa_plumbing.c
@@ -0,0 +1,1302 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file consists mostly of "glue" that hooks Homa into the rest of
+ * the Linux kernel. The guts of the protocol are in other files.
+ */
+
+#include "homa_impl.h"
+#include "homa_peer.h"
+#include "homa_pool.h"
+
+/* Identifier for retrieving Homa-specific data for a struct net. */
+unsigned int homa_net_id;
+
+/* This structure defines functions that allow Homa to be used as a
+ * pernet subsystem.
+ */
+static struct pernet_operations homa_net_ops = {
+	.init = homa_net_start,
+	.exit = homa_net_exit,
+	.id = &homa_net_id,
+	.size = sizeof(struct homa_net)
+};
+
+/* Global data for Homa. Avoid referencing directly except when there is
+ * no alternative (instead, use a homa pointer stored in a struct or
+ * passed via a parameter). This allows overriding during unit tests.
+ */
+static struct homa homa_data;
+
+/* This structure defines functions that handle various operations on
+ * Homa sockets. These functions are relatively generic: they are called
+ * to implement top-level system calls. Many of these operations can
+ * be implemented by PF_INET6 functions that are independent of the
+ * Homa protocol.
+ */
+static const struct proto_ops homa_proto_ops = {
+	.family		   = PF_INET,
+	.owner		   = THIS_MODULE,
+	.release	   = inet_release,
+	.bind		   = homa_bind,
+	.connect	   = inet_dgram_connect,
+	.socketpair	   = sock_no_socketpair,
+	.accept		   = sock_no_accept,
+	.getname	   = inet_getname,
+	.poll		   = homa_poll,
+	.ioctl		   = homa_ioctl,
+	.listen		   = sock_no_listen,
+	.shutdown	   = homa_shutdown,
+	.setsockopt	   = sock_common_setsockopt,
+	.getsockopt	   = sock_common_getsockopt,
+	.sendmsg	   = inet_sendmsg,
+	.recvmsg	   = inet_recvmsg,
+	.mmap		   = sock_no_mmap,
+	.set_peek_off	   = sk_set_peek_off,
+};
+
+static const struct proto_ops homav6_proto_ops = {
+	.family		   = PF_INET6,
+	.owner		   = THIS_MODULE,
+	.release	   = inet6_release,
+	.bind		   = homa_bind,
+	.connect	   = inet_dgram_connect,
+	.socketpair	   = sock_no_socketpair,
+	.accept		   = sock_no_accept,
+	.getname	   = inet6_getname,
+	.poll		   = homa_poll,
+	.ioctl		   = homa_ioctl,
+	.listen		   = sock_no_listen,
+	.shutdown	   = homa_shutdown,
+	.setsockopt	   = sock_common_setsockopt,
+	.getsockopt	   = sock_common_getsockopt,
+	.sendmsg	   = inet_sendmsg,
+	.recvmsg	   = inet_recvmsg,
+	.mmap		   = sock_no_mmap,
+	.set_peek_off	   = sk_set_peek_off,
+};
+
+/* This structure also defines functions that handle various operations
+ * on Homa sockets. However, these functions are lower-level than those
+ * in homa_proto_ops: they are specific to the PF_INET or PF_INET6
+ * protocol family, and in many cases they are invoked by functions in
+ * homa_proto_ops. Most of these functions have Homa-specific implementations.
+ */
+static struct proto homa_prot = {
+	.name		   = "HOMA",
+	.owner		   = THIS_MODULE,
+	.close		   = homa_close,
+	.connect	   = ip4_datagram_connect,
+	.init		   = homa_socket,
+	.destroy	   = homa_sock_destroy,
+	.setsockopt	   = homa_setsockopt,
+	.getsockopt	   = homa_getsockopt,
+	.sendmsg	   = homa_sendmsg,
+	.recvmsg	   = homa_recvmsg,
+	.hash		   = homa_hash,
+	.unhash		   = homa_unhash,
+	.obj_size	   = sizeof(struct homa_sock),
+	.no_autobind       = 1,
+};
+
+static struct proto homav6_prot = {
+	.name		   = "HOMAv6",
+	.owner		   = THIS_MODULE,
+	.close		   = homa_close,
+	.connect	   = ip6_datagram_connect,
+	.init		   = homa_socket,
+	.destroy	   = homa_sock_destroy,
+	.setsockopt	   = homa_setsockopt,
+	.getsockopt	   = homa_getsockopt,
+	.sendmsg	   = homa_sendmsg,
+	.recvmsg	   = homa_recvmsg,
+	.hash		   = homa_hash,
+	.unhash		   = homa_unhash,
+	.obj_size	   = sizeof(struct homa_v6_sock),
+	.ipv6_pinfo_offset = offsetof(struct homa_v6_sock, inet6),
+	.no_autobind       = 1,
+};
+
+/* Top-level structure describing the Homa protocol. */
+static struct inet_protosw homa_protosw = {
+	.type              = SOCK_DGRAM,
+	.protocol          = IPPROTO_HOMA,
+	.prot              = &homa_prot,
+	.ops               = &homa_proto_ops,
+	.flags             = INET_PROTOSW_REUSE,
+};
+
+static struct inet_protosw homav6_protosw = {
+	.type              = SOCK_DGRAM,
+	.protocol          = IPPROTO_HOMA,
+	.prot              = &homav6_prot,
+	.ops               = &homav6_proto_ops,
+	.flags             = INET_PROTOSW_REUSE,
+};
+
+/* This structure is used by IP to deliver incoming Homa packets to us. */
+static struct net_protocol homa_protocol = {
+	.handler =	homa_softirq,
+	.err_handler =	homa_err_handler_v4,
+	.no_policy =     1,
+};
+
+static struct inet6_protocol homav6_protocol = {
+	.handler =	homa_softirq,
+	.err_handler =	homa_err_handler_v6,
+	.flags =        INET6_PROTO_NOPOLICY | INET6_PROTO_FINAL,
+};
+
+/* Sizes of the headers for each Homa packet type, in bytes. */
+static u16 header_lengths[] = {
+	sizeof(struct homa_data_hdr),
+	0,
+	sizeof(struct homa_resend_hdr),
+	sizeof(struct homa_rpc_unknown_hdr),
+	sizeof(struct homa_busy_hdr),
+	0,
+	0,
+	sizeof(struct homa_need_ack_hdr),
+	sizeof(struct homa_ack_hdr)
+};
+
+/* Thread that runs timer code to detect lost packets and crashed peers. */
+static struct task_struct *timer_kthread;
+
+/* Used to wakeup timer_kthread at regular intervals. */
+static struct hrtimer hrtimer;
+
+/**
+ * homa_load() - invoked when this module is loaded into the Linux kernel
+ * Return: 0 on success, otherwise a negative errno.
+ */
+int __init homa_load(void)
+{
+	struct homa *homa = &homa_data;
+	bool init_protocol6 = false;
+	bool init_protosw6 = false;
+	bool init_protocol = false;
+	bool init_protosw = false;
+	bool init_net_ops = false;
+	bool init_proto6 = false;
+	bool init_proto = false;
+	bool init_homa = false;
+	int status;
+
+	/* Compile-time validations that no packet header is longer
+	 * than HOMA_MAX_HEADER.
+	 */
+	BUILD_BUG_ON(sizeof(struct homa_data_hdr) > HOMA_MAX_HEADER);
+	BUILD_BUG_ON(sizeof(struct homa_resend_hdr) > HOMA_MAX_HEADER);
+	BUILD_BUG_ON(sizeof(struct homa_rpc_unknown_hdr) > HOMA_MAX_HEADER);
+	BUILD_BUG_ON(sizeof(struct homa_busy_hdr) > HOMA_MAX_HEADER);
+	BUILD_BUG_ON(sizeof(struct homa_need_ack_hdr) > HOMA_MAX_HEADER);
+	BUILD_BUG_ON(sizeof(struct homa_ack_hdr) > HOMA_MAX_HEADER);
+
+	/* Extra constraints on data packets:
+	 * - Ensure minimum header length so Homa doesn't have to worry about
+	 *   padding data packets.
+	 * - Make sure data packet headers are a multiple of 4 bytes (needed
+	 *   for TCP/TSO compatibility).
+	 */
+	BUILD_BUG_ON(sizeof(struct homa_data_hdr) < HOMA_MIN_PKT_LENGTH);
+	BUILD_BUG_ON((sizeof(struct homa_data_hdr) -
+		      sizeof(struct homa_seg_hdr)) & 0x3);
+
+	/* Detect size changes in uAPI structs. */
+	BUILD_BUG_ON(sizeof(struct homa_sendmsg_args) != 24);
+	BUILD_BUG_ON(sizeof(struct homa_recvmsg_args) != 88);
+
+	status = homa_init(homa);
+	if (status)
+		goto error;
+	init_homa = true;
+
+	status = register_pernet_subsys(&homa_net_ops);
+	if (status != 0) {
+		pr_err("Homa got error from register_pernet_subsys: %d\n",
+		       status);
+		goto error;
+	}
+	init_net_ops = true;
+
+	status = proto_register(&homa_prot, 1);
+	if (status != 0) {
+		pr_err("proto_register failed for homa_prot: %d\n", status);
+		goto error;
+	}
+	init_proto = true;
+
+	status = proto_register(&homav6_prot, 1);
+	if (status != 0) {
+		pr_err("proto_register failed for homav6_prot: %d\n", status);
+		goto error;
+	}
+	init_proto6 = true;
+
+	inet_register_protosw(&homa_protosw);
+	init_protosw = true;
+
+	status = inet6_register_protosw(&homav6_protosw);
+	if (status != 0) {
+		pr_err("inet6_register_protosw failed in %s: %d\n", __func__,
+		       status);
+		goto error;
+	}
+	init_protosw6 = true;
+
+	status = inet_add_protocol(&homa_protocol, IPPROTO_HOMA);
+	if (status != 0) {
+		pr_err("inet_add_protocol failed in %s: %d\n", __func__,
+		       status);
+		goto error;
+	}
+	init_protocol = true;
+
+	status = inet6_add_protocol(&homav6_protocol, IPPROTO_HOMA);
+	if (status != 0) {
+		pr_err("inet6_add_protocol failed in %s: %d\n",  __func__,
+		       status);
+		goto error;
+	}
+	init_protocol6 = true;
+
+	timer_kthread = kthread_run(homa_timer_main, homa, "homa_timer");
+	if (IS_ERR(timer_kthread)) {
+		status = PTR_ERR(timer_kthread);
+		pr_err("couldn't create Homa timer thread: error %d\n",
+		       status);
+		timer_kthread = NULL;
+		goto error;
+	}
+
+	return 0;
+
+error:
+	if (timer_kthread)
+		kthread_stop(timer_kthread);
+	if (init_homa)
+		homa_destroy(homa);
+	if (init_protocol)
+		inet_del_protocol(&homa_protocol, IPPROTO_HOMA);
+	if (init_protocol6)
+		inet6_del_protocol(&homav6_protocol, IPPROTO_HOMA);
+	if (init_protosw)
+		inet_unregister_protosw(&homa_protosw);
+	if (init_protosw6)
+		inet6_unregister_protosw(&homav6_protosw);
+	if (init_proto)
+		proto_unregister(&homa_prot);
+	if (init_proto6)
+		proto_unregister(&homav6_prot);
+	if (init_net_ops)
+		unregister_pernet_subsys(&homa_net_ops);
+	return status;
+}
+
+/**
+ * homa_unload() - invoked when this module is unloaded from the Linux kernel.
+ */
+void __exit homa_unload(void)
+{
+	struct homa *homa = &homa_data;
+
+	pr_notice("Homa module unloading\n");
+
+	if (timer_kthread)
+		kthread_stop(timer_kthread);
+	inet_del_protocol(&homa_protocol, IPPROTO_HOMA);
+	inet_unregister_protosw(&homa_protosw);
+	inet6_del_protocol(&homav6_protocol, IPPROTO_HOMA);
+	inet6_unregister_protosw(&homav6_protosw);
+	proto_unregister(&homa_prot);
+	proto_unregister(&homav6_prot);
+	unregister_pernet_subsys(&homa_net_ops);
+	homa_destroy(homa);
+}
+
+module_init(homa_load);
+module_exit(homa_unload);
+
+/**
+ * homa_net_start() - Initialize Homa for a new network namespace.
+ * @net:    The net that Homa will be associated with.
+ * Return:  0 on success, otherwise a negative errno.
+ */
+int homa_net_start(struct net *net)
+{
+	pr_notice("Homa attaching to net namespace\n");
+	return homa_net_init(homa_net(net), &homa_data);
+}
+
+/**
+ * homa_net_exit() - Perform Homa cleanup needed when a network namespace
+ * is destroyed.
+ * @net:    The net from which Homa should be removed.
+ */
+void homa_net_exit(struct net *net)
+{
+	pr_notice("Homa detaching from net namespace\n");
+	homa_net_destroy(homa_net(net));
+}
+
+/**
+ * homa_bind() - Implements the bind system call for Homa sockets: associates
+ * a well-known service port with a socket. Unlike other AF_INET6 protocols,
+ * there is no need to invoke this system call for sockets that are only
+ * used as clients.
+ * @sock:     Socket on which the system call was invoked.
+ * @addr:     Contains the desired port number.
+ * @addr_len: Number of bytes in uaddr.
+ * Return:    0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *            on errors.
+ */
+int homa_bind(struct socket *sock, struct sockaddr_unsized *addr, int addr_len)
+{
+	union sockaddr_in_union *addr_in = (union sockaddr_in_union *)addr;
+	struct homa_sock *hsk = homa_sk(sock->sk);
+	int port = 0;
+
+	if (unlikely(addr->sa_family != sock->sk->sk_family)) {
+		hsk->error_msg = "address family in bind address didn't match socket";
+		return -EAFNOSUPPORT;
+	}
+	if (addr_in->in6.sin6_family == AF_INET6) {
+		if (addr_len < sizeof(struct sockaddr_in6)) {
+			hsk->error_msg = "ipv6 address too short";
+			return -EINVAL;
+		}
+		port = ntohs(addr_in->in6.sin6_port);
+	} else if (addr_in->in4.sin_family == AF_INET) {
+		if (addr_len < sizeof(struct sockaddr_in)) {
+			hsk->error_msg = "ipv4 address too short";
+			return -EINVAL;
+		}
+		port = ntohs(addr_in->in4.sin_port);
+	}
+	return homa_sock_bind(hsk->hnet, hsk, port);
+}
+
+/**
+ * homa_close() - Invoked when close system call is invoked on a Homa socket.
+ * @sk:      Socket being closed
+ * @timeout: ??
+ */
+void homa_close(struct sock *sk, long timeout)
+{
+	struct homa_sock *hsk = homa_sk(sk);
+
+	homa_sock_shutdown(hsk);
+	sk_common_release(sk);
+}
+
+/**
+ * homa_shutdown() - Implements the shutdown system call for Homa sockets.
+ * @sock:    Socket to shut down.
+ * @how:     Ignored: for other sockets, can independently shut down
+ *           sending and receiving, but for Homa any shutdown will
+ *           shut down everything.
+ *
+ * Return: 0 on success, otherwise a negative errno.
+ */
+int homa_shutdown(struct socket *sock, int how)
+{
+	homa_sock_shutdown(homa_sk(sock->sk));
+	return 0;
+}
+
+/**
+ * homa_ioc_info() - The top-level function that implements the
+ * HOMAIOCINFO ioctl for Homa sockets.
+ * @sock:  Socket for this request
+ * @arg:   The address in user space of the argument to ioctl, which
+ *          is a homa_info struct.
+ *
+ * Return:  0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *          on errors.
+ */
+int homa_ioc_info(struct socket *sock, unsigned long arg)
+{
+	struct homa_sock *hsk = homa_sk(sock->sk);
+	struct homa_rpc **rpcs = NULL;
+	struct homa_rpc_info rinfo;
+	struct homa_info hinfo;
+	struct homa_rpc *rpc;
+	int result = 0;
+	int bytes_avl;
+	int num_rpcs;
+	char *dst;
+	int i;
+
+	if (unlikely(copy_from_user(&hinfo, (void __user *)arg,
+				    sizeof(hinfo)))) {
+		hsk->error_msg = "invalid address for homa_info";
+		return -EFAULT;
+	}
+
+	if (!homa_protect_rpcs(hsk)) {
+		hsk->error_msg = "socket has been shut down";
+		return -ESHUTDOWN;
+	}
+	hinfo.bpool_avail_bytes = homa_pool_avail_bytes(hsk->buffer_pool);
+	hinfo.port = hsk->port;
+	dst = (char *)hinfo.rpc_info;
+	bytes_avl = hinfo.rpc_info_length;
+	hinfo.num_rpcs = 0;
+
+	/* This function is tricky because we need to hold an RCU lock
+	 * while scanning the RPCs of the socket, but we can't hold the
+	 * RCU lock while copying status information out to user space.
+	 * Thus, we first collect pointers to all the RPCs in a separate
+	 * array (while holding an RCU lock), acquire a reference on each
+	 * RPC, then release the RCU lock and copy out to user space.
+	 */
+	num_rpcs = 0;
+	rcu_read_lock();
+	list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links)
+		num_rpcs++;
+
+	if (num_rpcs > 0) {
+		/* Allocate an array and populate it with homa_rpc pointers.
+		 * Must release the RCU lock temporarily while allocating.
+		 */
+		rcu_read_unlock();
+		rpcs = kmalloc_objs(*rpcs, num_rpcs, GFP_KERNEL_ACCOUNT);
+		if (!rpcs) {
+			homa_unprotect_rpcs(hsk);
+			return -ENOMEM;
+		}
+		rcu_read_lock();
+		i = 0;
+		list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
+			homa_rpc_lock(rpc);
+			if (rpc->state != RPC_DEAD) {
+				rpcs[i] = rpc;
+				homa_rpc_hold(rpc);
+				i++;
+			}
+			homa_rpc_unlock(rpc);
+			if (i == num_rpcs)
+				break;
+		}
+		/* The number of RPCs could have changed between the first
+		 * pass and the second pass.
+		 */
+		num_rpcs = i;
+	}
+	rcu_read_unlock();
+	homa_unprotect_rpcs(hsk);
+
+	/* Now scan the array and copy information out to user space.  Note
+	 * that RPCs could have ended since we added them to the array.
+	 */
+	for (i = 0; i < num_rpcs; i++) {
+		rpc = rpcs[i];
+		homa_rpc_lock(rpc);
+		homa_rpc_put(rpc);
+		if (rpc->state == RPC_DEAD) {
+			homa_rpc_unlock(rpc);
+			continue;
+		}
+		homa_rpc_get_info(rpc, &rinfo);
+		homa_rpc_unlock(rpc);
+		if (dst && bytes_avl >= sizeof(rinfo) && result == 0) {
+			if (copy_to_user((void __user *)dst, &rinfo,
+					 sizeof(rinfo))) {
+				hsk->error_msg = "couldn't copy homa_rpc_info to user space: invalid or read-only address?";
+				result = -EFAULT;
+			}
+			dst += sizeof(rinfo);
+			bytes_avl -= sizeof(rinfo);
+		}
+		hinfo.num_rpcs++;
+	}
+	kfree(rpcs);
+
+	snprintf(hinfo.error_msg, HOMA_ERROR_MSG_SIZE, "%s", hsk->error_msg);
+
+	if (copy_to_user((void __user *)arg, &hinfo, sizeof(hinfo))) {
+		hsk->error_msg = "couldn't copy homa_info to user space: read-only address?";
+		return -EFAULT;
+	}
+	return result;
+}
+
+/**
+ * homa_ioctl() - Implements the ioctl system call for Homa sockets.
+ * @sock:  Socket on which the system call was invoked.
+ * @cmd:   Identifier for a particular ioctl operation.
+ * @arg:   Operation-specific argument; typically the address of a block
+ *         of data in user address space.
+ *
+ * Return: 0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *         on errors.
+ */
+int homa_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
+{
+	if (cmd == HOMAIOCINFO)
+		return homa_ioc_info(sock, arg);
+	homa_sk(sock->sk)->error_msg = "ioctl opcode isn't supported by Homa";
+	return -EINVAL;
+}
+
+/**
+ * homa_socket() - Implements the socket(2) system call for sockets.
+ * @sk:    Socket on which the system call was invoked. The non-Homa
+ *         parts have already been initialized.
+ *
+ * Return: always 0 (success).
+ */
+int homa_socket(struct sock *sk)
+{
+	return homa_sock_init(homa_sk(sk));
+}
+
+/**
+ * homa_setsockopt() - Implements the setsockopt system call for Homa sockets.
+ * @sk:      Socket on which the system call was invoked.
+ * @level:   Level at which the operation should be handled; will always
+ *           be IPPROTO_HOMA.
+ * @optname: Identifies a particular setsockopt operation.
+ * @optval:  Address in user space of information about the option.
+ * @optlen:  Number of bytes of data at @optval.
+ * Return:   0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *           on errors.
+ */
+int homa_setsockopt(struct sock *sk, int level, int optname,
+		    sockptr_t optval, unsigned int optlen)
+{
+	struct homa_sock *hsk = homa_sk(sk);
+	int ret;
+
+	if (level != IPPROTO_HOMA) {
+		hsk->error_msg = "homa_setsockopt invoked with level not IPPROTO_HOMA";
+		return -ENOPROTOOPT;
+	}
+
+	if (optname == SO_HOMA_RCVBUF) {
+		struct homa_rcvbuf_args args;
+
+		if (optlen != sizeof(struct homa_rcvbuf_args)) {
+			hsk->error_msg = "invalid optlen argument: must be sizeof(struct homa_rcvbuf_args)";
+			return -EINVAL;
+		}
+
+		if (copy_from_sockptr(&args, optval, optlen)) {
+			hsk->error_msg = "invalid address for homa_rcvbuf_args";
+			return -EFAULT;
+		}
+
+		/* Do a trivial test to make sure we can at least write the
+		 * first page of the region.
+		 */
+		if (copy_to_user(u64_to_user_ptr(args.start), &args,
+				 sizeof(args))) {
+			hsk->error_msg = "receive buffer region is not writable";
+			return -EFAULT;
+		}
+
+		ret = homa_pool_set_region(hsk, u64_to_user_ptr(args.start),
+					   args.length);
+	} else if (optname == SO_HOMA_SERVER) {
+		int arg;
+
+		if (optlen != sizeof(arg)) {
+			hsk->error_msg = "invalid optlen argument: must be sizeof(int)";
+			return -EINVAL;
+		}
+
+		if (copy_from_sockptr(&arg, optval, optlen)) {
+			hsk->error_msg = "invalid address for SO_HOMA_SERVER value";
+			return -EFAULT;
+		}
+
+		if (arg)
+			hsk->is_server = true;
+		else
+			hsk->is_server = false;
+		ret = 0;
+	} else {
+		hsk->error_msg = "setsockopt option not supported by Homa";
+		ret = -ENOPROTOOPT;
+	}
+	return ret;
+}
+
+/**
+ * homa_getsockopt() - Implements the getsockopt system call for Homa sockets.
+ * @sk:      Socket on which the system call was invoked.
+ * @level:   Selects level in the network stack to handle the request;
+ *           must be IPPROTO_HOMA.
+ * @optname: Identifies a particular setsockopt operation.
+ * @optval:  Address in user space where the option's value should be stored.
+ * @optlen:  Number of bytes available at optval; will be overwritten with
+ *           actual number of bytes stored.
+ * Return:   0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *           on errors.
+ */
+int homa_getsockopt(struct sock *sk, int level, int optname,
+		    char __user *optval, int __user *optlen)
+{
+	struct homa_sock *hsk = homa_sk(sk);
+	struct homa_rcvbuf_args rcvbuf_args;
+	int is_server;
+	void *result;
+	int len;
+
+	if (copy_from_sockptr(&len, USER_SOCKPTR(optlen), sizeof(int))) {
+		hsk->error_msg = "invalid address for optlen argument to getsockopt";
+		return -EFAULT;
+	}
+
+	if (level != IPPROTO_HOMA) {
+		hsk->error_msg = "homa_getsockopt invoked with level not IPPROTO_HOMA";
+		return -ENOPROTOOPT;
+	}
+	if (optname == SO_HOMA_RCVBUF) {
+		if (len < sizeof(rcvbuf_args)) {
+			hsk->error_msg = "invalid optlen argument: must be sizeof(struct homa_rcvbuf_args)";
+			return -EINVAL;
+		}
+
+		homa_sock_lock(hsk);
+		homa_pool_get_rcvbuf(hsk->buffer_pool, &rcvbuf_args);
+		homa_sock_unlock(hsk);
+		len = sizeof(rcvbuf_args);
+		result = &rcvbuf_args;
+	} else if (optname == SO_HOMA_SERVER) {
+		if (len < sizeof(is_server)) {
+			hsk->error_msg = "invalid optlen argument: must be sizeof(int)";
+			return -EINVAL;
+		}
+
+		is_server = hsk->is_server;
+		len = sizeof(is_server);
+		result = &is_server;
+	} else {
+		hsk->error_msg = "getsockopt option not supported by Homa";
+		return -ENOPROTOOPT;
+	}
+
+	if (copy_to_sockptr(USER_SOCKPTR(optlen), &len, sizeof(int))) {
+		hsk->error_msg = "couldn't update optlen argument to getsockopt: read-only?";
+		return -EFAULT;
+	}
+
+	if (copy_to_sockptr(USER_SOCKPTR(optval), result, len)) {
+		hsk->error_msg = "couldn't update optval argument to getsockopt: read-only?";
+		return -EFAULT;
+	}
+
+	return 0;
+}
+
+/**
+ * homa_sendmsg() - Send a request or response message on a Homa socket.
+ * @sk:     Socket on which the system call was invoked.
+ * @msg:    Structure describing the message to send; the msg_control
+ *          field points to additional information.
+ * @length: Number of bytes of the message.
+ * Return:  0 on success, otherwise a negative errno. Sets hsk->error_msg
+ *          on errors.
+ */
+int homa_sendmsg(struct sock *sk, struct msghdr *msg, size_t length)
+{
+	DECLARE_SOCKADDR(union sockaddr_in_union *, addr, msg->msg_name);
+	struct homa_sock *hsk = homa_sk(sk);
+	struct homa_sendmsg_args args;
+	struct homa_rpc *rpc = NULL;
+	int result = 0;
+
+	if (!addr) {
+		hsk->error_msg = "no msg_name passed to sendmsg";
+		result = -EINVAL;
+		goto error;
+	}
+
+	if (unlikely(!msg->msg_control_is_user)) {
+		hsk->error_msg = "msg_control argument for sendmsg isn't in user space";
+		result = -EINVAL;
+		goto error;
+	}
+	if (unlikely(copy_from_user(&args, (void __user *)msg->msg_control,
+				    sizeof(args)))) {
+		hsk->error_msg = "invalid address for msg_control argument to sendmsg";
+		result = -EFAULT;
+		goto error;
+	}
+	if (args.flags & ~HOMA_SENDMSG_VALID_FLAGS ||
+	    args.reserved != 0) {
+		hsk->error_msg = "reserved fields in homa_sendmsg_args must be zero";
+		result = -EINVAL;
+		goto error;
+	}
+
+	if (!homa_sock_wmem_avl(hsk)) {
+		result = homa_sock_wait_wmem(hsk,
+					     msg->msg_flags & MSG_DONTWAIT);
+		if (result != 0)
+			goto error;
+	}
+
+	if (addr->sa.sa_family != sk->sk_family) {
+		hsk->error_msg = "address family in sendmsg address must match the socket";
+		result = -EAFNOSUPPORT;
+		goto error;
+	}
+	if (msg->msg_namelen < sizeof(struct sockaddr_in) ||
+	    (msg->msg_namelen < sizeof(struct sockaddr_in6) &&
+	     addr->in6.sin6_family == AF_INET6)) {
+		hsk->error_msg = "msg_namelen too short";
+		result = -EINVAL;
+		goto error;
+	}
+
+	if (unlikely(msg->msg_iter.count == 0)) {
+		hsk->error_msg = "message has length zero";
+		result = -EINVAL;
+		goto error;
+	}
+	if (unlikely(msg->msg_iter.count > HOMA_MAX_MESSAGE_LENGTH)) {
+		hsk->error_msg = "message length exceeded HOMA_MAX_MESSAGE_LENGTH";
+		result = -EINVAL;
+		goto error;
+	}
+
+	if (!args.id) {
+		/* This is a request message. */
+		rpc = homa_rpc_alloc_client(hsk, addr);
+		if (IS_ERR(rpc)) {
+			result = PTR_ERR(rpc);
+			rpc = NULL;
+			goto error;
+		}
+		homa_rpc_hold(rpc);
+		if (args.flags & HOMA_SENDMSG_PRIVATE)
+			set_bit(RPC_PRIVATE, &rpc->flags);
+		rpc->completion_cookie = args.completion_cookie;
+		result = homa_tx_copy_from_user(rpc, &msg->msg_iter, true);
+		if (result)
+			goto error;
+		args.id = rpc->id;
+		homa_rpc_unlock(rpc); /* Locked by homa_rpc_alloc_client. */
+
+		if (unlikely(copy_to_user((void __user *)msg->msg_control,
+					  &args, sizeof(args)))) {
+			homa_rpc_lock(rpc);
+			hsk->error_msg = "couldn't update homa_sendmsg_args argument to sendmsg: read-only?";
+			result = -EFAULT;
+			goto error;
+		}
+		homa_rpc_put(rpc);
+	} else {
+		/* This is a response message. */
+		struct in6_addr canonical_dest;
+
+		if (args.completion_cookie != 0) {
+			hsk->error_msg = "completion_cookie must be zero when sending responses";
+			result = -EINVAL;
+			goto error;
+		}
+		canonical_dest = canonical_ipv6_addr(addr);
+
+		rpc = homa_rpc_find_server(hsk, &canonical_dest, args.id);
+		if (!rpc) {
+			/* Return without an error if the RPC doesn't exist;
+			 * this could be totally valid (e.g. client is
+			 * no longer interested in it).
+			 */
+			return 0;
+		}
+		homa_rpc_hold(rpc);
+		if (rpc->error) {
+			hsk->error_msg = "RPC has failed, so can't send response";
+			result = rpc->error;
+			goto error;
+		}
+		if (rpc->state != RPC_IN_SERVICE) {
+			hsk->error_msg = "RPC is not in a state where a response can be sent";
+			result = -EINVAL;
+			goto error_dont_end_rpc;
+		}
+		rpc->state = RPC_OUTGOING;
+
+		result = homa_tx_copy_from_user(rpc, &msg->msg_iter, true);
+		if (result && rpc->state != RPC_DEAD) {
+			hsk->error_msg = "error copying response message data from user space";
+			goto error;
+		}
+		homa_rpc_put(rpc);
+		homa_rpc_unlock(rpc); /* Locked by homa_rpc_find_server. */
+	}
+	return 0;
+
+error:
+	if (rpc)
+		homa_rpc_end(rpc);
+
+error_dont_end_rpc:
+	if (rpc) {
+		homa_rpc_put(rpc);
+
+		/* Locked by homa_rpc_find_server or homa_rpc_alloc_client. */
+		homa_rpc_unlock(rpc);
+	}
+	return result;
+}
+
+/**
+ * homa_recvmsg() - Receive a message from a Homa socket.
+ * @sk:          Socket on which the system call was invoked.
+ * @msg:         Controlling information for the receive.
+ * @len:         Total bytes of space available in msg->msg_iov; not used.
+ * @flags:       Flags from system call; only MSG_DONTWAIT is used.
+ * Return:       The length of the message on success, otherwise a negative
+ *               errno. Sets hsk->error_msg on errors.
+ */
+int homa_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags)
+{
+	struct homa_sock *hsk = homa_sk(sk);
+	struct homa_recvmsg_args control;
+	struct homa_rpc *rpc = NULL;
+	int nonblocking;
+	int result;
+
+	if (unlikely(!msg->msg_control)) {
+		/* This test isn't strictly necessary, but it provides a
+		 * hook for testing kernel call times.
+		 */
+		hsk->error_msg = "no msg_control passed to recvmsg";
+		return -EINVAL;
+	}
+	if (msg->msg_controllen != sizeof(control)) {
+		hsk->error_msg = "invalid msg_controllen in recvmsg";
+		return -EINVAL;
+	}
+	if (unlikely(copy_from_user(&control, (void __user *)msg->msg_control,
+				    sizeof(control)))) {
+		hsk->error_msg = "invalid address for msg_control argument to recvmsg";
+		return -EFAULT;
+	}
+	control.completion_cookie = 0;
+
+	if (control.num_bpages > HOMA_MAX_BPAGES) {
+		hsk->error_msg = "num_pages exceeds HOMA_MAX_BPAGES";
+		result = -EINVAL;
+		goto done;
+	}
+	if (control.reserved != 0) {
+		hsk->error_msg = "reserved fields in homa_recvmsg_args must be zero";
+		result = -EINVAL;
+		goto done;
+	}
+	if (!hsk->buffer_pool) {
+		hsk->error_msg = "SO_HOMA_RECVBUF socket option has not been set";
+		result = -EINVAL;
+		goto done;
+	}
+	result = homa_pool_free_bufs(hsk->buffer_pool, control.num_bpages,
+				     control.bpage_offsets);
+	control.num_bpages = 0;
+	if (result != 0) {
+		hsk->error_msg = "error while releasing buffer pages";
+		goto done;
+	}
+
+	nonblocking = flags & MSG_DONTWAIT;
+	if (control.id != 0) {
+		rpc = homa_rpc_find_client(hsk, control.id); /* Locks RPC. */
+		if (!rpc) {
+			hsk->error_msg = "invalid RPC id passed to recvmsg";
+			result = -EINVAL;
+			goto done;
+		}
+		homa_rpc_hold(rpc);
+		result = homa_wait_private(rpc, nonblocking);
+		if (result != 0) {
+			hsk->error_msg = "error while waiting for private RPC to complete";
+			control.id = 0;
+			goto done;
+		}
+	} else {
+		rpc = homa_wait_shared(hsk, nonblocking);
+		if (IS_ERR(rpc)) {
+			/* If we get here, it means there was an error that
+			 * prevented us from finding an RPC to return. Errors
+			 * in the RPC itself are handled below.
+			 */
+			hsk->error_msg = "error while waiting for shared RPC to complete";
+			result = PTR_ERR(rpc);
+			rpc = NULL;
+			goto done;
+		}
+	}
+	if (rpc->error) {
+		hsk->error_msg = "RPC failed";
+		result = rpc->error;
+	} else {
+		result = rpc->msgin.length;
+	}
+
+	/* Collect result information. */
+	control.id = rpc->id;
+	control.completion_cookie = rpc->completion_cookie;
+	if (likely(result > 0)) {
+		control.num_bpages = rpc->msgin.num_bpages;
+		memcpy(control.bpage_offsets, rpc->msgin.bpage_offsets,
+		       sizeof(rpc->msgin.bpage_offsets));
+	}
+	if (msg->msg_name) {
+		if (sk->sk_family == AF_INET6) {
+			DECLARE_SOCKADDR(struct sockaddr_in6 *, in6,
+					 msg->msg_name);
+
+			in6->sin6_family = AF_INET6;
+			in6->sin6_port = htons(rpc->dport);
+			in6->sin6_addr = rpc->route->peer->addr;
+			msg->msg_namelen = sizeof(*in6);
+		} else {
+			DECLARE_SOCKADDR(struct sockaddr_in *, in4,
+					 msg->msg_name);
+
+			in4->sin_family = AF_INET;
+			in4->sin_port = htons(rpc->dport);
+			in4->sin_addr.s_addr = ipv6_to_ipv4(rpc->route->peer->addr);
+			msg->msg_namelen = sizeof(*in4);
+		}
+	}
+
+	if (result < 0) {
+		homa_rpc_end(rpc);
+	} else {
+		/* This indicates that the application now owns the buffers, so
+		 * they won't be freed in homa_rpc_end.
+		 */
+		rpc->msgin.num_bpages = 0;
+		if (homa_is_client(rpc->id)) {
+			homa_peer_add_ack(rpc);
+			homa_rpc_end(rpc);
+		} else {
+			rpc->state = RPC_IN_SERVICE;
+		}
+	}
+
+done:
+	/* Note: must release the RPC lock before calling homa_rpc_reap
+	 * or copying results to user space.
+	 */
+	if (rpc) {
+		homa_rpc_put(rpc);
+
+		/* Locked by homa_rpc_find_client or homa_wait_shared. */
+		homa_rpc_unlock(rpc);
+	}
+
+	while (test_bit(HOMA_SOCK_NOSPACE, &hsk->flags)) {
+		/* There are tasks waiting for tx memory, so reap
+		 * immediately.
+		 */
+		if (!homa_rpc_reap(hsk))
+			break;
+	}
+
+	if (unlikely(copy_to_user((__force void __user *)msg->msg_control,
+				  &control, sizeof(control)))) {
+		hsk->error_msg = "couldn't update homa_recvmsg_args argument to recvmsg: read-only?";
+		result = -EFAULT;
+	}
+
+	return result;
+}
+
+/**
+ * homa_hash() - Not needed for Homa.
+ * @sk:    Socket for the operation
+ * Return: ??
+ */
+int homa_hash(struct sock *sk)
+{
+	return 0;
+}
+
+/**
+ * homa_unhash() - Not needed for Homa.
+ * @sk:    Socket for the operation
+ */
+void homa_unhash(struct sock *sk)
+{
+}
+
+/**
+ * homa_softirq() - This function is invoked at SoftIRQ level to handle
+ * incoming packets.
+ * @skb:   The incoming packet.
+ * Return: Always 0
+ */
+int homa_softirq(struct sk_buff *skb)
+{
+	struct sk_buff *packets, *other_pkts, *next;
+	struct sk_buff **prev_link, **other_link;
+	enum skb_drop_reason reason;
+	struct homa_common_hdr *h;
+	int header_offset;
+
+	/* skb may actually contain many distinct packets, linked through
+	 * skb_shinfo(skb)->frag_list by the Homa GRO mechanism. Make a
+	 * pass through the list to process all of the short packets,
+	 * leaving the longer packets in the list. Also, perform various
+	 * prep/cleanup/error checking functions.
+	 */
+	skb->next = skb_shinfo(skb)->frag_list;
+	skb_shinfo(skb)->frag_list = NULL;
+	packets = skb;
+	prev_link = &packets;
+	for (skb = packets; skb; skb = next) {
+		next = skb->next;
+
+		/* Make the header available at skb->data, even if the packet
+		 * is fragmented. One complication: it's possible that the IP
+		 * header hasn't yet been removed (this happens for GRO packets
+		 * on the frag_list, since they aren't handled explicitly by IP.
+		 */
+		if (!homa_make_header_avl(skb)) {
+			reason = SKB_DROP_REASON_HDR_TRUNC;
+			goto discard;
+		}
+		header_offset = skb_transport_header(skb) - skb->data;
+		if (header_offset)
+			__skb_pull(skb, header_offset);
+
+		/* Reject packets that are too short or have bogus types. */
+		h = (struct homa_common_hdr *)skb->data;
+		if (unlikely(skb->len < sizeof(struct homa_common_hdr) ||
+			     h->type < DATA || h->type > MAX_OP ||
+			     skb->len < header_lengths[h->type - DATA])) {
+			reason = SKB_DROP_REASON_PKT_TOO_SMALL;
+			goto discard;
+		}
+
+		/* Process the packet now if it is a control packet or
+		 * if it contains an entire short message.
+		 */
+		if (h->type != DATA || ntohl(((struct homa_data_hdr *)h)
+				->message_length) < 1400) {
+			*prev_link = skb->next;
+			skb->next = NULL;
+			homa_dispatch_pkts(skb);
+		} else {
+			prev_link = &skb->next;
+		}
+		continue;
+
+discard:
+		*prev_link = skb->next;
+		kfree_skb_reason(skb, reason);
+	}
+
+	/* Now process the longer packets. Each iteration of this loop
+	 * collects all of the packets for a particular RPC and dispatches
+	 * them (batching the packets for an RPC allows more efficient
+	 * generation of grants).
+	 */
+	while (packets) {
+		struct in6_addr saddr, saddr2;
+		struct homa_common_hdr *h2;
+		struct sk_buff *skb2;
+
+		skb = packets;
+		prev_link = &skb->next;
+		saddr = skb_canonical_ipv6_saddr(skb);
+		other_pkts = NULL;
+		other_link = &other_pkts;
+		h = (struct homa_common_hdr *)skb->data;
+		for (skb2 = skb->next; skb2; skb2 = next) {
+			next = skb2->next;
+			h2 = (struct homa_common_hdr *)skb2->data;
+			if (h2->sender_id == h->sender_id) {
+				saddr2 = skb_canonical_ipv6_saddr(skb2);
+				if (ipv6_addr_equal(&saddr, &saddr2)) {
+					*prev_link = skb2;
+					prev_link = &skb2->next;
+					continue;
+				}
+			}
+			*other_link = skb2;
+			other_link = &skb2->next;
+		}
+		*prev_link = NULL;
+		*other_link = NULL;
+		homa_dispatch_pkts(packets);
+		packets = other_pkts;
+	}
+
+	return 0;
+}
+
+/**
+ * homa_err_handler_v4() - Invoked by IP to handle an incoming error
+ * packet, such as ICMP UNREACHABLE.
+ * @skb:    The incoming packet; skb->data points to the byte just after
+ *          the ICMP header (the first byte of the embedded packet IP header).
+ * @skb:   The incoming packet.
+ * @info:  Information about the error that occurred?
+ *
+ * Return: zero, or a negative errno if the error couldn't be handled here.
+ */
+int homa_err_handler_v4(struct sk_buff *skb, u32 info)
+{
+	struct homa *homa = homa_net(dev_net(skb->dev))->homa;
+	const struct icmphdr *icmp = icmp_hdr(skb);
+	struct in6_addr daddr;
+	int type = icmp->type;
+	int code = icmp->code;
+	struct iphdr *iph;
+	int error = 0;
+	int port = 0;
+
+	iph = (struct iphdr *)(skb->data);
+	ipv6_addr_set_v4mapped(iph->daddr, &daddr);
+	if (type == ICMP_DEST_UNREACH && code == ICMP_PORT_UNREACH) {
+		struct homa_common_hdr *h = (struct homa_common_hdr *)(skb->data
+				+ iph->ihl * 4);
+
+		port = ntohs(h->dport);
+		error = -ENOTCONN;
+	} else if (type == ICMP_DEST_UNREACH) {
+		if (code == ICMP_PROT_UNREACH)
+			error = -EPROTONOSUPPORT;
+		else
+			error = -EHOSTUNREACH;
+	} else {
+		pr_notice("%s invoked with info %x, ICMP type %d, ICMP code %d\n",
+			  __func__, info, type, code);
+	}
+	if (error != 0)
+		homa_abort_rpcs(homa, &daddr, port, error);
+	return 0;
+}
+
+/**
+ * homa_err_handler_v6() - Invoked by IP to handle an incoming error
+ * packet, such as ICMP UNREACHABLE.
+ * @skb:    The incoming packet; skb->data points to the byte just after
+ *          the ICMP header (the first byte of the embedded packet IP header).
+ * @opt:    Not used.
+ * @type:   Type of ICMP packet.
+ * @code:   Additional information about the error.
+ * @offset: Total length of IPv6 header, including any extension headers.
+ * @info:   Information about the error that occurred?
+ *
+ * Return: zero, or a negative errno if the error couldn't be handled here.
+ */
+int homa_err_handler_v6(struct sk_buff *skb, struct inet6_skb_parm *opt,
+			u8 type,  u8 code,  int offset,  __be32 info)
+{
+	const struct ipv6hdr *iph = (const struct ipv6hdr *)skb->data;
+	struct homa *homa = homa_net(dev_net(skb->dev))->homa;
+	int error = 0;
+	int port = 0;
+
+	if (type == ICMPV6_DEST_UNREACH && code == ICMPV6_PORT_UNREACH) {
+		const struct homa_common_hdr *h;
+
+		h = (struct homa_common_hdr *)(skb->data + offset);
+		port = ntohs(h->dport);
+		error = -ENOTCONN;
+	} else if (type == ICMPV6_DEST_UNREACH && code == ICMPV6_ADDR_UNREACH) {
+		error = -EHOSTUNREACH;
+	} else if (type == ICMPV6_PARAMPROB && code == ICMPV6_UNK_NEXTHDR) {
+		error = -EPROTONOSUPPORT;
+	}
+	if (error != 0)
+		homa_abort_rpcs(homa, &iph->daddr, port, error);
+	return 0;
+}
+
+/**
+ * homa_poll() - Invoked by Linux as part of implementing select, poll,
+ * epoll, etc.
+ * @file:  Open file that is participating in a poll, select, etc.
+ * @sock:  A Homa socket, associated with @file.
+ * @wait:  This table will be registered with the socket, so that it
+ *         is notified when the socket's ready state changes.
+ *
+ * Return: A mask of bits such as EPOLLIN, which indicate the current
+ *         state of the socket.
+ */
+__poll_t homa_poll(struct file *file, struct socket *sock,
+		   struct poll_table_struct *wait)
+{
+	struct homa_sock *hsk = homa_sk(sock->sk);
+	__poll_t mask;
+
+	mask = 0;
+	sock_poll_wait(file, sock, wait);
+	if (homa_sock_wmem_avl(hsk))
+		mask |= EPOLLOUT | EPOLLWRNORM;
+	else
+		set_bit(HOMA_SOCK_NOSPACE, &hsk->flags);
+
+	if (hsk->shutdown)
+		mask |= EPOLLIN;
+
+	if (!list_empty(&hsk->ready_rpcs))
+		mask |= EPOLLIN | EPOLLRDNORM;
+	return mask;
+}
+
+/**
+ * homa_hrtimer() - This function is invoked by the hrtimer mechanism to
+ * wake up the timer thread. Runs at IRQ level.
+ * @timer:   The timer that triggered; not used.
+ *
+ * Return:   Always HRTIMER_NORESTART.
+ */
+enum hrtimer_restart homa_hrtimer(struct hrtimer *timer)
+{
+	wake_up_process(timer_kthread);
+	return HRTIMER_NORESTART;
+}
+
+/**
+ * homa_timer_main() - Top-level function for the timer thread.
+ * @transport:  Pointer to struct homa.
+ *
+ * Return:         Always 0.
+ */
+int homa_timer_main(void *transport)
+{
+	struct homa *homa = (struct homa *)transport;
+	ktime_t tick_interval;
+	u64 nsec;
+
+	hrtimer_setup(&hrtimer, homa_hrtimer, CLOCK_MONOTONIC,
+		      HRTIMER_MODE_REL);
+	nsec = 1000000;                   /* 1 ms */
+	tick_interval = ns_to_ktime(nsec);
+	while (1) {
+		set_current_state(TASK_UNINTERRUPTIBLE);
+		if (!kthread_should_stop()) {
+			hrtimer_start(&hrtimer, tick_interval,
+				      HRTIMER_MODE_REL);
+			schedule();
+		}
+		__set_current_state(TASK_RUNNING);
+		if (kthread_should_stop())
+			break;
+		homa_timer(homa);
+	}
+	hrtimer_cancel(&hrtimer);
+	return 0;
+}
+
+MODULE_LICENSE("Dual BSD/GPL");
+MODULE_AUTHOR("John Ousterhout <ouster@cs.stanford.edu>");
+MODULE_DESCRIPTION("Homa transport protocol");
+MODULE_VERSION("1.0");
+
+/* Arrange for this module to be loaded automatically when a Homa socket is
+ * opened. Apparently symbols don't work in the macros below, so must use
+ * numeric values for IPPROTO_HOMA (146) and SOCK_DGRAM(2).
+ */
+MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET, 146, 2);
+MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET6, 146, 2);
diff --git a/net/homa/homa_pool.c b/net/homa/homa_pool.c
new file mode 100644
index 0000000000000..0aadfbc53ef1b
--- /dev/null
+++ b/net/homa/homa_pool.c
@@ -0,0 +1,553 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+#include "homa_impl.h"
+#include "homa_pool.h"
+
+/* This file contains functions that manage user-space buffer pools. */
+
+/* Used when determining how many bpages to consider for allocation. */
+#define MIN_EXTRA 4
+
+/**
+ * set_bpages_needed() - Set the bpages_needed field of @pool based
+ * on the length of the first RPC that's waiting for buffer space.
+ * The caller must own the lock for @pool->hsk.
+ * @pool: Pool to update.
+ */
+static void set_bpages_needed(struct homa_pool *pool)
+{
+	struct homa_rpc *rpc = list_first_entry(&pool->hsk->waiting_for_bufs,
+						struct homa_rpc, buf_links);
+
+	pool->bpages_needed = (rpc->msgin.length + HOMA_BPAGE_SIZE - 1) >>
+			      HOMA_BPAGE_SHIFT;
+}
+
+/**
+ * homa_pool_alloc() - Allocate and initialize a new homa_pool (it will have
+ * no region associated with it until homa_pool_set_region is invoked).
+ * @hsk:          Socket the pool will be associated with.
+ * Return: A pointer to the new pool or a negative errno.
+ */
+struct homa_pool *homa_pool_alloc(struct homa_sock *hsk)
+{
+	struct homa_pool *pool;
+
+	pool = kzalloc_obj(*pool, GFP_KERNEL_ACCOUNT);
+	if (!pool)
+		return ERR_PTR(-ENOMEM);
+	pool->hsk = hsk;
+	return pool;
+}
+
+/**
+ * homa_pool_set_region() - Associate a region of memory with a pool.
+ * @hsk:          Socket whose pool the region will be associated with.
+ *                Must not be locked, and the pool must not currently
+ *                have a region associated with it.
+ * @region:       First byte of the memory region for the pool, allocated
+ *                by the application; must be page-aligned.
+ * @region_size:  Total number of bytes available at @buf_region.
+ * Return: Either zero (for success) or a negative errno for failure.
+ */
+int homa_pool_set_region(struct homa_sock *hsk, void __user *region,
+			 u64 region_size)
+{
+	struct homa_pool_core __percpu *cores;
+	struct homa_bpage *descriptors;
+	int i, result, num_bpages;
+	struct homa_pool *pool;
+	u64 min_size;
+
+	if (((uintptr_t)region) & ~PAGE_MASK) {
+		hsk->error_msg = "buffer pool is not page aligned";
+		return -EINVAL;
+	}
+
+	/* The region must be large enough to hold a private bpage for
+	 * each core, plus enough additional space for a couple of
+	 * full-size messages. Otherwise we could deadlock over allocation
+	 * (no free pages available, so no attempt is made to steal back
+	 * private pages).
+	 */
+	min_size = nr_cpu_ids;
+	min_size = min_size * HOMA_BPAGE_SIZE + 2 * HOMA_MAX_MESSAGE_LENGTH;
+	if (region_size < min_size) {
+		hsk->error_msg = "buffer pool is not large enough";
+		return -EINVAL;
+	}
+
+	/* The region must not be so large that offsets into the region
+	 * overflow the 32-bit values used in bpage_offsets in
+	 * homa_recvmsg_args.
+	 */
+	if (region_size > 0x100000000ULL) {
+		hsk->error_msg = "buffer pool cannot be larger than 4 GB";
+		return -EINVAL;
+	}
+
+	/* Allocate memory before locking the socket, so we can allocate
+	 * without GFP_ATOMIC.
+	 */
+	num_bpages = region_size >> HOMA_BPAGE_SHIFT;
+	descriptors = kmalloc_array(num_bpages, sizeof(struct homa_bpage),
+				    GFP_KERNEL | __GFP_ZERO | __GFP_ACCOUNT);
+	if (!descriptors)
+		return -ENOMEM;
+	cores = alloc_percpu_gfp(struct homa_pool_core, __GFP_ZERO);
+	if (!cores) {
+		result = -ENOMEM;
+		goto error;
+	}
+
+	homa_sock_lock(hsk);
+	pool = hsk->buffer_pool;
+	if (pool->region) {
+		result = -EINVAL;
+		homa_sock_unlock(hsk);
+		goto error;
+	}
+
+	pool->num_bpages = num_bpages;
+	pool->descriptors = descriptors;
+	atomic_set(&pool->free_bpages, pool->num_bpages);
+	pool->bpages_needed = INT_MAX;
+	pool->cores = cores;
+	pool->check_waiting_invoked = 0;
+
+	for (i = 0; i < pool->num_bpages; i++) {
+		struct homa_bpage *bp = &pool->descriptors[i];
+
+		spin_lock_init(&bp->lock);
+		bp->owner = -1;
+	}
+
+	/* Barrier ensures that concurrent cores trying to access
+	 * newly-created region will see all the region's data.
+	 */
+	smp_store_release(&pool->region, (char __user *)region);
+	homa_sock_unlock(hsk);
+	return 0;
+
+error:
+	kfree(descriptors);
+	free_percpu(cores);
+	return result;
+}
+
+/**
+ * homa_pool_free() - Destructor for homa_pool. After this method
+ * returns, the object should not be used (it will be freed here).
+ * @pool: Pool to destroy.
+ */
+void homa_pool_free(struct homa_pool *pool)
+{
+	if (homa_pool_exists(pool)) {
+		kfree(pool->descriptors);
+		free_percpu(pool->cores);
+		pool->region = NULL;
+	}
+	kfree(pool);
+}
+
+/**
+ * homa_pool_get_rcvbuf() - Return information needed to handle getsockopt
+ * for HOMA_SO_RCVBUF.
+ * @pool:         Pool for which information is needed.
+ * @args:         Store info here.
+ */
+void homa_pool_get_rcvbuf(struct homa_pool *pool,
+			  struct homa_rcvbuf_args *args)
+{
+	args->start = (uintptr_t)pool->region;
+	args->length = (u64)pool->num_bpages << HOMA_BPAGE_SHIFT;
+}
+
+/**
+ * homa_bpage_available() - Check whether a bpage is available for use.
+ * @bpage:      Bpage to check
+ * @now:        Current time (homa_clock() units)
+ * Return:      True if the bpage is free or if it can be stolen, otherwise
+ *              false.
+ */
+bool homa_bpage_available(struct homa_bpage *bpage, u64 now)
+{
+	return bpage->refs == 0 || (bpage->refs == 1 && bpage->owner >= 0 &&
+				    bpage->expiration <= now);
+}
+
+/**
+ * homa_pool_get_pages() - Allocate one or more full pages from the pool.
+ * @pool:         Pool from which to allocate pages
+ * @num_pages:    Number of pages needed
+ * @pages:        The indices of the allocated pages are stored here; caller
+ *                must ensure this array is big enough. Reference counts have
+ *                been set to 1 on all of these pages (or 2 if set_owner
+ *                was specified).
+ * @set_owner:    If nonzero, the current core is marked as owner of all
+ *                of the allocated pages (and the expiration time is also
+ *                set). Otherwise the pages are left unowned.
+ * Return: 0 for success, -1 if there wasn't enough free space in the pool.
+ */
+int homa_pool_get_pages(struct homa_pool *pool, int num_pages, u32 *pages,
+			int set_owner)
+{
+	int core_num = smp_processor_id();
+	struct homa_pool_core *core;
+	u64 now = homa_clock();
+	int alloced = 0;
+	int limit = 0;
+	int free;
+
+	core = this_cpu_ptr(pool->cores);
+
+	/* Atomically check for available space and decrement the
+	 * free page counter.
+	 */
+	free = atomic_read_acquire(&pool->free_bpages);
+	while (1) {
+		if (free < num_pages)
+			return -1;
+		if (atomic_try_cmpxchg(&pool->free_bpages, &free,
+				       free - num_pages))
+			break;
+	}
+
+	/* Once we get to this point we know we will be able to find
+	 * enough free pages; now we just have to find them.
+	 */
+	while (alloced != num_pages) {
+		struct homa_bpage *bpage;
+		int cur;
+
+		/* If we don't need to use all of the bpages in the pool,
+		 * then try to use only the ones with low indexes. This
+		 * will reduce the cache footprint for the pool by reusing
+		 * a few bpages over and over. Specifically this code will
+		 * not consider any candidate page whose index is >= limit.
+		 * Limit is chosen to make sure there are a reasonable
+		 * number of free pages in the range, so we won't have to
+		 * check a huge number of pages.
+		 */
+		if (limit == 0) {
+			int extra;
+
+			limit = pool->num_bpages -
+				atomic_read(&pool->free_bpages);
+			extra = limit >> 2;
+			limit += (extra < MIN_EXTRA) ? MIN_EXTRA : extra;
+			if (limit > pool->num_bpages)
+				limit = pool->num_bpages;
+		}
+
+		cur = core->next_candidate;
+		core->next_candidate++;
+		if (cur >= limit) {
+			core->next_candidate = 0;
+
+			/* Must recompute the limit for each new loop through
+			 * the bpage array: we may need to consider a larger
+			 * range of pages because of concurrent allocations.
+			 */
+			limit = 0;
+			continue;
+		}
+		bpage = &pool->descriptors[cur];
+
+		/* Figure out whether this candidate is free (or can be
+		 * stolen). Do a quick check without locking the page, and
+		 * if the page looks promising, then lock it and check again
+		 * (must check again in case someone else snuck in and
+		 * grabbed the page).
+		 */
+		if (!homa_bpage_available(bpage, now))
+			continue;
+		if (!spin_trylock_bh(&bpage->lock))
+			/* Rather than wait for a locked page to become free,
+			 * just go on to the next page. If the page is locked,
+			 * it probably won't turn out to be available anyway.
+			 */
+			continue;
+		if (!homa_bpage_available(bpage, now)) {
+			spin_unlock_bh(&bpage->lock);
+			continue;
+		}
+		if (bpage->owner >= 0)
+			atomic_fetch_inc_release(&pool->free_bpages);
+		if (set_owner) {
+			bpage->refs = 2;
+			bpage->owner = core_num;
+			bpage->expiration = now +
+					    pool->hsk->homa->bpage_lease_cycles;
+		} else {
+			bpage->refs = 1;
+			bpage->owner = -1;
+		}
+		spin_unlock_bh(&bpage->lock);
+		pages[alloced] = cur;
+		alloced++;
+	}
+	return 0;
+}
+
+/**
+ * homa_pool_alloc_msg() - Allocate buffer space for an incoming message.
+ * @rpc:  RPC that needs space allocated for its incoming message (space must
+ *        not already have been allocated). The fields @msgin->num_buffers
+ *        and @msgin->buffers are filled in. Must be locked by caller.
+ * Return: The return value is normally 0, which means either buffer space
+ * was allocated or the @rpc was queued on @hsk->waiting. If a fatal error
+ * occurred, such as no buffer pool present, then a negative errno is
+ * returned.
+ */
+int homa_pool_alloc_msg(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_pool *pool = rpc->hsk->buffer_pool;
+	int full_pages, partial, i, core_id;
+	struct homa_pool_core *core;
+	u32 pages[HOMA_MAX_BPAGES];
+	struct homa_bpage *bpage;
+	struct homa_rpc *other;
+
+	if (!homa_pool_exists(pool))
+		return -ENOMEM;
+	if (rpc->state == RPC_DEAD)
+		return 0;
+
+	/* First allocate any full bpages that are needed. */
+	full_pages = rpc->msgin.length >> HOMA_BPAGE_SHIFT;
+	if (unlikely(full_pages)) {
+		if (homa_pool_get_pages(pool, full_pages, pages, 0) != 0)
+			goto out_of_space;
+		for (i = 0; i < full_pages; i++)
+			rpc->msgin.bpage_offsets[i] = pages[i] <<
+					HOMA_BPAGE_SHIFT;
+	}
+	rpc->msgin.num_bpages = full_pages;
+
+	/* The last chunk may be less than a full bpage; for this we use
+	 * the bpage that we own (and reuse it for multiple messages).
+	 */
+	partial = rpc->msgin.length & (HOMA_BPAGE_SIZE - 1);
+	if (unlikely(partial == 0))
+		goto success;
+	core_id = smp_processor_id();
+	core = this_cpu_ptr(pool->cores);
+	bpage = &pool->descriptors[core->page_hint];
+	spin_lock_bh(&bpage->lock);
+	if (bpage->owner != core_id) {
+		spin_unlock_bh(&bpage->lock);
+		goto new_page;
+	}
+	if ((core->allocated + partial) > HOMA_BPAGE_SIZE) {
+		if (bpage->refs == 1) {
+			/* Bpage is totally free, so we can reuse it. */
+			core->allocated = 0;
+		} else {
+			bpage->owner = -1;
+
+			/* We know the reference count can't reach zero here
+			 * because of check above, so we won't have to decrement
+			 * pool->free_bpages.
+			 */
+			bpage->refs--;
+			spin_unlock_bh(&bpage->lock);
+			goto new_page;
+		}
+	}
+	bpage->expiration = homa_clock() +
+			    pool->hsk->homa->bpage_lease_cycles;
+	bpage->refs++;
+	spin_unlock_bh(&bpage->lock);
+	goto allocate_partial;
+
+	/* Can't use the current page; get another one. */
+new_page:
+	if (homa_pool_get_pages(pool, 1, pages, 1) != 0) {
+		homa_pool_free_bufs(pool, rpc->msgin.num_bpages,
+				    rpc->msgin.bpage_offsets);
+		rpc->msgin.num_bpages = 0;
+		goto out_of_space;
+	}
+	core->page_hint = pages[0];
+	core->allocated = 0;
+
+allocate_partial:
+	rpc->msgin.bpage_offsets[rpc->msgin.num_bpages] = core->allocated
+			+ (core->page_hint << HOMA_BPAGE_SHIFT);
+	rpc->msgin.num_bpages++;
+	core->allocated += partial;
+
+success:
+	return 0;
+
+	/* We get here if there wasn't enough buffer space for this
+	 * message; add the RPC to hsk->waiting_for_bufs. The list is sorted
+	 * by RPC length in order to implement SRPT.
+	 */
+out_of_space:
+	homa_sock_lock(pool->hsk);
+	list_for_each_entry(other, &pool->hsk->waiting_for_bufs, buf_links) {
+		if (other->msgin.length > rpc->msgin.length) {
+			list_add_tail(&rpc->buf_links, &other->buf_links);
+			goto queued;
+		}
+	}
+	list_add_tail(&rpc->buf_links, &pool->hsk->waiting_for_bufs);
+
+queued:
+	set_bpages_needed(pool);
+	homa_sock_unlock(pool->hsk);
+	return 0;
+}
+
+/**
+ * homa_pool_get_buffer() - Given an RPC, figure out where to store incoming
+ * message data.
+ * @rpc:        RPC for which incoming message data is being processed; its
+ *              msgin must be properly initialized and buffer space must have
+ *              been allocated for the message.
+ * @offset:     Offset within @rpc's incoming message.
+ * @available:  Will be filled in with the number of bytes of space available
+ *              at the returned address (could be zero if offset is
+ *              (erroneously) past the end of the message).
+ * Return:      The application's virtual address for buffer space corresponding
+ *              to @offset in the incoming message for @rpc.
+ */
+void __user *homa_pool_get_buffer(struct homa_rpc *rpc, int offset,
+				  int *available)
+{
+	int bpage_index, bpage_offset;
+
+	bpage_index = offset >> HOMA_BPAGE_SHIFT;
+	if (offset >= rpc->msgin.length) {
+		WARN_ONCE(true, "%s got offset %d >= message length %d\n",
+			  __func__, offset, rpc->msgin.length);
+		*available = 0;
+		return NULL;
+	}
+	bpage_offset = offset & (HOMA_BPAGE_SIZE - 1);
+	*available = (bpage_index < (rpc->msgin.num_bpages - 1))
+			? HOMA_BPAGE_SIZE - bpage_offset
+			: rpc->msgin.length - offset;
+	return rpc->hsk->buffer_pool->region +
+			rpc->msgin.bpage_offsets[bpage_index] + bpage_offset;
+}
+
+/**
+ * homa_pool_free_bufs() - Release buffer space so that it can be
+ * reused.
+ * @pool:         Pool that the buffer space belongs to. Doesn't need to
+ *                be locked.
+ * @num_buffers:  How many buffers to release.
+ * @buffers:      Points to @num_buffers values, each of which is an offset
+ *                from the start of the pool to the buffer to be released.
+ * Return:        0 for success, otherwise a negative errno.
+ */
+int homa_pool_free_bufs(struct homa_pool *pool, int num_buffers, u32 *buffers)
+{
+	int i;
+
+	if (!homa_pool_exists(pool))
+		return -EINVAL;
+	for (i = 0; i < num_buffers; i++) {
+		u32 bpage_index = buffers[i] >> HOMA_BPAGE_SHIFT;
+		struct homa_bpage *bpage;
+
+		if (bpage_index >= pool->num_bpages)
+			return -EINVAL;
+		bpage = &pool->descriptors[bpage_index];
+
+		spin_lock_bh(&bpage->lock);
+		if (bpage->refs == 0 || (bpage->refs == 1 &&
+					 bpage->owner >= 0)) {
+			/* This bpage is already free; looks like the app
+			 * has misbehaved and freed an offset multiple times.
+			 */
+			spin_unlock_bh(&bpage->lock);
+			return -EINVAL;
+		}
+		bpage->refs--;
+		if (bpage->refs == 0)
+			atomic_fetch_inc(&pool->free_bpages);
+		spin_unlock_bh(&bpage->lock);
+	}
+	return 0;
+}
+
+/**
+ * homa_pool_check_waiting() - Checks to see if there are enough free
+ * bpages to wake up any RPCs that were blocked. Whenever
+ * homa_pool_free_bufs is invoked, this function must be invoked later,
+ * at a point when the caller holds no locks (homa_pool_free_bufs may
+ * be invoked with locks held, so it can't safely invoke this function).
+ * This is regrettably tricky, but I can't think of a better solution.
+ * @pool:         Information about the buffer pool.
+ */
+void homa_pool_check_waiting(struct homa_pool *pool)
+{
+	if (!homa_pool_exists(pool))
+		return;
+	while (atomic_read_acquire(&pool->free_bpages) >= pool->bpages_needed) {
+		struct homa_rpc *rpc;
+
+		homa_sock_lock(pool->hsk);
+		if (list_empty(&pool->hsk->waiting_for_bufs)) {
+			pool->bpages_needed = INT_MAX;
+			homa_sock_unlock(pool->hsk);
+			break;
+		}
+		rpc = list_first_entry(&pool->hsk->waiting_for_bufs,
+				       struct homa_rpc, buf_links);
+		if (!homa_rpc_try_lock(rpc)) {
+			/* Can't just spin on the RPC lock because we're
+			 * holding the socket lock and the lock order is
+			 * rpc-then-socket (see "Homa Locking Strategy" in
+			 * homa_impl.h). Instead, release the socket lock
+			 * and try the entire operation again.
+			 */
+			homa_sock_unlock(pool->hsk);
+			cpu_relax();
+			continue;
+		}
+		list_del_init(&rpc->buf_links);
+		if (list_empty(&pool->hsk->waiting_for_bufs))
+			pool->bpages_needed = INT_MAX;
+		else
+			set_bpages_needed(pool);
+		homa_sock_unlock(pool->hsk);
+		homa_pool_alloc_msg(rpc);
+		homa_rpc_unlock(rpc);
+	}
+}
+
+/**
+ * homa_pool_avail_bytes() - Return a count of the number of bytes currently
+ * unused and available for allocation in a pool.
+ * @pool:    Pool of interest.
+ * Return:    See above.
+ */
+u64 homa_pool_avail_bytes(struct homa_pool *pool)
+{
+	struct homa_pool_core *core;
+	struct homa_bpage *bpage;
+	u64 avail;
+	int cpu;
+
+	if (!homa_pool_exists(pool))
+		return 0;
+	avail = atomic_read(&pool->free_bpages);
+	avail *= HOMA_BPAGE_SIZE;
+	for (cpu = 0; cpu < nr_cpu_ids; cpu++) {
+		core = per_cpu_ptr(pool->cores, cpu);
+		bpage = &pool->descriptors[core->page_hint];
+		if (bpage->owner == cpu) {
+			if (bpage->refs > 1)
+				avail += HOMA_BPAGE_SIZE - core->allocated;
+			else
+				avail += HOMA_BPAGE_SIZE;
+		}
+	}
+	return avail;
+}
diff --git a/net/homa/homa_pool.h b/net/homa/homa_pool.h
new file mode 100644
index 0000000000000..80b14475d0be2
--- /dev/null
+++ b/net/homa/homa_pool.h
@@ -0,0 +1,184 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file contains definitions used to manage user-space buffer pools.
+ */
+
+#ifndef _HOMA_POOL_H
+#define _HOMA_POOL_H
+
+#include <linux/percpu.h>
+
+#include "homa_rpc.h"
+
+/**
+ * struct homa_bpage - Contains information about a single page in
+ * a buffer pool.
+ */
+struct homa_bpage {
+	/** @lock: to synchronize shared access. */
+	spinlock_t lock;
+
+	/**
+	 * @refs: Counts number of distinct uses of this
+	 * bpage (1 tick for each message that is using
+	 * this page, plus an additional tick if the @owner
+	 * field is set).
+	 */
+	int refs;
+
+	/**
+	 * @owner: kernel core that currently owns this page
+	 * (< 0 if none).
+	 */
+	int owner;
+
+	/**
+	 * @expiration: homa_clock() time after which it's OK to steal this
+	 * page from its current owner (if @refs is 1).
+	 */
+	u64 expiration;
+} ____cacheline_aligned_in_smp;
+
+/**
+ * struct homa_pool_core - Holds core-specific data for a homa_pool (a bpage
+ * out of which that core is allocating small chunks).
+ */
+struct homa_pool_core {
+	/**
+	 * @page_hint: Index of bpage in pool->descriptors,
+	 * which may be owned by this core. If so, we'll use it
+	 * for allocating partial pages.
+	 */
+	int page_hint;
+
+	/**
+	 * @allocated: if the page given by @page_hint is
+	 * owned by this core, this variable gives the number of
+	 * (initial) bytes that have already been allocated
+	 * from the page.
+	 */
+	int allocated;
+
+	/**
+	 * @next_candidate: when searching for free bpages,
+	 * check this index next.
+	 */
+	int next_candidate;
+};
+
+/**
+ * struct homa_pool - Describes a pool of buffer space for incoming
+ * messages for a particular socket; managed by homa_pool.c. The pool is
+ * divided up into "bpages", which are a multiple of the hardware page size.
+ * A bpage may be owned by a particular core so that it can more efficiently
+ * allocate space for small messages.
+ */
+struct homa_pool {
+	/**
+	 * @hsk: the socket that this pool belongs to.
+	 */
+	struct homa_sock *hsk;
+
+	/**
+	 * @region: beginning of the pool's region (in the app's virtual
+	 * memory). Divided into bpages. 0 means the pool hasn't yet been
+	 * initialized. This pointer is used for lock-free synchronization
+	 * between a core creating the region and other cores attempting
+	 * to use it.
+	 */
+	char __user *region;
+
+	/** @num_bpages: total number of bpages in the pool. */
+	int num_bpages;
+
+	/** @descriptors: kmalloced area containing one entry for each bpage. */
+	struct homa_bpage *descriptors;
+
+	/**
+	 * @free_bpages: the number of pages still available for allocation
+	 * by homa_pool_get_pages. This equals the number of pages with zero
+	 * reference counts, minus the number of pages that have been claimed
+	 * by homa_pool_get_pages but not yet allocated.
+	 */
+	atomic_t free_bpages;
+
+	/**
+	 * @bpages_needed: the number of free bpages required to satisfy the
+	 * needs of the first RPC on @hsk->waiting_for_bufs, or INT_MAX if
+	 * that queue is empty.
+	 */
+	int bpages_needed;
+
+	/** @cores: core-specific info; dynamically allocated. */
+	struct homa_pool_core __percpu *cores;
+
+	/**
+	 * @check_waiting_invoked: incremented during unit tests when
+	 * homa_pool_check_waiting is invoked.
+	 */
+	int check_waiting_invoked;
+};
+
+bool     homa_bpage_available(struct homa_bpage *bpage, u64 now);
+struct   homa_pool *homa_pool_alloc(struct homa_sock *hsk);
+int      homa_pool_alloc_msg(struct homa_rpc *rpc);
+u64      homa_pool_avail_bytes(struct homa_pool *pool);
+void     homa_pool_check_waiting(struct homa_pool *pool);
+void     homa_pool_free(struct homa_pool *pool);
+void __user *homa_pool_get_buffer(struct homa_rpc *rpc, int offset,
+				  int *available);
+int      homa_pool_get_pages(struct homa_pool *pool, int num_pages,
+			     u32 *pages, int leave_locked);
+void     homa_pool_get_rcvbuf(struct homa_pool *pool,
+			      struct homa_rcvbuf_args *args);
+int      homa_pool_free_bufs(struct homa_pool *pool, int num_buffers,
+			     u32 *buffers);
+int      homa_pool_set_region(struct homa_sock *hsk, void __user *region,
+			      u64 region_size);
+
+/**
+ * homa_pool_unlink() - Remove an RPC from any lists related to buffer
+ * pool memory, so the RPC will not be accessed by this module again.
+ * @rpc:     RPC to unlink. Must be locked, and the rpc's socket must
+ *           also be locked.
+ */
+static inline void homa_pool_unlink(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+	__must_hold(rpc->hsk->lock)
+{
+	list_del_init(&rpc->buf_links);
+}
+
+/**
+ * homa_pool_release() - Invoked when RPCs are being reaped: releases
+ * pool space owned by the RPC.
+ * @rpc:        RPC to clean up. Caller must ensure that no-one else can
+ *              access the RPC concurrently (e.g., it is being reaped).
+ */
+static inline void homa_pool_release(struct homa_rpc *rpc)
+{
+	if (rpc->msgin.num_bpages > 0) {
+		homa_pool_free_bufs(rpc->hsk->buffer_pool,
+				    rpc->msgin.num_bpages,
+				    rpc->msgin.bpage_offsets);
+		rpc->msgin.num_bpages = 0;
+	}
+}
+
+/**
+ * homa_pool_exists() - Determine whether a pool has been fully initialized
+ * with a memory region.
+ * @pool:     Pool to check.
+ * Return:    True if there is a memory region associated with the pool,
+ *            false if SO_HOMA_RCVBUF hasn't been invoked for the socket.
+ */
+static inline bool homa_pool_exists(struct homa_pool *pool)
+{
+	/* This barrier allows lockless concurrent allocation of the pool:
+	 * it ensures that if the pool exists we'll see all of the initialized
+	 * values related to the pool.
+	 */
+	return smp_load_acquire(&pool->region) != NULL;
+}
+
+#endif /* _HOMA_POOL_H */
diff --git a/net/homa/homa_rpc.c b/net/homa/homa_rpc.c
new file mode 100644
index 0000000000000..3c94489641c21
--- /dev/null
+++ b/net/homa/homa_rpc.c
@@ -0,0 +1,735 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file contains functions for managing homa_rpc structs. */
+
+#include "homa_impl.h"
+#include "homa_interest.h"
+#include "homa_peer.h"
+#include "homa_pool.h"
+#include "homa_tx_pool.h"
+
+/**
+ * homa_rpc_alloc_client() - Allocate and initialize a client RPC (one that
+ * is used to issue an outgoing request). Doesn't send any packets. Invoked
+ * with no locks held.
+ * @hsk:      Socket to which the RPC belongs.
+ * @dest:     Address of host (ip and port) to which the RPC will be sent.
+ *
+ * Return:    A pointer to the newly allocated object, or a negative
+ *            errno if an error occurred. The RPC will be locked; the
+ *            caller must eventually unlock it. Sets hsk->error_msg on errors.
+ */
+struct homa_rpc *homa_rpc_alloc_client(struct homa_sock *hsk,
+				       const union sockaddr_in_union *dest)
+	__cond_acquires(nonnull, crpc->bucket->lock)
+{
+	struct in6_addr dest_addr_as_ipv6 = canonical_ipv6_addr(dest);
+	struct homa_rpc_bucket *bucket;
+	struct homa_rpc *crpc;
+	int err;
+
+	crpc = kzalloc_obj(*crpc, GFP_KERNEL_ACCOUNT);
+	if (unlikely(!crpc)) {
+		hsk->error_msg = "couldn't allocate memory for client RPC";
+		return ERR_PTR(-ENOMEM);
+	}
+
+	/* Initialize fields that don't require the socket lock. */
+	crpc->hsk = hsk;
+	crpc->id = atomic64_fetch_add(2, &hsk->homa->next_outgoing_id);
+	bucket = homa_client_rpc_bucket(hsk, crpc->id);
+	crpc->bucket = bucket;
+	crpc->state = RPC_OUTGOING;
+	refcount_set(&crpc->refs, 1);
+	crpc->route = homa_route_get(hsk, &dest_addr_as_ipv6);
+	if (IS_ERR(crpc->route)) {
+		err = PTR_ERR(crpc->route);
+		crpc->route = NULL;
+		goto error;
+	}
+	crpc->dport = ntohs(dest->in6.sin6_port);
+	crpc->msgin.length = -1;
+	crpc->msgout.length = -1;
+	INIT_LIST_HEAD(&crpc->ready_links);
+	INIT_LIST_HEAD(&crpc->buf_links);
+	INIT_LIST_HEAD(&crpc->dead_links);
+	crpc->resend_timer_ticks = hsk->homa->timer_ticks;
+	crpc->magic = HOMA_RPC_MAGIC;
+	crpc->start_time = homa_clock();
+
+	/* Initialize fields that require locking. This allows the most
+	 * expensive work, such as copying in the message from user space,
+	 * to be performed without holding locks. Also, can't hold spin
+	 * locks while doing things that could block, such as memory allocation.
+	 */
+	homa_bucket_lock(bucket, crpc->id);
+	homa_sock_lock(hsk);
+	if (hsk->shutdown) {
+		homa_sock_unlock(hsk);
+		homa_rpc_unlock(crpc);
+		hsk->error_msg = "socket has been shut down";
+		err = -ESHUTDOWN;
+		goto error;
+	}
+	hlist_add_head(&crpc->hash_links, &bucket->rpcs);
+	rcu_read_lock();
+	list_add_tail_rcu(&crpc->active_links, &hsk->active_rpcs);
+	rcu_read_unlock();
+	homa_sock_unlock(hsk);
+
+	return crpc;
+
+error:
+	if (crpc->route)
+		homa_route_release(crpc->route);
+	kfree(crpc);
+	return ERR_PTR(err);
+}
+
+/**
+ * homa_rpc_alloc_server() - Allocate and initialize a server RPC (one that is
+ * used to manage an incoming request). If appropriate, the RPC will also
+ * be handed off (we do it here, while we have the socket locked, to avoid
+ * acquiring the socket lock a second time later for the handoff).
+ * @hsk:      Socket that owns this RPC.
+ * @source:   IP address (network byte order) of the RPC's client.
+ * @h:        Header for the first data packet received for this RPC; used
+ *            to initialize the RPC.
+ *
+ * Return:  A pointer to a new RPC, which is locked, or a negative errno
+ *          if an error occurred. If there is already an RPC corresponding
+ *          to h, then it is returned instead of creating a new RPC.
+ */
+struct homa_rpc *homa_rpc_alloc_server(struct homa_sock *hsk,
+				       const struct in6_addr *source,
+				       struct homa_data_hdr *h)
+	__cond_acquires(nonnull, srpc->bucket->lock)
+{
+	u64 id = homa_local_id(h->common.sender_id);
+	struct homa_rpc_bucket *bucket;
+	struct homa_rpc *srpc = NULL;
+	int err;
+
+	if (!hsk->buffer_pool)
+		return ERR_PTR(-ENOMEM);
+
+	/* Lock the bucket, and make sure no-one else has already created
+	 * the desired RPC.
+	 */
+	bucket = homa_server_rpc_bucket(hsk, id);
+	homa_bucket_lock(bucket, id);
+	hlist_for_each_entry(srpc, &bucket->rpcs, hash_links) {
+		if (srpc->id == id &&
+		    srpc->dport == ntohs(h->common.sport) &&
+		    ipv6_addr_equal(&srpc->route->peer->addr, source)) {
+			/* RPC already exists; just return it instead
+			 * of creating a new RPC.
+			 */
+			return srpc;
+		}
+	}
+
+	/* Initialize fields that don't require the socket lock. */
+	if (hsk->sock.sk_memcg) {
+		struct mem_cgroup *old = set_active_memcg(hsk->sock.sk_memcg);
+
+		srpc = kzalloc_obj(*srpc, GFP_ATOMIC | __GFP_ACCOUNT);
+		set_active_memcg(old);
+	} else {
+		srpc = kzalloc_obj(*srpc, GFP_ATOMIC);
+	}
+	if (!srpc) {
+		err = -ENOMEM;
+		goto error;
+	}
+
+	/* Must be initialized before any errors can occur in this function. */
+	INIT_LIST_HEAD(&srpc->buf_links);
+
+	srpc->hsk = hsk;
+	srpc->bucket = bucket;
+	srpc->state = RPC_INCOMING;
+	refcount_set(&srpc->refs, 1);
+	srpc->route = homa_route_get(hsk, source);
+	if (IS_ERR(srpc->route)) {
+		err = PTR_ERR(srpc->route);
+		srpc->route = NULL;
+		goto error;
+	}
+	srpc->dport = ntohs(h->common.sport);
+	srpc->id = id;
+	srpc->msgin.length = -1;
+	srpc->msgout.length = -1;
+	INIT_LIST_HEAD(&srpc->ready_links);
+	INIT_LIST_HEAD(&srpc->dead_links);
+	srpc->resend_timer_ticks = hsk->homa->timer_ticks;
+	srpc->magic = HOMA_RPC_MAGIC;
+	srpc->start_time = homa_clock();
+	err = homa_message_in_init(srpc, ntohl(h->message_length));
+	if (err != 0)
+		goto error;
+
+	/* Initialize fields that require socket to be locked. */
+	homa_sock_lock(hsk);
+	if (hsk->shutdown) {
+		homa_sock_unlock(hsk);
+		err = -ESHUTDOWN;
+		goto error;
+	}
+	hlist_add_head(&srpc->hash_links, &bucket->rpcs);
+	list_add_tail_rcu(&srpc->active_links, &hsk->active_rpcs);
+	homa_sock_unlock(hsk);
+	if (ntohl(h->seg.offset) == 0 && srpc->msgin.num_bpages > 0) {
+		set_bit(RPC_PKTS_READY, &srpc->flags);
+		homa_rpc_handoff(srpc);
+	}
+	return srpc;
+
+error:
+	if (srpc) {
+		homa_pool_release(srpc);
+		if (srpc->route)
+			homa_route_release(srpc->route);
+	}
+	homa_bucket_unlock(bucket, id);
+	kfree(srpc);
+	return ERR_PTR(err);
+}
+
+/**
+ * homa_rpc_ack() - Handle one or more acknowledgments for RPCs.
+ * @hsk:      Socket on which the ack(s) were received. Can sometimes be used
+ *            to avoid a socket lookup.
+ * @rpc:      RPC for which caller holds lock (NULL if none).
+ * @saddr:    Source address from which the ack was received (the client
+ *            node for the RPC)
+ * @num_acks: Number of acknowledgments in @acks
+ * @acks:     Information about one or more RPCs from @saddr that may now be
+ *            deleted safely.
+ */
+void homa_rpc_ack(struct homa_sock *hsk, struct homa_rpc *rpc,
+		  const struct in6_addr *saddr, int num_acks,
+		  struct homa_ack *acks)
+{
+	struct homa_sock *hsk2;
+	struct homa_rpc *rpc2;
+	u16 server_port;
+	u64 id;
+	int i;
+
+	if (rpc)
+		homa_rpc_unlock(rpc);
+	for (i = 0; i < num_acks; i++) {
+		struct homa_ack *ack = &acks[i];
+
+		server_port = ntohs(ack->server_port);
+		id = homa_local_id(ack->client_id);
+		if (hsk->port != server_port) {
+			/* Without RCU, sockets other than hsk can be deleted
+			 * out from under us.
+			 */
+			hsk2 = homa_sock_find(hsk->hnet, server_port);
+			if (!hsk2)
+				continue;
+		} else {
+			hsk2 = hsk;
+		}
+		rpc2 = homa_rpc_find_server(hsk2, saddr, id);
+		if (rpc2) {
+			homa_rpc_end(rpc2);
+			homa_rpc_unlock(rpc2); /* Locked by homa_rpc_find_server. */
+		}
+		if (hsk2 != hsk)
+			sock_put(&hsk2->sock);
+	}
+	if (rpc)
+		homa_rpc_lock(rpc);
+}
+
+/**
+ * homa_rpc_end() - Stop all activity on an RPC and begin the process of
+ * releasing its resources; this process will continue in the background
+ * until homa_rpc_reap eventually completes it.
+ * @rpc:  Structure to clean up, or NULL. Must be locked. Its socket must
+ *        not be locked. The RPC may still be used after this function returns
+ *        (there are many places where the RPC lock is temporarily released,
+ *        and it would add too much complexity to put checks for death
+ *        every time the lock is reacquired). However, any code that could
+ *        make the RPC visible again must check rpc->state; if the RPC is
+ *        dead then that code must no-op itself.
+ */
+void homa_rpc_end(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	/* The goal for this function is to make the RPC inaccessible,
+	 * so that no other code will ever access it again. However, don't
+	 * actually release resources or tear down the internal structure
+	 * of the RPC; leave that to homa_rpc_reap, which runs later. There
+	 * are two reasons for this. First, releasing resources may be
+	 * expensive, so we don't want to keep the caller waiting; homa_rpc_reap
+	 * will run in situations where there is time to spare. Second, there
+	 * may be other code that currently has pointers to this RPC but
+	 * temporarily released the lock (e.g. to copy data to/from user space).
+	 * It isn't safe to clean up until that code has finished its work and
+	 * released any pointers to the RPC (homa_rpc_reap will ensure that
+	 * this has happened). So, this function should only make changes
+	 * needed to make the RPC inaccessible.
+	 */
+	if (!rpc || rpc->state == RPC_DEAD)
+		return;
+	rpc->state = RPC_DEAD;
+	rpc->error = -EINVAL;
+
+	/* Unlink from all lists, so no-one will ever find this RPC again. */
+	homa_sock_lock(rpc->hsk);
+	__hlist_del(&rpc->hash_links);
+	list_del_rcu(&rpc->active_links);
+	list_add_tail(&rpc->dead_links, &rpc->hsk->dead_rpcs);
+	__list_del_entry(&rpc->ready_links);
+	homa_pool_unlink(rpc);
+	homa_interest_notify_private(rpc);
+
+	rpc->hsk->dead_frags += rpc->msgout.num_frags + 1;
+	if (rpc->hsk->dead_frags > rpc->hsk->homa->max_dead_frags)
+		/* This update isn't thread-safe; it's just a
+		 * statistic so it's OK if updates occasionally get
+		 * missed.
+		 */
+		rpc->hsk->homa->max_dead_frags = rpc->hsk->dead_frags;
+
+	homa_sock_unlock(rpc->hsk);
+}
+
+/**
+ * homa_rpc_abort() - Terminate an RPC.
+ * @rpc:     RPC to be terminated.  Must be locked by caller.
+ * @error:   A negative errno value indicating the error that caused the abort.
+ *           If this is a client RPC, the error will be returned to the
+ *           application; if it's a server RPC, the error is ignored and
+ *           we just free the RPC.
+ */
+void homa_rpc_abort(struct homa_rpc *rpc, int error)
+	__must_hold(rpc->bucket->lock)
+{
+	if (!homa_is_client(rpc->id)) {
+		homa_rpc_end(rpc);
+		return;
+	}
+	rpc->error = error;
+	homa_rpc_handoff(rpc);
+}
+
+/**
+ * homa_abort_rpcs() - Abort all RPCs to/from a particular peer.
+ * @homa:    Overall data about the Homa protocol implementation.
+ * @addr:    Address (network order) of the destination whose RPCs are
+ *           to be aborted.
+ * @port:    If nonzero, then RPCs will only be aborted if they were
+ *	     targeted at this server port.
+ * @error:   Negative errno value indicating the reason for the abort.
+ */
+void homa_abort_rpcs(struct homa *homa, const struct in6_addr *addr,
+		     int port, int error)
+{
+	struct homa_socktab_scan scan;
+	struct homa_sock *hsk;
+	struct homa_rpc *rpc;
+
+	for (hsk = homa_socktab_start_scan(homa->socktab, &scan); hsk;
+	     hsk = homa_socktab_next(&scan)) {
+		/* Skip the (expensive) lock acquisition if there's no
+		 * work to do.
+		 */
+		if (list_empty(&hsk->active_rpcs))
+			continue;
+		if (!homa_protect_rpcs(hsk))
+			continue;
+		rcu_read_lock();
+		list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
+			if (!ipv6_addr_equal(&rpc->route->peer->addr, addr))
+				continue;
+			if (port && rpc->dport != port)
+				continue;
+			homa_rpc_lock(rpc);
+			if (rpc->state != RPC_DEAD)
+				homa_rpc_abort(rpc, error);
+			homa_rpc_unlock(rpc);
+		}
+		rcu_read_unlock();
+		homa_unprotect_rpcs(hsk);
+	}
+	homa_socktab_end_scan(&scan);
+}
+
+/**
+ * homa_rpc_reap() - Invoked to release resources associated with dead
+ * RPCs for a given socket. Each call will do a small amount of work; there
+ * may still be unreaped RPCs on return.
+ * @hsk:      Homa socket that may contain dead RPCs. Must not be locked by the
+ *            caller; this function will lock and release.
+ *
+ * Return: A return value of 0 means that we ran out of work to do; calling
+ *         again may not do any work (there could be unreaped RPCs, but if so,
+ *         they cannot currently be reaped).  A value greater than zero means
+ *         there is still more reaping work to be done.
+ */
+int homa_rpc_reap(struct homa_sock *hsk)
+{
+	/* RPC Reaping Strategy:
+	 *
+	 * (Note: there are references to this comment elsewhere in the
+	 * Homa code)
+	 *
+	 * This function is separate from homa_rpc_end for two reasons.
+	 * First, there may be outstanding references to an RPC when
+	 * homa_rpc_end is invoked; the storage for the RPC cannot be
+	 * freed until all of those references have been released.
+	 * Second, reaping an RPC is potentially expensive (if it owns a
+	 * lot of buffer memory) and homa_rpc_end could be invoked in
+	 * homa_softirq when there are short messages waiting to be processed.
+	 * Taking time to reap a long RPC could result in delays for
+	 * subsequent short RPCs. This second reason is less important
+	 * now than it used to be (in earlier versions of Homa skbs for both
+	 * inbound and outbound messages were retained until the RPC was
+	 * reaped, and freeing the skbs was relatively expensive; now no
+	 * skbs are retained; there are only pages of tx message memory to
+	 * return to homa_tx_pool).
+	 *
+	 * Thus Homa doesn't reap immediately in homa_rpc_end. Instead, dead
+	 * RPCs are queued up and reaping occurs in this function, which is
+	 * invoked later. The challenge is to do this so that (a) we don't allow
+	 * large numbers of dead RPCs to accumulate and (b) we minimize the
+	 * impact of reaping on latency of unrelated messages.
+	 *
+	 * The primary place where homa_rpc_reap is invoked is when threads
+	 * are waiting for incoming messages. The thread has nothing else to
+	 * do (it may even be polling for input), so reaping can be performed
+	 * with no latency impact on the application.  However, if a machine
+	 * is overloaded then it may never wait, so this mechanism isn't always
+	 * sufficient.
+	 *
+	 * Homa now reaps in two other places, if reaping while waiting for
+	 * messages isn't adequate:
+	 * 1. If too many dead RPCs accumulate, then homa_timer will call
+	 *    homa_rpc_reap.
+	 * 2. If the timer thread cannot keep up with all the reaping to be
+	 *    done then as a last resort homa_dispatch_pkts will reap in small
+	 *    increments (a few sk_buffs or RPCs) for every incoming batch
+	 *    of packets. This is undesirable because it will impact Homa's
+	 *    latency.
+	 *
+	 * During the introduction of homa_pools for managing input
+	 * buffers, freeing of packets for incoming messages was moved to
+	 * homa_copy_to_user under the assumption that this code wouldn't be
+	 * on the critical path. However, there is evidence that with
+	 * fast networks (e.g. 100 Gbps) copying to user space is the
+	 * bottleneck for incoming messages, and packet freeing takes about
+	 * 20-25% of the total time in homa_copy_to_user. So, it may eventually
+	 * be desirable to move packet freeing out of homa_copy_to_user.
+	 */
+#define BATCH_MAX_RPCS 5
+#define BATCH_MAX_FRAGS 30
+	struct homa_rpc *rpcs[BATCH_MAX_RPCS];
+	int checked_all_rpcs;
+	int total_dead_frags;
+	struct homa_rpc *rpc;
+	struct homa_rpc *tmp;
+	int i, num_rpcs;
+
+	/* Each iteration through the following loop will reap
+	 * up to BATCH_MAX_RPCS RPCs.
+	 */
+	checked_all_rpcs = list_empty(&hsk->dead_rpcs);
+	if (checked_all_rpcs)
+		return 0;
+	num_rpcs = 0;
+	total_dead_frags = 0;
+
+	homa_sock_lock(hsk);
+	if (atomic_read(&hsk->protect_count)) {
+		homa_sock_unlock(hsk);
+		return 0;
+	}
+
+	/* Collect freeable RPCs. */
+	list_for_each_entry_safe(rpc, tmp, &hsk->dead_rpcs, dead_links) {
+		int refs;
+
+		if (num_rpcs >= BATCH_MAX_RPCS ||
+		    total_dead_frags >= BATCH_MAX_FRAGS)
+			goto release;
+
+		/* Make sure that all outstanding uses of the RPC have
+		 * completed. We can read the reference count safely
+		 * only when we're holding the lock. Note: it isn't
+		 * safe to block while locking the RPC here, since we
+		 * hold the socket lock.
+		 */
+		if (homa_rpc_try_lock(rpc)) {
+			refs = refcount_read(&rpc->refs);
+			homa_rpc_unlock(rpc);
+		} else {
+			refs = 2;
+		}
+		if (refs > 1)
+			continue;
+
+		rpcs[num_rpcs] = rpc;
+		num_rpcs++;
+		list_del(&rpc->dead_links);
+		hsk->dead_frags -= (rpc->msgout.num_frags + 1);
+		total_dead_frags += rpc->msgout.num_frags;
+	}
+	checked_all_rpcs = true;
+
+	/* Free all of the collected resources; release the socket lock
+	 * while doing this.
+	 */
+release:
+	homa_sock_unlock(hsk);
+	for (i = 0; i < num_rpcs; i++) {
+		rpc = rpcs[i];
+
+		/* Free any unconsumed input packets and gaps (there
+		 * shouldn't usually be any of either).
+		 */
+		if (rpc->msgin.length >= 0) {
+			struct sk_buff *skb;
+
+			for (skb = __skb_dequeue(&rpc->msgin.packets); skb;
+			     skb = __skb_dequeue(&rpc->msgin.packets))
+				consume_skb(skb);
+			while (1) {
+				struct homa_gap *gap;
+
+				gap = list_first_entry_or_null(&rpc->msgin.gaps,
+							       struct homa_gap,
+							       links);
+				if (!gap)
+					break;
+				list_del(&gap->links);
+				kfree(gap);
+			}
+		}
+
+		if (rpc->route) {
+			homa_route_release(rpc->route);
+			rpc->route = NULL;
+		}
+		homa_pool_release(rpc);
+		homa_tx_pool_free(hsk->homa, rpc->msgout.num_frags,
+				  rpc->msgout.frags);
+		WARN_ON(refcount_sub_and_test(rpc->msgout.frag_bytes,
+					      &hsk->sock.sk_wmem_alloc));
+		if (rpc->msgout.frags != &rpc->msgout.frag)
+			kfree(rpc->msgout.frags);
+		rpc->state = 0;
+		rpc->magic = 0;
+		kfree(rpc);
+	}
+	homa_sock_wakeup_wmem(hsk);
+	if (hsk->buffer_pool)
+		homa_pool_check_waiting(hsk->buffer_pool);
+	return !checked_all_rpcs;
+}
+
+/**
+ * homa_abort_sock_rpcs() - Abort all outgoing (client-side) RPCs on a given
+ * socket.
+ * @hsk:         Socket whose RPCs should be aborted.
+ * @error:       Zero means that the aborted RPCs should be freed immediately.
+ *               A nonzero value means that the RPCs should be marked
+ *               complete, so that they can be returned to the application;
+ *               this value (a negative errno) will be returned from
+ *               recvmsg.
+ */
+void homa_abort_sock_rpcs(struct homa_sock *hsk, int error)
+{
+	struct homa_rpc *rpc;
+
+	if (list_empty(&hsk->active_rpcs))
+		return;
+	if (!homa_protect_rpcs(hsk))
+		return;
+	rcu_read_lock();
+	list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
+		if (!homa_is_client(rpc->id))
+			continue;
+		homa_rpc_lock(rpc);
+		if (rpc->state == RPC_DEAD) {
+			homa_rpc_unlock(rpc);
+			continue;
+		}
+		if (error)
+			homa_rpc_abort(rpc, error);
+		else
+			homa_rpc_end(rpc);
+		homa_rpc_unlock(rpc);
+	}
+	rcu_read_unlock();
+	homa_unprotect_rpcs(hsk);
+}
+
+/**
+ * homa_rpc_find_client() - Locate client-side information about the RPC that
+ * a packet belongs to, if there is any. Thread-safe without socket lock.
+ * @hsk:      Socket via which packet was received.
+ * @id:       Unique identifier for the RPC.
+ *
+ * Return:    A pointer to the homa_rpc for this id, or NULL if none.
+ *            The RPC will be locked; the caller must eventually unlock it
+ *            by invoking homa_rpc_unlock.
+ */
+struct homa_rpc *homa_rpc_find_client(struct homa_sock *hsk, u64 id)
+	__cond_acquires(nonnull, crpc->bucket->lock)
+{
+	struct homa_rpc_bucket *bucket = homa_client_rpc_bucket(hsk, id);
+	struct homa_rpc *crpc;
+
+	homa_bucket_lock(bucket, id);
+	hlist_for_each_entry(crpc, &bucket->rpcs, hash_links) {
+		if (crpc->id == id)
+			return crpc;
+	}
+	homa_bucket_unlock(bucket, id);
+	return NULL;
+}
+
+/**
+ * homa_rpc_find_server() - Locate server-side information about the RPC that
+ * a packet belongs to, if there is any. Thread-safe without socket lock.
+ * @hsk:      Socket via which packet was received.
+ * @saddr:    Address from which the packet was sent.
+ * @id:       Unique identifier for the RPC (must have server bit set).
+ *
+ * Return:    A pointer to the homa_rpc matching the arguments, or NULL
+ *            if none. The RPC will be locked; the caller must eventually
+ *            unlock it by invoking homa_rpc_unlock.
+ */
+struct homa_rpc *homa_rpc_find_server(struct homa_sock *hsk,
+				      const struct in6_addr *saddr, u64 id)
+	__cond_acquires(nonnull, srpc->bucket->lock)
+{
+	struct homa_rpc_bucket *bucket = homa_server_rpc_bucket(hsk, id);
+	struct homa_rpc *srpc;
+
+	homa_bucket_lock(bucket, id);
+	hlist_for_each_entry(srpc, &bucket->rpcs, hash_links) {
+		if (srpc->id == id && ipv6_addr_equal(&srpc->route->peer->addr,
+						      saddr))
+			return srpc;
+	}
+	homa_bucket_unlock(bucket, id);
+	return NULL;
+}
+
+/**
+ * homa_rpc_find_from_skb() - Given an skb for a Homa packet, find the homa_rpc
+ * associated with the packet and lock it.
+ * @skb:        Packet buffer; must contain a Homa packet that is "fully
+ *              populated" (e.g. the dev field and IP header are initialized).
+ * @incoming:   True means this is an incoming packet, false means outgoing.
+ * Return:      Pointer an RPC that has been locked; the caller is responsible
+ *              for unlocking it. If no RPC could be found, NULL is returned.
+ */
+struct homa_rpc *homa_rpc_find_from_skb(struct sk_buff *skb, bool incoming)
+{
+	struct homa_common_hdr *h;
+	struct homa_sock *hsk;
+	struct homa_net *hnet;
+	struct homa_rpc *rpc;
+	int port;
+	u64 id;
+
+	/* Find the appropriate socket.*/
+	h = (struct homa_common_hdr *)skb_transport_header(skb);
+	id = be64_to_cpu(h->sender_id);
+	if (incoming) {
+		port = ntohs(h->dport);
+		id ^= 1;
+	} else {
+		port = ntohs(h->sport);
+	}
+	hnet = homa_net(dev_net(skb->dev));
+	hsk = homa_sock_find(hnet, port);
+	if (!hsk)
+		return NULL;
+
+	/* Look up the RPC (client and server RPCs are handled differently) */
+	if (homa_is_client(id)) {
+		rpc = homa_rpc_find_client(hsk, id);
+	} else {
+		if (skb_is_ipv6(skb)) {
+			struct in6_addr *addr;
+
+			addr = (incoming) ? &ipv6_hdr(skb)->saddr :
+					&ipv6_hdr(skb)->daddr;
+			rpc = homa_rpc_find_server(hsk, addr, id);
+		} else {
+			struct in6_addr addr;
+
+			if (incoming)
+				ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
+						       &addr);
+			else
+				ipv6_addr_set_v4mapped(ip_hdr(skb)->daddr,
+						       &addr);
+			rpc = homa_rpc_find_server(hsk, &addr, id);
+		}
+	}
+	sock_put(&hsk->sock);
+	return rpc;
+}
+
+/**
+ * homa_rpc_get_info() - Extract information from an RPC for returning to
+ * an application via the HOMAIOCINFO ioctl.
+ * @rpc:   RPC for which information is desired.
+ * @info:  Structure in which to store the information.
+ */
+void homa_rpc_get_info(struct homa_rpc *rpc, struct homa_rpc_info *info)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa_gap *gap;
+
+	memset(info, 0, sizeof(*info));
+	info->id = rpc->id;
+	if (rpc->hsk->inet.sk.sk_family == AF_INET6) {
+		info->peer.in6.sin6_family = AF_INET6;
+		info->peer.in6.sin6_addr = rpc->route->peer->addr;
+		info->peer.in6.sin6_port = htons(rpc->dport);
+	} else {
+		info->peer.in6.sin6_family = AF_INET;
+		info->peer.in4.sin_addr.s_addr = ipv6_to_ipv4(rpc->route->peer->addr);
+		info->peer.in4.sin_port = htons(rpc->dport);
+	}
+	info->completion_cookie = rpc->completion_cookie;
+	if (rpc->msgout.length >= 0) {
+		info->tx_length = rpc->msgout.length;
+		info->tx_sent = rpc->msgout.next_xmit_offset;
+		info->tx_granted = rpc->msgout.length;
+	} else {
+		info->tx_length = -1;
+	}
+	if (rpc->msgin.length >= 0) {
+		info->rx_length = rpc->msgin.length;
+		info->rx_remaining = rpc->msgin.bytes_remaining;
+		list_for_each_entry(gap, &rpc->msgin.gaps, links) {
+			info->rx_gaps++;
+			info->rx_gap_bytes += gap->end - gap->start;
+		}
+		info->rx_granted = rpc->msgin.length;
+		if (skb_queue_len(&rpc->msgin.packets) > 0)
+			info->flags |= HOMA_RPC_RX_COPY;
+	} else {
+		info->rx_length = -1;
+	}
+	if (!list_empty(&rpc->buf_links))
+		info->flags |= HOMA_RPC_BUF_STALL;
+	if (!list_empty(&rpc->ready_links) &&
+	    rpc->msgin.bytes_remaining == 0 &&
+	    skb_queue_len(&rpc->msgin.packets) == 0)
+		info->flags |= HOMA_RPC_RX_READY;
+	if (rpc->flags & RPC_PRIVATE)
+		info->flags |= HOMA_RPC_PRIVATE;
+}
diff --git a/net/homa/homa_rpc.h b/net/homa/homa_rpc.h
new file mode 100644
index 0000000000000..fa082d229740a
--- /dev/null
+++ b/net/homa/homa_rpc.h
@@ -0,0 +1,545 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file defines homa_rpc and related structs.  */
+
+#ifndef _HOMA_RPC_H
+#define _HOMA_RPC_H
+
+#include <linux/percpu-defs.h>
+#include <linux/skbuff.h>
+#include <linux/types.h>
+
+#include "homa_sock.h"
+#include "homa_wire.h"
+
+/* Forward references. */
+struct homa_ack;
+
+/**
+ * struct homa_message_out - Describes a message (either request or response)
+ * for which this machine is the sender.
+ */
+struct homa_message_out {
+	/**
+	 * @length: Total bytes in message (excluding headers).  A value
+	 * less than 0 means this structure is uninitialized and therefore
+	 * not in use (all other fields will be zero in this case).
+	 */
+	int length;
+
+	/**
+	 * @frags: Array of fragments that hold the tx message in a ready-
+	 * to-transmit form, consisting of segments, each with a
+	 * homa_seg_hdr followed by the data for that segment. These
+	 * fragments will be incorporated into skb's to transmit the message.
+	 * If this doesn't point to @frag below then it is dynamically
+	 * allocated and must be freed.
+	 */
+	skb_frag_t *frags;
+
+	/** @num_frags: Number of fragments at @frags. */
+	int num_frags;
+
+	/**
+	 * @frag_bytes: Total amount of memory in all of @frags; this is
+	 * included in sk_wmem_alloc.
+	 */
+	int frag_bytes;
+
+	/**
+	 * @frag: @frags will point here if the message data all fits in a
+	 * single fragment (avoid alloc/free overhead).
+	 */
+	skb_frag_t frag;
+
+	/**
+	 * @max_seg_data: Maximum amount of message data to include in each
+	 * segment of tx packets.
+	 */
+	int max_seg_data;
+
+	/**
+	 * @max_gso_segs: Maximum number of segments that can be present in a
+	 * single GSO packet.
+	 */
+	int max_gso_segs;
+
+	/**
+	 * @max_gso_data: Maximum amount of message data in a GSO frame
+	 * (@max_seg_data * @max_gso_segs).
+	 */
+	int max_gso_data;
+
+	/**
+	 * @copied_from_user: Number of bytes of the message that have
+	 * been copied from user space into @frags. Used for lockless
+	 * communication between one core copying in data and another
+	 * core transmitting the data in skbs.
+	 */
+	int copied_from_user;
+
+	/**
+	 * @next_xmit_offset: All bytes in the message, up to but not
+	 * including this one, have been passed to ip_queue_xmit or
+	 * ip6_xmit at least once.
+	 */
+	int next_xmit_offset;
+
+	/**
+	 * @init_time: homa_clock() time when this structure was initialized.
+	 * Used to find the oldest outgoing message.
+	 */
+	u64 init_time;
+};
+
+/**
+ * struct homa_gap - Represents a range of bytes within a message that have
+ * not yet been received.
+ */
+struct homa_gap {
+	/** @start: offset of first byte in this gap. */
+	int start;
+
+	/** @end: offset of byte just after last one in this gap. */
+	int end;
+
+	/**
+	 * @time: homa_clock() time when the gap was first detected.
+	 * As of 7/2024 this isn't used for anything.
+	 */
+	u64 time;
+
+	/** @links: for linking into list in homa_message_in. */
+	struct list_head links;
+};
+
+/**
+ * struct homa_message_in - Holds the state of a message received by
+ * this machine; used for both requests and responses.
+ */
+struct homa_message_in {
+	/**
+	 * @length: Payload size in bytes. -1 means this structure is
+	 * uninitialized and therefore not in use.
+	 */
+	int length;
+
+	/**
+	 * @packets: DATA packets for this message that have been received but
+	 * not yet copied to user space (ordered by increasing offset). The
+	 * lock in this structure is not used (the RPC lock is used instead).
+	 */
+	struct sk_buff_head packets;
+
+	/**
+	 * @recv_end: Offset of the byte just after the highest one that
+	 * has been received so far.
+	 */
+	int recv_end;
+
+	/**
+	 * @gaps: List of homa_gaps describing all of the bytes with
+	 * offsets less than @recv_end that have not yet been received.
+	 */
+	struct list_head gaps;
+
+	/**
+	 * @bytes_remaining: Amount of data for this message that has
+	 * not yet been received; will determine the message's priority.
+	 */
+	int bytes_remaining;
+
+	/**
+	 * @num_bpages: The number of entries in @bpage_offsets used for this
+	 * message (0 means buffers not allocated yet or the buffers have
+	 * been handed off to the application).
+	 */
+	u32 num_bpages;
+
+	/**
+	 * @bpage_offsets: Describes buffer space allocated for this message.
+	 * Each entry is an offset from the start of the buffer region.
+	 * All but the last pointer refer to areas of size HOMA_BPAGE_SIZE.
+	 */
+	u32 bpage_offsets[HOMA_MAX_BPAGES];
+
+};
+
+/**
+ * struct homa_rpc - One of these structures exists for each active
+ * RPC. The same structure is used to manage both outgoing RPCs on
+ * clients and incoming RPCs on servers.
+ */
+struct homa_rpc {
+	/** @hsk:  Socket that owns the RPC. */
+	struct homa_sock *hsk;
+
+	/**
+	 * @bucket: Pointer to the bucket in hsk->client_rpc_buckets or
+	 * hsk->server_rpc_buckets where this RPC is linked. Used primarily
+	 * for locking the RPC (which is done by locking its bucket).
+	 */
+	struct homa_rpc_bucket *bucket;
+
+	/**
+	 * @state: The current state of this RPC:
+	 *
+	 * @RPC_OUTGOING:     The RPC is waiting for @msgout to be transmitted
+	 *                    to the peer.
+	 * @RPC_INCOMING:     The RPC is waiting for data @msgin to be received
+	 *                    from the peer; at least one packet has already
+	 *                    been received.
+	 * @RPC_IN_SERVICE:   Used only for server RPCs: the request message
+	 *                    has been read from the socket, but the response
+	 *                    message has not yet been presented to the kernel.
+	 * @RPC_DEAD:         The RPC has been killed and is waiting to be
+	 *                    reaped. The RPC may continue to be used in this
+	 *                    state using references that existed when
+	 *                    homa_rpc_end was invoked, but it can no longer
+	 *                    be discovered and no code may make it
+	 *                    discoverable.
+	 *
+	 * Client RPCs pass through states in the following order:
+	 * RPC_OUTGOING, RPC_INCOMING, RPC_DEAD.
+	 *
+	 * Server RPCs pass through states in the following order:
+	 * RPC_INCOMING, RPC_IN_SERVICE, RPC_OUTGOING, RPC_DEAD.
+	 */
+	enum {
+		RPC_OUTGOING            = 5,
+		RPC_INCOMING            = 6,
+		RPC_IN_SERVICE          = 8,
+		RPC_DEAD                = 9
+	} state;
+
+	/**
+	 * @flags: Additional state information: an OR'ed combination of
+	 * various single-bit flags. See below for definitions. Must be
+	 * manipulated with atomic operations because some of the manipulations
+	 * occur without holding the RPC lock.
+	 */
+	unsigned long flags;
+
+	/* Valid bit numbers for @flags:
+	 * RPC_PKTS_READY -        The RPC has input packets ready to be
+	 *                         copied to user space.
+	 * APP_NEEDS_LOCK -        Means that code in the application thread
+	 *                         needs the RPC lock (e.g. so it can start
+	 *                         copying data to user space) so others
+	 *                         (e.g. SoftIRQ processing) should relinquish
+	 *                         the lock ASAP. Without this, SoftIRQ can
+	 *                         lock out the application for a long time,
+	 *                         preventing data copies to user space from
+	 *                         starting (and they limit throughput at
+	 *                         high network speeds).
+	 * RPC_PRIVATE -           This RPC will be waited on in "private" mode,
+	 *                         where the app explicitly requests the
+	 *                         response from this particular RPC.
+	 * RPC_GRANTABLE -         1 means this RPC needs help from the grant
+	 *                         mechanism to receive its incoming message. 0
+	 *                         means either it is entirely unscheduled or
+	 *                         the message has been completely received.
+	 *                         This bit gets set at most once in the life
+	 *                         of an RPC; once cleared, it never gets set
+	 *                         again.
+	 * RPC_GRANT_MANAGED -     1 means this RPC has been inserted in the
+	 *                         grant management data structures. This
+	 *                         doesn't happen until the first time
+	 *                         homa_grant_check_rpc is called, so it is
+	 *                         possible for RPC_GRANTABLE to be set but
+	 *                         not RPC_GRANT_MANAGED.
+	 */
+#define RPC_PKTS_READY        0
+#define APP_NEEDS_LOCK        1
+#define RPC_PRIVATE           2
+#define RPC_GRANTABLE         3
+#define RPC_GRANT_MANAGED     4
+
+	/**
+	 * @refs: Number of references to this RPC, including one for each
+	 * unmatched call to homa_rpc_hold plus one for the socket's reference
+	 * in either active_rpcs or dead_rpcs. References are acquired at
+	 * "top level", such as homa_dispatch_pkts or homa_recvmsg. If a
+	 * function receives a locked RPC as parameter, it can assume
+	 * that the caller is also holding a reference to it.
+	 */
+	refcount_t refs;
+
+	/**
+	 * @route: Holds a dst_entry that can be used to route to the peer;
+	 * also provides indirect access to a homa_peer for the peer. This
+	 * value can change due to route invalidations, if RPC lock not held.
+	 */
+	struct homa_route *route;
+
+	/** @dport: Port number on @peer that will handle packets. */
+	u16 dport;
+
+	/**
+	 * @id: Unique identifier for the RPC among all those issued
+	 * from its port. The low-order bit indicates whether we are
+	 * server (1) or client (0) for this RPC.
+	 */
+	u64 id;
+
+	/**
+	 * @completion_cookie: Only used on clients. Contains identifying
+	 * information about the RPC provided by the application; returned to
+	 * the application with the RPC's result.
+	 */
+	u64 completion_cookie;
+
+	/**
+	 * @error: Only used on clients. If nonzero, then the RPC has
+	 * failed and the value is a negative errno that describes the
+	 * problem.
+	 */
+	int error;
+
+	/**
+	 * @msgin: Information about the message we receive for this RPC
+	 * (for server RPCs this is the request, for client RPCs this is the
+	 * response).
+	 */
+	struct homa_message_in msgin;
+
+	/**
+	 * @msgout: Information about the message we send for this RPC
+	 * (for client RPCs this is the request, for server RPCs this is the
+	 * response).
+	 */
+	struct homa_message_out msgout;
+
+	/**
+	 * @hash_links: Used to link this object into a hash bucket for
+	 * either @hsk->client_rpc_buckets (for a client RPC), or
+	 * @hsk->server_rpc_buckets (for a server RPC).
+	 */
+	struct hlist_node hash_links;
+
+	/**
+	 * @ready_links: Used to link this object into @hsk->ready_rpcs.
+	 */
+	struct list_head ready_links;
+
+	/**
+	 * @buf_links: Used to link this RPC into @hsk->waiting_for_bufs.
+	 * If the RPC isn't on @hsk->waiting_for_bufs, this is an empty
+	 * list pointing to itself.
+	 */
+	struct list_head buf_links;
+
+	/**
+	 * @active_links: For linking this object into @hsk->active_rpcs.
+	 * The next field will be LIST_POISON1 if this RPC hasn't yet been
+	 * linked into @hsk->active_rpcs. Access with RCU.
+	 */
+	struct list_head active_links;
+
+	/** @dead_links: For linking this object into @hsk->dead_rpcs. */
+	struct list_head dead_links;
+
+	/**
+	 * @private_interest: If there is a thread waiting for this RPC in
+	 * homa_wait_private, then this points to that thread's interest.
+	 */
+	struct homa_interest *private_interest;
+
+	/**
+	 * @silent_ticks: Number of times homa_timer has been invoked
+	 * since the last time a packet indicating progress was received
+	 * for this RPC, so we don't need to send a resend for a while.
+	 */
+	int silent_ticks;
+
+	/**
+	 * @resend_timer_ticks: Value of homa->timer_ticks the last time
+	 * we sent a RESEND for this RPC.
+	 */
+	u32 resend_timer_ticks;
+
+	/**
+	 * @done_timer_ticks: The value of homa->timer_ticks the first
+	 * time we noticed that this (server) RPC is done (all response
+	 * packets have been transmitted), so we're ready for an ack.
+	 * Zero means we haven't reached that point yet.
+	 */
+	u32 done_timer_ticks;
+
+	/**
+	 * @magic: when the RPC is alive, this holds a distinct value that
+	 * is unlikely to occur naturally. The value is cleared when the
+	 * RPC is reaped, so we can detect accidental use of an RPC after
+	 * it has been reaped.
+	 */
+#define HOMA_RPC_MAGIC 0xdeadbeef
+	int magic;
+
+	/**
+	 * @start_time: homa_clock() time when this RPC was created. Used
+	 * occasionally for testing.
+	 */
+	u64 start_time;
+};
+
+void     homa_abort_rpcs(struct homa *homa, const struct in6_addr *addr,
+			 int port, int error);
+void     homa_abort_sock_rpcs(struct homa_sock *hsk, int error);
+void     homa_rpc_abort(struct homa_rpc *crpc, int error);
+void     homa_rpc_ack(struct homa_sock *hsk, struct homa_rpc *rpc,
+		      const struct in6_addr *saddr, int num_acks,
+		      struct homa_ack *acks);
+struct homa_rpc
+	*homa_rpc_alloc_client(struct homa_sock *hsk,
+			       const union sockaddr_in_union *dest);
+struct homa_rpc
+	*homa_rpc_alloc_server(struct homa_sock *hsk,
+			       const struct in6_addr *source,
+			       struct homa_data_hdr *h);
+void     homa_rpc_end(struct homa_rpc *rpc);
+struct homa_rpc
+	*homa_rpc_find_client(struct homa_sock *hsk, u64 id);
+struct homa_rpc
+	*homa_rpc_find_from_skb(struct sk_buff *skb, bool incoming);
+struct homa_rpc
+	*homa_rpc_find_server(struct homa_sock *hsk,
+			      const struct in6_addr *saddr, u64 id);
+void     homa_rpc_get_info(struct homa_rpc *rpc, struct homa_rpc_info *info);
+int      homa_rpc_reap(struct homa_sock *hsk);
+
+/**
+ * homa_rpc_lock() - Acquire the lock for an RPC.
+ * @rpc:    RPC to lock.
+ */
+static inline void homa_rpc_lock(struct homa_rpc *rpc)
+	__acquires(rpc->bucket->lock)
+{
+	homa_bucket_lock(rpc->bucket, rpc->id);
+}
+
+/**
+ * homa_rpc_try_lock() - Acquire the lock for an RPC if it is available.
+ * @rpc:       RPC to lock.
+ * Return:     Nonzero if lock was successfully acquired, zero if it is
+ *             currently owned by someone else.
+ */
+static inline int homa_rpc_try_lock(struct homa_rpc *rpc)
+	__cond_acquires(nonzero, rpc->bucket->lock)
+{
+	if (!spin_trylock_bh(&rpc->bucket->lock))
+		return 0;
+	return 1;
+}
+
+/**
+ * homa_rpc_lock_preempt() - Same as homa_rpc_lock, except sets the
+ * APP_NEEDS_LOCK flags while waiting to encourage the existing lock
+ * owner to relinquish the lock.
+ * @rpc:   RPC to lock.
+ */
+static inline void homa_rpc_lock_preempt(struct homa_rpc *rpc)
+	__acquires(rpc->bucket->lock)
+{
+	set_bit(APP_NEEDS_LOCK, &rpc->flags);
+	homa_bucket_lock(rpc->bucket, rpc->id);
+	clear_bit(APP_NEEDS_LOCK, &rpc->flags);
+}
+
+/**
+ * homa_rpc_unlock() - Release the lock for an RPC.
+ * @rpc:   RPC to unlock.
+ */
+static inline void homa_rpc_unlock(struct homa_rpc *rpc)
+	__releases(rpc->bucket->lock)
+{
+	homa_bucket_unlock(rpc->bucket, rpc->id);
+}
+
+/**
+ * homa_protect_rpcs() - Ensures that no RPCs will be reaped for a given
+ * socket until homa_unprotect_rpcs is called. Typically used by functions
+ * that want to scan the active RPCs for a socket without holding the socket
+ * lock.  Multiple calls to this function may be in effect at once. See
+ * "Homa Locking Strategy" in homa_impl.h for more info on why this function
+ * is needed.
+ * @hsk:    Socket whose RPCs should be protected. Must not be locked
+ *          by the caller; will be locked here.
+ *
+ * Return:  1 for success, 0 if the socket has been shutdown, in which
+ *          case its RPCs cannot be protected.
+ */
+static inline int homa_protect_rpcs(struct homa_sock *hsk)
+{
+	int result;
+
+	homa_sock_lock(hsk);
+	result = !hsk->shutdown;
+	if (result)
+		atomic_inc(&hsk->protect_count);
+	homa_sock_unlock(hsk);
+	return result;
+}
+
+/**
+ * homa_unprotect_rpcs() - Cancel the effect of a previous call to
+ * homa_protect_rpcs(), so that RPCs can once again be reaped.
+ * @hsk:    Socket whose RPCs should be unprotected.
+ */
+static inline void homa_unprotect_rpcs(struct homa_sock *hsk)
+{
+	atomic_dec(&hsk->protect_count);
+}
+
+/**
+ * homa_rpc_hold() - Increment the reference count on an RPC, which will
+ * prevent it from being freed until homa_rpc_put() is called. References
+ * are taken in two situations:
+ * 1. An RPC is going to be manipulated by a collection of functions. In
+ *    this case the top-most function that identifies the RPC takes the
+ *    reference; any function that receives an RPC as an argument can
+ *    assume that a reference has been taken on the RPC by some higher
+ *    function on the call stack.
+ * 2. A pointer to an RPC is stored in an object for use later, such as
+ *    an interest. A reference must be held as long as the pointer remains
+ *    accessible in the object.
+ * @rpc:      RPC on which to take a reference.
+ */
+static inline void homa_rpc_hold(struct homa_rpc *rpc)
+{
+	refcount_inc(&rpc->refs);
+}
+
+/**
+ * homa_rpc_put() - Release a reference on an RPC (cancels the effect of
+ * a previous call to homa_rpc_hold).
+ * @rpc:      RPC to release.
+ */
+static inline void homa_rpc_put(struct homa_rpc *rpc)
+{
+	refcount_dec(&rpc->refs);
+}
+
+/**
+ * homa_is_client(): returns true if we are the client for a particular RPC,
+ * false if we are the server.
+ * @id:  Id of the RPC in question.
+ * Return: true if we are the client for RPC id, false otherwise
+ */
+static inline bool homa_is_client(u64 id)
+{
+	return (id & 1) == 0;
+}
+
+/**
+ * homa_rpc_needs_attention() - Returns true if @rpc has failed or if
+ * its incoming message is ready for attention by an application thread
+ * (e.g., packets are ready to copy to user space).
+ * @rpc: RPC to check.
+ * Return: See above
+ */
+static inline bool homa_rpc_needs_attention(struct homa_rpc *rpc)
+{
+	return (rpc->error != 0 || test_bit(RPC_PKTS_READY, &rpc->flags));
+}
+
+#endif /* _HOMA_RPC_H */
diff --git a/net/homa/homa_sock.c b/net/homa/homa_sock.c
new file mode 100644
index 0000000000000..a5fd321bacf23
--- /dev/null
+++ b/net/homa/homa_sock.c
@@ -0,0 +1,544 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file manages homa_sock and homa_socktab objects. */
+
+#include "homa_impl.h"
+#include "homa_interest.h"
+#include "homa_peer.h"
+#include "homa_pool.h"
+
+/**
+ * homa_socktab_init() - Constructor for homa_socktabs.
+ * @socktab:  The object to initialize; previous contents are discarded.
+ */
+void homa_socktab_init(struct homa_socktab *socktab)
+{
+	int i;
+
+	spin_lock_init(&socktab->write_lock);
+	socktab->next_sequence = 1;
+	for (i = 0; i < HOMA_SOCKTAB_BUCKETS; i++)
+		INIT_HLIST_HEAD(&socktab->buckets[i]);
+}
+
+/**
+ * homa_socktab_destroy() - Destructor for homa_socktabs: deletes all
+ * existing sockets.
+ * @socktab:  The object to destroy.
+ * @hnet:     If non-NULL, only sockets for this namespace are deleted.
+ */
+void homa_socktab_destroy(struct homa_socktab *socktab, struct homa_net *hnet)
+{
+	struct homa_socktab_scan scan;
+	struct homa_sock *hsk;
+
+	for (hsk = homa_socktab_start_scan(socktab, &scan); hsk;
+			hsk = homa_socktab_next(&scan)) {
+		if (hnet && hnet != hsk->hnet)
+			continue;
+
+		/* In actual use there should be no sockets left when this
+		 * function is invoked, so the code below will never be
+		 * invoked. However, it is useful during unit tests.
+		 */
+		homa_sock_shutdown(hsk);
+		homa_sock_destroy(&hsk->sock);
+	}
+	homa_socktab_end_scan(&scan);
+}
+
+/**
+ * homa_socktab_start_scan() - Begin an iteration over all of the sockets
+ * in a socktab.
+ * @socktab:   Socktab to scan.
+ * @scan:      Will hold the current state of the scan; any existing
+ *             contents are discarded. The caller must eventually pass this
+ *             to homa_socktab_end_scan.
+ *
+ * Return:     The first socket in the table, or NULL if the table is
+ *             empty. If non-NULL, a reference is held on the socket to
+ *             prevent its deletion.
+ *
+ * Each call to homa_socktab_next will return the next socket in the table.
+ * All sockets that are present in the table at the time this function is
+ * invoked will eventually be returned, as long as they are not removed
+ * from the table. It is safe to remove sockets from the table while the
+ * scan is in progress. If a socket is removed from the table during the scan,
+ * it may or may not be returned by homa_socktab_next. New entries added
+ * during the scan may or may not be returned.
+ */
+struct homa_sock *homa_socktab_start_scan(struct homa_socktab *socktab,
+					  struct homa_socktab_scan *scan)
+{
+	scan->socktab = socktab;
+	scan->hsk = NULL;
+	scan->current_bucket = 0;
+	scan->avail = 0;
+	scan->sequence = U64_MAX;
+
+	return homa_socktab_next(scan);
+}
+
+/**
+ * homa_socktab_fill_scan() - Refill the @socks array for a homa_socktab_scan.
+ * On return, if its @avail member is zero it means all of the sockets in
+ * the socktab have been scanned.
+ * @scan:      State of the scan. Normally the @avail member will be zero,
+ *             but this is not necessary.
+ */
+void homa_socktab_fill_scan(struct homa_socktab_scan *scan)
+{
+	struct homa_sock_link *slink;
+	struct hlist_head *bucket;
+	struct hlist_node *next;
+
+	rcu_read_lock();
+	bucket = &scan->socktab->buckets[scan->current_bucket];
+	next = rcu_dereference(hlist_first_rcu(bucket));
+	while (scan->avail < HOMA_MAX_SCANNED_SOCKS) {
+		if (!next) {
+			if (scan->current_bucket >= HOMA_SOCKTAB_BUCKETS - 1)
+				break;
+			scan->current_bucket++;
+			scan->sequence = U64_MAX;
+			bucket = &scan->socktab->buckets[scan->current_bucket];
+			next = rcu_dereference(hlist_first_rcu(bucket));
+			continue;
+		}
+		slink = hlist_entry(next, struct homa_sock_link, links);
+		next = rcu_dereference(hlist_next_rcu(next));
+		if (slink->sequence < scan->sequence) {
+			scan->sequence = slink->sequence;
+			scan->socks[scan->avail] = slink->hsk;
+			if (refcount_inc_not_zero(&slink->hsk->sock.sk_refcnt))
+				scan->avail++;
+		}
+	}
+	rcu_read_unlock();
+}
+
+/**
+ * homa_socktab_next() - Return the next socket in an iteration over a socktab.
+ * @scan:      State of the scan.
+ *
+ * Return:     The next socket in the table, or NULL if the iteration has
+ *             returned all of the sockets in the table.  If non-NULL, a
+ *             reference is held on the socket to prevent its deletion (this
+ *             module will release the reference in the next call to
+ *             homa_socktab_next or homa_socktab_end). Sockets are not returned
+ *             in any particular order. It's possible that the returned socket
+ *             has been shutdown.
+ */
+struct homa_sock *homa_socktab_next(struct homa_socktab_scan *scan)
+{
+	if (scan->hsk) {
+		sock_put(&scan->hsk->sock);
+		scan->hsk = NULL;
+	}
+
+	if (scan->avail == 0) {
+		homa_socktab_fill_scan(scan);
+		if (scan->avail == 0)
+			return NULL;
+	}
+
+	scan->hsk = scan->socks[scan->avail - 1];
+	scan->avail--;
+	return scan->hsk;
+}
+
+/**
+ * homa_socktab_end_scan() - Must be invoked on completion of each scan
+ * to clean up state associated with the scan.
+ * @scan:      State of the scan.
+ */
+void homa_socktab_end_scan(struct homa_socktab_scan *scan)
+{
+	if (scan->hsk) {
+		sock_put(&scan->hsk->sock);
+		scan->hsk = NULL;
+	}
+	while (scan->avail > 0) {
+		sock_put(&scan->socks[scan->avail - 1]->sock);
+		scan->avail--;
+	}
+}
+
+/**
+ * homa_sock_init() - Constructor for homa_sock objects. This function
+ * handles Homa-specific initialization.
+ * @hsk:    Object to initialize. The Homa-specific parts must have been
+ *          initialized to zeroes by the caller.
+ *
+ * Return:  0 for success, otherwise a negative errno.
+ */
+int homa_sock_init(struct homa_sock *hsk)
+{
+	struct homa_pool *buffer_pool;
+	struct homa_socktab *socktab;
+	struct homa_sock *other;
+	struct homa_net *hnet;
+	struct homa *homa;
+	int starting_port;
+	int result = 0;
+	int i;
+
+	hnet = (struct homa_net *)net_generic(sock_net(&hsk->sock),
+					      homa_net_id);
+	homa = hnet->homa;
+	socktab = homa->socktab;
+
+	/* Do things requiring memory allocation before locking the socket,
+	 * so that GFP_ATOMIC is not needed.
+	 */
+	buffer_pool = homa_pool_alloc(hsk);
+	if (IS_ERR(buffer_pool))
+		return PTR_ERR(buffer_pool);
+
+	/* Initialize the fields private to Homa. We can initialize
+	 * everything except the port and hash table links without acquiring
+	 * the socket table lock.
+	 */
+	hsk->homa = homa;
+	hsk->hnet = hnet;
+	hsk->buffer_pool = buffer_pool;
+
+	hsk->is_server = false;
+	hsk->shutdown = false;
+	hsk->ip_header_length = (hsk->inet.sk.sk_family == AF_INET) ?
+				sizeof(struct iphdr) : sizeof(struct ipv6hdr);
+	hsk->error_msg = "no error";
+	spin_lock_init(&hsk->lock);
+	atomic_set(&hsk->protect_count, 0);
+	INIT_LIST_HEAD(&hsk->active_rpcs);
+	INIT_LIST_HEAD(&hsk->dead_rpcs);
+	INIT_LIST_HEAD(&hsk->waiting_for_bufs);
+	INIT_LIST_HEAD(&hsk->ready_rpcs);
+	INIT_LIST_HEAD(&hsk->interests);
+	for (i = 0; i < HOMA_CLIENT_RPC_BUCKETS; i++) {
+		struct homa_rpc_bucket *bucket = &hsk->client_rpc_buckets[i];
+
+		spin_lock_init(&bucket->lock);
+		bucket->id = i;
+		INIT_HLIST_HEAD(&bucket->rpcs);
+	}
+	for (i = 0; i < HOMA_SERVER_RPC_BUCKETS; i++) {
+		struct homa_rpc_bucket *bucket = &hsk->server_rpc_buckets[i];
+
+		spin_lock_init(&bucket->lock);
+		bucket->id = i + 1000000;
+		INIT_HLIST_HEAD(&bucket->rpcs);
+	}
+
+	/* Initialize fields outside the Homa part. */
+	hsk->sock.sk_sndbuf = homa->wmem_max;
+	sock_set_flag(&hsk->inet.sk, SOCK_RCU_FREE);
+
+	/* This is needed to prevent blocking when allocating memory in
+	 * functions like ip_route_output_flow, which could be invoked
+	 * while atomic.
+	 */
+	hsk->sock.sk_allocation = GFP_ATOMIC;
+
+	/* Pick a default port. Must keep the socktab locked from now
+	 * until the new socket is added to the socktab, to ensure that
+	 * no other socket chooses the same port.
+	 */
+	spin_lock_bh(&socktab->write_lock);
+	starting_port = hnet->prev_default_port;
+	while (1) {
+		hnet->prev_default_port++;
+		if (hnet->prev_default_port < HOMA_MIN_DEFAULT_PORT)
+			hnet->prev_default_port = HOMA_MIN_DEFAULT_PORT;
+		other = homa_sock_find(hnet, hnet->prev_default_port);
+		if (!other)
+			break;
+		sock_put(&other->sock);
+		if (hnet->prev_default_port == starting_port) {
+			spin_unlock_bh(&socktab->write_lock);
+			result = -EADDRNOTAVAIL;
+			goto error;
+		}
+		spin_unlock_bh(&socktab->write_lock);
+		cond_resched();
+		spin_lock_bh(&socktab->write_lock);
+	}
+	result = homa_sock_link(hsk, hnet->prev_default_port);
+	spin_unlock_bh(&socktab->write_lock);
+	if (result == 0)
+		return result;
+
+error:
+	hsk->shutdown = true;
+	hsk->homa = NULL;
+	homa_pool_free(buffer_pool);
+	return result;
+}
+
+/**
+ * homa_sock_link() - Add a socket to the hash table for its socktab,
+ * so that it will be discoverable through homa_sock_find. If the socket
+ * is already linked, the current link will be removed.
+ * @hsk:    Socket to link in; hsk->port will be used to determine
+ *          where the socket is linked in it socktab. Caller must hold
+ *          the lock for the socket's socktab.
+ * @port:   Port to use for the socket; if this function succeeds, this
+ *          number will be stored in hsk.
+ *
+ * Return:  0 for success, otherwise a negative errno.
+ */
+int homa_sock_link(struct homa_sock *hsk, int port)
+	__must_hold(hsk->homa->socktab->write_lock)
+{
+	struct homa_socktab *socktab = hsk->homa->socktab;
+	struct homa_sock_link *slink;
+
+	slink = kmalloc_obj(*slink, GFP_ATOMIC | __GFP_ACCOUNT);
+	if (!slink)
+		return -ENOMEM;
+	homa_sock_unlink(hsk);
+	slink->hsk = hsk;
+	slink->sequence = socktab->next_sequence;
+	socktab->next_sequence++;
+	hlist_add_head_rcu(&slink->links,
+			   &socktab->buckets[homa_socktab_bucket(hsk->hnet,
+								 port)]);
+	hsk->port = port;
+	hsk->inet.inet_num = port;
+	hsk->inet.inet_sport = htons(port);
+	hsk->slink = slink;
+	return 0;
+}
+
+/*
+ * homa_sock_unlink() - Unlinks a socket from its socktab. Once this method
+ * returns, the socket will not be discoverable through the socktab.
+ * @hsk:  Socket to unlink. Caller must hold the lock for the socket's
+ *        socktab.
+ */
+void homa_sock_unlink(struct homa_sock *hsk)
+	__must_hold(hsk->homa->socktab->write_lock)
+{
+	struct homa_sock_link *slink;
+
+	slink = hsk->slink;
+	if (!slink)
+		return;
+	hsk->slink = NULL;
+	hlist_del_rcu(&slink->links);
+	kfree_rcu(slink, rcu_head);
+}
+
+/**
+ * homa_sock_shutdown() - Disable a socket so that it can no longer
+ * be used for either sending or receiving messages. Any system calls
+ * currently waiting to send or receive messages will be aborted. This
+ * function will terminate any existing use of the socket, but it does
+ * not free up socket resources: that happens in homa_sock_destroy.
+ * @hsk:       Socket to shut down.
+ */
+void homa_sock_shutdown(struct homa_sock *hsk)
+{
+	struct homa_socktab *socktab;
+	struct homa_rpc *rpc;
+
+	homa_sock_lock(hsk);
+	if (hsk->shutdown || !hsk->homa) {
+		homa_sock_unlock(hsk);
+		return;
+	}
+
+	/* The order of cleanup is very important, because there could be
+	 * active operations that hold RPC locks but not the socket lock.
+	 * 1. Set @shutdown; this ensures that no new RPCs will be created for
+	 *    this socket (though some creations might already be in progress)
+	 *    and incoming packets will be dropped.
+	 * 2. Remove the socket from its socktab, so no-one will ever find
+	 *    it again.
+	 * 3. Go through all of the RPCs and delete them; this will
+	 *    synchronize with any operations in progress.
+	 * 4. Perform other socket cleanup: at this point we know that
+	 *    there will be no concurrent activities on individual RPCs.
+	 * 5. Don't delete the buffer pool until after all of the RPCs
+	 *    have been reaped.
+	 * See "Homa Locking Strategy" in homa_impl.h for additional information
+	 * about locking.
+	 */
+	hsk->shutdown = true;
+
+	/* This protects against RPC deletions during the RCU scan of
+	 * active_rpcs below.
+	 */
+	atomic_inc(&hsk->protect_count);
+	homa_sock_unlock(hsk);
+
+	socktab = hsk->homa->socktab;
+	spin_lock_bh(&socktab->write_lock);
+	homa_sock_unlink(hsk);
+	spin_unlock_bh(&socktab->write_lock);
+
+	rcu_read_lock();
+	list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
+		homa_rpc_lock(rpc);
+		homa_rpc_end(rpc);
+		homa_rpc_unlock(rpc);
+	}
+	wake_up_interruptible_poll(sk_sleep(&hsk->sock), EPOLLOUT);
+	rcu_read_unlock();
+	homa_unprotect_rpcs(hsk);
+
+	homa_sock_lock(hsk);
+	while (!list_empty(&hsk->interests))
+		homa_interest_notify_shared(hsk, NULL);
+	homa_sock_unlock(hsk);
+}
+
+/**
+ * homa_sock_destroy() - Release all of the internal resources associated
+ * with a socket; is invoked at time when that is safe (i.e., all references
+ * on the socket have been dropped).
+ * @sk:       Socket to destroy.
+ */
+void homa_sock_destroy(struct sock *sk)
+{
+	struct homa_sock *hsk = homa_sk(sk);
+
+	if (!hsk->homa)
+		return;
+
+	while (!list_empty(&hsk->dead_rpcs))
+		homa_rpc_reap(hsk);
+
+	WARN_ON_ONCE(refcount_read(&hsk->sock.sk_wmem_alloc) != 1);
+
+	if (hsk->buffer_pool) {
+		homa_pool_free(hsk->buffer_pool);
+		hsk->buffer_pool = NULL;
+	}
+}
+
+/**
+ * homa_sock_bind() - Associates a server port with a socket; if there
+ * was a previous server port assignment for @hsk, it is abandoned.
+ * @hnet:      Network namespace with which port is associated.
+ * @hsk:       Homa socket.
+ * @port:      Desired server port for @hsk. If 0, then this call
+ *             becomes a no-op: the socket will continue to use
+ *             its randomly assigned client port.
+ *
+ * Return:  0 for success, otherwise a negative errno. If an error is
+ *          returned, hsk->error_msg is set.
+ */
+int homa_sock_bind(struct homa_net *hnet, struct homa_sock *hsk,
+		   u16 port)
+{
+	struct homa_socktab *socktab = hnet->homa->socktab;
+	struct homa_sock *owner;
+	int result = 0;
+
+	if (port == 0)
+		return result;
+	if (port >= HOMA_MIN_DEFAULT_PORT) {
+		hsk->error_msg = "port number invalid: in the automatically assigned range";
+		return -EINVAL;
+	}
+	homa_sock_lock(hsk);
+	spin_lock_bh(&socktab->write_lock);
+	if (hsk->shutdown) {
+		hsk->error_msg = "socket has been shut down";
+		result = -ESHUTDOWN;
+		goto done;
+	}
+
+	owner = homa_sock_find(hnet, port);
+	if (owner) {
+		sock_put(&owner->sock);
+		if (owner != hsk) {
+			hsk->error_msg = "requested port number is already in use";
+			result = -EADDRINUSE;
+		}
+		goto done;
+	}
+	result = homa_sock_link(hsk, port);
+	if (result == 0)
+		hsk->is_server = true;
+done:
+	spin_unlock_bh(&socktab->write_lock);
+	homa_sock_unlock(hsk);
+	return result;
+}
+
+/**
+ * homa_sock_find() - Returns the socket associated with a given port.
+ * @hnet:       Network namespace where the socket will be used.
+ * @port:       The port of interest.
+ * Return:      The socket that owns @port, or NULL if none. If non-NULL
+ *              then this method has taken a reference on the socket and
+ *              the caller must call sock_put to release it.
+ */
+struct homa_sock *homa_sock_find(struct homa_net *hnet, u16 port)
+{
+	int bucket = homa_socktab_bucket(hnet, port);
+	struct homa_sock *result = NULL;
+	struct homa_sock_link *slink;
+	struct homa_sock *hsk;
+
+	rcu_read_lock();
+	hlist_for_each_entry_rcu(slink, &hnet->homa->socktab->buckets[bucket],
+				 links) {
+		hsk = slink->hsk;
+		if (hsk && hsk->port == port && hsk->hnet == hnet &&
+		    !hsk->shutdown &&
+		    refcount_inc_not_zero(&hsk->sock.sk_refcnt)) {
+			result = hsk;
+			break;
+		}
+	}
+	rcu_read_unlock();
+	return result;
+}
+
+/**
+ * homa_sock_wait_wmem() - Block the thread until @hsk's usage of tx
+ * packet memory drops below the socket's limit.
+ * @hsk:          Socket of interest.
+ * @nonblocking:  If there's not enough memory, return -EWOLDBLOCK instead
+ *                of blocking.
+ * Return: 0 for success, otherwise a negative errno.
+ */
+int homa_sock_wait_wmem(struct homa_sock *hsk, int nonblocking)
+{
+	long timeo = hsk->sock.sk_sndtimeo;
+	int result;
+
+	/* Note: we can't use sock_wait_for_wmem because that function
+	 * is not available to modules (as of August 2025 it's static).
+	 */
+	if (nonblocking)
+		timeo = 0;
+	set_bit(HOMA_SOCK_NOSPACE, &hsk->flags);
+
+	/* Must wakeup if either memory becomes available or HOMA_SOCK_NOSPACE
+	 * gets cleared. The wmem_avl check is needed to handle a race where
+	 * memory gets freed just before HOMA_SOCK_NOSPACE is set above. The
+	 * HOMA_SOCK_NOSPACE check is needed to handle a race where multiple
+	 * threads wakeup and one thread consumes enough memory that the
+	 * wmem_avl check fails for the other. This approach means that we may
+	 * exceed the memory limit if multiple threads wake up at once, but
+	 * it prevents thread starvation that could occur if the second
+	 * thread were to go back to sleep.
+	 */
+	result = wait_event_interruptible_timeout(*sk_sleep(&hsk->sock),
+						  homa_sock_wmem_avl(hsk) ||
+						  hsk->shutdown ||
+						  !test_bit(HOMA_SOCK_NOSPACE,
+							    &hsk->flags),
+						  timeo);
+	if (hsk->shutdown)
+		return -ESHUTDOWN;
+	if (signal_pending(current))
+		return -EINTR;
+	if (result == 0)
+		return -EWOULDBLOCK;
+	return 0;
+}
diff --git a/net/homa/homa_sock.h b/net/homa/homa_sock.h
new file mode 100644
index 0000000000000..21a7802a999c0
--- /dev/null
+++ b/net/homa/homa_sock.h
@@ -0,0 +1,513 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file defines structs and other things related to Homa sockets.  */
+
+#ifndef _HOMA_SOCK_H
+#define _HOMA_SOCK_H
+
+/* Forward declarations. */
+struct homa;
+struct homa_pool;
+struct homa_sock;
+
+/* Number of hash buckets in a homa_socktab. Must be a power of 2. */
+#define HOMA_SOCKTAB_BUCKET_BITS 10
+#define HOMA_SOCKTAB_BUCKETS BIT(HOMA_SOCKTAB_BUCKET_BITS)
+
+/**
+ * struct homa_socktab - A hash table that maps from port numbers (either
+ * client or server) to homa_sock objects.
+ *
+ * This table is managed exclusively by homa_socktab.c, using RCU to
+ * minimize synchronization during lookups.
+ */
+struct homa_socktab {
+	/**
+	 * @write_lock: Controls all modifications to this object; not needed
+	 * for socket lookups (RCU is used instead). Also used to
+	 * synchronize port allocation.
+	 */
+	spinlock_t write_lock;
+
+	/**
+	 * @next_sequence: Next sequence number to assign for a
+	 * homa_sock_link.
+	 */
+	u64 next_sequence;
+
+	/**
+	 * @buckets: Heads of chains for hash table buckets. Chains
+	 * consist of homa_sock_link objects, in decreasing order of
+	 * sequence number.
+	 */
+	struct hlist_head buckets[HOMA_SOCKTAB_BUCKETS];
+};
+
+/**
+ * struct homa_sock_link - Used to link a socket into a list associated
+ * with a bucket in a homa_socktab. This is a separate dynamically
+ * allocated object because a socket may need to change its position in
+ * the homa_socktab (because its port number changes); during the
+ * transition, multiple of these objects may exist for a socket so that
+ * socktab scans are not disrupted by the change in position. The lifetime
+ * of these objects is managed with RCU.
+ */
+struct homa_sock_link {
+	/** @hsk: The socket associated with this link. */
+	struct homa_sock *hsk;
+
+	/**
+	 * @sequence: Unique sequence number for this struct among all structs
+	 * in a socktab (smaller means older).
+	 */
+	u64 sequence;
+
+	/**
+	 * @links: Links this object into the chain for a bucket in a
+	 * homa_socktab.
+	 */
+	struct hlist_node links;
+
+	/** @rcu_head: Used for RCU-based freeing of this object. */
+	struct rcu_head rcu_head;
+};
+
+/**
+ * struct homa_socktab_scan - Records the state of an iteration over all
+ * the entries in a homa_socktab, in a way that is safe against concurrent
+ * reclamation of sockets.
+ */
+struct homa_socktab_scan {
+	/** @socktab: The table that is being scanned. */
+	struct homa_socktab *socktab;
+
+	/**
+	 * @hsk: Points to the current socket in the iteration, or NULL if
+	 * we're at the beginning of the iteration or have reached the end of
+	 * the current bucket. If non-NULL then we are holding a reference
+	 * to this socket.
+	 */
+	struct homa_sock *hsk;
+
+	/**
+	 * @current_bucket: The index of the bucket in socktab->buckets
+	 * currently being scanned.
+	 */
+	int current_bucket;
+
+	/**
+	 * @avail: The first @avail entries in @links are valid and
+	 * available for homa_sock_next to return.
+	 */
+	int avail;
+
+	/**
+	 * @socks: Used to collect a bunch of sockets by scanning hash table
+	 * bucket chains. Sockets are then returned from here by
+	 * homa_socktab_next. We own a reference for each of these sockets.
+	 */
+#define HOMA_MAX_SCANNED_SOCKS 5
+	struct homa_sock *socks[HOMA_MAX_SCANNED_SOCKS];
+
+	/**
+	 * @sequence: All homa_sock_links with @sequence numbers >= this
+	 * have already been scanned from @current_bucket.
+	 */
+	u64 sequence;
+};
+
+/**
+ * struct homa_rpc_bucket - One bucket in a hash table of RPCs.
+ */
+
+struct homa_rpc_bucket {
+	/**
+	 * @lock: serves as a lock both for this bucket (e.g., when
+	 * adding and removing RPCs) and also for all of the RPCs in
+	 * the bucket. Must be held whenever looking up an RPC in
+	 * this bucket or manipulating an RPC in the bucket. This approach
+	 * has the following properties:
+	 * 1. An RPC can be looked up and locked (a common operation) with
+	 *    a single lock acquisition.
+	 * 2. Looking up and locking are atomic: there is no window of
+	 *    vulnerability where someone else could delete an RPC after
+	 *    it has been looked up and before it has been locked.
+	 * 3. The lookup mechanism does not use RCU.  This is important because
+	 *    RPCs are created rapidly and typically live only a few tens of
+	 *    microseconds.  As of May 2025 RCU introduces a lag of about
+	 *    25 ms before objects can be deleted; for RPCs this would result
+	 *    in hundreds or thousands of RPCs accumulating before RCU allows
+	 *    them to be deleted.
+	 * This approach has the disadvantage that RPCs within a bucket share
+	 * locks and thus may not be able to work concurrently, but there are
+	 * enough buckets in the table to make such colllisions rare.
+	 *
+	 * See "Homa Locking Strategy" in homa_impl.h for more info about
+	 * locking.
+	 */
+	spinlock_t lock;
+
+	/**
+	 * @id: identifier for this bucket, used in error messages etc.
+	 * It's the index of the bucket within its hash table bucket
+	 * array, with an additional offset to separate server and
+	 * client RPCs.
+	 */
+	int id;
+
+	/** @rpcs: list of RPCs that hash to this bucket. */
+	struct hlist_head rpcs;
+};
+
+/**
+ * define HOMA_CLIENT_RPC_BUCKETS - Number of buckets in hash tables for
+ * client RPCs. Must be a power of 2.
+ */
+#define HOMA_CLIENT_RPC_BUCKETS 1024
+
+/**
+ * define HOMA_SERVER_RPC_BUCKETS - Number of buckets in hash tables for
+ * server RPCs. Must be a power of 2.
+ */
+#define HOMA_SERVER_RPC_BUCKETS 1024
+
+/**
+ * struct homa_sock - Information about an open socket.
+ */
+struct homa_sock {
+	/* Info for other network layers. Note: IPv6 info (struct ipv6_pinfo
+	 * comes at the very end of the struct, *after* Homa's data, if this
+	 * socket uses IPv6).
+	 */
+	union {
+		/** @sock: generic socket data; must be the first field. */
+		struct sock sock;
+
+		/**
+		 * @inet: generic Internet socket data; must also be the
+		 first field (contains sock as its first member).
+		 */
+		struct inet_sock inet;
+	};
+
+	/**
+	 * @homa: Overall state about the Homa implementation. NULL
+	 * means this socket was never initialized or has been deleted.
+	 */
+	struct homa *homa;
+
+	/**
+	 * @hnet: Overall state specific to the network namespace for
+	 * this socket.
+	 */
+	struct homa_net *hnet;
+
+	/**
+	 * @buffer_pool: used to allocate buffer space for incoming messages.
+	 * Storage is dynamically allocated.
+	 */
+	struct homa_pool *buffer_pool;
+
+	/**
+	 * @port: Port number: identifies this socket uniquely among all
+	 * those on this node.
+	 */
+	u16 port;
+
+	/**
+	 * @is_server: True means that this socket can act as both client
+	 * and server; false means the socket is client-only.
+	 */
+	bool is_server;
+
+	/**
+	 * @shutdown: True means the socket is no longer usable (either
+	 * shutdown has already been invoked, or the socket was never
+	 * properly initialized). Note: can't use the SOCK_DEAD flag for
+	 * this because that flag doesn't get set until much later in the
+	 * process of closing a socket.
+	 */
+	bool shutdown;
+
+	/**
+	 * @ip_header_length: Length of IP headers for this socket (depends
+	 * on IPv4 vs. IPv6).
+	 */
+	int ip_header_length;
+
+	/** @slink: Links this socket into a homa_socktab bucket. */
+	struct homa_sock_link *slink;
+
+	/**
+	 * @error_msg: Static string giving human-readable information about
+	 * the reason for the last error returned by a Homa kernel call.
+	 * Applications can fetch this with the HOMAIOCINFO ioctl to figure
+	 * out why a call failed.
+	 */
+	char *error_msg;
+
+	/* Information above is (almost) never modified; start a new
+	 * cache line below for info that is modified frequently.
+	 */
+
+	/**
+	 * @lock: Must be held when modifying fields such as interests
+	 * and lists of RPCs. This lock is used in place of sk->sk_lock
+	 * because it's used differently (it's always used as a simple
+	 * spin lock).  See "Homa Locking Strategy" in homa_impl.h
+	 * for more on Homa's synchronization strategy.
+	 */
+	spinlock_t lock ____cacheline_aligned_in_smp;
+
+	/**
+	 * @protect_count: counts the number of calls to homa_protect_rpcs
+	 * for which there have not yet been calls to homa_unprotect_rpcs.
+	 */
+	atomic_t protect_count;
+
+	/**
+	 * @flags: Additional state information: an OR'ed combination of
+	 * various single-bit flags. See below for definitions. Must be
+	 * manipulated with test_bit etc. because some of the manipulations
+	 * occur without holding @lock.
+	 */
+	unsigned long flags;
+
+	/* Valid bit numbers for @flags:
+	 * HOMA_SOCK_NOSPACE -     Nonzero means that the socket has hit its
+	 *                         limit on tx buffer space and threads are
+	 *                         blocked waiting for skbs to be released. Used
+	 *                         instead of the SOCK_NOSPACE flag in
+	 *                         @sock.sk_socket->flags. This is because
+	 *                         @sock.sk_socket can become NULL unexpectedly
+	 *                         (especially since Homa never acquires the
+	 *                         Linux socket lock). Thus code using sk_socket
+	 *                         requires tricky synchronization and is
+	 *                         error-prone.
+	 */
+#define HOMA_SOCK_NOSPACE        0
+
+	/**
+	 * @active_rpcs: List of all existing RPCs related to this socket,
+	 * including both client and server RPCs. This list isn't strictly
+	 * needed, since RPCs are already in one of the hash tables below,
+	 * but it's more efficient for homa_timer to have this list
+	 * (so it doesn't have to scan large numbers of hash buckets).
+	 * The list is sorted, with the oldest RPC first. Manipulate with
+	 * RCU so timer can access without locking.
+	 */
+	struct list_head active_rpcs;
+
+	/**
+	 * @dead_rpcs: Contains RPCs for which homa_rpc_end has been
+	 * called, but which have not yet been reaped by homa_rpc_reap.
+	 */
+	struct list_head dead_rpcs;
+
+	/**
+	 * @dead_frags: An estimate of the amount of memory tied up in
+	 * RPCs that are dead but have not yet been reaped. The sum of
+	 * rpc->msgout.num_frags + 1 for all of the dead RPCs (the 1 accounts
+	 * for the RPC itself). Used to detect when the reaper is lagging
+	 * behind. See "RPC Reaping Strategy" in homa_rpc_reap code for
+	 * deetails.
+	 */
+	u64 dead_frags;
+
+	/**
+	 * @waiting_for_bufs: Contains RPCs that are blocked because there
+	 * wasn't enough space in the buffer pool region for their incoming
+	 * messages. Sorted in increasing order of message length.
+	 */
+	struct list_head waiting_for_bufs;
+
+	/**
+	 * @ready_rpcs: List of all RPCs that are ready for attention from
+	 * an application thread.
+	 */
+	struct list_head ready_rpcs;
+
+	/**
+	 * @interests: List of threads that are currently waiting for
+	 * incoming messages via homa_wait_shared.
+	 */
+	struct list_head interests;
+
+	/**
+	 * @client_rpc_buckets: Hash table for fast lookup of client RPCs.
+	 * Modifications are synchronized with bucket locks, not
+	 * the socket lock.
+	 */
+	struct homa_rpc_bucket client_rpc_buckets[HOMA_CLIENT_RPC_BUCKETS];
+
+	/**
+	 * @server_rpc_buckets: Hash table for fast lookup of server RPCs.
+	 * Modifications are synchronized with bucket locks, not
+	 * the socket lock.
+	 */
+	struct homa_rpc_bucket server_rpc_buckets[HOMA_SERVER_RPC_BUCKETS];
+};
+
+/**
+ * struct homa_v6_sock - For IPv6, additional IPv6-specific information
+ * is present in the socket struct after Homa-specific information.
+ */
+struct homa_v6_sock {
+	/** @homa: All socket info except for IPv6-specific stuff. */
+	struct homa_sock homa;
+
+	/** @inet6: Socket info specific to IPv6. */
+	struct ipv6_pinfo inet6;
+};
+
+int                homa_sock_bind(struct homa_net *hnet, struct homa_sock *hsk,
+				  u16 port);
+void               homa_sock_destroy(struct sock *sk);
+void               homa_socktab_fill_scan(struct homa_socktab_scan *scan);
+struct homa_sock  *homa_sock_find(struct homa_net *hnet, u16 port);
+int                homa_sock_init(struct homa_sock *hsk);
+int                homa_sock_link(struct homa_sock *hsk, int port);
+void               homa_sock_shutdown(struct homa_sock *hsk);
+void               homa_sock_unlink(struct homa_sock *hsk);
+int                homa_sock_wait_wmem(struct homa_sock *hsk, int nonblocking);
+void               homa_socktab_destroy(struct homa_socktab *socktab,
+					struct homa_net *hnet);
+void               homa_socktab_end_scan(struct homa_socktab_scan *scan);
+void               homa_socktab_init(struct homa_socktab *socktab);
+struct homa_sock  *homa_socktab_next(struct homa_socktab_scan *scan);
+struct homa_sock  *homa_socktab_start_scan(struct homa_socktab *socktab,
+					   struct homa_socktab_scan *scan);
+
+/**
+ * homa_sock_lock() - Acquire the lock for a socket.
+ * @hsk:     Socket to lock.
+ */
+static inline void homa_sock_lock(struct homa_sock *hsk)
+	__acquires(hsk->lock)
+{
+	spin_lock_bh(&hsk->lock);
+}
+
+/**
+ * homa_sock_unlock() - Release the lock for a socket.
+ * @hsk:   Socket to lock.
+ */
+static inline void homa_sock_unlock(struct homa_sock *hsk)
+	__releases(hsk->lock)
+{
+	spin_unlock_bh(&hsk->lock);
+}
+
+/**
+ * homa_socktab_bucket() - Compute the bucket number in a homa_socktab
+ * that will contain a particular socket.
+ * @hnet:   Network namespace of the desired socket.
+ * @port:   Port number of the socket.
+ *
+ * Return:  The index of the bucket in which a socket matching @hnet and
+ *          @port will be found (if it exists).
+ */
+static inline int homa_socktab_bucket(struct homa_net *hnet, u16 port)
+{
+	return hash_32((uintptr_t)hnet ^ port, HOMA_SOCKTAB_BUCKET_BITS);
+}
+
+/**
+ * homa_client_rpc_bucket() - Find the bucket containing a given
+ * client RPC.
+ * @hsk:      Socket associated with the RPC.
+ * @id:       Id of the desired RPC.
+ *
+ * Return:    The bucket in which this RPC will appear, if the RPC exists.
+ */
+static inline struct homa_rpc_bucket
+		*homa_client_rpc_bucket(struct homa_sock *hsk, u64 id)
+{
+	/* We can use a really simple hash function here because RPC ids
+	 * are allocated sequentially.
+	 */
+	return &hsk->client_rpc_buckets[(id >> 1) &
+	       (HOMA_CLIENT_RPC_BUCKETS - 1)];
+}
+
+/**
+ * homa_server_rpc_bucket() - Find the bucket containing a given
+ * server RPC.
+ * @hsk:         Socket associated with the RPC.
+ * @id:          Id of the desired RPC.
+ *
+ * Return:    The bucket in which this RPC will appear, if the RPC exists.
+ */
+static inline struct homa_rpc_bucket
+		*homa_server_rpc_bucket(struct homa_sock *hsk, u64 id)
+{
+	/* Each client allocates RPC ids sequentially, so they will
+	 * naturally distribute themselves across the hash space.
+	 * Thus we can use the id directly as hash.
+	 */
+	return &hsk->server_rpc_buckets[(id >> 1)
+			& (HOMA_SERVER_RPC_BUCKETS - 1)];
+}
+
+/**
+ * homa_bucket_lock() - Acquire the lock for an RPC hash table bucket.
+ * @bucket:    Bucket to lock.
+ * @id:        Id of the RPC on whose behalf the bucket is being locked.
+ *             Used only for metrics.
+ */
+static inline void homa_bucket_lock(struct homa_rpc_bucket *bucket, u64 id)
+	__acquires(bucket->lock)
+{
+	spin_lock_bh(&bucket->lock);
+}
+
+/**
+ * homa_bucket_unlock() - Release the lock for an RPC hash table bucket.
+ * @bucket:   Bucket to unlock.
+ * @id:       ID of the RPC that was using the lock.
+ */
+static inline void homa_bucket_unlock(struct homa_rpc_bucket *bucket, u64 id)
+	__releases(bucket->lock)
+{
+	spin_unlock_bh(&bucket->lock);
+}
+
+static inline struct homa_sock *homa_sk(const struct sock *sk)
+{
+	return (struct homa_sock *)sk;
+}
+
+/**
+ * homa_sock_wmem_avl() - Returns true if the socket is within its limit
+ * for output memory usage. False means that no new messages should be sent
+ * until memory is freed.
+ * @hsk:   Socket of interest.
+ * Return: See above.
+ */
+static inline bool homa_sock_wmem_avl(struct homa_sock *hsk)
+{
+	return refcount_read(&hsk->sock.sk_wmem_alloc) < hsk->sock.sk_sndbuf;
+}
+
+/**
+ * homa_sock_wakeup_wmem() - Invoked when tx packet memory has been freed;
+ * if memory usage is below the limit and there are tasks waiting for memory,
+ * wake them up.
+ * @hsk:   Socket of interest.
+ */
+static inline void homa_sock_wakeup_wmem(struct homa_sock *hsk)
+{
+	/* Note: can't use sk_stream_write_space for this functionality
+	 * because it uses a different test to determine whether enough
+	 * memory is available.
+	 */
+	if (test_bit(HOMA_SOCK_NOSPACE, &hsk->flags) &&
+	    homa_sock_wmem_avl(hsk)) {
+		clear_bit(HOMA_SOCK_NOSPACE, &hsk->flags);
+		rcu_read_lock();
+		wake_up_interruptible_poll(sk_sleep(&hsk->sock), EPOLLOUT);
+		rcu_read_unlock();
+	}
+}
+
+#endif /* _HOMA_SOCK_H */
diff --git a/net/homa/homa_timer.c b/net/homa/homa_timer.c
new file mode 100644
index 0000000000000..2fa86f523088d
--- /dev/null
+++ b/net/homa/homa_timer.c
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file handles timing-related functions for Homa, such as retries
+ * and timeouts.
+ */
+
+#include "homa_impl.h"
+#include "homa_peer.h"
+#include "homa_rpc.h"
+#include "homa_tx_pool.h"
+
+/**
+ * homa_timer_check_rpc() -  Invoked for each RPC during each timer pass; does
+ * most of the work of checking for time-related actions such as sending
+ * resends, aborting RPCs for which there is no response, and sending
+ * requests for acks. It is separate from homa_timer because homa_timer
+ * got too long and deeply indented.
+ * @rpc:     RPC to check; must be locked by the caller.
+ */
+void homa_timer_check_rpc(struct homa_rpc *rpc)
+	__must_hold(rpc->bucket->lock)
+{
+	struct homa *homa = rpc->hsk->homa;
+	int tx_end = homa_rpc_tx_end(rpc);
+
+	/* See if we need to request an ack for this RPC. */
+	if (!homa_is_client(rpc->id) && rpc->state == RPC_OUTGOING &&
+	    tx_end == rpc->msgout.length) {
+		if (rpc->done_timer_ticks == 0) {
+			rpc->done_timer_ticks = homa->timer_ticks;
+		} else {
+			/* >= comparison that handles tick wrap-around. */
+			if ((rpc->done_timer_ticks + homa->request_ack_ticks
+					- 1 - homa->timer_ticks) & 1 << 31) {
+				struct homa_need_ack_hdr h;
+
+				homa_xmit_control(NEED_ACK, &h, sizeof(h), rpc);
+			}
+		}
+	}
+
+	if (rpc->state == RPC_INCOMING) {
+		if (rpc->msgin.num_bpages == 0) {
+			/* Waiting for buffer space, so no problem. */
+			rpc->silent_ticks = 0;
+			return;
+		}
+	} else if (!homa_is_client(rpc->id)) {
+		/* We're the server and we've received the input message;
+		 * no need to worry about retries.
+		 */
+		rpc->silent_ticks = 0;
+		return;
+	}
+
+	if (rpc->state == RPC_OUTGOING) {
+		if (tx_end < rpc->msgout.length) {
+			/* There are granted bytes that we haven't transmitted,
+			 * so no need to be concerned; the ball is in our court.
+			 */
+			rpc->silent_ticks = 0;
+			return;
+		}
+	}
+
+	if (rpc->silent_ticks < homa->resend_ticks)
+		return;
+	if (rpc->silent_ticks >= homa->timeout_ticks) {
+		homa_rpc_abort(rpc, -ETIMEDOUT);
+		return;
+	}
+	if (((rpc->silent_ticks - homa->resend_ticks) % homa->resend_interval)
+			== 0)
+		homa_request_retrans(rpc);
+}
+
+/**
+ * homa_timer() - This function is invoked at regular intervals ("ticks")
+ * to implement retries and aborts for Homa.
+ * @homa:    Overall data about the Homa protocol implementation.
+ */
+void homa_timer(struct homa *homa)
+{
+	struct homa_socktab_scan scan;
+	struct homa_sock *hsk;
+	struct homa_rpc *rpc;
+	int rpc_count = 0;
+
+	homa->timer_ticks++;
+
+	/* Scan all existing RPCs in all sockets. */
+	for (hsk = homa_socktab_start_scan(homa->socktab, &scan);
+			hsk; hsk = homa_socktab_next(&scan)) {
+		while (hsk->dead_frags > homa->dead_frags_limit)
+			/* If we get here, it means that Homa isn't keeping
+			 * up with RPC reaping, so we'll help out.  See
+			 * "RPC Reaping Strategy" in homa_rpc_reap code for
+			 * details.
+			 */
+			if (homa_rpc_reap(hsk) == 0)
+				break;
+
+		if (list_empty(&hsk->active_rpcs) || hsk->shutdown)
+			continue;
+
+		if (!homa_protect_rpcs(hsk))
+			continue;
+		rcu_read_lock();
+		list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
+			homa_rpc_lock(rpc);
+			if (rpc->state == RPC_IN_SERVICE) {
+				rpc->silent_ticks = 0;
+				homa_rpc_unlock(rpc);
+				continue;
+			}
+			rpc->silent_ticks++;
+			homa_timer_check_rpc(rpc);
+			homa_rpc_unlock(rpc);
+			rpc_count++;
+			if (rpc_count >= 10) {
+				/* Give other kernel threads a chance to run
+				 * on this core.
+				 */
+				rcu_read_unlock();
+				schedule();
+				rcu_read_lock();
+				rpc_count = 0;
+			}
+		}
+		rcu_read_unlock();
+		homa_unprotect_rpcs(hsk);
+	}
+	homa_socktab_end_scan(&scan);
+	homa_tx_pool_gc(homa);
+	homa_route_gc(homa->peertab);
+}
diff --git a/net/homa/homa_tx_pool.c b/net/homa/homa_tx_pool.c
new file mode 100644
index 0000000000000..c6420ffe2d19c
--- /dev/null
+++ b/net/homa/homa_tx_pool.c
@@ -0,0 +1,527 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file manages a reusable pools of pages (one per NUMA node), that
+ * are used to hold the data of outgoing Homa messages. Homa uses these
+ * custom pools rather than, say, page_pools because Homa can free pages
+ * from its pools more aggressively than in page_pool. And, this module
+ * also implements a one-page cache page per core to use for allocating
+ * smaller chunks of tx memory.
+ */
+
+#include "homa_impl.h"
+#include "homa_tx_pool.h"
+
+DEFINE_PER_CPU(struct homa_tx_pool_core, homa_tx_pool_core);
+
+static void frag_page_set(skb_frag_t *frag, struct page *page)
+{
+	frag->netmem = page_to_netmem(page);
+}
+
+/**
+ * homa_tx_pool_init() - Invoked when a struct homa is created; initializes
+ * information related to this module.
+ * @homa:        Shared information about the Homa transport; pool-related
+ *               fields are assumed to have been initialized to zero.
+ * Return:       0 for success, negative errno on error
+ */
+int homa_tx_pool_init(struct homa *homa)
+{
+	u64 min_kb;
+	int i;
+
+	homa->tx_page_pool_min_kb = 1000;
+	min_kb = 3 * HOMA_MAX_MESSAGE_LENGTH;
+	do_div(min_kb, 1000);
+	homa->tx_page_pool_min_kb = min_kb;
+
+	/* Initialize NUMA-specfific page pools. */
+	homa->max_numa = -1;
+	for (i = 0; i < nr_cpu_ids; i++) {
+		struct homa_tx_pool_core *tx_core;
+		int numa = cpu_to_node(i);
+
+		BUG_ON(numa >= MAX_NUMNODES);
+		if (numa > homa->max_numa)
+			homa->max_numa = numa;
+		if (!homa->tx_pools[numa]) {
+			struct homa_tx_pool *pool;
+
+			pool = kzalloc_obj(*pool, GFP_ATOMIC);
+			if (!pool)
+				goto error;
+			homa->tx_pools[numa] = pool;
+		}
+		tx_core = &per_cpu(homa_tx_pool_core, i);
+		tx_core->pool = homa->tx_pools[numa];
+	}
+	pr_notice("%s found max NUMA node %d\n", __func__, homa->max_numa);
+	return 0;
+
+error:
+	homa_tx_pool_cleanup(homa);
+	return -ENOMEM;
+}
+
+/**
+ * homa_tx_pool_cleanup() - Invoked when a struct homa is deleted; cleans
+ * up information related to this module.
+ * @homa:  Overall information about the Homa transport.
+ */
+void homa_tx_pool_cleanup(struct homa *homa)
+{
+	int i, j;
+
+	for (i = 0; i < nr_cpu_ids; i++) {
+		struct homa_tx_pool_core *tx_core;
+
+		tx_core = &per_cpu(homa_tx_pool_core, i);
+		if (!tx_core)
+			continue;
+		if (tx_core->page) {
+			put_page(tx_core->page);
+			tx_core->page = NULL;
+			tx_core->page_size = 0;
+			tx_core->allocated = 0;
+		}
+		tx_core->pool = NULL;
+	}
+
+	for (i = 0; i < MAX_NUMNODES; i++) {
+		struct homa_tx_pool *pool = homa->tx_pools[i];
+
+		if (!pool)
+			continue;
+		for (j = pool->avail - 1; j >= 0; j--)
+			put_page(pool->pages[j]);
+		pool->avail = 0;
+		kfree(pool);
+		homa->tx_pools[i] = NULL;
+	}
+
+	kfree(homa->tx_pages_to_free);
+	homa->tx_pages_to_free = NULL;
+	homa->tx_pages_to_free_slots = 0;
+}
+
+/**
+ * homa_tx_pool_alloc() - Allocate a block of memory in one or more
+ * fragments.
+ * @homa:        Shared information about the Homa transport.
+ * @length:       Total number of bytes to allocate.
+ * @num_frags:   Number of fragments of storage initially available at **frags;
+ *               modified to hold the total number of fragments
+ *               allocated.
+ * @frags:       Pointer to pointer to space in which to store fragments;
+ *               if this initial space is insufficient to hold all of the
+ *               fragments needed, will be overwritten with a dynamically
+ *               allocated block.
+ * Return:       0 for success, negative errno on error.
+ */
+int homa_tx_pool_alloc(struct homa *homa, int length, int *num_frags,
+		       skb_frag_t **frags)
+{
+	struct homa_tx_pool_core *tx_core;
+	skb_frag_t *cur_frags = *frags;
+	int max_frags = *num_frags;
+	int bytes_left = length;
+	int frags_allocated = 0;
+	skb_frag_t *frag;
+	int err;
+
+	/* Asssure atomicity with respect to SoftIRQ invocations or
+	 * task preemption (so we can access per-core info without races).
+	 */
+	local_bh_disable();
+	tx_core = &per_cpu(homa_tx_pool_core, smp_processor_id());
+
+	while (bytes_left  > 0) {
+		/* Expand the frag array if needed. */
+		if (frags_allocated == max_frags) {
+			skb_frag_t *new_frags;
+			int num_new;
+
+			num_new = ((bytes_left + HOMA_TX_PAGE_SIZE - 1) >>
+				   (PAGE_SHIFT + HOMA_TX_PAGE_ORDER)) +
+				  frags_allocated;
+			new_frags = kvmalloc_array(num_new, sizeof(*new_frags),
+						   GFP_ATOMIC);
+			if (!new_frags) {
+				err = -ENOMEM;
+				goto error;
+			}
+			memcpy(new_frags, cur_frags,
+			       frags_allocated * sizeof(*new_frags));
+			if (cur_frags != *frags)
+				kfree(cur_frags);
+			cur_frags = new_frags;
+			max_frags = num_new;
+		}
+
+		frag = &cur_frags[frags_allocated];
+		err = __homa_tx_pool_alloc_frag(tx_core, bytes_left, frag);
+		if (err != 0)
+			goto error;
+		frags_allocated++;
+		bytes_left -= skb_frag_size(frag);
+	}
+	local_bh_enable();
+	*frags  = cur_frags;
+	*num_frags = frags_allocated;
+	return 0;
+
+error:
+	homa_tx_pool_free(homa, frags_allocated, cur_frags);
+	if (cur_frags != *frags)
+		kfree(cur_frags);
+	*num_frags = 0;
+	local_bh_enable();
+	return err;
+}
+
+/**
+ * __homa_tx_pool_alloc_frag() - Allocate space for a single fragment.
+ * Caller must have disabled interrupts.
+ * @tx_core:   Core-specific information to use for the allocation.
+ * @length:    Desired length: actual length of fragment may be less
+ *             than this.
+ * @frag:      Store information about the allocated fragment here. Its
+ *             length may be less than @length. A reference will be taken
+ *             on its page.
+ * Return:     0 for success, otherwise a negative errno.
+ */
+int __homa_tx_pool_alloc_frag(struct homa_tx_pool_core *tx_core, int length,
+			      skb_frag_t *frag)
+{
+	struct page *page;
+	int page_size;
+
+	/* See if the allocation can be handled with the core's cached page. */
+	if (tx_core->page_size - tx_core->allocated >= length) {
+		get_page(tx_core->page);
+		frag_page_set(frag, tx_core->page);
+		frag->offset = tx_core->allocated;
+		skb_frag_size_set(frag, length);
+		tx_core->allocated += length;
+		if (tx_core->allocated == tx_core->page_size) {
+			put_page(tx_core->page);
+			tx_core->page = NULL;
+			tx_core->page_size = 0;
+			tx_core->allocated = 0;
+		}
+		return 0;
+	}
+
+	/* Must allocate a new page. */
+	page = homa_tx_pool_alloc_page(tx_core, &page_size);
+	if (!page)
+		return -ENOMEM;
+	frag_page_set(frag, page);
+	frag->offset = 0;
+	skb_frag_size_set(frag, min(page_size, length));
+
+	/* Retain the leftover part of the page as the core's cached page,
+	 * if it has more space available than the current cached page.
+	 */
+	if (!tx_core->page || (tx_core->page_size - tx_core->allocated) <
+			       (page_size - skb_frag_size(frag))) {
+		if (tx_core->page)
+			put_page(tx_core->page);
+		get_page(page);
+		tx_core->page = page;
+		tx_core->page_size = page_size;
+		tx_core->allocated = skb_frag_size(frag);
+	}
+	return 0;
+}
+
+/**
+ * homa_tx_pool_alloc_frag() - Allocate space for a single fragment.
+ * @homa:      Overall information about the Homa transport.
+ * @length:    Desired length: actual length of fragment may be less
+ *             than this.
+ * @frag:      Store information about the allocated fragment here. Its
+ *             length may be less than @length. A reference will be taken
+ *             on its page.
+ * Return:     0 for success, otherwise a negative errno.
+ */
+int homa_tx_pool_alloc_frag(struct homa *homa, int length, skb_frag_t *frag)
+{
+	struct homa_tx_pool_core *tx_core;
+	int result;
+
+	tx_core = &per_cpu(homa_tx_pool_core, smp_processor_id());
+	local_bh_disable();
+	result = __homa_tx_pool_alloc_frag(tx_core, length, frag);
+	local_bh_enable();
+	return result;
+}
+
+/**
+ * homa_tx_pool_alloc_page() - Allocate a new page for skb allocation for a
+ * given core. Any existing page is released.
+ * @tx_core:    Core-specific info; the page will be allocated in this core.
+ * @length:     The length of the allocated page (if any) will be stored here.
+ * Return:      The allocated page (with reference count 1) or NULL if
+ *              no page could be allocated.
+ */
+struct page *homa_tx_pool_alloc_page(struct homa_tx_pool_core *tx_core,
+				     int *length)
+{
+	struct homa_tx_pool *pool;
+	struct page *page;
+
+	/* Step 1: can we reuse the core's cached page? */
+	page = tx_core->page;
+	if (page && page_ref_count(page) == 1) {
+		*length = tx_core->page_size;
+		tx_core->page = NULL;
+		tx_core->page_size = 0;
+		tx_core->allocated = 0;
+		return page;
+	}
+
+	/* Step 2: can we retrieve a page from the pool for this NUMA node? */
+	pool = tx_core->pool;
+	if (pool->avail) {
+		spin_lock_bh(&pool->mutex);
+
+		/* Must recheck: could have changed before locked. */
+		if (pool->avail) {
+			pool->avail--;
+			if (pool->avail < pool->low_mark)
+				pool->low_mark = pool->avail;
+			page = pool->pages[pool->avail];
+			spin_unlock_bh(&pool->mutex);
+			*length = HOMA_TX_PAGE_SIZE;
+			return page;
+		}
+		spin_unlock_bh(&pool->mutex);
+	}
+
+	/* Step 3: can we allocate a big page? */
+	page = alloc_pages(GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN |
+			   __GFP_NORETRY, HOMA_TX_PAGE_ORDER);
+	if (likely(page)) {
+		*length = HOMA_TX_PAGE_SIZE;
+		return page;
+	}
+
+	/* Step 4: can we allocate a normal page? */
+	page = alloc_page(GFP_ATOMIC);
+	if (likely(page)) {
+		*length = PAGE_SIZE;
+		return page;
+	}
+	return NULL;
+}
+
+/**
+ * homa_tx_pool_free() - Release one or more fragments previously allocated
+ * by homa_tx_pool_alloc.
+ * @homa:        Shared information about the Homa transport.
+ * @num_frags:   Number of fragments at *frags.
+ * @frags:       Pointer to array of fragments to free; must not be used
+ *               after this function returns.
+ */
+void homa_tx_pool_free(struct homa *homa, int num_frags, skb_frag_t *frags)
+{
+	struct homa_tx_pool *pool;
+	int i;
+
+	if (num_frags <= 0)
+		return;
+
+	pool = homa->tx_pools[page_to_nid(skb_frag_page(&frags[0]))];
+	spin_lock_bh(&pool->mutex);
+	for (i = 0; i < num_frags; i++) {
+		struct page *page = skb_frag_page(&frags[i]);
+
+		if (compound_order(page) == HOMA_TX_PAGE_ORDER &&
+		    page_ref_count(page) == 1 &&
+		    pool->avail < HOMA_TX_POOL_LIMIT) {
+			pool->pages[pool->avail] = page;
+			pool->avail++;
+		} else {
+			put_page(page);
+		}
+	}
+	spin_unlock_bh(&pool->mutex);
+}
+
+/**
+ * homa_tx_pool_gc() - This function is invoked occasionally; its
+ * job is to gradually release pages from the page pools back to
+ * Linux, based on sysctl parameters such as tx_page_frees_per_sec.
+ * @homa:  Overall information about the Homa transport.
+ */
+void homa_tx_pool_gc(struct homa *homa)
+{
+	int i, max_low_mark, min_pages, release, release_max;
+	struct homa_tx_pool *max_pool;
+	u64 now = homa_clock();
+
+	if (now < homa->tx_page_free_time)
+		return;
+
+	/* Free pages every 0.5 second. */
+	homa->tx_page_free_time = now + (500 * homa_clock_khz());
+
+	/* Make sure we have space in which to collect pages to free. */
+	release_max = homa->tx_page_frees_per_sec / 2;
+	if (homa->tx_pages_to_free_slots < release_max) {
+		struct page **old = homa->tx_pages_to_free;
+
+		homa->tx_pages_to_free = kmalloc_array(release_max,
+						       sizeof(struct page *),
+						       GFP_ATOMIC);
+		if (homa->tx_pages_to_free) {
+			kfree(old);
+			homa->tx_pages_to_free_slots = release_max;
+		} else {
+			/* Couldn't allocate space; reuse existing space
+			 * and reduce how many pages we'll free.
+			 */
+			homa->tx_pages_to_free = old;
+			release_max = homa->tx_pages_to_free_slots;
+		}
+	}
+
+	/* Find the pool with the largest number of pages that haven't
+	 * been used recently.
+	 */
+	max_low_mark = -1;
+	for (i = 0; i <= homa->max_numa; i++) {
+		struct homa_tx_pool *pool = homa->tx_pools[i];
+
+		if (!pool)
+			continue;
+		spin_lock_bh(&pool->mutex);
+		if (pool->low_mark > max_low_mark) {
+			max_low_mark = pool->low_mark;
+			max_pool = pool;
+		}
+		pool->low_mark = pool->avail;
+		spin_unlock_bh(&pool->mutex);
+	}
+
+	/* Collect pages to free (but don't free them until after
+	 * releasing the lock, since freeing is expensive).
+	 */
+	spin_lock_bh(&max_pool->mutex);
+	min_pages = ((homa->tx_page_pool_min_kb * 1000)
+			+ (HOMA_TX_PAGE_SIZE - 1)) >> HOMA_TX_PAGE_SHIFT;
+
+	/* Note: may need to adjust max_low_mark to reflect changes made
+	 * while lock wasn't held.
+	 */
+	if (max_low_mark > max_pool->low_mark)
+		max_low_mark = max_pool->low_mark;
+	release = max_low_mark - min_pages;
+	if (release > release_max)
+		release = release_max;
+	for (i = 0; i < release; i++) {
+		max_pool->avail--;
+		homa->tx_pages_to_free[i] = max_pool->pages[max_pool->avail];
+	}
+	max_pool->low_mark = max_pool->avail;
+	spin_unlock_bh(&max_pool->mutex);
+
+	/* Free the pages that were collected. */
+	for (i = 0; i < release; i++) {
+		struct page *page = homa->tx_pages_to_free[i];
+
+		put_page(page);
+	}
+}
+
+/**
+ * homa_copy_to_frags() - Copy a block of data into an array of fragments.
+ * @filler:    Describes the current position in the array of fragments;
+ *             will be updated to reflect the copied data.
+ * @src:       Copy bytes from here into the fragments.
+ * @num_bytes: Number of bytes to copy.
+ * Return:     0 for success; -EINVAL if there isn't enough room in the
+ *             fragments for the new bytes.
+ */
+int homa_copy_to_frags(struct homa_frag_filler *filler, void *src,
+		       int num_bytes)
+{
+	int p_off, copied, p_len;
+	int bytes_this_frag;
+	struct page *p;
+	u8 *src_cur;
+
+	src_cur = src;
+	while (num_bytes > 0) {
+		if (filler->offset >= skb_frag_size(filler->frag)) {
+			filler->frag++;
+			filler->num_frags--;
+			if (filler->num_frags <= 0)
+				return -EINVAL;
+			filler->offset = 0;
+		}
+		bytes_this_frag = min(num_bytes,
+				      skb_frag_size(filler->frag) -
+				      filler->offset);
+		skb_frag_foreach_page(filler->frag,
+				      skb_frag_off(filler->frag) +
+				      filler->offset, bytes_this_frag, p,
+				      p_off, p_len, copied) {
+			u8 *vaddr = kmap_local_page(p);
+
+			memcpy(vaddr + p_off, src_cur, p_len);
+			kunmap_local(vaddr);
+			src_cur += p_len;
+		}
+		filler->offset += bytes_this_frag;
+		num_bytes -= bytes_this_frag;
+	}
+	return 0;
+}
+
+/**
+ * homa_copy_iter_to_frags() - Copy data from an iterator (presumably
+ * referring to user-space data) into an array of fragments.
+ * @filler:    Describes the current position in the array of fragments;
+ *             will be updated to reflect the copied data.
+ * @iter:      Copy bytes from here into the fragments.
+ * @num_bytes: Number of bytesto copy.
+ * Return:     0 for success; -EINVAL if there isn't enough room in the
+ *             fragments for the new bytes.
+ */
+int homa_copy_iter_to_frags(struct homa_frag_filler *filler,
+			    struct iov_iter *iter, int num_bytes)
+{
+	int p_off, copied, p_len;
+	int bytes_this_frag;
+	struct page *p;
+
+	while (num_bytes > 0) {
+		if (filler->offset >= skb_frag_size(filler->frag)) {
+			filler->frag++;
+			filler->num_frags--;
+			if (filler->num_frags <= 0)
+				return -EINVAL;
+			filler->offset = 0;
+		}
+		bytes_this_frag = min(num_bytes,
+				      skb_frag_size(filler->frag) -
+				      filler->offset);
+		skb_frag_foreach_page(filler->frag,
+				      skb_frag_off(filler->frag) +
+				      filler->offset, bytes_this_frag, p,
+				      p_off, p_len, copied) {
+			int result;
+			void *vaddr = kmap_local_page(p);
+
+			result = copy_from_iter(vaddr + p_off, p_len, iter);
+			kunmap_local(vaddr);
+			if (result != p_len)
+				return -EFAULT;
+		}
+		filler->offset += bytes_this_frag;
+		num_bytes -= bytes_this_frag;
+	}
+	return 0;
+}
diff --git a/net/homa/homa_tx_pool.h b/net/homa/homa_tx_pool.h
new file mode 100644
index 0000000000000..aca47f9a3184a
--- /dev/null
+++ b/net/homa/homa_tx_pool.h
@@ -0,0 +1,139 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This module manages a pool of memory pages used for outgoing sk_buffs. */
+
+#ifndef _HOMA_TX_POOL_H
+#define _HOMA_TX_POOL_H
+
+#include <linux/percpu-defs.h>
+
+/**
+ * define HOMA_TX_PAGE_ORDER - exponent (power of two) determining how
+ * many pages to allocate in a high-order page for skb pages (e.g.,
+ * 2 means allocate in units of 4 pages).
+ */
+#define HOMA_TX_PAGE_ORDER 4
+
+/**
+ * define HOMA_TX_PAGE_SIZE - number of bytes corresponding to HOMA_PAGE_ORDER.
+ */
+#define HOMA_TX_PAGE_SIZE (PAGE_SIZE << HOMA_TX_PAGE_ORDER)
+
+/**
+ * define HOMA_TX_PAGE_SHIFT: HOMA_PAGE_SIZE == 1 << HOMA_TX_PAGE_SHIFT
+ */
+#define HOMA_TX_PAGE_SHIFT (PAGE_SHIFT + HOMA_TX_PAGE_ORDER)
+
+/**
+ * struct homa_tx_pool - A cache of free pages available for use.
+ * Each page is of size HOMA_TX_PAGE_SIZE, and a given pool is dedicated for
+ * use by a single NUMA node.
+ */
+struct homa_tx_pool {
+	/** @mutex: Used to synchronize access to the fields in this struct. */
+	spinlock_t mutex;
+
+	/** @avail: Number of free pages currently in the pool. */
+	int avail;
+
+	/**
+	 * @low_mark: Low water mark: smallest value of avail since the
+	 * last time homa_tx_pool_gc reset it.
+	 */
+	int low_mark;
+
+#define HOMA_TX_POOL_LIMIT 1000
+
+	/**
+	 * @pages: Pointers to pages that are currently free; the ref count
+	 * is 1 in each of these pages.
+	 */
+	struct page *pages[HOMA_TX_POOL_LIMIT];
+};
+
+/**
+ * struct homa_tx_pool_core - Stores core-specific information related to
+ * tx memory allocation. All values are assumed to be zero initially.
+ */
+struct homa_tx_pool_core {
+	/**
+	 * @pool: NUMA-specific page pool from which to allocate skb pages
+	 * for this core.
+	 */
+	struct homa_tx_pool *pool;
+
+	/**
+	 * @page: a page of data that is "owned" by this core and used for
+	 * allocation on this core (or NULL). This pointer is included in
+	 * the page's reference count.
+	 */
+	struct page *page;
+
+	/**
+	 * @page_size: total number of bytes in @page (including any
+	 * already allocated).
+	 */
+	int page_size;
+
+	/**
+	 * @allocated: number of (initial) bytes in @page that have already
+	 * been allocated for use.
+	 */
+	int allocated;
+};
+DECLARE_PER_CPU(struct homa_tx_pool_core, homa_tx_pool_core);
+
+/**
+ * struct homa_frag_filler - Used to iterate over an array of skb_frag_t's
+ * to copy data into them.
+ */
+struct homa_frag_filler {
+	/** @frag: Fragment currently being filled (in an array of frags). */
+	skb_frag_t *frag;
+
+	/**
+	 * @offset: Offset within @frag where the next byte of data should be
+	 * stored.
+	 */
+	int offset;
+
+	/**
+	 * @num_frags: Number of fragments in the array including @frag:
+	 * if this reaches zero then we have run out of space.
+	 */
+	int num_frags;
+};
+
+/**
+ * homa_frag_filler_init() - Initialize a frag filler.
+ * @filler:     Struct to initialize.
+ * @num_frags:  Number of fragments available to fill.
+ * @frags:      First in array of @num_frags fragments.
+ */
+static inline void homa_frag_filler_init(struct homa_frag_filler *filler,
+					 int num_frags, skb_frag_t *frags)
+{
+	filler->frag = frags;
+	filler->offset = 0;
+	filler->num_frags = num_frags;
+}
+
+int          homa_copy_iter_to_frags(struct homa_frag_filler *filler,
+				     struct iov_iter *iter, int num_bytes);
+int          homa_copy_to_frags(struct homa_frag_filler *filler, void *src,
+				int num_bytes);
+int          homa_tx_pool_alloc(struct homa *homa, int length, int *num_frags,
+				skb_frag_t **frags);
+int          __homa_tx_pool_alloc_frag(struct homa_tx_pool_core *tx_core,
+				       int length, skb_frag_t *frag);
+int          homa_tx_pool_alloc_frag(struct homa *homa, int length,
+				     skb_frag_t *frag);
+struct page *homa_tx_pool_alloc_page(struct homa_tx_pool_core *tx_core,
+				     int *length);
+void         homa_tx_pool_cleanup(struct homa *homa);
+void         homa_tx_pool_free(struct homa *homa, int num_frags,
+			       skb_frag_t *frags);
+void         homa_tx_pool_gc(struct homa *homa);
+int          homa_tx_pool_init(struct homa *homa);
+
+#endif /* _HOMA_TX_POOL_H */
diff --git a/net/homa/homa_utils.c b/net/homa/homa_utils.c
new file mode 100644
index 0000000000000..94799976a8ab4
--- /dev/null
+++ b/net/homa/homa_utils.c
@@ -0,0 +1,119 @@
+// SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
+
+/* This file contains miscellaneous utility functions for Homa, such
+ * as initializing and destroying homa structs.
+ */
+
+#include "homa_impl.h"
+#include "homa_peer.h"
+#include "homa_rpc.h"
+#include "homa_tx_pool.h"
+
+/**
+ * homa_init() - Constructor for homa objects.
+ * @homa:   Object to initialize.
+ *
+ * Return:  0 on success, or a negative errno if there was an error.
+ */
+int homa_init(struct homa *homa)
+{
+	int err;
+
+	memset(homa, 0, sizeof(*homa));
+
+	atomic64_set(&homa->next_outgoing_id, 2);
+	homa->link_mbps = 25000;
+	homa->peertab = homa_peer_alloc_peertab();
+	if (IS_ERR(homa->peertab)) {
+		err = PTR_ERR(homa->peertab);
+		homa->peertab = NULL;
+		goto error;
+	}
+	homa->socktab = kmalloc(sizeof(*homa->socktab), GFP_KERNEL);
+	if (!homa->socktab) {
+		err = -ENOMEM;
+		goto error;
+	}
+	homa_socktab_init(homa->socktab);
+	err = homa_tx_pool_init(homa);
+	if (err) {
+		pr_err("Couldn't initialize homa_tx_pool (errno %d)\n",
+		       -err);
+		goto error;
+	}
+
+	/* Wild guesses to initialize configuration values... */
+	homa->resend_ticks = 5;
+	homa->resend_interval = 5;
+	homa->timeout_ticks = 100;
+	homa->timeout_resends = 5;
+	homa->request_ack_ticks = 2;
+	homa->dead_frags_limit = 100;
+	homa->max_gso_size = 1000;
+	homa->wmem_max = 100000000;
+	homa->bpage_lease_usecs = 10000;
+	homa->bpage_lease_cycles = homa->bpage_lease_usecs  * 2500;
+	return 0;
+
+error:
+	homa_destroy(homa);
+	return err;
+}
+
+/**
+ * homa_destroy() -  Destructor for homa objects.
+ * @homa:      Object to destroy. It is safe if this object has already
+ *             been previously destroyed.
+ */
+void homa_destroy(struct homa *homa)
+{
+	/* The order of the following cleanups matters! */
+	if (homa->socktab) {
+		homa_socktab_destroy(homa->socktab, NULL);
+		kfree(homa->socktab);
+		homa->socktab = NULL;
+	}
+	if (homa->peertab) {
+		homa_peer_free_peertab(homa->peertab);
+		homa->peertab = NULL;
+	}
+	homa_tx_pool_cleanup(homa);
+}
+
+/**
+ * homa_net_init() - Initialize a new struct homa_net.
+ * @hnet:    Struct to initialize.
+ * @homa:    The main Homa data structure to use for the net.
+ * Return:  0 on success, otherwise a negative errno.
+ */
+int homa_net_init(struct homa_net *hnet, struct homa *homa)
+{
+	memset(hnet, 0, sizeof(*hnet));
+	hnet->homa = homa;
+	hnet->prev_default_port = HOMA_MIN_DEFAULT_PORT - 1;
+	return 0;
+}
+
+/**
+ * homa_net_destroy() - Release any resources associated with a homa_net.
+ * @hnet:    Object to destroy; must not be used again after this function
+ *           returns.
+ */
+void homa_net_destroy(struct homa_net *hnet)
+{
+	homa_socktab_destroy(hnet->homa->socktab, hnet);
+	homa_peer_free_net(hnet);
+}
+
+/**
+ * homa_spin() - Delay (without sleeping) for a given time interval.
+ * @ns:   How long to delay (in nanoseconds)
+ */
+void homa_spin(int ns)
+{
+	u64 end;
+
+	end = homa_clock() + homa_ns_to_cycles(ns);
+	while (homa_clock() < end)
+		cpu_relax();
+}
diff --git a/net/homa/homa_wire.h b/net/homa/homa_wire.h
new file mode 100644
index 0000000000000..5bc4a25ec9200
--- /dev/null
+++ b/net/homa/homa_wire.h
@@ -0,0 +1,346 @@
+/* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+ */
+
+/* This file defines the on-the-wire format of Homa packets. */
+
+#ifndef _HOMA_WIRE_H
+#define _HOMA_WIRE_H
+
+#include <linux/skbuff.h>
+#include <net/tcp.h>
+
+/* Defines the possible types of Homa packets.
+ *
+ * See the xxx_header structs below for more information about each type.
+ */
+enum homa_packet_type {
+	DATA               = 0x10,
+	RESEND             = 0x12,
+	RPC_UNKNOWN        = 0x13,
+	BUSY               = 0x14,
+	NEED_ACK           = 0x17,
+	ACK                = 0x18,
+	MAX_OP             = 0x18,
+	/* If you add a new type here, you must also do the following:
+	 * 1. Change MAX_OP so it is the highest valid opcode
+	 * 2. Add support for the new opcode in homa_print_packet,
+	 *    homa_print_packet_short, homa_symbol_for_type, and mock_skb_alloc.
+	 * 3. Add the header length to header_lengths in homa_plumbing.c.
+	 */
+};
+
+/**
+ * define HOMA_SKB_EXTRA - How many bytes of additional space to allow at the
+ * beginning of each sk_buff, before the Homa header. This includes room for
+ * either an IPV4 or IPV6 header, Ethernet header, VLAN header, etc. This is
+ * a bit of an overestimate, since it also includes space for a TCP header.
+ */
+#define HOMA_SKB_EXTRA MAX_TCP_HEADER
+
+/**
+ * define HOMA_ETH_FRAME_OVERHEAD - Additional overhead bytes for each
+ * Ethernet packet that are not included in the packet header (preamble,
+ * start frame delimiter, CRC, and inter-packet gap).
+ */
+#define HOMA_ETH_FRAME_OVERHEAD 24
+
+/**
+ * define HOMA_ETH_OVERHEAD - Number of bytes per Ethernet packet for Ethernet
+ * header, CRC, preamble, and inter-packet gap.
+ */
+#define HOMA_ETH_OVERHEAD (18 + HOMA_ETH_FRAME_OVERHEAD)
+
+/**
+ * define HOMA_MIN_PKT_LENGTH - Every Homa packet must be padded to at least
+ * this length to meet Ethernet frame size limitations. This number includes
+ * Homa headers and data, but not IP or Ethernet headers.
+ */
+#define HOMA_MIN_PKT_LENGTH 26
+
+/**
+ * define HOMA_MAX_HEADER - Number of bytes in the largest Homa header.
+ */
+#define HOMA_MAX_HEADER 90
+
+/**
+ * struct homa_common_hdr - Wire format for the first bytes in every Homa
+ * packet. This must (mostly) match the format of a TCP header to enable
+ * Homa packets to actually be transmitted as TCP packets (and thereby
+ * take advantage of TSO and other features).
+ */
+struct homa_common_hdr {
+	/**
+	 * @sport: Port on source machine from which packet was sent.
+	 * Must be in the same position as in a TCP header.
+	 */
+	__be16 sport;
+
+	/**
+	 * @dport: Port on destination that is to receive packet. Must be
+	 * in the same position as in a TCP header.
+	 */
+	__be16 dport;
+
+	/**
+	 * @sequence: corresponds to the sequence number field in TCP headers;
+	 * not used by Homa (may be auto-incremented by TSO).
+	 */
+	__be32 sequence;
+
+	/**
+	 * @ack: Corresponds to the high-order bits of the acknowledgment
+	 * field in TCP headers; not used by Homa.
+	 */
+	char ack[3];
+
+	/**
+	 * @type: Homa packet type (one of the values of the homa_packet_type
+	 * enum). Corresponds to the low-order byte of the ack in TCP.
+	 */
+	u8 type;
+
+	/**
+	 * @doff: High order 4 bits correspond to the Data Offset field of a
+	 * TCP header. In DATA packets they hold the number of 4-byte chunks
+	 * in a homa_data_hdr; used by TSO to determine where the replicated
+	 * header portion ends. For other packets the offset is always 5
+	 * (standard TCP header length); other values may cause some NICs
+	 * (such as Intel E810-C) to drop outgoing data packets when TCP
+	 * hijacking is enabled. The low-order bits are always 0.
+	 */
+	u8 doff;
+
+	/** @reserved1: Not used (corresponds to TCP flags). */
+	u8 reserved1;
+
+	/**
+	 * @window: Corresponds to the window field in TCP headers. Not used
+	 * by HOMA.
+	 */
+	__be16 window;
+
+	/**
+	 * @checksum: occupies the same bytes as the checksum in a TCP
+	 * header. Set by Homa only during TCP hijacking.
+	 */
+	__be16 checksum;
+
+	/** @reserved2: Not used (corresponds to TCP urgent field). */
+	__be16 reserved2;
+
+	/**
+	 * @sender_id: the identifier of this RPC as used on the sender (i.e.,
+	 * if the low-order bit is set, then the sender is the server for
+	 * this RPC).
+	 */
+	__be64 sender_id;
+} __packed;
+
+/**
+ * struct homa_ack - Identifies an RPC that can be safely deleted by its
+ * server. After sending the response for an RPC, the server must retain its
+ * state for the RPC until it knows that the client has successfully
+ * received the entire response. An ack indicates this. Clients will
+ * piggyback acks on future data packets, but if a client doesn't send
+ * any data to the server, the server will eventually request an ack
+ * explicitly with a NEED_ACK packet, in which case the client will
+ * return an explicit ACK.
+ */
+struct homa_ack {
+	/**
+	 * @client_id: The client's identifier for the RPC. 0 means this ack
+	 * is invalid.
+	 */
+	__be64 client_id;
+
+	/** @server_port: The server-side port for the RPC. */
+	__be16 server_port;
+} __packed;
+
+/* struct homa_data_hdr - Contains data for part or all of a Homa message.
+ * An incoming packet consists of a homa_data_hdr followed by message data.
+ * An outgoing packet can have this simple format as well, or it can be
+ * structured as a GSO packet with the following format:
+ *
+ *    |-----------------------|
+ *    |                       |
+ *    |     data_header       |
+ *    |                       |
+ *    |---------------------- |
+ *    |                       |
+ *    |                       |
+ *    |     segment data      |
+ *    |                       |
+ *    |                       |
+ *    |-----------------------|
+ *    |      seg_header       |
+ *    |-----------------------|
+ *    |                       |
+ *    |                       |
+ *    |     segment data      |
+ *    |                       |
+ *    |                       |
+ *    |-----------------------|
+ *    |      seg_header       |
+ *    |-----------------------|
+ *    |                       |
+ *    |                       |
+ *    |     segment data      |
+ *    |                       |
+ *    |                       |
+ *    |-----------------------|
+ *
+ * TSO may not adjust @homa_common_hdr.sequence in the segments, so Homa
+ * sprinkles correct offsets (in homa_seg_hdrs) throughout the segment data;
+ * TSO/GSO will include a different homa_seg_hdr in each generated packet.
+ */
+
+struct homa_seg_hdr {
+	/**
+	 * @offset: Offset within message of the first byte of data in
+	 * this segment.
+	 */
+	__be32 offset;
+} __packed;
+
+struct homa_data_hdr {
+	struct homa_common_hdr common;
+
+	/** @message_length: Total #bytes in the message. */
+	__be32 message_length;
+
+	__be32 reserved1;
+
+	/** @ack: If the @client_id field of this is nonzero, provides info
+	 * about an RPC that the recipient can now safely free. Note: in
+	 * TSO packets this will get duplicated in each of the segments;
+	 * in order to avoid repeated attempts to ack the same RPC,
+	 * homa_gro_receive will clear this field in all segments but the
+	 * first.
+	 */
+	struct homa_ack ack;
+
+	__be16 reserved2;
+
+	/**
+	 * @retransmit: 1 means this packet was sent in response to a RESEND
+	 * (it has already been sent previously).
+	 */
+	u8 retransmit;
+
+	char pad[3];
+
+	/** @seg: First of possibly many segments. */
+	struct homa_seg_hdr seg;
+} __packed;
+
+/**
+ * homa_data_len() - Returns the total number of bytes in a DATA packet
+ * after the homa_data_hdr. Note: if the packet is a GSO packet, the result
+ * may include metadata as well as packet data.
+ * @skb:   Incoming data packet
+ * Return: see above
+ */
+static inline u32 homa_data_len(struct sk_buff *skb)
+{
+	return skb->len - skb_transport_offset(skb) -
+			sizeof(struct homa_data_hdr);
+}
+
+/**
+ * struct homa_resend_hdr - Wire format for RESEND packets.
+ *
+ * A RESEND is sent by the receiver when it believes that message data may
+ * have been lost in transmission (or if it is concerned that the sender may
+ * have crashed). The receiver should resend the specified portion of the
+ * message, even if it already sent it previously.
+ */
+struct homa_resend_hdr {
+	/** @common: Fields common to all packet types. */
+	struct homa_common_hdr common;
+
+	/**
+	 * @offset: Offset within the message of the first byte of data that
+	 * should be retransmitted.
+	 */
+	__be32 offset;
+
+	/**
+	 * @length: Number of bytes of data to retransmit. -1 means no data
+	 * has been received for the message, so everything sent previously
+	 * should be retransmitted.
+	 */
+	__be32 length;
+
+} __packed;
+
+/**
+ * struct homa_rpc_unknown_hdr - Wire format for RPC_UNKNOWN packets.
+ *
+ * An RPC_UNKNOWN packet is sent by either server or client when it receives a
+ * packet for an RPC that is unknown to it. When a client receives an
+ * RPC_UNKNOWN packet it will typically restart the RPC from the beginning;
+ * when a server receives an RPC_UNKNOWN packet it will typically discard its
+ * state for the RPC.
+ */
+struct homa_rpc_unknown_hdr {
+	/** @common: Fields common to all packet types. */
+	struct homa_common_hdr common;
+} __packed;
+
+/**
+ * struct homa_busy_hdr - Wire format for BUSY packets.
+ *
+ * These packets tell the recipient that the sender is still alive (even if
+ * it isn't sending data expected by the recipient).
+ */
+struct homa_busy_hdr {
+	/** @common: Fields common to all packet types. */
+	struct homa_common_hdr common;
+} __packed;
+
+/**
+ * struct homa_need_ack_hdr - Wire format for NEED_ACK packets.
+ *
+ * These packets ask the recipient (a client) to return an ACK message if
+ * the packet's RPC is no longer active.
+ */
+struct homa_need_ack_hdr {
+	/** @common: Fields common to all packet types. */
+	struct homa_common_hdr common;
+} __packed;
+
+/**
+ * struct homa_ack_hdr - Wire format for ACK packets.
+ *
+ * These packets are sent from a client to a server to indicate that
+ * a set of RPCs is no longer active on the client, so the server can
+ * free any state it may have for them.
+ */
+struct homa_ack_hdr {
+	/** @common: Fields common to all packet types. */
+	struct homa_common_hdr common;
+
+	/** @num_acks: Number of (leading) elements in @acks that are valid. */
+	__be16 num_acks;
+
+#define HOMA_MAX_ACKS_PER_PKT 5
+	/** @acks: Info about RPCs that are no longer active. */
+	struct homa_ack acks[HOMA_MAX_ACKS_PER_PKT];
+} __packed;
+
+/**
+ * homa_local_id(): given an RPC identifier from an input packet (which
+ * is network-encoded), return the decoded id we should use for that
+ * RPC on this machine.
+ * @sender_id:  RPC id from an incoming packet, such as h->common.sender_id
+ * Return: see above
+ */
+static inline u64 homa_local_id(__be64 sender_id)
+{
+	/* If the client bit was set on the sender side, it needs to be
+	 * removed here, and conversely.
+	 */
+	return be64_to_cpu(sender_id) ^ 1;
+}
+
+#endif /* _HOMA_WIRE_H */

9/3 2026/09/15 00:56 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 113255
							output: 19
							thoughts: 3498
						

Thoughts:
**KMSAN Evaluation for HOMA Protocol Patch Series**

Okay, let's break this down. My goal is to determine if this new HOMA transport protocol patch series necessitates a dedicated KMSAN fuzzing session. Following the established guidelines, I need to identify any potential risks of uninitialized memory usage, especially those related to data structures being copied to user space or used in conditional logic. The primary concern is information leaks. Standard detectors like KASAN and LOCKDEP handle the usual suspects: out-of-bounds accesses, use-after-free, etc.

First, let's inventory the changes: this introduces HOMA, so it is a significant addition. I see a lot of new files, including headers, source, documentation, and the Kconfig files. This indicates a potentially large surface area for uninitialized memory issues. My instinct is telling me to go through the most likely areas one by one.

The initial scan suggests `homa_ioc_info` looks interesting due to the interaction with user space via `copy_to_user` and `copy_from_user`. I've identified the use of a struct `homa_info` being copied both to and from user space, and within that structure the `homa_rpc_info` structure is also being copied to user space.  I have to be extremely meticulous here.

I noticed a potential issue with `homa_info.error_msg`.  Initially, I thought this could be a source of uninitialized memory, but then I remembered that the `homa_info` structure itself is populated via `copy_from_user`. This means whatever is in user space will be copied to the kernel. `snprintf` is used, but even though it does not zero the remainder of the buffer, if copied from user, that isn't a vulnerability.

I have to carefully analyze padding, because, after all, there *is* padding within the `homa_rpc_info` structure.  The `homa_rpc_get_info` function looks promising, as it zeroes the `info` parameter before filling it with data, meaning that even though there's padding in the struct, it should be zeroed out. This is good.

I need to meticulously check all instances of data transfers to user space. `homa_recvmsg` is another area of concern. Specifically, I'm analyzing the `msg_control` buffer and the data within it. It uses `copy_from_user` to initialize a `control` struct. I am carefully analyzing the control flow.  I need to check that even when errors occur, the data structures are properly initialized or handled before being sent back to user space.  A key point is that `control` is copied from user, so that's okay.  I *must* be careful about the `msg_name` field of `recvmsg`! `msg_name` may be a kernel stack buffer, so what data is being copied there? Is it being initialized? I am going to have to do a deep dive here using grepping and static analysis to fully evaluate the use of `msg_name` within the `homa_recvmsg` function. It seems to be copied into the `sockaddr` struct, and so I *must* ensure that the data is initialized correctly.



10/3 2026/09/15 00:57 tool grepper
0m Args:
{
  "Expression": "___sys_recvmsg"
}

Results:
{
  "Output": "net/socket.c=2886=static int recvmsg_copy_msghdr(struct msghdr *msg,\n--\nnet/socket.c-2906-\nnet/socket.c:2907:static int ____sys_recvmsg(struct socket *sock, struct msghdr *msg_sys,\nnet/socket.c-2908-\t\t\t   struct user_msghdr __user *msg,\n--\nnet/socket.c-2962-\nnet/socket.c:2963:static int ___sys_recvmsg(struct socket *sock, struct user_msghdr __user *msg,\nnet/socket.c-2964-\t\t\t struct msghdr *msg_sys, unsigned int flags, int nosec)\n--\nnet/socket.c-2974-\nnet/socket.c:2975:\terr = ____sys_recvmsg(sock, msg_sys, msg, uaddr, flags, nosec);\nnet/socket.c-2976-\tkfree(iov);\n--\nnet/socket.c=2984=long __sys_recvmsg_sock(struct socket *sock, struct msghdr *msg,\n--\nnet/socket.c-2987-{\nnet/socket.c:2988:\treturn ____sys_recvmsg(sock, msg, umsg, uaddr, flags, 0);\nnet/socket.c-2989-}\n--\nnet/socket.c=2991=long __sys_recvmsg(int fd, struct user_msghdr __user *msg, unsigned int flags,\n--\nnet/socket.c-3007-\nnet/socket.c:3008:\treturn ___sys_recvmsg(sock, msg, \u0026msg_sys, flags, 0);\nnet/socket.c-3009-}\n--\nnet/socket.c=3021=static int do_recvmmsg(int fd, struct mmsghdr __user *mmsg,\n--\nnet/socket.c-3061-\t\tif (MSG_CMSG_COMPAT \u0026 flags) {\nnet/socket.c:3062:\t\t\terr = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry,\nnet/socket.c-3063-\t\t\t\t\t     \u0026msg_sys, flags \u0026 ~MSG_WAITFORONE,\n--\nnet/socket.c-3069-\t\t} else {\nnet/socket.c:3070:\t\t\terr = ___sys_recvmsg(sock,\nnet/socket.c-3071-\t\t\t\t\t     (struct user_msghdr __user *)entry,\n"
}

11/3 2026/09/15 00:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 118125
							output: 34
							thoughts: 41
						

Thoughts:
Here's my summary, as if I were thinking these thoughts:

**Dissecting recvmsg in net/socket.c**

Alright, let's dive into the guts of `net/socket.c`. I'm particularly interested in how `msg_name` and `uaddr` get processed within `____sys_recvmsg`. I'll zero in around line 2907; that's usually where the meat of the argument handling for that system call tends to be. I need to refresh my memory on the interactions of those two fields and how they work in the kernel. Let's see how the address information is copied, validated and handled. Hopefully, by understanding this, I can learn how to fix the issue I'm dealing with.



12/3 2026/09/15 00:57 tool read-file
0m Args:
{
  "File": "net/socket.c",
  "FirstLine": 2907,
  "LineCount": 50
}

Results:
{
  "Contents": "2907:\tstatic int ____sys_recvmsg(struct socket *sock, struct msghdr *msg_sys,\n2908:\t\t\t\t   struct user_msghdr __user *msg,\n2909:\t\t\t\t   struct sockaddr __user *uaddr,\n2910:\t\t\t\t   unsigned int flags, int nosec)\n2911:\t{\n2912:\t\tstruct compat_msghdr __user *msg_compat =\n2913:\t\t\t\t\t\t(struct compat_msghdr __user *) msg;\n2914:\t\tint __user *uaddr_len = COMPAT_NAMELEN(msg);\n2915:\t\tstruct sockaddr_storage addr;\n2916:\t\tunsigned long cmsg_ptr;\n2917:\t\tint len;\n2918:\t\tssize_t err;\n2919:\t\n2920:\t\tmsg_sys-\u003emsg_name = \u0026addr;\n2921:\t\tcmsg_ptr = (unsigned long)msg_sys-\u003emsg_control;\n2922:\t\tmsg_sys-\u003emsg_flags = flags \u0026 (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT);\n2923:\t\n2924:\t\t/* We assume all kernel code knows the size of sockaddr_storage */\n2925:\t\tmsg_sys-\u003emsg_namelen = 0;\n2926:\t\n2927:\t\tif (sock-\u003efile-\u003ef_flags \u0026 O_NONBLOCK)\n2928:\t\t\tflags |= MSG_DONTWAIT;\n2929:\t\n2930:\t\tif (unlikely(nosec))\n2931:\t\t\terr = sock_recvmsg_nosec(sock, msg_sys, flags);\n2932:\t\telse\n2933:\t\t\terr = sock_recvmsg(sock, msg_sys, flags);\n2934:\t\n2935:\t\tif (err \u003c 0)\n2936:\t\t\tgoto out;\n2937:\t\tlen = err;\n2938:\t\n2939:\t\tif (uaddr != NULL) {\n2940:\t\t\terr = move_addr_to_user(\u0026addr,\n2941:\t\t\t\t\t\tmsg_sys-\u003emsg_namelen, uaddr,\n2942:\t\t\t\t\t\tuaddr_len);\n2943:\t\t\tif (err \u003c 0)\n2944:\t\t\t\tgoto out;\n2945:\t\t}\n2946:\t\terr = __put_user((msg_sys-\u003emsg_flags \u0026 ~MSG_CMSG_COMPAT),\n2947:\t\t\t\t COMPAT_FLAGS(msg));\n2948:\t\tif (err)\n2949:\t\t\tgoto out;\n2950:\t\tif (MSG_CMSG_COMPAT \u0026 flags)\n2951:\t\t\terr = __put_user((unsigned long)msg_sys-\u003emsg_control - cmsg_ptr,\n2952:\t\t\t\t\t \u0026msg_compat-\u003emsg_controllen);\n2953:\t\telse\n2954:\t\t\terr = __put_user((unsigned long)msg_sys-\u003emsg_control - cmsg_ptr,\n2955:\t\t\t\t\t \u0026msg-\u003emsg_controllen);\n2956:\t\tif (err)\n"
}

13/3 2026/09/15 00:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 119170
							output: 29
							thoughts: 1270
						

Thoughts:
**Vulnerability Discovery: Uninitialized Memory Leak in Homa's `recvmsg` Implementation**

Okay, let's break this down. I've been digging into the `recvmsg` implementation, specifically within the Homa protocol. My initial suspicion was aroused by how `struct sockaddr_storage addr;` is declared on the stack in `____sys_recvmsg` *without* zeroing it out. That immediately screams potential for information leakage.

Now, the code path is: `____sys_recvmsg` -> `sock_recvmsg` -> `homa_recvmsg`. Inside `homa_recvmsg` (in `net/homa/homa_plumbing.c`), if `msg->msg_name` is set, which it is in this instance, it proceeds to populate either a `struct sockaddr_in6` or `struct sockaddr_in` depending on the socket family.

Looking closely at the `struct sockaddr_in6` initialization, only `sin6_family`, `sin6_port`, and `sin6_addr` are set. **Critically, `sin6_flowinfo` and `sin6_scope_id` are *not* initialized**. The code then sets `msg->msg_namelen` to `sizeof(*in6)`, which is 28 bytes. The vulnerable line `move_addr_to_user(&addr, msg_sys->msg_namelen, uaddr, uaddr_len)` then copies those 28 bytes from the uninitialized stack variable `addr` into userspace. This means that 8 bytes of uninitialized stack data, corresponding to `sin6_flowinfo` and `sin6_scope_id`, are leaked to user space!

The situation is similar with `struct sockaddr_in`. `sin_family`, `sin_port`, and `sin_addr` are initialized, but `in4->sin_zero` or the `__pad` is *not* zeroed. The code sets `msg->msg_namelen` to 16, which is `sizeof(struct sockaddr_in)`.  This also causes another 8 bytes of uninitialized stack memory to be leaked to userspace!

This is a clear vulnerability; we're essentially leaking arbitrary stack data to user space in both IPv6 and IPv4 cases! I am now grepping for similar vulnerabilities. This is an egregious oversight, especially considering the sensitivity of this data.



14/3 2026/09/15 00:57 tool grepper
0m Args:
{
  "Expression": "DECLARE_SOCKADDR.*sin6",
  "PathPrefix": "net/"
}

Results:
{
  "Output": "net/ipv4/ping.c=842=int ping_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags)\n--\nnet/ipv4/ping.c-893-\t\tstruct ipv6hdr *ip6 = ipv6_hdr(skb);\nnet/ipv4/ping.c:894:\t\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg-\u003emsg_name);\nnet/ipv4/ping.c-895-\n--\nnet/ipv6/datagram.c=286=int ip6_datagram_connect_v6_only(struct sock *sk, struct sockaddr_unsized *uaddr,\n--\nnet/ipv6/datagram.c-288-{\nnet/ipv6/datagram.c:289:\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, uaddr);\nnet/ipv6/datagram.c-290-\tif (sin6-\u003esin6_family != AF_INET6)\n--\nnet/ipv6/raw.c=435=static int rawv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,\n--\nnet/ipv6/raw.c-438-\tstruct ipv6_pinfo *np = inet6_sk(sk);\nnet/ipv6/raw.c:439:\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg-\u003emsg_name);\nnet/ipv6/raw.c-440-\tstruct sk_buff *skb;\n--\nnet/ipv6/raw.c=742=static int rawv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)\n--\nnet/ipv6/raw.c-745-\tstruct ipv6_txoptions opt_space;\nnet/ipv6/raw.c:746:\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg-\u003emsg_name);\nnet/ipv6/raw.c-747-\tstruct in6_addr *daddr, *final_p, final;\n--\nnet/ipv6/udp.c=464=int udpv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,\n--\nnet/ipv6/udp.c-531-\tif (msg-\u003emsg_name) {\nnet/ipv6/udp.c:532:\t\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg-\u003emsg_name);\nnet/ipv6/udp.c-533-\t\tsin6-\u003esin6_family = AF_INET6;\n--\nnet/ipv6/udp.c=1466=int udpv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)\n--\nnet/ipv6/udp.c-1468-\tint corkreq = udp_test_bit(CORK, sk) || msg-\u003emsg_flags \u0026 MSG_MORE;\nnet/ipv6/udp.c:1469:\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg-\u003emsg_name);\nnet/ipv6/udp.c-1470-\tstruct ipv6_txoptions *opt_to_free = NULL;\n--\nnet/rds/recv.c=689=int rds_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,\n--\nnet/rds/recv.c-695-\tint ret = 0, nonblock = msg_flags \u0026 MSG_DONTWAIT;\nnet/rds/recv.c:696:\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg-\u003emsg_name);\nnet/rds/recv.c-697-\tDECLARE_SOCKADDR(struct sockaddr_in *, sin, msg-\u003emsg_name);\n--\nnet/rds/send.c=1154=int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n--\nnet/rds/send.c-1157-\tstruct rds_sock *rs = rds_sk_to_rs(sk);\nnet/rds/send.c:1158:\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg-\u003emsg_name);\nnet/rds/send.c-1159-\tDECLARE_SOCKADDR(struct sockaddr_in *, usin, msg-\u003emsg_name);\n"
}

15/3 2026/09/15 00:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 122085
							output: 36
							thoughts: 30
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:

**Diving into the Network Socket Details**

Alright, so the question is how the kernel handles the `msg->msg_name` field during receive operations with `UDPv6` or `RDS` sockets, specifically in the context of `udpv6_recvmsg` and `rds_recvmsg`. I'm immediately thinking, "Let's dig into the source code for those functions." I need to understand the exact mechanics. What does the kernel *do* with that `msg_name` pointer when it's handling an incoming datagram or message? Is it always populated? Is it optional? Does it depend on the socket's configuration (bound vs. unbound, connected vs. unconnected)? My focus is on the nuances: what are the potential edge cases and how do the different transport protocols – namely, `UDPv6` and `RDS` – manage the destination address information? This feels like an interesting point to explore in a deeper dive.



16/3 2026/09/15 00:57 tool read-file
0m Args:
{
  "File": "net/ipv6/udp.c",
  "FirstLine": 530,
  "LineCount": 20
}

Results:
{
  "Contents": " 530:\t\t/* Copy the address. */\n 531:\t\tif (msg-\u003emsg_name) {\n 532:\t\t\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg-\u003emsg_name);\n 533:\t\t\tsin6-\u003esin6_family = AF_INET6;\n 534:\t\t\tsin6-\u003esin6_port = udp_hdr(skb)-\u003esource;\n 535:\t\t\tsin6-\u003esin6_flowinfo = 0;\n 536:\t\n 537:\t\t\tif (is_udp4) {\n 538:\t\t\t\tipv6_addr_set_v4mapped(ip_hdr(skb)-\u003esaddr,\n 539:\t\t\t\t\t\t       \u0026sin6-\u003esin6_addr);\n 540:\t\t\t\tsin6-\u003esin6_scope_id = 0;\n 541:\t\t\t} else {\n 542:\t\t\t\tsin6-\u003esin6_addr = ipv6_hdr(skb)-\u003esaddr;\n 543:\t\t\t\tsin6-\u003esin6_scope_id =\n 544:\t\t\t\t\tipv6_iface_scope_id(\u0026sin6-\u003esin6_addr,\n 545:\t\t\t\t\t\t\t    inet6_iif(skb));\n 546:\t\t\t}\n 547:\t\t\tmsg-\u003emsg_namelen = sizeof(*sin6);\n 548:\t\n 549:\t\t\tBPF_CGROUP_RUN_PROG_UDP6_RECVMSG_LOCK(sk,\n"
}

17/3 2026/09/15 00:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 122755
							output: 35
							thoughts: 52
						

Thoughts:
Okay, here's my take on those code snippets, thinking through the implications as I would in my own work:

**Quick Initial Assessment: UDPv6 and RDS Receive Paths**

Alright, I'm focusing in on the receive paths here, specifically looking at how IPv6 and RDS (Reliable Datagram Sockets) handle incoming messages. My immediate thought is, "What are the commonalities, and where are the potential differences?".

First, I'm zeroing in on `udpv6_recvmsg`. That `sin6->sin6_flowinfo = 0;` line is interesting. That's setting the flow information field to zero in the IPv6 socket address structure. This is pretty standard practice for incoming packets in many network stacks. It essentially tells the system that we don't care about the flow label for this specific incoming message – the system will handle any flow control as it sees fit based on other parameters.

Next, the code is assigning a value to `sin6->sin6_scope_id`. This is crucial for IPv6, especially on link-local addresses, and when dealing with multiple network interfaces. The scope ID correctly identifies the network interface the packet arrived on and to which it should be routed. That's a fundamental part of IPv6 address management, and it needs to be right.

Now, I'm pivoting to `rds_recvmsg`. My mind is racing to compare the two. I want to see how RDS, with its more reliable datagram characteristics, manages the same socket information. Does it need to set any similar fields? Are there any optimizations specific to RDS in terms of the received data, checksums, or acknowledgements? I need to check how it deals with the same socket address information, potentially to ensure proper delivery within a reliable transport context. Comparing these two receiver paths will give me a better understanding of their underlying architectures and implementation details. I need to understand if the packet handling logic is identical or radically different.



18/3 2026/09/15 00:57 tool read-file
0m Args:
{
  "File": "net/rds/recv.c",
  "FirstLine": 775,
  "LineCount": 25
}

Results:
{
  "Contents": " 775:\t\t\trds_recvmsg_zcookie(rs, msg);\n 776:\t\n 777:\t\t\trds_stats_inc(s_recv_delivered);\n 778:\t\n 779:\t\t\tif (msg-\u003emsg_name) {\n 780:\t\t\t\tif (ipv6_addr_v4mapped(\u0026inc-\u003ei_saddr)) {\n 781:\t\t\t\t\tsin-\u003esin_family = AF_INET;\n 782:\t\t\t\t\tsin-\u003esin_port = inc-\u003ei_hdr.h_sport;\n 783:\t\t\t\t\tsin-\u003esin_addr.s_addr =\n 784:\t\t\t\t\t    inc-\u003ei_saddr.s6_addr32[3];\n 785:\t\t\t\t\tmemset(sin-\u003esin_zero, 0, sizeof(sin-\u003esin_zero));\n 786:\t\t\t\t\tmsg-\u003emsg_namelen = sizeof(*sin);\n 787:\t\t\t\t} else {\n 788:\t\t\t\t\tsin6-\u003esin6_family = AF_INET6;\n 789:\t\t\t\t\tsin6-\u003esin6_port = inc-\u003ei_hdr.h_sport;\n 790:\t\t\t\t\tsin6-\u003esin6_addr = inc-\u003ei_saddr;\n 791:\t\t\t\t\tsin6-\u003esin6_flowinfo = 0;\n 792:\t\t\t\t\tsin6-\u003esin6_scope_id = rs-\u003ers_bound_scope_id;\n 793:\t\t\t\t\tmsg-\u003emsg_namelen = sizeof(*sin6);\n 794:\t\t\t\t}\n 795:\t\t\t}\n 796:\t\t\tbreak;\n 797:\t\t}\n 798:\t\n 799:\t\tif (inc)\n"
}

19/3 2026/09/15 00:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 123680
							output: 21
							thoughts: 6583
						

Thoughts:
**Uninitialized Kernel Memory Leak in Homa's `recvmsg` Implementation**

Okay, after carefully examining the Homa code, I've identified a critical information leak vulnerability within the `homa_recvmsg` function. It stems from how socket addresses are handled and passed to user space.

Specifically, when a user process calls `recvmsg` and requests the source address information, the kernel allocates a `struct sockaddr_storage addr` on the stack. This `addr` variable is then used to populate the `msg->msg_name` field.  The problem arises in `homa_recvmsg` when the code populates this structure for `AF_INET` or `AF_INET6` families.

For `AF_INET`, the code correctly sets the `sin_family`, `sin_port`, and `sin_addr` fields of the `struct sockaddr_in` pointed to by `msg->msg_name`.  However, it **leaves the 8 bytes of `sin_zero` UNINITIALIZED**.

Similarly, for `AF_INET6`, the code sets `sin6_family`, `sin6_port`, and `sin6_addr`, but **leaves `sin6_flowinfo` and `sin6_scope_id` (4 bytes each) UNINITIALIZED**.

Crucially, the `____sys_recvmsg` function then copies *all* the bytes of the `addr` structure, including the uninitialized padding or unused fields, to user space using `move_addr_to_user()`. This is a direct leak of uninitialized kernel stack memory to a user-space process.  KMSAN will detect this.

I've checked other related areas, such as `homa_sendmsg`, `homa_gap_alloc`, `homa_tx_skb_alloc`, `homa_xmit_control`, `homa_request_retrans`, `homa_timer_check_rpc`, `homa_busy_hdr`, `homa_setsockopt`, `homa_getsockopt`, and others. In most cases, memory is properly initialized using `memset`, `kzalloc`, or by explicitly assigning values to all relevant fields.

Also, the `homa_recvmsg` function is further vulnerable. The `control.bpage_offsets` array in `homa_recvmsg`, which is copied to user space, is only populated for the actually allocated `bpages` for the RPC. The remaining entries of the array are left to whatever value was allocated. However, since the RPC struct is kzalloc'd, those values are 0.

However, `sin_zero` in AF_INET and `sin6_flowinfo` and `sin6_scope_id` in AF_INET6 are **NOT** being explicitly initialized.

Therefore, this uninitialized memory in the `msg->msg_name` field during `recvmsg` meets the criteria for a KMSAN fix.  Specifically, it satisfies the "Kernel structures sent to user space...where fields or structure padding might not be fully initialized/zeroed" condition.



20/3 2026/09/15 00:57 tool grepper
0m Args:
{
  "Expression": "#define DECLARE_SOCKADDR"
}

Results:
{
  "Output": "include/linux/net.h=204=struct proto_ops {\n--\ninclude/linux/net.h-274-\ninclude/linux/net.h:275:#define DECLARE_SOCKADDR(type, dst, src)\t\\\ninclude/linux/net.h-276-\ttype dst = ({ __sockaddr_check_size(sizeof(*dst)); (type) src; })\n"
}

21/3 2026/09/15 00:57 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 131056
							output: 461
							thoughts: 1170
						

Thoughts:
**KMSAN to the Rescue: An Uninitialized Stack Memory Leak in `homa_recvmsg()`**

Alright, let's break this down. The core issue immediately jumps out: a classic uninitialized memory problem in the `homa_recvmsg()` function. Specifically, it centers around the handling of the `msg->msg_name` field during `recvmsg()` operations.

It appears that `____sys_recvmsg()`, the kernel syscall entry, allocates a `struct sockaddr_storage addr` on the stack. The critical point is that this memory is uninitialized. The pointer to this uninitialized memory is then passed down the call chain.

Now, within `homa_recvmsg()`, the code sets up parts of either a `struct sockaddr_in` (for AF_INET) or a `struct sockaddr_in6` (for AF_INET6) within this `addr` storage. Importantly, not all of the `struct` is initialized. If `AF_INET` is used, the 8 trailing bytes in `sin_zero` are uninitialized; for `AF_INET6`, there are eight bytes `sin6_flowinfo` and `sin6_scope_id` that are left untouched. The length of the address (`msg->msg_namelen`) is subsequently set to include these uninitialized bytes.

The problem escalates in `____sys_recvmsg()` when the `move_addr_to_user()` function is invoked. This function, in effect, performs a `copy_to_user()` operation, transferring the contents of the `&addr` structure directly to userspace. Because parts of the `addr` structure are uninitialized, those uninitialized bytes are now being leaked to userspace.

The immediate consequence? A KMSAN report like "kernel-infoleak in move_addr_to_user" or "copy_to_user" due to the uninitialized stack data leaking to userspace.

Now, why does this warrant specific KMSAN attention? Because neither KASAN, LOCKDEP, nor UB-sanitizers will catch it. KASAN is designed to detect memory errors such as out-of-bounds access or use-after-free conditions. However, the `addr` variable is valid memory within the bounds of the stack frame. LOCKDEP is concerned with lock ordering issues. UB-sanitizers do not detect issues around the reading of uninitialized variables.

Only KMSAN is equipped to detect this. KMSAN's job is to track uninitialized memory and raise a flag when uninitialized kernel data is copied to user space. KMSAN's shadowing mechanism and origin tracking is the only tool that can find this bug, making `NeedsKMSAN=true`.

This bug, in a nutshell, is the perfect example of how kernel-to-user information leaks can occur due to subtle uninitialized memory issues, and why careful attention to memory initialization, especially when dealing with user-space interactions, is critical in kernel development.



22/3 2026/09/15 00:59 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch introduces the Homa transport protocol implementation, which includes a kernel-to-user memory information leak in `homa_recvmsg()`:\n\n1. In `homa_recvmsg()` (`net/homa/homa_plumbing.c`), when `msg-\u003emsg_name` is provided (which points to an uninitialized `struct sockaddr_storage addr` on the kernel stack in `____sys_recvmsg()` in `net/socket.c`):\n   - For `AF_INET` sockets, only `sin_family`, `sin_port`, and `sin_addr.s_addr` are populated in `struct sockaddr_in *in4`. The trailing 8-byte `sin_zero` padding array is left uninitialized, and `msg-\u003emsg_namelen` is set to `sizeof(*in4)` (16 bytes).\n   - For `AF_INET6` sockets, only `sin6_family`, `sin6_port`, and `sin6_addr` are set in `struct sockaddr_in6 *in6`. The `sin6_flowinfo` (4 bytes) and `sin6_scope_id` (4 bytes) fields are left uninitialized, and `msg-\u003emsg_namelen` is set to `sizeof(*in6)` (28 bytes).\n2. Upon return from `homa_recvmsg()`, `____sys_recvmsg()` invokes `move_addr_to_user(\u0026addr, msg_sys-\u003emsg_namelen, uaddr, uaddr_len)`, which copies the uninitialized kernel stack bytes from `addr` directly to userspace memory.\n\nKASAN, LOCKDEP, and UB sanitizers cannot detect this vulnerability because `addr` resides within the valid bounds of the caller's kernel stack frame and no out-of-bounds or use-after-free memory access occurs. KMSAN specifically tracks shadow initialization bits and detects kernel-to-user information leaks of uninitialized memory. Therefore, a dedicated KMSAN fuzzing session is justified.",
  "NeedsKMSAN": true
}

Results:
{
  "KMSANReasoning": "The patch introduces the Homa transport protocol implementation, which includes a kernel-to-user memory information leak in `homa_recvmsg()`:\n\n1. In `homa_recvmsg()` (`net/homa/homa_plumbing.c`), when `msg-\u003emsg_name` is provided (which points to an uninitialized `struct sockaddr_storage addr` on the kernel stack in `____sys_recvmsg()` in `net/socket.c`):\n   - For `AF_INET` sockets, only `sin_family`, `sin_port`, and `sin_addr.s_addr` are populated in `struct sockaddr_in *in4`. The trailing 8-byte `sin_zero` padding array is left uninitialized, and `msg-\u003emsg_namelen` is set to `sizeof(*in4)` (16 bytes).\n   - For `AF_INET6` sockets, only `sin6_family`, `sin6_port`, and `sin6_addr` are set in `struct sockaddr_in6 *in6`. The `sin6_flowinfo` (4 bytes) and `sin6_scope_id` (4 bytes) fields are left uninitialized, and `msg-\u003emsg_namelen` is set to `sizeof(*in6)` (28 bytes).\n2. Upon return from `homa_recvmsg()`, `____sys_recvmsg()` invokes `move_addr_to_user(\u0026addr, msg_sys-\u003emsg_namelen, uaddr, uaddr_len)`, which copies the uninitialized kernel stack bytes from `addr` directly to userspace memory.\n\nKASAN, LOCKDEP, and UB sanitizers cannot detect this vulnerability because `addr` resides within the valid bounds of the caller's kernel stack frame and no out-of-bounds or use-after-free memory access occurs. KMSAN specifically tracks shadow initialization bits and detects kernel-to-user information leaks of uninitialized memory. Therefore, a dedicated KMSAN fuzzing session is justified.",
  "NeedsKMSAN": true
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)