Skip to contentSkip to conversation

Begin upstreaming Homa transport protocol

PATCH Superseded John Ousterhout 3 participants 36 messages Mar 16 – Apr 7

Subsystems (2)

v17 of 19 Superseded Latest is v19 →

lore
Share & tools
lore
#0 lore raw

v17 cover Begin upstreaming Homa transport protocol

This patch series begins the process of upstreaming the Homa transport protocol. Homa is an alternative to TCP for use in datacenter environments. It provides 10-100x reductions in tail latency for short messages relative to TCP. Its benefits are greatest for mixed workloads containing both short and long messages running under high network loads. Homa is not API-compatible with TCP: it is connectionless and message- oriented (but still reliable and flow-controlled). Homa's new API not only contributes to its performance gains, but it also eliminates the massive amount of connection state required by TCP for highly connected datacenter workloads (Homa uses ~ 1 socket per application, whereas TCP requires a separate socket for each peer).

For more details on Homa, please consult the Homa Wiki:
https://homa-transport.atlassian.net/wiki/spaces/HOMA/overview
The Wiki has pointers to two papers on Homa (one of which describes this implementation) as well as man pages describing the application API and other information.

There is also a GitHub repo for Homa:
https://github.com/PlatformLab/HomaModule
The GitHub repo contains a superset of this patch set, including:
* Additional source code that will eventually be upstreamed
* Extensive unit tests (which will also be upstreamed eventually)
* Application-level library functions (which need to go in glibc?)
* Man pages (which need to be upstreamed as well)
* Benchmarking and instrumentation code

For this patch series, Homa has been stripped down to the bare minimum functionality capable of actually executing remote procedure calls. (about 8000 lines of source code, compared to 20000 lines in the complete Homa). The remaining code will be upstreamed in smaller batches once this patch series has been accepted. Note: the code in this patch series is functional but its performance is not very interesting (about the same as TCP).

The patch series is arranged to introduce the major functional components of Homa. Until the last patch has been applied, the code is inert (it will not be compiled).

Note: this implementation of Homa supports both IPv4 and IPv6.

Changes for v17:
* This revision contains only minor changes to reflect changes elsewhere in the kernel, such as the addition of kmalloc_obj and struct sockaddr_unsized.

Major changes for v16 (see individual patches for additional details):
* Remove homa_pacer.c
* Refactor homa_peer.c to simplify and clean up reference counting
* Implement HOMAIOCINFO ioctl.
* Use refcount_t instead of atomic_t for reference counts
* Use consume_skb and kfree_skb_reason instead of kfree_skb
* Use set_bit, clear_bit, etc. for flag bits

Changes for v15:
* This series is a resubmit of the v14 series to repair broken Author email addresses in the commits. There are no other changes.

Changes for v14:
* There were no comments on the v13 patch series.
* Fix a couple of bugs and clean up a few APIs (see individual patches for details).

Changes for v13:
* Modify all files to include GPL-2.0+ as an option in the SPDX license line
* Fix a couple of bugs in homa_outgoing.c and one bug in homa_plumbing.c

Major changes for v12:
* There were no comments on the v11 patch series, so there are no major changes in this version. See individual patch files for a few small local changes.

Major changes for v11 (see individual patches for additional details):
* There were no comments on the v10 patch series, so there are not many changes in this version
* Rework the mechanism for waking up RPCs that stalled waiting for buffer pool space (the old approach deprioritized waking RPCs, which led to starvation and server overload).
* Cleanup and simplify use of RPC reference counts. Before, references were only acquired to bridge gaps in lock ownership; this was complicated and error-prone. Now, reference counts are acquired at the "top level" when an RPC is selected for working on. Any function that receives a homa_rpc as argument can assume it is protected with a reference.
* Clean up sparse annotations (use name of lock variable, not address)

Major changes for v10 (see individual patches for additional details):
- Refactor resend mechanism: consolidate code for sending RESEND packets in new function homa_request_retrans (simplifies homa_timer.c); a few bug fixes (updating "granted" field in homa_resend_pkt, etc.)
- Revise sparse annotations to eliminate __context__ definition
- Use the destroy function from struct proto properly (fixes races in socket cleanup)

Major changes for v9 (see individual patches for additional details):
- Introduce homa_net objects; there is now a single global struct homa shared by all network namespaces, with one homa_net per network namespace with netns-specific information. Most info, including socket table and peer table, is stored in the struct homa.
- Introduce homa_clock as an abstraction layer for the fine-grain clock.
- Implement limits on the number of active homa_peer objects. This includes adding reference counts in homa_peers and adding code to release peers where there are too many.
- Switch to using rhashtable to store homa_peers; the table is shared across all network namespaces, though individual peers are namespace- specific.

v8 changes:
- There were no reviews of the v7 patch series, so there are not many changes in this version
- Pull out pacer code into separate files pacer.h and pacer.c
- Refactor homa_pool APIs (move allocation/deallocation into homa_pool.c, move locking responsibility out)
- Fix various problems from sparse, checkpatch, and kernel-doc

v7 changes:
- Add documentation files reap.txt and sync.txt.
- Replace __u64 with _u64 (and __s64 with s64) in non-uapi settings.
- Replace '__aligned(L1_CACHE_BYTES)' with '____cacheline_aligned_in_smp'.
- Use alloc_percpu_gfp for homa_pool::cores.
- Extract bool homa_bpage_available from homa_pool_get_pages.
- Rename homa_rpc_free to homa_rpc_end.
- Use skb_queue_purge in homa_rpc_reap instead of hand-coding.
- Clean up RCU usage in several places:
- Eliminate unnecessary use of RCU for homa_sock::dead_rpcs.
- Eliminate use of RCU for homa::throttled_rpcs (unnecessary, unclear that it would have worked). Added return value from homa_pacer_xmit.
- Call rcu_read_lock/unlock in homa_peer_find (just to be safe; probably isn't necessary)
- Eliminate extraneous use of RCU in homa_pool_allocate.
- Cleaned up RCU usage around homa_sock::active_rpcs.
- Change homa_sock_find to take a reference on the returned socket; caller no longer has to worry about RCU issues.
- Remove "locker" arguments from homa_lock_rpc, homa_lock_sock, homa_rpc_try_lock, and homa_bucket_lock (shouldn't be needed, given CONFIG_PROVE_LOCKING).
- Use __GFP_ZERO in *alloc calls instead of initializing individual struct fields to zero.
- Don't use raw_smp_processor_id; use smp_processor_id instead.
- Remove homa_peertab_get_peers from this patch series (and also fix problems in it related to RCU usage).
- Add annotation to homa_peertab_gc_dsts requiring write_lock.
- Remove "lock_slow" functions, which don't add functionality in this patch series.
- Remove unused fields from homa_peer structs.
- Reorder fields in homa_rpc_bucket to squeeze out padding.
- Refactor homa_sock_start_scan etc.
- Take a reference on the current socket to keep it from being freed.
- No need now for homa_socktab::active_scans or struct homa_socktab_links.
- rcu_read_lock/unlock is now entirely in the homa_sock scan methods; no need for callers to worry about this.
- Add homa_rpc_hold and homa_rpc_put. Replaces several ad-hoc mechanisms, such as RPC_COPYING_FROM_USER and RPC_COPYING_TO_USER, with a single general-purpose mechanism.
- Use __skb_queue_purge instead of skb_queue_purge (locking isn't needed because Homa has its own locks).
- Rename UNKNOWN packet type to RPC_UNKNOWN.
- Add hsk->is_server plus SO_HOMA_SERVER setsockopt: by default, sockets will not accept incoming RPCs unless they have been bound.
- Refactor waiting mechanism for incoming packets: simplify wait criteria and use standard mechanisms (wait_event_*) for blocking threads. Create homa_interest.c and homa_interest.h.
* Add memory accounting for outbound messages (e.g. new sysctl value wmem_max); senders now block when memory limit is exceeded.
* Made Homa a pernet subsystem (a separate Homa transport for each network namespace).

v6 changes:
- Make hrtimer variable in homa_timer_main static instead of stack-allocated (avoids complaints when in debug mode).
- Remove unnecessary cast in homa_dst_refresh.
- Replace erroneous uses of GFP_KERNEL with GFP_ATOMIC.
- Check for "all ports in use" in homa_sock_init.
- Refactor API for homa_rpc_reap to incorporate "reap all" feature, eliminate need for callers to specify exact amount of work to do when in "reap a few" mode.
- Fix bug in homa_rpc_reap (wasn't resetting rx_frees for each iteration of outer loop).

v5 changes:
- Change type of start in struct homa_rcvbuf_args from void* to __u64; also add more __user annotations.
- Refactor homa_interest: replace awkward ready_rpc field with two
fields: rpc and rpc_ready. Added new functions homa_interest_get_rpc and homa_interest_set_rpc to encapsulate/clarify access to interest->rpc_ready.
- Eliminate use of LIST_POISON1 etc. in homa_interests (use list_del_init instead of list_del).
- Remove homa_next_skb function, which is obsolete, unused, and incorrect
- Eliminate ipv4_to_ipv6 function (use ipv6_addr_set_v4mapped instead)
- Eliminate is_mapped_ipv4 function (use ipv6_addr_v4mapped instead)
- Use __u64 instead of uint64_t in homa.h
- Remove 'extern "C"' from homa.h
- Various fixes from patchwork checks (checkpatch.pl, etc.)
- A few improvements to comments

v4 changes:
- Remove sport argument for homa_find_server_rpc (unneeded). Also remove client_port field from struct homa_ack
- Refactor ICMP packet handling (v6 was incorrect)
- Check for socket shutdown in homa_poll
- Fix potential for memory garbling in homa_symbol_for_type
- Remove unused ETHERNET_MAX_PAYLOAD declaration
- Rename classes in homa_wire.h so they all have "homa_" prefixes
- Various fixes from patchwork checks (checkpatch.pl, etc.)
- A few improvements to comments

v3 changes:
- Fix formatting in Kconfig
- Set ipv6_pinfo_offset in struct proto
- Check return value of inet6_register_protosw
- In homa_load cleanup, don't cleanup things that haven't been initialized
- Add MODULE_ALIAS_NET_PF_PROTO_TYPE to auto-load module
- Check return value from kzalloc call in homa_sock_init
- Change SO_HOMA_SET_BUF to SO_HOMA_RCVBUF
- Change struct homa_set_buf_args to struct homa_rcvbuf_args
- Implement getsockopt for SO_HOMA_RCVBUF
- Return ENOPROTOOPT instead of EINVAL where appropriate in setsockopt and getsockopt
- Fix crash in homa_pool_check_waiting if pool has no region yet
- Check for NULL msg->msg_name in homa_sendmsg
- Change addr->in6.sin6_family to addr->sa.sa_family in homa_sendmsg for clarity
- For some errors in homa_recvmsg, return directly rather than "goto done"
- Return error from recvmsg if offsets of returned read buffers are bogus
- Added comments to clarify lock-unlock pairs for RPCs
- Renamed homa_try_bucket_lock to homa_try_rpc_lock
- Fix issues found by test robot and checkpatch.pl
- Ensure first argument to do_div is 64 bits
- Remove C++ style comments
- Removed some code that will only be relevant in future patches that fill in missing Homa functionality

v2 changes:
- Remove sockaddr_in_union declaration from public API in homa.h
- Remove kernel wrapper functions (homa_send, etc.) from homa.h
- Fix many sparse warnings (still more work to do here) and other issues uncovered by test robot
- Fix checkpatch.pl issues
- Remove residual code related to unit tests
- Remove references to tt_record from comments
- Make it safe to delete sockets during homa_socktab scans
- Use uintptr_t for portability fo 32-bit platforms
- Use do_div instead of "/" for portability
- Remove homa->busy_usecs and homa->gro_busy_usecs (not needed in this stripped down version of Homa)
- Eliminate usage of cpu_khz, use sched_clock instead of get_cycles
- Add missing checks of kmalloc return values
- Remove "inline" qualifier from functions in .c files
- Document that pad fields must be zero
- Use more precise type "uint32_t" rather than "int"
- Remove unneeded #include of linux/version.h

John Ousterhout (14):
net: homa: define user-visible API for Homa
net: homa: create homa_wire.h
net: homa: create shared Homa header files
net: homa: create homa_pool.h and homa_pool.c
net: homa: create homa_peer.h and homa_peer.c
net: homa: create homa_sock.h and homa_sock.c
net: homa: create homa_interest.h and homa_interest.c
net: homa: create homa_rpc.h and homa_rpc.c
net: homa: create homa_outgoing.c
net: homa: create homa_utils.c
net: homa: create homa_incoming.c
net: homa: create homa_timer.c
net: homa: create homa_plumbing.c
net: homa: create Makefile and Kconfig

 MAINTAINERS               |    7 +
 include/uapi/linux/homa.h |  300 +++++++++
 net/Kconfig               |    1 +
 net/Makefile              |    1 +
 net/homa/Kconfig          |   21 +
 net/homa/Makefile         |   15 +
 net/homa/homa_impl.h      |  585 +++++++++++++++++
 net/homa/homa_incoming.c  |  887 ++++++++++++++++++++++++++
 net/homa/homa_interest.c  |  114 ++++
 net/homa/homa_interest.h  |   93 +++
 net/homa/homa_outgoing.c  |  568 +++++++++++++++++
 net/homa/homa_peer.c      |  565 +++++++++++++++++
 net/homa/homa_peer.h      |  312 +++++++++
 net/homa/homa_plumbing.c  | 1259 +++++++++++++++++++++++++++++++++++++
 net/homa/homa_pool.c      |  507 +++++++++++++++
 net/homa/homa_pool.h      |  137 ++++
 net/homa/homa_rpc.c       |  698 ++++++++++++++++++++
 net/homa/homa_rpc.h       |  532 ++++++++++++++++
 net/homa/homa_sock.c      |  448 +++++++++++++
 net/homa/homa_sock.h      |  424 +++++++++++++
 net/homa/homa_stub.h      |   91 +++
 net/homa/homa_timer.c     |  136 ++++
 net/homa/homa_utils.c     |  110 ++++
 net/homa/homa_wire.h      |  360 +++++++++++
 net/homa/murmurhash3.h    |   44 ++
 25 files changed, 8215 insertions(+)
 create mode 100644 include/uapi/linux/homa.h
 create mode 100644 net/homa/Kconfig
 create mode 100644 net/homa/Makefile
 create mode 100644 net/homa/homa_impl.h
 create mode 100644 net/homa/homa_incoming.c
 create mode 100644 net/homa/homa_interest.c
 create mode 100644 net/homa/homa_interest.h
 create mode 100644 net/homa/homa_outgoing.c
 create mode 100644 net/homa/homa_peer.c
 create mode 100644 net/homa/homa_peer.h
 create mode 100644 net/homa/homa_plumbing.c
 create mode 100644 net/homa/homa_pool.c
 create mode 100644 net/homa/homa_pool.h
 create mode 100644 net/homa/homa_rpc.c
 create mode 100644 net/homa/homa_rpc.h
 create mode 100644 net/homa/homa_sock.c
 create mode 100644 net/homa/homa_sock.h
 create mode 100644 net/homa/homa_stub.h
 create mode 100644 net/homa/homa_timer.c
 create mode 100644 net/homa/homa_utils.c
 create mode 100644 net/homa/homa_wire.h
 create mode 100644 net/homa/murmurhash3.h

--
2.43.0

#1 lore raw

PATCH v17 1/14 net: homa: define user-visible API for Homa

Note: for man pages, see the Homa Wiki at:
https://homa-transport.atlassian.net/wiki/spaces/HOMA/overview

---
Changes for v16:
* Implement HOMAIOCINFO ioctl.

Changes for v14:
* Add "WITH Linux-syscall-note" SPDX license note

Changes for v11:
* Add explicit padding to struct homa_recvmsg_args to fix problems compiling on 32-bit machines.

Changes for v9:
* Eliminate use of _Static_assert
* Remove declarations related to now-defunct homa_api.c

Changes for v7:
* Add HOMA_SENDMSG_NONBLOCKING flag for sendmsg
* API changes for new mechanism for waiting for incoming messages
* Add setsockopt SO_HOMA_SERVER (enable incoming requests)
* Use u64 and __u64 properly

---
 MAINTAINERS               |   7 +
 include/uapi/linux/homa.h | 300 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 307 insertions(+)
 create mode 100644 include/uapi/linux/homa.h
MAINTAINERS +7 -0
index 77fdfcb55f06..1ea0811588ae 100644
@@ -11656,6 +11656,13 @@ F:	lib/test_hmm*
 F:	mm/hmm*
 F:	tools/testing/selftests/mm/*hmm*
 
+HOMA TRANSPORT PROTOCOL
+M:	John Ousterhout <[email protected]>
+S:	Maintained
+W:	https://homa-transport.atlassian.net/wiki/spaces/HOMA
+F:	net/homa/
+F:      include/uapi/linux/homa.h
+
 HONEYWELL ABP2030PA PRESSURE SENSOR SERIES IIO DRIVER
 M:	Petre Rodan <[email protected]>
 L:	[email protected]
include/uapi/linux/homa.h new file +300 -0

300 lines not on this page · raw message

Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH net-next v17 01/14] net: homa: define user-visible API for Homa

kernel test robot noticed the following build errors:

Hi John,

kernel test robot noticed the following build errors:

[auto build test ERROR on net-next/main]

url:    https://github.com/intel-lab-lkp/linux/commits/John-Ousterhout/net-homa-define-user-visible-API-for-Homa/20260317-070659
base:   net-next/main
patch link:    https://lore.kernel.org/r/20260316223228.2611-2-ouster%40cs.stanford.edu
patch subject: [PATCH net-next v17 01/14] net: homa: define user-visible API for Homa
config: x86_64-rhel-9.4-ltp (https://download.01.org/0day-ci/archive/20260317/[email protected]/config)
compiler: gcc-14 (Debian 14.2.0-19) 14.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260317/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

In file included from <command-line>:

>> ./usr/include/linux/homa.h:11:10: fatal error: netinet/in.h: No such file or directory
      11 | #include <netinet/in.h>
         |          ^~~~~~~~~~~~~~

compilation terminated.

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#3 lore raw

Re: [PATCH net-next v17 01/14] net: homa: define user-visible API for Homa

In reply to John Ousterhout
kernel test robot noticed the following build errors:

Hi John,

kernel test robot noticed the following build errors:

[auto build test ERROR on net-next/main]

url:    https://github.com/intel-lab-lkp/linux/commits/John-Ousterhout/net-homa-define-user-visible-API-for-Homa/20260317-070659
base:   net-next/main
patch link:    https://lore.kernel.org/r/20260316223228.2611-2-ouster%40cs.stanford.edu
patch subject: [PATCH net-next v17 01/14] net: homa: define user-visible API for Homa
config: hexagon-randconfig-r071-20260317 (https://download.01.org/0day-ci/archive/20260318/[email protected]/config)
compiler: clang version 23.0.0git (https://github.com/llvm/llvm-project 4abb927bacf37f18f6359a41639a6d1b3bffffb5)
smatch: v0.5.0-9004-gb810ac53
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260318/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

In file included from <built-in>:1:

>> ./usr/include/linux/homa.h:11:10: fatal error: 'netinet/in.h' file not found
      11 | #include <netinet/in.h>
         |          ^~~~~~~~~~~~~~

1 error generated.

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#4 lore raw

PATCH v17 2/14 net: homa: create homa_wire.h

In reply to John Ousterhout

This file defines the on-the-wire packet formats for Homa.

---
Changes for v11:
* Rework the mechanism for waking up RPCs that stalled waiting for buffer pool space

Changes for v10:
* Replace __u16 with u16, __u8 with u8, etc.
* Refactor resend mechanism

Changes for v9:
* Eliminate use of _Static_assert
* Various name improvements (e.g. use "alloc" instead of "new" for functions that allocate memory, Replace BOGUS in enum homa_packet_type with MAX_OP)
* Remove HOMA_IPV6_HEADER_LENGTH and similar defs, use sizeof(ipv6hdr) instead

Changes for v7:
* Rename UNKNOWN packet type to RPC_UNKNOWN
* Use u64 and __u64 properly

---
 net/homa/homa_wire.h | 360 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 360 insertions(+)
 create mode 100644 net/homa/homa_wire.h
net/homa/homa_wire.h new file +360 -0
new file mode 100644
index 000000000000..b06801a4407a
@@ -0,0 +1,360 @@
+/* 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;
+	 * used in DATA packets to hold the offset in the message of the first
+	 * byte of data. However, when TSO is used without TCP hijacking, this
+	 * value will only be correct in the first segment of a GSO packet.
+	 */
+	__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 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: Not used by Homa, but must occupy the same bytes as
+	 * the checksum in a TCP header (TSO may modify this?).
+	 */
+	__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 will 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 int 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;
+}
+
+/**
+ * homa_get_offset() - Returns the offset within message of the first byte
+ * of data in a Homa DATA packet (the offset is stored in different places
+ * in different situations).
+ * @h:       Header for DATA packet
+ * Return:   See above
+ */
+static inline int homa_get_offset(struct homa_data_hdr *h)
+{
+	return ntohl(h->seg.offset);
+}
+
+#endif /* _HOMA_WIRE_H */
Signature · 1 line
2.43.0
#5 lore raw

PATCH v17 3/14 net: homa: create shared Homa header files

In reply to John Ousterhout

homa_impl.h defines "struct homa", which contains overall information about the Homa transport, plus various odds and ends that are used throughout the Homa implementation.

homa_stub.h is a temporary header file that provides stubs for facilities that have omitted for this first patch series. This file will go away once Home is fully upstreamed.

---
Changes for v16:
* Remove various fields and functions:
* net field in struct homa_net
* bytes_left, next_sibling, and last_sibling fields in struct homa_skb_info
* is_homa_pkt()
* homa_from_skb()
* homa_net_from_skb()
* homa_usecs_to_cycles()
* Rename homa_net_from_net to homa_net
* Use consume_skb and kfree_skb_reason instead of kfree_skb

Changes for v12:
* Use tsc_khz instead of cpu_khz
* Make is_homa_pkt work properly with IPv6 (it only worked for IPv4)

Changes for v11:
* Move link_mbps variable from struct homa_pacer back to struct homa.

Changes for v10:
* Eliminate __context__ definition
* Replace __u16 with u16, __u8 with u8, etc.
* Refactor resend mechanism

Changes for v9:
* Move information from sync.txt into comments in homa_impl.h
* Add limits on number of active peer structs
* Introduce homa_net objects; there is now a single global struct homa shared by all network namespaces, with one homa_net per network namespace with netns-specific information.
* Introduce homa_clock as an abstraction layer for the fine-grain clock.
* Various name improvements (e.g. use "alloc" instead of "new" for functions that allocate memory)
* Eliminate sizeof32 definition

Changes for v8:
* Pull out pacer-related fields into separate struct homa_pacer in homa_pacer.h

Changes for v7:
* Make Homa a per-net subsystem
* Track tx buffer memory usage
* Refactor waiting mechanism for incoming packets: simplify wait criteria and use standard Linux mechanisms for waiting
* Remove "lock_slow" functions, which don't add functionality in this patch series
* Rename homa_rpc_free to homa_rpc_end
* Add homa_make_header_avl function
* Use u64 and __u64 properly

---
 net/homa/homa_impl.h | 512 +++++++++++++++++++++++++++++++++++++++++++
 net/homa/homa_stub.h |  91 ++++++++
 2 files changed, 603 insertions(+)
 create mode 100644 net/homa/homa_impl.h
 create mode 100644 net/homa/homa_stub.h
net/homa/homa_impl.h new file +512 -0
new file mode 100644
index 000000000000..f55a7b80431d
@@ -0,0 +1,512 @@
+/* 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_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;
+
+	/** @max_numa: Highest NUMA node id in use by any core. */
+	int max_numa;
+
+	/**
+	 * @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;
+
+	/**
+	 * @reap_limit: Maximum number of packet buffers to free in a
+	 * single call to home_rpc_reap.
+	 */
+	int reap_limit;
+
+	/**
+	 * @dead_buffs_limit: If the number of packet buffers in dead but
+	 * not yet reaped RPCs is less than this number, then Homa reaps
+	 * RPCs in a way that minimizes impact on performance but may permit
+	 * dead RPCs to accumulate. If the number of dead packet buffers
+	 * exceeds this value, then Homa switches to a more aggressive approach
+	 * to reaping RPCs. Set externally via sysctl.
+	 */
+	int dead_buffs_limit;
+
+	/**
+	 * @max_dead_buffs: The largest aggregate number of packet buffers
+	 * in dead (but not yet reaped) RPCs that has existed so far in a
+	 * single socket.  Readable via sysctl, and may be reset via sysctl
+	 * to begin recalculating.
+	 */
+	int max_dead_buffs;
+
+	/**
+	 * @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;
+
+	/**
+	 * @gso_force_software: A non-zero value will cause Homa to perform
+	 * segmentation in software using GSO; zero means ask the NIC to
+	 * perform TSO. Set externally via sysctl.
+	 */
+	int gso_force_software;
+
+	/**
+	 * @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;
+
+	/**
+	 * @flags: a collection of bits that can be set using sysctl
+	 * to trigger various behaviors.
+	 */
+	int flags;
+
+	/**
+	 * @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_peers: The total number of struct homa_peers that exist
+	 * for this namespace. Managed by homa_peer.c under the peertab lock.
+	 */
+	int num_peers;
+};
+
+/**
+ * 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 {
+	/** @next_skb: used to link together outgoing skb's for a message. */
+	struct sk_buff *next_skb;
+
+	/**
+	 * @wire_bytes: total number of bytes of network bandwidth that
+	 * will be consumed by this packet. This includes everything,
+	 * including additional headers added by GSO, IP header, Ethernet
+	 * header, CRC, preamble, and inter-packet gap.
+	 */
+	int wire_bytes;
+
+	/**
+	 * @data_bytes: total bytes of message data across all of the
+	 * segments in this packet.
+	 */
+	int data_bytes;
+
+	/** @seg_length: maximum number of data bytes in each GSO segment. */
+	int seg_length;
+
+	/**
+	 * @offset: offset within the message of the first byte of data in
+	 * this packet.
+	 */
+	int offset;
+
+	/** @rpc: RPC that this packet belongs to. */
+	void *rpc;
+};
+
+/**
+ * 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 Homa packet.
+ * @h:     Packet header whose doff field is to be set.
+ * @size:  Size of the "header", bytes (must be a multiple of 4). This
+ *         information is used only for TSO; it's the number of bytes
+ *         that should be replicated in each segment. The bytes after
+ *         this will be distributed among segments.
+ */
+static inline void homa_set_doff(struct homa_data_hdr *h, int size)
+{
+	/* Drop the 2 low-order bits from size and set the 4 high-order
+	 * bits of doff from what's left.
+	 */
+	h->common.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;
+
+/**
+ * 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 and socket locks, all locks should be considered
+ *    "leaf" locks: don't acquire other locks while holding them.
+ * 2. The lock order is:
+ *    * 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 things is 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.
+ */
+
+#endif /* _HOMA_IMPL_H */
net/homa/homa_stub.h new file +91 -0

91 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#6 lore raw

Re: [net-next,v17,03/14] net: homa: create shared Homa header files

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.

For local reproduction steps see https://netdev-ai.bots.linux.dev/ai-local.html
---
net: homa: create shared Homa header files

homa_impl.h defines "struct homa", which contains overall information about the Homa transport, plus various odds and ends that are used throughout the Homa implementation. homa_stub.h is a temporary header file that provides stubs for facilities that have omitted for this first patch series. This file will go away once Homa is fully upstreamed.

Quoted 5 lines
net/homa/homa_impl.h new file +0 -0
new file mode 100644
index 000000000000..f55a7b80431d

[ ... ]

Quoted 1 line
net/homa/homa_impl.h new file +0 -0
@@ -0,0 +1,512 @@

[ ... ]

Quoted 5 lines
net/homa/homa_impl.h new file +5 -0
+/**
+ * homa_set_doff() - Fills in the doff TCP header field for a Homa packet.
+ * @h:     Packet header whose doff field is to be set.
+ * @size:  Size of the "header", bytes (must be a multiple of 4). This
+ *         information is used only for TSO; it's the number of bytes

net/homa/homa_impl.h line 286

Quoted 10 lines
net/homa/homa_impl.h new file +10 -0
+ *         that should be replicated in each segment. The bytes after
+ *         this will be distributed among segments.
+ */
+static inline void homa_set_doff(struct homa_data_hdr *h, int size)
+{
+	/* Drop the 2 low-order bits from size and set the 4 high-order
+	 * bits of doff from what's left.
+	 */
+	h->common.doff = size << 2;
+}

Does the comment in homa_set_doff() accurately describe what the code does? The comment says "Drop the 2 low-order bits from size" which would be a right shift (size >> 2), but the code performs a left shift (size << 2).

Looking at similar usage patterns in TCP where the doff field stores header length in 4-byte word units, the code appears correct - it's converting a byte size to 4-byte word units by shifting left.

The comment should probably say "Shift size left by 2 bits to store in 4-byte word units" or "Multiply size by 4 and store in doff field" to match what the code actually does.

[ ... ]

#7 lore raw

Re: [net-next,v17,03/14] net: homa: create shared Homa header files

Quoted 6 lines · Paolo Abeni

Does the comment in homa_set_doff() accurately describe what the code does? The comment says "Drop the 2 low-order bits from size" which would be a right shift (size >> 2), but the code performs a left shift (size << 2).

Quoted 7 lines

Looking at similar usage patterns in TCP where the doff field stores header length in 4-byte word units, the code appears correct - it's converting a byte size to 4-byte word units by shifting left.

The comment should probably say "Shift size left by 2 bits to store in 4-byte word units" or "Multiply size by 4 and store in doff field" to match what the code actually does.

I have rewritten the comment.

#8 lore raw

PATCH v17 4/14 net: homa: create homa_pool.h and homa_pool.c

In reply to John Ousterhout

These files implement Homa's mechanism for managing application-level buffer space for incoming messages This mechanism is needed to allow Homa to copy data out to user space in parallel with receiving packets; it was discussed in a talk at NetDev 0x17.

---
Changes for v16:
* Add homa_pool_avail_bytes() for new HOMAIOCINFO ioctl

Changes for v11:
* Rework the mechanism for waking up RPCs that stalled waiting for buffer pool space

Changes for v10:
* Fix minor syntactic issues such as reverse xmas tree

Changes for v9:
* Eliminate use of _Static_assert
* Use new homa_clock abstraction layer.
* Allow memory to be allocated without GFP_ATOMIC
* Various name improvements (e.g. use "alloc" instead of "new" for functions that allocate memory)
* Remove sync.txt, move its contents into comments (mostly in homa_impl.h)

Changes for v8:
* Refactor homa_pool APIs (move allocation/deallocation into homa_pool.c, move locking responsibility out)

Changes for v7:
* Use u64 and __u64 properly
* Eliminate extraneous use of RCU
* Refactor pool->cores to use percpu variable
* Use smp_processor_id instead of raw_smp_processor_id

---
 net/homa/homa_pool.c | 507 +++++++++++++++++++++++++++++++++++++++++++
 net/homa/homa_pool.h | 137 ++++++++++++
 2 files changed, 644 insertions(+)
 create mode 100644 net/homa/homa_pool.c
 create mode 100644 net/homa/homa_pool.h
net/homa/homa_pool.c new file +507 -0
new file mode 100644
index 000000000000..f89266c3a87d
@@ -0,0 +1,507 @@
+// 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. */
+
+/* Pools must always have at least this many bpages (no particular
+ * reasoning behind this value).
+ */
+#define MIN_POOL_SIZE 2
+
+/* 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);
+	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;
+
+	if (((uintptr_t)region) & ~PAGE_MASK)
+		return -EINVAL;
+
+	/* Allocate memory before locking the socket, so we can allocate
+	 * without GFP_ATOMIC.
+	 */
+	num_bpages = region_size >> HOMA_BPAGE_SHIFT;
+	if (num_bpages < MIN_POOL_SIZE)
+		return -EINVAL;
+	descriptors = kmalloc_array(num_bpages, sizeof(struct homa_bpage),
+				    GFP_KERNEL | __GFP_ZERO);
+	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->region = (char __user *)region;
+	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;
+	}
+
+	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 (pool->region) {
+		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 = 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)
+{
+	int ref_count = atomic_read(&bpage->refs);
+
+	return ref_count == 0 || (ref_count == 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;
+
+	core = this_cpu_ptr(pool->cores);
+	if (atomic_sub_return(num_pages, &pool->free_bpages) < 0) {
+		atomic_add(num_pages, &pool->free_bpages);
+		return -1;
+	}
+
+	/* 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_inc(&pool->free_bpages);
+		if (set_owner) {
+			atomic_set(&bpage->refs, 2);
+			bpage->owner = core_num;
+			bpage->expiration = now +
+					    pool->hsk->homa->bpage_lease_cycles;
+		} else {
+			atomic_set(&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 (!pool->region)
+		return -ENOMEM;
+
+	/* 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 (atomic_read(&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.
+			 */
+			atomic_dec_return(&bpage->refs);
+			spin_unlock_bh(&bpage->lock);
+			goto new_page;
+		}
+	}
+	bpage->expiration = homa_clock() +
+			    pool->hsk->homa->bpage_lease_cycles;
+	atomic_inc(&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_release_buffers(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_release_buffers() - 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_release_buffers(struct homa_pool *pool, int num_buffers,
+			      u32 *buffers)
+{
+	int result = 0;
+	int i;
+
+	if (!pool->region)
+		return result;
+	for (i = 0; i < num_buffers; i++) {
+		u32 bpage_index = buffers[i] >> HOMA_BPAGE_SHIFT;
+		struct homa_bpage *bpage = &pool->descriptors[bpage_index];
+
+		if (bpage_index < pool->num_bpages) {
+			if (atomic_dec_return(&bpage->refs) == 0)
+				atomic_inc(&pool->free_bpages);
+		} else {
+			result = -EINVAL;
+		}
+	}
+	return result;
+}
+
+/**
+ * homa_pool_check_waiting() - Checks to see if there are enough free
+ * bpages to wake up any RPCs that were blocked. Whenever
+ * homa_pool_release_buffers is invoked, this function must be invoked later,
+ * at a point when the caller holds no locks (homa_pool_release_buffers 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 (!pool->region)
+		return;
+	while (atomic_read(&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);
+			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;
+	u64 avail;
+	int cpu;
+
+	if (!pool->region)
+		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);
+		if (pool->descriptors[core->page_hint].owner == cpu)
+			avail += HOMA_BPAGE_SIZE - core->allocated;
+	}
+	return avail;
+}
net/homa/homa_pool.h new file +137 -0

137 lines not on this page · raw message

Signature · 1 line
2.43.0
#9 lore raw

PATCH v17 5/14 net: homa: create homa_peer.h and homa_peer.c

In reply to John Ousterhout

Homa needs to keep a small amount of information for each peer that it has communicated with. These files define that state and provide functions for storing and accessing it.

---
Changes for v16:
* Clean up and simplify reference counting mechanism (use refcount_t instead of atomic_t, eliminate dead_peers mechanism)
* Fix synchronization bugs in homa_dst_refresh (use RCU properly)
* Remove addr field of struct homa_peer
* Create separate header file for murmurhash hash function

Changes for v11:
* Clean up sparse annotations

Changes for v10:
* Use kzalloc instead of __GFP_ZERO
* Remove log messages after alloc errors
* Fix issues found by sparse, xmastree.py, etc.
* Add missing initialization for peertab->lock

Changes for v9:
* Add support for homa_net objects
* Implement limits on the number of active homa_peer objects. This includes adding reference counts in homa_peers and adding code to release peers where there are too many.
* Switch to using rhashtable to store homa_peers; the table is shared across all network namespaces, though individual peers are namespace- specific
* Invoke dst->ops->check in addition to checking the obsolete flag
* Various name improvements
* Remove the homa_peertab_gc_dsts mechanism, which is unnecessary

Changes for v7:
* Remove homa_peertab_get_peers
* Remove "lock_slow" functions, which don't add functionality in this patch
* Remove unused fields from homa_peer structs
* Use u64 and __u64 properly
* Add lock annotations
* Refactor homa_peertab_get_peers
* Use __GFP_ZERO in kmalloc calls

---
 net/homa/homa_peer.c   | 565 +++++++++++++++++++++++++++++++++++++++++
 net/homa/homa_peer.h   | 312 +++++++++++++++++++++++
 net/homa/murmurhash3.h |  44 ++++
 3 files changed, 921 insertions(+)
 create mode 100644 net/homa/homa_peer.c
 create mode 100644 net/homa/homa_peer.h
 create mode 100644 net/homa/murmurhash3.h
net/homa/homa_peer.c new file +565 -0
new file mode 100644
index 000000000000..1e5301cdef41
@@ -0,0 +1,565 @@
+// SPDX-License-Identifier: BSD-2-Clause or GPL-2.0+
+
+/* This file provides functions related to homa_peer and homa_peertab
+ * objects.
+ */
+
+#include "homa_impl.h"
+#include "homa_peer.h"
+#include "homa_rpc.h"
+#include "murmurhash3.h"
+
+static const struct rhashtable_params 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 = murmurhash3,
+	.obj_cmpfn = homa_peer_compare
+};
+
+/**
+ * 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->ht, &ht_params);
+	if (err) {
+		kfree(peertab);
+		return ERR_PTR(err);
+	}
+	peertab->ht_valid = true;
+	rhashtable_walk_enter(&peertab->ht, &peertab->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;
+}
+
+/**
+ * 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_peer *peer;
+
+	spin_lock_bh(&peertab->lock);
+	peertab->gc_stop_count++;
+	spin_unlock_bh(&peertab->lock);
+
+	rhashtable_walk_enter(&peertab->ht, &iter);
+	rhashtable_walk_start(&iter);
+	while (1) {
+		peer = rhashtable_walk_next(&iter);
+		if (!peer)
+			break;
+		if (IS_ERR(peer))
+			continue;
+		if (peer->ht_key.hnet != hnet)
+			continue;
+		if (rhashtable_remove_fast(&peertab->ht, &peer->ht_linkage,
+					   ht_params) == 0) {
+			homa_peer_release(peer);
+			hnet->num_peers--;
+			peertab->num_peers--;
+		}
+	}
+	rhashtable_walk_stop(&iter);
+	rhashtable_walk_exit(&iter);
+	WARN(hnet->num_peers != 0, "%s ended up with hnet->num_peers %d",
+	     __func__, hnet->num_peers);
+
+	spin_lock_bh(&peertab->lock);
+	peertab->gc_stop_count--;
+	spin_unlock_bh(&peertab->lock);
+}
+
+/**
+ * homa_peer_release_fn() - This function is invoked for each entry in
+ * the peer 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_peer_release_fn(void *object, void *dummy)
+{
+	struct homa_peer *peer = object;
+
+	homa_peer_release(peer);
+}
+
+/**
+ * homa_peer_free_peertab() - Destructor for homa_peertabs.
+ * @peertab:  The table to destroy.
+ */
+void homa_peer_free_peertab(struct homa_peertab *peertab)
+{
+	spin_lock_bh(&peertab->lock);
+	peertab->gc_stop_count++;
+	spin_unlock_bh(&peertab->lock);
+
+	if (peertab->ht_valid) {
+		rhashtable_walk_exit(&peertab->ht_iter);
+		rhashtable_free_and_destroy(&peertab->ht, homa_peer_release_fn,
+					    NULL);
+	}
+	kfree(peertab);
+}
+
+/**
+ * homa_peer_prefer_evict() - Given two peers, determine which one is
+ * a better candidate for eviction.
+ * @peertab:    Overall information used to manage peers.
+ * @peer1:      First peer.
+ * @peer2:      Second peer.
+ * Return:      True if @peer1 is a better candidate for eviction than @peer2.
+ */
+int homa_peer_prefer_evict(struct homa_peertab *peertab,
+			   struct homa_peer *peer1,
+			   struct homa_peer *peer2)
+{
+	/* Prefer a peer whose homa-net is over its limit; if both are either
+	 * over or under, then prefer the peer with the shortest idle time.
+	 */
+	if (peer1->ht_key.hnet->num_peers > peertab->net_max) {
+		if (peer2->ht_key.hnet->num_peers <= peertab->net_max)
+			return true;
+		else
+			return peer1->access_jiffies < peer2->access_jiffies;
+	}
+	if (peer2->ht_key.hnet->num_peers > peertab->net_max)
+		return false;
+	else
+		return peer1->access_jiffies < peer2->access_jiffies;
+}
+
+/**
+ * homa_peer_pick_victims() - Select a few peers that can be freed.
+ * @peertab:      Choose peers 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 peers stored in @victims; may be zero.
+ */
+int homa_peer_pick_victims(struct homa_peertab *peertab,
+			   struct homa_peer *victims[], int max_victims)
+{
+	struct homa_peer *peer;
+	int num_victims = 0;
+	int to_scan;
+	int i, idle;
+
+	/* Scan 2 peers for every potential victim and keep the "best"
+	 * peers for removal.
+	 */
+	rhashtable_walk_start(&peertab->ht_iter);
+	for (to_scan = 2 * max_victims; to_scan > 0; to_scan--) {
+		peer = rhashtable_walk_next(&peertab->ht_iter);
+		if (!peer) {
+			/* Reached the end of the table; restart at
+			 * the beginning.
+			 */
+			rhashtable_walk_stop(&peertab->ht_iter);
+			rhashtable_walk_exit(&peertab->ht_iter);
+			rhashtable_walk_enter(&peertab->ht, &peertab->ht_iter);
+			rhashtable_walk_start(&peertab->ht_iter);
+			peer = rhashtable_walk_next(&peertab->ht_iter);
+			if (!peer)
+				break;
+		}
+		if (IS_ERR(peer)) {
+			/* rhashtable decided to restart the search at the
+			 * beginning.
+			 */
+			peer = rhashtable_walk_next(&peertab->ht_iter);
+			if (!peer || IS_ERR(peer))
+				break;
+		}
+
+		/* Has this peer been idle long enough to be candidate for
+		 * eviction?
+		 */
+		idle = jiffies - peer->access_jiffies;
+		if (idle < peertab->idle_jiffies_min)
+			continue;
+		if (idle < peertab->idle_jiffies_max &&
+		    peer->ht_key.hnet->num_peers <= peertab->net_max)
+			continue;
+
+		/* Sort the candidate into the existing list of victims. */
+		for (i = 0; i < num_victims; i++) {
+			if (peer == victims[i]) {
+				/* This can happen if there aren't very many
+				 * peers and we wrapped around in the hash
+				 * table.
+				 */
+				peer = NULL;
+				break;
+			}
+			if (homa_peer_prefer_evict(peertab, peer, victims[i])) {
+				struct homa_peer *tmp;
+
+				tmp = victims[i];
+				victims[i] = peer;
+				peer = tmp;
+			}
+		}
+
+		if (num_victims < max_victims && peer) {
+			victims[num_victims] = peer;
+			num_victims++;
+		}
+	}
+	rhashtable_walk_stop(&peertab->ht_iter);
+	return num_victims;
+}
+
+/**
+ * homa_peer_gc() - This function is invoked by Homa at regular intervals;
+ * its job is to ensure that the number of peers stays within limits.
+ * If the number grows too large, it selectively deletes peers to get
+ * back under the limit.
+ * @peertab:   Structure whose peers should be considered for garbage
+ *             collection.
+ */
+void homa_peer_gc(struct homa_peertab *peertab)
+{
+#define EVICT_BATCH_SIZE 5
+	struct homa_peer *victims[EVICT_BATCH_SIZE];
+	int num_victims;
+	int i;
+
+	spin_lock_bh(&peertab->lock);
+	if (peertab->gc_stop_count != 0)
+		goto done;
+	if (peertab->num_peers < peertab->gc_threshold)
+		goto done;
+	num_victims = homa_peer_pick_victims(peertab, victims,
+					     EVICT_BATCH_SIZE);
+	if (num_victims == 0)
+		goto done;
+
+	for (i = 0; i < num_victims; i++) {
+		struct homa_peer *peer = victims[i];
+
+		if (rhashtable_remove_fast(&peertab->ht, &peer->ht_linkage,
+					   ht_params) == 0) {
+			homa_peer_release(peer);
+			peertab->num_peers--;
+			peer->ht_key.hnet->num_peers--;
+		}
+	}
+done:
+	spin_unlock_bh(&peertab->lock);
+}
+
+/**
+ * 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;
+	int status;
+
+	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);
+	peer->access_jiffies = jiffies;
+	spin_lock_init(&peer->lock);
+	peer->current_ticks = -1;
+
+	status = homa_peer_reset_dst(peer, hsk);
+	if (status != 0) {
+		hsk->error_msg = "couldn't find route for peer";
+		kfree(peer);
+		return ERR_PTR(status);
+	}
+	return peer;
+}
+
+/**
+ * homa_peer_free() - Release any resources in a peer and free the homa_peer
+ * struct. Invoked by the RCU mechanism via homa_peer_release.
+ * @head:   Pointer to the rcu_head field of the peer to free.
+ */
+void homa_peer_free(struct rcu_head *head)
+{
+	struct homa_peer *peer;
+
+	peer = container_of(head, struct homa_peer, rcu_head);
+	dst_release(rcu_dereference(peer->dst));
+	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)
+{
+	struct homa_peertab *peertab = hsk->homa->peertab;
+	struct homa_peer *peer, *other;
+	struct homa_peer_key key;
+
+	key.addr = *addr;
+	key.hnet = hsk->hnet;
+	rcu_read_lock();
+	peer = rhashtable_lookup(&peertab->ht, &key, ht_params);
+	if (peer) {
+		homa_peer_hold(peer);
+		peer->access_jiffies = jiffies;
+		rcu_read_unlock();
+		return peer;
+	}
+
+	/* No existing entry, so we have to create a new one. */
+	peer = homa_peer_alloc(hsk, addr);
+	if (IS_ERR(peer)) {
+		rcu_read_unlock();
+		return peer;
+	}
+	spin_lock_bh(&peertab->lock);
+	other = rhashtable_lookup_get_insert_fast(&peertab->ht,
+						  &peer->ht_linkage, ht_params);
+	if (IS_ERR(other)) {
+		/* Couldn't insert; return the error info. */
+		homa_peer_release(peer);
+		peer = other;
+	} else if (other) {
+		/* Someone else already created the desired peer; use that
+		 * one instead of ours.
+		 */
+		homa_peer_release(peer);
+		homa_peer_hold(other);
+		peer = other;
+		peer->access_jiffies = jiffies;
+	} else {
+		homa_peer_hold(peer);
+		peertab->num_peers++;
+		key.hnet->num_peers++;
+	}
+	spin_unlock_bh(&peertab->lock);
+	rcu_read_unlock();
+	return peer;
+}
+
+/**
+ * homa_get_dst() - Returns destination information associated with a peer,
+ * updating it if the cached information is stale.
+ * @peer:   Peer whose destination information is desired.
+ * @hsk:    Homa socket with which the dst will be used; needed by lower-level
+ *          code to recreate the dst.
+ * Return:  Up-to-date destination for peer; a reference has been taken
+ *          on this dst_entry, which the caller must eventually release.
+ */
+struct dst_entry *homa_get_dst(struct homa_peer *peer, struct homa_sock *hsk)
+{
+	struct dst_entry *dst;
+	int pass;
+
+	rcu_read_lock();
+	for (pass = 0; ; pass++) {
+		do {
+			/* This loop repeats only if we happen to fetch
+			 * the dst right when it is being reset.
+			 */
+			dst = rcu_dereference(peer->dst);
+		} while (!dst_hold_safe(dst));
+
+		/* After the first pass it's OK to return an obsolete dst
+		 * (we're basically giving up; continuing could result in
+		 * an infinite loop if homa_dst_refresh can't create a new dst).
+		 */
+		if (dst_check(dst, peer->dst_cookie) || pass > 0)
+			break;
+		dst_release(dst);
+		homa_peer_reset_dst(peer, hsk);
+	}
+	rcu_read_unlock();
+	return dst;
+}
+
+/**
+ * homa_peer_reset_dst() - Find an appropriate dst_entry for a peer and
+ * store it in the peer's dst field. If the field is already set, the
+ * current value is assumed to be stale and will be discarded if a new
+ * dst_entry can be created.
+ * @peer:   The peer whose dst field should be reset.
+ * @hsk:    Socket that will be used for sending packets.
+ * Return:  Zero for success, or a negative errno if there was an error
+ *          (in which case the existing value for the dst field is left
+ *          in place).
+ */
+int homa_peer_reset_dst(struct homa_peer *peer, struct homa_sock *hsk)
+{
+	struct dst_entry *dst;
+	int result = 0;
+
+	homa_peer_lock(peer);
+	memset(&peer->flow, 0, sizeof(peer->flow));
+	if (hsk->sock.sk_family == AF_INET) {
+		struct rtable *rt;
+
+		flowi4_init_output(&peer->flow.u.ip4, hsk->sock.sk_bound_dev_if,
+				   hsk->sock.sk_mark, hsk->inet.tos,
+				   RT_SCOPE_UNIVERSE, hsk->sock.sk_protocol, 0,
+				   ipv6_to_ipv4(peer->addr),
+				   hsk->inet.inet_saddr, 0, 0,
+				   hsk->sock.sk_uid);
+		security_sk_classify_flow(&hsk->sock,
+					  &peer->flow.u.__fl_common);
+		rt = ip_route_output_flow(sock_net(&hsk->sock),
+					  &peer->flow.u.ip4, &hsk->sock);
+		if (IS_ERR(rt)) {
+			result = PTR_ERR(rt);
+			goto done;
+		}
+		dst = &rt->dst;
+		peer->dst_cookie = 0;
+	} else {
+		/* This code is derived from code in tcp_v6_connect. */
+		peer->flow.u.ip6.flowi6_proto = hsk->sock.sk_protocol;
+		peer->flow.u.ip6.daddr = peer->addr;
+		peer->flow.u.ip6.saddr = hsk->inet.pinet6->saddr;
+		peer->flow.u.ip6.flowlabel = ip6_make_flowinfo(hsk->inet.tos,
+							       0);
+		peer->flow.u.ip6.flowi6_oif = hsk->sock.sk_bound_dev_if;
+		peer->flow.u.ip6.flowi6_mark = hsk->sock.sk_mark;
+		peer->flow.u.ip6.fl6_dport = 0;
+		peer->flow.u.ip6.fl6_sport = 0;
+		peer->flow.u.ip6.flowi6_uid = hsk->sock.sk_uid;
+		security_sk_classify_flow(&hsk->sock,
+					  &peer->flow.u.__fl_common);
+		dst = ip6_dst_lookup_flow(sock_net(&hsk->sock), &hsk->sock,
+					  &peer->flow.u.ip6, NULL);
+		if (IS_ERR(dst)) {
+			result = PTR_ERR(dst);
+			goto done;
+		}
+		peer->dst_cookie = rt6_get_cookie(dst_rt6_info(dst));
+	}
+
+	/* From the standpoint of homa_get_dst, peer->dst is not updated
+	 * atomically with peer->dst_cookie, which means homa_get_dst could
+	 * use a new cookie with an old dest. Fortunately, this is benign; at
+	 * worst, it might cause an obsolete dst to be reused (resulting in
+	 * a lost packet) or a valid dst to be replaced (resulting in
+	 * unnecessary work).
+	 */
+	dst_release(rcu_replace_pointer(peer->dst, dst, true));
+
+done:
+	homa_peer_unlock(peer);
+	return result;
+}
+
+/**
+ * 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.
+ */
+void homa_peer_add_ack(struct homa_rpc *rpc)
+{
+	struct homa_peer *peer = rpc->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;
+}
+
net/homa/homa_peer.h new file +312 -0

312 lines not on this page · raw message

net/homa/murmurhash3.h new file +44 -0

44 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#10 lore raw

Re: [net-next,v17,05/14] net: homa: create homa_peer.h and homa_peer.c

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.

For local reproduction steps see https://netdev-ai.bots.linux.dev/ai-local.html
---
net: homa: create homa_peer.h and homa_peer.c

Homa needs to keep a small amount of information for each peer that it has communicated with. These files define that state and provide functions for storing and accessing it.

Quoted 5 lines
net/homa/homa_peer.c new file +0 -0
new file mode 100644
index 000000000000..1e5301cdef41

[ ... ]

Quoted 25 lines
net/homa/homa_peer.c new file +25 -0
+/**
+ * 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_peer *peer;
+
+	spin_lock_bh(&peertab->lock);
+	peertab->gc_stop_count++;
+	spin_unlock_bh(&peertab->lock);
+
+	rhashtable_walk_enter(&peertab->ht, &iter);
+	rhashtable_walk_start(&iter);
+	while (1) {
+		peer = rhashtable_walk_next(&iter);
+		if (!peer)
+			break;
+		if (IS_ERR(peer))
+			continue;
+		if (peer->ht_key.hnet != hnet)

net/homa/homa_peer.c line 87

Quoted 10 lines
net/homa/homa_peer.c new file +10 -0
+			continue;
+		if (rhashtable_remove_fast(&peertab->ht, &peer->ht_linkage,
+					   ht_params) == 0) {
+			homa_peer_release(peer);
+			hnet->num_peers--;
+			peertab->num_peers--;
+		}
+	}
+	rhashtable_walk_stop(&iter);
+	rhashtable_walk_exit(&iter);

Does this code correctly protect peertab->num_peers updates? Looking at homa_peer_gc():

net/homa/homa_peer.c:homa_peer_gc() {
    spin_lock_bh(&peertab->lock);
    ...
    if (rhashtable_remove_fast(&peertab->ht, &peer->ht_linkage,
                               ht_params) == 0) {
        homa_peer_release(peer);
        peertab->num_peers--;
        peer->ht_key.hnet->num_peers--;
    }
    ...
    spin_unlock_bh(&peertab->lock);
}

and homa_peer_get():

net/homa/homa_peer.c:homa_peer_get() {
    ...
    spin_lock_bh(&peertab->lock);
    other = rhashtable_lookup_get_insert_fast(&peertab->ht,
                                              &peer->ht_linkage, ht_params);
    ...
    peertab->num_peers++;
    key.hnet->num_peers++;
    ...
    spin_unlock_bh(&peertab->lock);
}

Both those functions hold peertab->lock while updating peertab->num_peers.

But homa_peer_free_net() drops peertab->lock before the rhashtable walk and doesn't reacquire it before decrementing peertab->num_peers. Can a concurrent homa_peer_get() call (for any namespace) produce lost updates to peertab->num_peers? The gc_stop_count mechanism prevents concurrent GC but doesn't prevent concurrent homa_peer_get().

Corrupted num_peers affects GC threshold decisions in the peertab->num_peers < peertab->gc_threshold check in homa_peer_gc().

Quoted 5 lines
net/homa/homa_peer.c new file +5 -0
+/**
+ * homa_peer_prefer_evict() - Given two peers, determine which one is
+ * a better candidate for eviction.
+ * @peertab:    Overall information used to manage peers.
+ * @peer1:      First peer.

net/homa/homa_peer.c line 142

Quoted 10 lines
net/homa/homa_peer.c new file +10 -0
+ * @peer2:      Second peer.
+ * Return:      True if @peer1 is a better candidate for eviction than @peer2.
+ */
+int homa_peer_prefer_evict(struct homa_peertab *peertab,
+			   struct homa_peer *peer1,
+			   struct homa_peer *peer2)
+{
+	/* Prefer a peer whose homa-net is over its limit; if both are either
+	 * over or under, then prefer the peer with the shortest idle time.
+	 */
                                                      ^^^^^^^^

This isn't a bug, but the comment says "shortest idle time" while the code returns peer1->access_jiffies < peer2->access_jiffies, which prefers the peer accessed earlier (longest idle time). Since eviction should prefer stale peers, the code is correct but the comment should say "longest idle time".

[ ... ]

net/homa/homa_peer.c line 324

Quoted 13 lines
net/homa/homa_peer.c new file +13 -0
+/**
+ * homa_peer_free() - Release any resources in a peer and free the homa_peer
+ * struct. Invoked by the RCU mechanism via homa_peer_release.
+ * @head:   Pointer to the rcu_head field of the peer to free.
+ */
+void homa_peer_free(struct rcu_head *head)
+{
+	struct homa_peer *peer;
+
+	peer = container_of(head, struct homa_peer, rcu_head);
+	dst_release(rcu_dereference(peer->dst));
+	kfree(peer);
+}

Is the RCU API correct here? homa_peer_free() is an RCU callback invoked via call_rcu from homa_peer_release():

net/homa/homa_peer.h:homa_peer_release() {
    if (refcount_dec_and_test(&peer->refs))
        call_rcu(&peer->rcu_head, homa_peer_free);
}

RCU callbacks run after the grace period, outside any RCU read-side critical section. Using rcu_dereference() without holding rcu_read_lock() triggers lockdep 'suspicious rcu_dereference_check() usage' warnings at runtime.

The peer is exclusively owned at this point (refcount was zero, grace period has passed). The same codebase uses the correct pattern in homa_peer_reset_dst():

net/homa/homa_peer.c:homa_peer_reset_dst() {
    ...
    dst_release(rcu_replace_pointer(peer->dst, dst, true));
    ...
}

Should this use rcu_dereference_protected(peer->dst, 1) instead of rcu_dereference(peer->dst)?

Quoted 19 lines
net/homa/homa_peer.c new file +19 -0
+/**
+ * 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)
+{
+	struct homa_peertab *peertab = hsk->homa->peertab;
+	struct homa_peer *peer, *other;
+	struct homa_peer_key key;
+

net/homa/homa_peer.c line 354

Quoted 10 lines
net/homa/homa_peer.c new file +10 -0
+	key.addr = *addr;
+	key.hnet = hsk->hnet;
+	rcu_read_lock();
+	peer = rhashtable_lookup(&peertab->ht, &key, ht_params);
+	if (peer) {
+		homa_peer_hold(peer);
+		peer->access_jiffies = jiffies;
+		rcu_read_unlock();
+		return peer;
+	}

Can this sequence race with homa_peer_gc()? The lookup uses rhashtable_lookup() under rcu_read_lock() but without peertab->lock. Then it calls homa_peer_hold() which uses refcount_inc():

net/homa/homa_peer.h:homa_peer_hold() {
    refcount_inc(&peer->refs);
}

Concurrently, homa_peer_gc() can:

net/homa/homa_peer.c:homa_peer_gc() {
    spin_lock_bh(&peertab->lock);
    ...
    if (rhashtable_remove_fast(&peertab->ht, &peer->ht_linkage,
                               ht_params) == 0) {
        homa_peer_release(peer);
        ...
    }
    ...
    spin_unlock_bh(&peertab->lock);
}
net/homa/homa_peer.h:homa_peer_release() {
    if (refcount_dec_and_test(&peer->refs))
        call_rcu(&peer->rcu_head, homa_peer_free);
}

If homa_peer_gc() removes the peer from the rhashtable and calls homa_peer_release() (dropping refcount to 0 and scheduling call_rcu) between the lookup and the hold, then refcount_inc() on a zero refcount triggers REFCOUNT_WARN and refuses the increment. This leaves the caller with an unref'd peer that will be freed after the RCU grace period.

The standard kernel pattern for RCU + rhashtable lookups is refcount_inc_not_zero() with retry or fallback if it returns false. The RCU read lock keeps the memory valid but doesn't prevent the refcount from reaching zero.

[ ... ]

Quoted 19 lines
net/homa/homa_peer.c new file +19 -0
+/**
+ * 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.
+ */
+void homa_peer_add_ack(struct homa_rpc *rpc)
+{
+	struct homa_peer *peer = rpc->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;
+	}

net/homa/homa_peer.c line 525

Quoted 10 lines
net/homa/homa_peer.c new file +10 -0
+
+	/* 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);
+}

Does this code leak kernel stack memory? The 'struct homa_ack_hdr ack' is declared on the stack without zeroing it. Only ack.acks (via memcpy) and ack.num_acks are initialized before calling homa_xmit_control().

Looking at how homa_xmit_control() uses the ack:

The function sets ack.common.type, sport, dport, and sender_id, but the following homa_common_hdr fields remain uninitialized: sequence, ack[3], doff, reserved1, window, checksum, and reserved2.

These uninitialized stack bytes are then memcpy'd into an skb by __homa_xmit_control() and transmitted on the network, leaking kernel stack memory.

Additionally, the homa_common_hdr comment for doff warns: "other values may cause some NICs (such as Intel E810-C) to drop outgoing packets when TCP hijacking is enabled", so garbage in doff can cause packet drops.

The homa_xmit_control() doc comment claims "the common header will be filled in by this function" but only 4 of 11 fields are actually set.

#11 lore raw

Re: [net-next,v17,05/14] net: homa: create homa_peer.h and homa_peer.c

Quoted 69 lines · Paolo Abeni
Quoted 26 lines
net/homa/homa_peer.c new file +25 -0
+/**
+ * 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_peer *peer;
+
+     spin_lock_bh(&peertab->lock);
+     peertab->gc_stop_count++;
+     spin_unlock_bh(&peertab->lock);
+
+     rhashtable_walk_enter(&peertab->ht, &iter);
+     rhashtable_walk_start(&iter);
+     while (1) {
+             peer = rhashtable_walk_next(&iter);
+             if (!peer)
+                     break;
+             if (IS_ERR(peer))
+                     continue;
+             if (peer->ht_key.hnet != hnet)

net/homa/homa_peer.c line 87

Quoted 10 lines
net/homa/homa_peer.c new file +10 -0
+                     continue;
+             if (rhashtable_remove_fast(&peertab->ht, &peer->ht_linkage,
+                                        ht_params) == 0) {
+                     homa_peer_release(peer);
+                     hnet->num_peers--;
+                     peertab->num_peers--;
+             }
+     }
+     rhashtable_walk_stop(&iter);
+     rhashtable_walk_exit(&iter);

Does this code correctly protect peertab->num_peers updates? Looking at homa_peer_gc():

net/homa/homa_peer.c:homa_peer_gc() {
    spin_lock_bh(&peertab->lock);
    ...
    if (rhashtable_remove_fast(&peertab->ht, &peer->ht_linkage,
                               ht_params) == 0) {
        homa_peer_release(peer);
        peertab->num_peers--;
        peer->ht_key.hnet->num_peers--;
    }
    ...
    spin_unlock_bh(&peertab->lock);
}

and homa_peer_get():

net/homa/homa_peer.c:homa_peer_get() {
    ...
    spin_lock_bh(&peertab->lock);
    other = rhashtable_lookup_get_insert_fast(&peertab->ht,
                                              &peer->ht_linkage, ht_params);
    ...
    peertab->num_peers++;
    key.hnet->num_peers++;
    ...
    spin_unlock_bh(&peertab->lock);
}

Both those functions hold peertab->lock while updating peertab->num_peers.

Quoted 8 lines

But homa_peer_free_net() drops peertab->lock before the rhashtable walk and doesn't reacquire it before decrementing peertab->num_peers. Can a concurrent homa_peer_get() call (for any namespace) produce lost updates to peertab->num_peers? The gc_stop_count mechanism prevents concurrent GC but doesn't prevent concurrent homa_peer_get().

Corrupted num_peers affects GC threshold decisions in the peertab->num_peers < peertab->gc_threshold check in homa_peer_gc().

Yep, this was a bug. I've changed the synchronization structure to hold the lock continuously in homa_peer_free_net. This also eliminates the need for gc_stop_count, so the code is now simpler.

Quoted 17 lines
Quoted 5 lines
net/homa/homa_peer.c new file +5 -0
+/**
+ * homa_peer_prefer_evict() - Given two peers, determine which one is
+ * a better candidate for eviction.
+ * @peertab:    Overall information used to manage peers.
+ * @peer1:      First peer.

net/homa/homa_peer.c line 142

Quoted 10 lines
net/homa/homa_peer.c new file +10 -0
+ * @peer2:      Second peer.
+ * Return:      True if @peer1 is a better candidate for eviction than @peer2.
+ */
+int homa_peer_prefer_evict(struct homa_peertab *peertab,
+                        struct homa_peer *peer1,
+                        struct homa_peer *peer2)
+{
+     /* Prefer a peer whose homa-net is over its limit; if both are either
+      * over or under, then prefer the peer with the shortest idle time.
+      */
                                                      ^^^^^^^^
Quoted 4 lines

This isn't a bug, but the comment says "shortest idle time" while the code returns peer1->access_jiffies < peer2->access_jiffies, which prefers the peer accessed earlier (longest idle time). Since eviction should prefer stale peers, the code is correct but the comment should say "longest idle time".

Fixed.

Quoted 30 lines

net/homa/homa_peer.c line 324

Quoted 13 lines
net/homa/homa_peer.c new file +13 -0
+/**
+ * homa_peer_free() - Release any resources in a peer and free the homa_peer
+ * struct. Invoked by the RCU mechanism via homa_peer_release.
+ * @head:   Pointer to the rcu_head field of the peer to free.
+ */
+void homa_peer_free(struct rcu_head *head)
+{
+     struct homa_peer *peer;
+
+     peer = container_of(head, struct homa_peer, rcu_head);
+     dst_release(rcu_dereference(peer->dst));
+     kfree(peer);
+}

Is the RCU API correct here? homa_peer_free() is an RCU callback invoked via call_rcu from homa_peer_release():

net/homa/homa_peer.h:homa_peer_release() {
    if (refcount_dec_and_test(&peer->refs))
        call_rcu(&peer->rcu_head, homa_peer_free);
}

RCU callbacks run after the grace period, outside any RCU read-side critical section. Using rcu_dereference() without holding rcu_read_lock() triggers lockdep 'suspicious rcu_dereference_check() usage' warnings at runtime.

The peer is exclusively owned at this point (refcount was zero, grace period has passed). The same codebase uses the correct pattern in homa_peer_reset_dst():

Quoted 8 lines
net/homa/homa_peer.c:homa_peer_reset_dst() {
    ...
    dst_release(rcu_replace_pointer(peer->dst, dst, true));
    ...
}

Should this use rcu_dereference_protected(peer->dst, 1) instead of rcu_dereference(peer->dst)?

I have switched to rcu_dereference_protected.

Quoted 63 lines
Quoted 19 lines
net/homa/homa_peer.c new file +19 -0
+/**
+ * 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)
+{
+     struct homa_peertab *peertab = hsk->homa->peertab;
+     struct homa_peer *peer, *other;
+     struct homa_peer_key key;
+

net/homa/homa_peer.c line 354

Quoted 10 lines
net/homa/homa_peer.c new file +10 -0
+     key.addr = *addr;
+     key.hnet = hsk->hnet;
+     rcu_read_lock();
+     peer = rhashtable_lookup(&peertab->ht, &key, ht_params);
+     if (peer) {
+             homa_peer_hold(peer);
+             peer->access_jiffies = jiffies;
+             rcu_read_unlock();
+             return peer;
+     }

Can this sequence race with homa_peer_gc()? The lookup uses rhashtable_lookup() under rcu_read_lock() but without peertab->lock. Then it calls homa_peer_hold() which uses refcount_inc():

net/homa/homa_peer.h:homa_peer_hold() {
    refcount_inc(&peer->refs);
}

Concurrently, homa_peer_gc() can:

net/homa/homa_peer.c:homa_peer_gc() {
    spin_lock_bh(&peertab->lock);
    ...
    if (rhashtable_remove_fast(&peertab->ht, &peer->ht_linkage,
                               ht_params) == 0) {
        homa_peer_release(peer);
        ...
    }
    ...
    spin_unlock_bh(&peertab->lock);
}
net/homa/homa_peer.h:homa_peer_release() {
    if (refcount_dec_and_test(&peer->refs))
        call_rcu(&peer->rcu_head, homa_peer_free);
}

If homa_peer_gc() removes the peer from the rhashtable and calls homa_peer_release() (dropping refcount to 0 and scheduling call_rcu) between the lookup and the hold, then refcount_inc() on a zero refcount triggers REFCOUNT_WARN and refuses the increment. This leaves the caller with an unref'd peer that will be freed after the RCU grace period.

Quoted 4 lines

The standard kernel pattern for RCU + rhashtable lookups is refcount_inc_not_zero() with retry or fallback if it returns false. The RCU read lock keeps the memory valid but doesn't prevent the refcount from reaching zero.

Yep, there was a race. I switched to refcount_inc_not_zero as suggested.

Quoted 23 lines
Quoted 23 lines
net/homa/homa_peer.c new file +23 -0
+/**
+ * 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.
+ */
+void homa_peer_add_ack(struct homa_rpc *rpc)
+{
+     struct homa_peer *peer = rpc->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.
+      */
Quoted 8 lines

net/homa/homa_peer.c line 525

Quoted 6 lines
net/homa/homa_peer.c new file +6 -0
+     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);
+}

Does this code leak kernel stack memory?

Yes, it does. I have fixed this everywhere, so there are no uninitialized fields in control packets.

I'm pretty impressed at the ability of AI tools to find subtle bugs.

maintainer
#12 lore raw

Re: [net-next,v17,05/14] net: homa: create homa_peer.h and homa_peer.c

Quoted 1 line · John Ousterhout

I'm pretty impressed at the ability of AI tools to find subtle bugs.

Note that you can use the AI prompt locally, see:

https://github.com/masoncl/review-prompts

/P

#13 lore raw

PATCH v17 6/14 net: homa: create homa_sock.h and homa_sock.c

In reply to John Ousterhout

These files provide functions for managing the state that Homa keeps for each open Homa socket.

---
Changes for v16:
* Add error_msg field to struct homa_sock (for HOMAIOCINFO)
* Acquire RCU read lock in homa_sock_wakeup_wmem for safety
* Refactor homa_sock_init to reduce time in atomic context

Changes for v11:
* Clean up sparse annotations

Changes for v10:
* Revise sparse annotations to eliminate __context__ definition
* Replace __u16 with u16, __u8 with u8, etc.
* Use the destroy function from struct proto properly (fixes races in socket cleanup)

Changes for v9:
* Add support for homa_net objects; there is now a single socket table shared across all network namespaces
* Set SOCK_RCU_FREE in homa_sock_init, not homa_sock_shutdown
* Various name improvements (e.g. use "alloc" instead of "new" for functions that allocate memory)

Changes for v8:
* Update for new homa_pool APIs

Changes for v7:
* Refactor homa_sock_start_scan etc. (take a reference on the socket, so homa_socktab::active_scans and struct homa_socktab_links are no longer needed; encapsulate RCU usage entirely in homa_sock.c).
* Add functions for tx memory accounting
* Refactor waiting mechanism for incoming messages
* Add hsk->is_server, setsockopt SO_HOMA_SERVER
* Remove "lock_slow" functions, which don't add functionality in this patch series
* Remove locker argument from locking functions
* Use u64 and __u64 properly
* Take a reference to the socket in homa_sock_find

---
 net/homa/homa_sock.c | 448 +++++++++++++++++++++++++++++++++++++++++++
 net/homa/homa_sock.h | 424 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 872 insertions(+)
 create mode 100644 net/homa/homa_sock.c
 create mode 100644 net/homa/homa_sock.h
net/homa/homa_sock.c new file +448 -0
new file mode 100644
index 000000000000..758906e975a4
@@ -0,0 +1,448 @@
+// 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);
+	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 = -1;
+
+	return homa_socktab_next(scan);
+}
+
+/**
+ * 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.
+ *             Sockets are not returned in any particular order. It's
+ *             possible that the returned socket has been destroyed.
+ */
+struct homa_sock *homa_socktab_next(struct homa_socktab_scan *scan)
+{
+	struct hlist_head *bucket;
+	struct hlist_node *next;
+
+	rcu_read_lock();
+	if (scan->hsk) {
+		sock_put(&scan->hsk->sock);
+		next = rcu_dereference(hlist_next_rcu(&scan->hsk->socktab_links));
+		if (next)
+			goto success;
+	}
+	for (scan->current_bucket++;
+	     scan->current_bucket < HOMA_SOCKTAB_BUCKETS;
+	     scan->current_bucket++) {
+		bucket = &scan->socktab->buckets[scan->current_bucket];
+		next = rcu_dereference(hlist_first_rcu(bucket));
+		if (next)
+			goto success;
+	}
+	scan->hsk = NULL;
+	rcu_read_unlock();
+	return NULL;
+
+success:
+	scan->hsk = hlist_entry(next, struct homa_sock, socktab_links);
+	sock_hold(&scan->hsk->sock);
+	rcu_read_unlock();
+	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;
+	}
+}
+
+/**
+ * homa_sock_init() - Constructor for homa_sock objects. This function
+ * initializes only the parts of the socket that are owned by Homa.
+ * @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;
+
+	/* Initialize fields outside the Homa part. */
+	hsk->sock.sk_sndbuf = homa->wmem_max;
+	sock_set_flag(&hsk->inet.sk, SOCK_RCU_FREE);
+
+	/* 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 Homa-specific fields. We can initialize everything
+	 * except the port and hash table links without acquiring the
+	 * socket lock.
+	 */
+	hsk->homa = homa;
+	hsk->hnet = hnet;
+	hsk->buffer_pool = buffer_pool;
+	hsk->inet.inet_num = hsk->port;
+	hsk->inet.inet_sport = htons(hsk->port);
+
+	hsk->is_server = false;
+	hsk->shutdown = false;
+	hsk->ip_header_length = (hsk->inet.sk.sk_family == AF_INET) ?
+				sizeof(struct iphdr) : sizeof(struct ipv6hdr);
+	spin_lock_init(&hsk->lock);
+	atomic_set(&hsk->protect_count, 0);
+	INIT_LIST_HEAD(&hsk->active_rpcs);
+	INIT_LIST_HEAD(&hsk->dead_rpcs);
+	hsk->dead_skbs = 0;
+	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);
+	}
+
+	/* 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);
+			hsk->shutdown = true;
+			hsk->homa = NULL;
+			result = -EADDRNOTAVAIL;
+			goto error;
+		}
+		spin_unlock_bh(&socktab->write_lock);
+		cond_resched();
+		spin_lock_bh(&socktab->write_lock);
+	}
+	hsk->port = hnet->prev_default_port;
+	hlist_add_head_rcu(&hsk->socktab_links,
+			   &socktab->buckets[homa_socktab_bucket(hnet,
+								 hsk->port)]);
+	spin_unlock_bh(&socktab->write_lock);
+	return result;
+
+error:
+	homa_pool_free(buffer_pool);
+	return result;
+}
+
+/*
+ * homa_sock_unlink() - Unlinks a socket from its socktab and does
+ * related cleanups. Once this method returns, the socket will not be
+ * discoverable through the socktab.
+ * @hsk:  Socket to unlink.
+ */
+void homa_sock_unlink(struct homa_sock *hsk)
+{
+	struct homa_socktab *socktab = hsk->homa->socktab;
+
+	spin_lock_bh(&socktab->write_lock);
+	hlist_del_rcu(&hsk->socktab_links);
+	spin_unlock_bh(&socktab->write_lock);
+}
+
+/**
+ * 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_interest *interest;
+	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).
+	 * 2. Remove the socket from its socktab: this ensures that
+	 *    incoming packets for the socket will be dropped.
+	 * 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;
+	homa_sock_unlink(hsk);
+	homa_sock_unlock(hsk);
+
+	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);
+	}
+	rcu_read_unlock();
+
+	homa_sock_lock(hsk);
+	while (!list_empty(&hsk->interests)) {
+		interest = list_first_entry(&hsk->interests,
+					    struct homa_interest, links);
+		list_del_init(&interest->links);
+		atomic_set_release(&interest->ready, 1);
+		wake_up(&interest->wait_queue);
+	}
+	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, true);
+
+	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;
+	}
+	hlist_del_rcu(&hsk->socktab_links);
+	hsk->port = port;
+	hsk->inet.inet_num = port;
+	hsk->inet.inet_sport = htons(hsk->port);
+	hlist_add_head_rcu(&hsk->socktab_links,
+			   &socktab->buckets[homa_socktab_bucket(hnet, port)]);
+	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 *hsk;
+
+	rcu_read_lock();
+	hlist_for_each_entry_rcu(hsk, &hnet->homa->socktab->buckets[bucket],
+				 socktab_links) {
+		if (hsk->port == port && hsk->hnet == hnet) {
+			result = hsk;
+			sock_hold(&hsk->sock);
+			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(SOCK_NOSPACE, &hsk->sock.sk_socket->flags);
+	result = wait_event_interruptible_timeout(*sk_sleep(&hsk->sock),
+				homa_sock_wmem_avl(hsk) || hsk->shutdown,
+				timeo);
+	if (signal_pending(current))
+		return -EINTR;
+	if (result == 0)
+		return -EWOULDBLOCK;
+	return 0;
+}
net/homa/homa_sock.h new file +424 -0

424 lines not on this page · raw message

Signature · 1 line
2.43.0
#14 lore raw

PATCH v17 7/14 net: homa: create homa_interest.h and homa_interest.c

In reply to John Ousterhout

These files implement the homa_interest struct, which is used to wait for incoming messages.

---
Changes for v14:
* Fix race in homa_wait_shared (an RPC could get lost if it became ready at the same time that homa_interest_wait returned with an error)
* Remove nonblocking parameter from homa_interest_wait (handle this elsewhere)

Changes for v11:
* Clean up sparse annotations

Changes for v10: none

Changes for v9:
* Remove unused field homa_interest->core

---
 net/homa/homa_interest.c | 114 +++++++++++++++++++++++++++++++++++++++
 net/homa/homa_interest.h |  93 ++++++++++++++++++++++++++++++++
 2 files changed, 207 insertions(+)
 create mode 100644 net/homa/homa_interest.c
 create mode 100644 net/homa/homa_interest.h
net/homa/homa_interest.c new file +114 -0
new file mode 100644
index 000000000000..6daeedd21309
@@ -0,0 +1,114 @@
+// 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"
+
+/**
+ * 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->ready, 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->ready, 0);
+	interest->blocked = 0;
+	init_waitqueue_head(&interest->wait_queue);
+	interest->hsk = rpc->hsk;
+	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 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.
+ */
+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->ready) != 0)
+			goto done;
+
+		/* See if we can cleanup dead RPCs while waiting. */
+		if (homa_rpc_reap(hsk, false) != 0)
+			continue;
+
+		break;
+	}
+
+	interest->blocked = 1;
+	wait_err = wait_event_interruptible_exclusive(interest->wait_queue,
+			atomic_read_acquire(&interest->ready) != 0);
+	if (wait_err == -ERESTARTSYS)
+		result = -EINTR;
+
+done:
+	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) {
+		atomic_set_release(&rpc->private_interest->ready, 1);
+		wake_up(&rpc->private_interest->wait_queue);
+	}
+}
+
net/homa/homa_interest.h new file +93 -0

93 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#15 lore raw

Re: [net-next,v17,07/14] net: homa: create homa_interest.h and homa_interest.c

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.

For local reproduction steps see https://netdev-ai.bots.linux.dev/ai-local.html
---
net: homa: create homa_interest.h and homa_interest.c

These files implement the homa_interest struct, which is used to wait for incoming messages.

Quoted 5 lines
net/homa/homa_interest.c new file +0 -0
new file mode 100644
index 000000000000..6daeedd21309

[ ... ]

Quoted 6 lines
net/homa/homa_interest.h new file +0 -0
new file mode 100644
index 000000000000..d9f932960fd8
@@ -0,0 +1,93 @@

[ ... ]

net/homa/homa_interest.h line 69

Quoted 12 lines
net/homa/homa_interest.h new file +12 -0
+/**
+ * homa_interest_unlink_shared() - Remove an interest from the list for a
+ * socket. 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_shared.
+ */
+static inline void homa_interest_unlink_shared(struct homa_interest *interest)
+	__must_hold(hsk->lock)
+{
+	list_del_init(&interest->links);
+}

The __must_hold annotation references 'hsk->lock' but 'hsk' is not in scope. This will cause sparse to report an error when checking with 'make C=1'. Should this be '__must_hold(interest->hsk->lock)' to match the pattern used in homa_interest_unlink_private?

#16 lore raw

PATCH v17 8/14 net: homa: create homa_rpc.h and homa_rpc.c

In reply to John Ousterhout

These files provide basic functions for managing remote procedure calls, which are the fundamental entities managed by Homa. Each RPC consists of a request message from a client to a server, followed by a response message returned from the server to the client.

---
Changes for v16:
* Retain retransmitted packets until homa_rpc_reap (to ensure that RPCs don't get reaped with retransmitted packets still in the tx pipeline)
* Fix deadlock over hsk->protect_count in homa_rpc_reap
* Fix bugs in wmem management
* Use set_bit and clear_bit for flag bits
* Use refcount_t instead of atomic_t for reference counts
* Replace inline code with homa_rpc_lock_preempt function
* Reduce stack usage in homa_rpc_reap
* Use consume_skb and kfree_skb_reason instead of kfree_skb
* Add homa_rpc_get_info() for use in HOMAIOCINFO
* Set hsk->error_msg

Changes for v14:
* Add msgout.first_not_tx field needed by homa_rpc_tx_end function (better abstraction)

Changes for v11:
* Cleanup and simplify use of RPC reference counts.
* Rework the mechanism for waking up RPCs that stalled waiting for buffer pool space.

Changes for v10:
* Replace __u16 with u16, __u8 with u8, etc.
* Improve documentation
* Revise sparse annotations to eliminate __context__ definition
* Use kzalloc instead of __GFP_ZERO
* Fix issues from xmastree, sparse, etc.

Changes for v9:
* Eliminate reap.txt; move its contents into code as a comment in homa_rpc_reap
* Various name improvements (e.g. use "alloc" instead of "new" for functions that allocate memory)
* Add support for homa_net objects
* Use new homa_clock abstraction layer

Changes for v8:
* Updates to reflect pacer refactoring

Changes for v7:
* Implement accounting for bytes in tx skbs
* Fix potential races related to homa->active_rpcs
* Refactor waiting mechanism for incoming packets: simplify wait criteria and use standard Linux mechanisms for waiting
* Add reference counting for RPCs (homa_rpc_hold, homa_rpc_put)
* Remove locker argument from locking functions
* Rename homa_rpc_free to homa_rpc_end
* Use u64 and __u64 properly
* Use __skb_queue_purge instead of skb_queue_purge
* Use __GFP_ZERO in kmalloc calls
* Eliminate spurious RCU usage

---
 net/homa/homa_impl.h |   7 +
 net/homa/homa_rpc.c  | 698 +++++++++++++++++++++++++++++++++++++++++++
 net/homa/homa_rpc.h  | 532 +++++++++++++++++++++++++++++++++
 3 files changed, 1237 insertions(+)
 create mode 100644 net/homa/homa_rpc.c
 create mode 100644 net/homa/homa_rpc.h
net/homa/homa_impl.h +7 -0
index f55a7b80431d..adedc8757e5b 100644
@@ -362,6 +362,13 @@ static inline bool homa_make_header_avl(struct sk_buff *skb)
 
 extern unsigned int homa_net_id;
 
+void     homa_rpc_handoff(struct homa_rpc *rpc);
+int      homa_xmit_control(enum homa_packet_type type, void *contents,
+			   size_t length, struct homa_rpc *rpc);
+
+int      homa_message_in_init(struct homa_rpc *rpc, int unsched);
+void     homa_xmit_data(struct homa_rpc *rpc);
+
 /**
  * homa_net() - Return the struct homa_net associated with a particular
  * struct net.
net/homa/homa_rpc.c new file +698 -0

698 lines not on this page · raw message

net/homa/homa_rpc.h new file +532 -0

532 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#17 lore raw

Re: [net-next,v17,08/14] net: homa: create homa_rpc.h and homa_rpc.c

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.

For local reproduction steps see https://netdev-ai.bots.linux.dev/ai-local.html
---
net: homa: create homa_rpc.h and homa_rpc.c

These files provide basic functions for managing remote procedure calls, which are the fundamental entities managed by Homa. Each RPC consists of a request message from a client to a server, followed by a response message returned from the server to the client.

Quoted 4 lines
net/homa/homa_impl.h +0 -0
index f55a7b80431d..adedc8757e5b 100644

[ ... ]

Quoted 6 lines
net/homa/homa_rpc.c new file +0 -0
new file mode 100644
index 000000000000..9d4b05149805
@@ -0,0 +1,698 @@

[ ... ]

Quoted 38 lines
net/homa/homa_rpc.c new file +38 -0
+/**
+ * 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.
+ * @created:  Will be set to 1 if a new RPC was created and 0 if an
+ *            existing RPC was found.
+ *
+ * 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, int *created)
+	__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->peer->addr, source)) {

net/homa/homa_rpc.c line 138

Quoted 10 lines
net/homa/homa_rpc.c new file +10 -0
+			/* RPC already exists; just return it instead
+			 * of creating a new RPC.
+			 */
+			*created = 0;
+			return srpc;
+		}
+	}
+
+	/* Initialize fields that don't require the socket lock. */
+	srpc = kzalloc(sizeof(*srpc), GFP_ATOMIC);

In v6, Paolo Abeni suggested avoiding GFP_ATOMIC by doing the allocation outside the bucket lock. The current code allocates while holding the bucket lock (acquired above), which forces GFP_ATOMIC.

Paolo's suggestion was to do a lockless RCU lookup first, and only if that fails, allocate outside the lock with GFP_KERNEL. Could this allocation be moved outside the lock to use GFP_KERNEL instead?

Reference: https://lore.kernel.org/netdev/[email protected]/

Additionally, in a later review on January 28, Paolo and Eric Dumazet suggested using SLAB_TYPESAFE_BY_RCU with a dedicated kmem_cache for RPC allocations to improve performance and handle high RPC rates.

This approach would allow lockless RCU lookups and faster reclamation. Paolo referenced tcp established socket lookup as an example:

"Have a look at tcp established socket lookup and the SLAB_TYPESAFE_BY_RCU
flag usage for slab-based allocations. A combo of such flag for RPC allocation (using a dedicated kmem_cache) and RCU lookup should improve consistently the performances, with a consolidate code layout and no unmanageable problems with large number of objects waiting for the grace period."

The current code still uses plain kzalloc/kfree without a dedicated cache. Would it make sense to implement this optimization?

Reference: https://lore.kernel.org/netdev/[email protected]/

Quoted 4 lines
net/homa/homa_rpc.c new file +4 -0
+	if (!srpc) {
+		err = -ENOMEM;
+		goto error;
+	}

[ ... ]

net/homa/homa_rpc.c line 191

Quoted 7 lines
net/homa/homa_rpc.c new file +7 -0
+error:
+	homa_bucket_unlock(bucket, id);
+	if (srpc && srpc->peer)
+		homa_peer_release(srpc->peer);
+	kfree(srpc);
+	return ERR_PTR(err);
+}

[ ... ]

In the v6 review thread, Paolo and Eric raised concerns about SKB freeing costs and suggested optimizations. Eric noted that proper software GRO significantly reduces SKB count using napi_get_frags() and napi_reuse_skb().

Paolo also suggested using deferred SKB freeing (skb_attempt_defer_free) to reduce the cost. While you mentioned that GRO is implemented in the full Homa but was left out of the initial patch series, would it be beneficial to include at least some of these optimizations in this initial submission?

Reference: https://lore.kernel.org/netdev/[email protected]/

[ ... ]

Quoted 5 lines
net/homa/homa_rpc.h new file +0 -0
new file mode 100644
index 000000000000..98bfd389f5b1

[ ... ]

Quoted 3 lines

+/**
+ * homa_protect_rpcs() - Ensures that no RPCs will be reaped for a given
+ * socket until homa_sock_unprotect is called. Typically used by functions

This isn't a bug, but the comment references 'homa_sock_unprotect' which doesn't exist. Should this be 'homa_unprotect_rpcs'?

Quoted 15 lines

+ * 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.
+ */

net/homa/homa_rpc.h new file +5 -0
+static inline int homa_protect_rpcs(struct homa_sock *hsk)
+{
+	int result;
+
+	homa_sock_lock(hsk);

net/homa/homa_rpc.h line 472

Quoted 10 lines
net/homa/homa_rpc.h new file +10 -0
+	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_sock_protect(), so that RPCs can once again be reaped.

This isn't a bug, but the comment references 'homa_sock_protect()' which doesn't exist. Should this be 'homa_protect_rpcs()'?

Quoted 10 lines

+ * @hsk: Socket whose RPCs should be unprotected.
+ */

net/homa/homa_rpc.h new file +8 -0
+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

[ ... ]

net/homa/homa_rpc.h line 507

Quoted 9 lines
net/homa/homa_rpc.h new file +9 -0
+/**
+ * homa_rpc_put() - Release a reference on an RPC (cancels the effect of
+ * a previous call to homa_rpc_put).
+ * @rpc:      RPC to release.
+ */
+static inline void homa_rpc_put(struct homa_rpc *rpc)
+{
+	refcount_dec(&rpc->refs);
+}

This isn't a bug, but the kdoc comment says "cancels the effect of a previous call to homa_rpc_put" which is self-referential. Should this say "cancels the effect of a previous call to homa_rpc_hold" instead?

The function decrements rpc->refs via refcount_dec(), which is the inverse operation of homa_rpc_hold() that calls refcount_inc(). This misleading comment could confuse maintainers about the refcount lifecycle.

[ ... ]

#18 lore raw

Re: [net-next,v17,08/14] net: homa: create homa_rpc.h and homa_rpc.c

Quoted 55 lines · Paolo Abeni

[ ... ]

Quoted 38 lines
net/homa/homa_rpc.c new file +38 -0
+/**
+ * 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.
+ * @created:  Will be set to 1 if a new RPC was created and 0 if an
+ *            existing RPC was found.
+ *
+ * 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, int *created)
+     __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->peer->addr, source)) {

net/homa/homa_rpc.c line 138

Quoted 10 lines
net/homa/homa_rpc.c new file +10 -0
+                     /* RPC already exists; just return it instead
+                      * of creating a new RPC.
+                      */
+                     *created = 0;
+                     return srpc;
+             }
+     }
+
+     /* Initialize fields that don't require the socket lock. */
+     srpc = kzalloc(sizeof(*srpc), GFP_ATOMIC);

In v6, Paolo Abeni suggested avoiding GFP_ATOMIC by doing the allocation outside the bucket lock. The current code allocates while holding the bucket lock (acquired above), which forces GFP_ATOMIC.

Quoted 5 lines

Paolo's suggestion was to do a lockless RCU lookup first, and only if that fails, allocate outside the lock with GFP_KERNEL. Could this allocation be moved outside the lock to use GFP_KERNEL instead?

Reference: https://lore.kernel.org/netdev/[email protected]/

This code is invoked at SoftIRQ level, so the allocation must use GFP_ATOMIC even if a lockless RCU lookup is used. In previous patch versions I've discussed why Homa does not use RCU for homa_rpc objects.

Quoted 14 lines

Additionally, in a later review on January 28, Paolo and Eric Dumazet suggested using SLAB_TYPESAFE_BY_RCU with a dedicated kmem_cache for RPC allocations to improve performance and handle high RPC rates.

This approach would allow lockless RCU lookups and faster reclamation. Paolo referenced tcp established socket lookup as an example:

"Have a look at tcp established socket lookup and the SLAB_TYPESAFE_BY_RCU
flag usage for slab-based allocations. A combo of such flag for RPC allocation (using a dedicated kmem_cache) and RCU lookup should improve consistently the performances, with a consolidate code layout and no unmanageable problems with large number of objects waiting for the grace period."

Quoted 4 lines

The current code still uses plain kzalloc/kfree without a dedicated cache. Would it make sense to implement this optimization?

Reference: https://lore.kernel.org/netdev/[email protected]/

I tried using a kmem_cache, but it made performance slightly worse:
average allocation time for a struct homa_rpc increased from about 380 cycles to about 400 cycles in my benchmarks. Since there is no performance advantage to using kmem_cache I removed it.

I'm surprised how long allocation takes: 400 cycles seems like a *lot* if there are per-cpu caches of the right size. Presumably no synchronization is needed and all the function has to do in the normal case is pull the top entry off a list.

Quoted 18 lines
Quoted 5 lines
net/homa/homa_rpc.c new file +4 -0
+     if (!srpc) {
+             err = -ENOMEM;
+             goto error;
+     }

[ ... ]

Quoted 7 lines
net/homa/homa_rpc.c new file +7 -0
+error:
+     homa_bucket_unlock(bucket, id);
+     if (srpc && srpc->peer)
+             homa_peer_release(srpc->peer);
+     kfree(srpc);
+     return ERR_PTR(err);
+}

[ ... ]

Quoted 3 lines

In the v6 review thread, Paolo and Eric raised concerns about SKB freeing costs and suggested optimizations. Eric noted that proper software GRO significantly reduces SKB count using napi_get_frags() and napi_reuse_skb().

Unfortunately napi_reuse_skb is not currently exported. My understanding is that I need to wait until Homa GRO is upstreamed before I can request that it be exported. Once that happens I'll be happy to use napi_reuse_skb.

Quoted 7 lines

Paolo also suggested using deferred SKB freeing (skb_attempt_defer_free) to reduce the cost. While you mentioned that GRO is implemented in the full Homa but was left out of the initial patch series, would it be beneficial to include at least some of these optimizations in this initial submission?

Reference: https://lore.kernel.org/netdev/[email protected]/

When I asked ChatGPT about homa_attempt_defer_free it said that it only works if the skb has no dst, no destructor, and no skb_nfct. I'm a bit unsure how to proceed. Is homa_attempt_defer_free only intended for incoming packets? If so, then presumably there is no dst? But what about the other fields? Do I need to do something to clean them up before calling homa_attempt_defer_free?

Quoted 10 lines

[ ... ]

Quoted 5 lines
net/homa/homa_rpc.h new file +0 -0
new file mode 100644
index 000000000000..98bfd389f5b1

[ ... ]

Quoted 6 lines
Quoted 3 lines

+/**
+ * homa_protect_rpcs() - Ensures that no RPCs will be reaped for a given
+ * socket until homa_sock_unprotect is called. Typically used by functions

This isn't a bug, but the comment references 'homa_sock_unprotect' which doesn't exist. Should this be 'homa_unprotect_rpcs'?

Fixed.

Quoted 20 lines
Quoted 20 lines

+ * 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.
+ */

net/homa/homa_rpc.h new file +10 -0
+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;
Quoted 8 lines

net/homa/homa_rpc.h line 472

Quoted 5 lines
net/homa/homa_rpc.h new file +5 -0
+}
+
+/**
+ * homa_unprotect_rpcs() - Cancel the effect of a previous call to
+ * homa_sock_protect(), so that RPCs can once again be reaped.

This isn't a bug, but the comment references 'homa_sock_protect()' which doesn't exist. Should this be 'homa_protect_rpcs()'?

Fixed.

Quoted 16 lines

[ ... ]

net/homa/homa_rpc.h line 507

Quoted 9 lines
net/homa/homa_rpc.h new file +9 -0
+/**
+ * homa_rpc_put() - Release a reference on an RPC (cancels the effect of
+ * a previous call to homa_rpc_put).
+ * @rpc:      RPC to release.
+ */
+static inline void homa_rpc_put(struct homa_rpc *rpc)
+{
+     refcount_dec(&rpc->refs);
+}

This isn't a bug, but the kdoc comment says "cancels the effect of a previous call to homa_rpc_put" which is self-referential. Should this say "cancels the effect of a previous call to homa_rpc_hold" instead?

Quoted 3 lines

The function decrements rpc->refs via refcount_dec(), which is the inverse operation of homa_rpc_hold() that calls refcount_inc(). This misleading comment could confuse maintainers about the refcount lifecycle.

Fixed.

maintainer
#19 lore raw

Re: [net-next,v17,08/14] net: homa: create homa_rpc.h and homa_rpc.c

Quoted 14 lines · John Ousterhout
Quoted 13 lines · Paolo Abeni

This approach would allow lockless RCU lookups and faster reclamation. Paolo referenced tcp established socket lookup as an example:

"Have a look at tcp established socket lookup and the SLAB_TYPESAFE_BY_RCU
flag usage for slab-based allocations. A combo of such flag for RPC allocation (using a dedicated kmem_cache) and RCU lookup should improve consistently the performances, with a consolidate code layout and no unmanageable problems with large number of objects waiting for the grace period."

The current code still uses plain kzalloc/kfree without a dedicated cache. Would it make sense to implement this optimization?

Quoted 6 lines
Quoted 1 line

Reference: https://lore.kernel.org/netdev/[email protected]/

I tried using a kmem_cache, but it made performance slightly worse:
average allocation time for a struct homa_rpc increased from about 380 cycles to about 400 cycles in my benchmarks. Since there is no performance advantage to using kmem_cache I removed it.

So kzalloc/kfree is faster than kmem_cache?!? That is quite unexpected, possibly the kmem_cache pointer ends up on a contended cacheline?!? I guess it would be useful to understand the extra overhead, as kmalloc is basically another layer on top of kmem_cache.

Quoted 23 lines

I'm surprised how long allocation takes: 400 cycles seems like a *lot* if there are per-cpu caches of the right size. Presumably no synchronization is needed and all the function has to do in the normal case is pull the top entry off a list.

Quoted 18 lines
Quoted 5 lines
net/homa/homa_rpc.c new file +4 -0
+     if (!srpc) {
+             err = -ENOMEM;
+             goto error;
+     }

[ ... ]

Quoted 7 lines
net/homa/homa_rpc.c new file +7 -0
+error:
+     homa_bucket_unlock(bucket, id);
+     if (srpc && srpc->peer)
+             homa_peer_release(srpc->peer);
+     kfree(srpc);
+     return ERR_PTR(err);
+}

[ ... ]

Quoted 8 lines
Quoted 3 lines

In the v6 review thread, Paolo and Eric raised concerns about SKB freeing costs and suggested optimizations. Eric noted that proper software GRO significantly reduces SKB count using napi_get_frags() and napi_reuse_skb().

Unfortunately napi_reuse_skb is not currently exported. My understanding is that I need to wait until Homa GRO is upstreamed before I can request that it be exported. Once that happens I'll be happy to use napi_reuse_skb.

Ok

Quoted 5 lines
Quoted 5 lines

Paolo also suggested using deferred SKB freeing (skb_attempt_defer_free) to reduce the cost. While you mentioned that GRO is implemented in the full Homa but was left out of the initial patch series, would it be beneficial to include at least some of these optimizations in this initial submission?

Quoted 8 lines
Quoted 1 line

Reference: https://lore.kernel.org/netdev/[email protected]/

When I asked ChatGPT about homa_attempt_defer_free it said that it only works if the skb has no dst, no destructor, and no skb_nfct. I'm a bit unsure how to proceed. Is homa_attempt_defer_free only intended for incoming packets? If so, then presumably there is no dst? But what about the other fields? Do I need to do something to clean them up before calling homa_attempt_defer_free?

skb_attempt_defer_free() usage is intended for the RX path only.

Incoming packets get state (dst, extensions, ct...) attached in the rx path before reaching the socket. You should free/release the state, if possible, before inserting the skb into the receive queue, so that you could defer free them after read.

/P

#20 lore raw

Re: [net-next,v17,08/14] net: homa: create homa_rpc.h and homa_rpc.c

Quoted 15 lines · Paolo Abeni
Quoted 7 lines
Quoted 7 lines

[ ... ]
Paolo also suggested using deferred SKB freeing (skb_attempt_defer_free) to reduce the cost. While you mentioned that GRO is implemented in the full Homa but was left out of the initial patch series, would it be beneficial to include at least some of these optimizations in this initial submission?

Quoted 8 lines
Quoted 1 line

Reference: https://lore.kernel.org/netdev/[email protected]/

When I asked ChatGPT about homa_attempt_defer_free it said that it only works if the skb has no dst, no destructor, and no skb_nfct. I'm a bit unsure how to proceed. Is homa_attempt_defer_free only intended for incoming packets? If so, then presumably there is no dst? But what about the other fields? Do I need to do something to clean them up before calling homa_attempt_defer_free?

Quoted 6 lines

skb_attempt_defer_free() usage is intended for the RX path only.

Incoming packets get state (dst, extensions, ct...) attached in the rx path before reaching the socket. You should free/release the state, if possible, before inserting the skb into the receive queue, so that you could defer free them after read.

I have modified Homa to use skb_attempt_defer_free, and this made a significant difference in the throughput of the critical path copying data from skbs to user space. Thanks for the suggestion.

However, skb_attempt_defer_free is not currently exported, so the patch series will now include an EXPORT_SYMBOL line for that in skbuff.c; hopefully that will be OK...

-John-

maintainer
#21 lore raw

Re: [net-next,v17,08/14] net: homa: create homa_rpc.h and homa_rpc.c

Quoted 23 lines · John Ousterhout
Quoted 15 lines · Paolo Abeni
Quoted 7 lines
Quoted 7 lines

[ ... ]
Paolo also suggested using deferred SKB freeing (skb_attempt_defer_free) to reduce the cost. While you mentioned that GRO is implemented in the full Homa but was left out of the initial patch series, would it be beneficial to include at least some of these optimizations in this initial submission?

Quoted 8 lines
Quoted 1 line

Reference: https://lore.kernel.org/netdev/[email protected]/

When I asked ChatGPT about homa_attempt_defer_free it said that it only works if the skb has no dst, no destructor, and no skb_nfct. I'm a bit unsure how to proceed. Is homa_attempt_defer_free only intended for incoming packets? If so, then presumably there is no dst? But what about the other fields? Do I need to do something to clean them up before calling homa_attempt_defer_free?

Quoted 6 lines

skb_attempt_defer_free() usage is intended for the RX path only.

Incoming packets get state (dst, extensions, ct...) attached in the rx path before reaching the socket. You should free/release the state, if possible, before inserting the skb into the receive queue, so that you could defer free them after read.

Quoted 7 lines

I have modified Homa to use skb_attempt_defer_free, and this made a significant difference in the throughput of the critical path copying data from skbs to user space. Thanks for the suggestion.

However, skb_attempt_defer_free is not currently exported, so the patch series will now include an EXPORT_SYMBOL line for that in skbuff.c; hopefully that will be OK...

Yes, it is as long as such export is bundled with the module user - i.e. this series.

Cheers,

Paolo

#22 lore raw

PATCH v17 9/14 net: homa: create homa_outgoing.c

In reply to John Ousterhout

This file does most of the work of transmitting outgoing messages. It is also responsible for copying data from user space into skbs.

---
Changes for v16:
* Set hsk->error_msg (for HOMAIOCINFO)
* Refactor pipelining mechanism in homa_message_out_fill
* Retain retransmitted packets until homa_rpc_reap (to ensure that RPCs don't get reaped with retransmitted packets still in the tx pipeline)

Changes for v14:
* Implement homa_rpc_tx_end function

Changes for v13:
* Fix bug in homa_resend_data: wasn't fully initializing new skb.
* Fix bug in homa_tx_data_pkt_alloc: wasn't allocating enough space in the new skb.

Changes for v12:
* Move RPC_DEAD check in homa_xmit_data to eliminate window for more complete coverage.

Changes for v11:
* Cleanup and simplify use of RPC reference counts.

Changes for v10:
* Revise sparse annotations to eliminate __context__ definition
* Remove log messages after alloc errors

Changes for v9:
* Use new homa_clock abstraction layer
* Various name improvements (e.g. use "alloc" instead of "new" for functions that allocate memory)
* Eliminate sizeof32 define: use sizeof instead

Changes for v7:
* Implement accounting for bytes in tx skbs
* Rename UNKNOWN packet type to RPC_UNKNOWN
* Use new RPC reference counts; eliminates need for RCU
* Remove locker argument from locking functions
* Use u64 and __u64 properly
* Fix incorrect skb check in homa_message_out_fill

---
 net/homa/homa_impl.h     |  14 +
 net/homa/homa_outgoing.c | 568 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 582 insertions(+)
 create mode 100644 net/homa/homa_outgoing.c
net/homa/homa_impl.h +14 -0
index adedc8757e5b..f17c9ecd8056 100644
@@ -362,12 +362,26 @@ static inline bool homa_make_header_avl(struct sk_buff *skb)
 
 extern unsigned int homa_net_id;
 
+int      homa_fill_data_interleaved(struct homa_rpc *rpc,
+				    struct sk_buff *skb, struct iov_iter *iter);
+int      homa_message_out_fill(struct homa_rpc *rpc,
+			       struct iov_iter *iter, int xmit);
+void     homa_message_out_init(struct homa_rpc *rpc, int length);
 void     homa_rpc_handoff(struct homa_rpc *rpc);
+int      homa_rpc_tx_end(struct homa_rpc *rpc);
+struct sk_buff *homa_tx_data_pkt_alloc(struct homa_rpc *rpc,
+				       struct iov_iter *iter, int offset,
+				       int length, int max_seg_data);
 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_peer *peer, struct homa_sock *hsk);
+void     homa_xmit_unknown(struct sk_buff *skb, struct homa_sock *hsk);
 
 int      homa_message_in_init(struct homa_rpc *rpc, int unsched);
+void     homa_resend_data(struct homa_rpc *rpc, int start, int end);
 void     homa_xmit_data(struct homa_rpc *rpc);
+void     __homa_xmit_data(struct sk_buff *skb, struct homa_rpc *rpc);
 
 /**
  * homa_net() - Return the struct homa_net associated with a particular
net/homa/homa_outgoing.c new file +568 -0

568 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#23 lore raw

Re: [net-next,v17,09/14] net: homa: create homa_outgoing.c

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.

For local reproduction steps see https://netdev-ai.bots.linux.dev/ai-local.html
---
net: homa: create homa_outgoing.c

This file does most of the work of transmitting outgoing messages. It is also responsible for copying data from user space into skbs.

Quoted 3 lines
net/homa/homa_impl.h +0 -0

[ ... ]

Quoted 3 lines
net/homa/homa_outgoing.c new file +0 -0

[ ... ]

net/homa/homa_outgoing.c line 375

Quoted 11 lines
net/homa/homa_outgoing.c new file +11 -0
+/**
+ * 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;
                                        ^^^^^^^^^^

Does this code send uninitialized kernel stack memory over the network? The struct homa_rpc_unknown_hdr unknown is only partially initialized.

Four fields are set:

	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));

But the remaining fields of homa_common_hdr (sequence, ack[3], doff, reserved1, window, checksum, reserved2) are left uninitialized. These total 15 bytes of data.

__homa_xmit_control() copies the entire struct via memcpy():

	h = skb_put(skb, length);
	memcpy(h, contents, length);

and the packet is then transmitted over the network via ip_queue_xmit() or ip6_xmit().

This sends uninitialized kernel stack memory contents over the wire, which is an information leak.

net/homa/homa_outgoing.c line 385

Quoted 10 lines
net/homa/homa_outgoing.c new file +10 -0
+	struct homa_peer *peer;
+
+	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));
+	peer = homa_peer_get(hsk, &saddr);
+	if (!IS_ERR(peer))
+		__homa_xmit_control(&unknown, sizeof(unknown), peer, hsk);
+	homa_peer_release(peer);
          ^^^^^^^^^^^^^^^^^^^^

Can this dereference an error pointer? When homa_peer_get() fails and returns an ERR_PTR (for example, -ENOMEM from allocation failure or rhashtable insert error), homa_peer_release(peer) is called unconditionally on the error pointer.

homa_peer_release() calls refcount_dec_and_test(&peer->refs), which dereferences the invalid ERR_PTR address.

The IS_ERR check on the previous line correctly guards __homa_xmit_control but does not guard homa_peer_release.

Quoted 1 line

+}

[ ... ]

#24 lore raw

Re: [net-next,v17,09/14] net: homa: create homa_outgoing.c

Quoted 28 lines · Paolo Abeni

net/homa/homa_outgoing.c line 375

Quoted 11 lines
net/homa/homa_outgoing.c new file +11 -0
+/**
+ * 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;
                                        ^^^^^^^^^^

Does this code send uninitialized kernel stack memory over the network? The struct homa_rpc_unknown_hdr unknown is only partially initialized.

Four fields are set:

        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));

But the remaining fields of homa_common_hdr (sequence, ack[3], doff, reserved1, window, checksum, reserved2) are left uninitialized. These total 15 bytes of data.

__homa_xmit_control() copies the entire struct via memcpy():

Quoted 8 lines
        h = skb_put(skb, length);
        memcpy(h, contents, length);

and the packet is then transmitted over the network via ip_queue_xmit() or ip6_xmit().

This sends uninitialized kernel stack memory contents over the wire, which is an information leak.

Fixed (here and for other calls to __homa_xmit_control).

Quoted 17 lines

net/homa/homa_outgoing.c line 385

Quoted 10 lines
net/homa/homa_outgoing.c new file +10 -0
+     struct homa_peer *peer;
+
+     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));
+     peer = homa_peer_get(hsk, &saddr);
+     if (!IS_ERR(peer))
+             __homa_xmit_control(&unknown, sizeof(unknown), peer, hsk);
+     homa_peer_release(peer);
          ^^^^^^^^^^^^^^^^^^^^

Can this dereference an error pointer? When homa_peer_get() fails and returns an ERR_PTR (for example, -ENOMEM from allocation failure or rhashtable insert error), homa_peer_release(peer) is called unconditionally on the error pointer.

Quoted 5 lines

homa_peer_release() calls refcount_dec_and_test(&peer->refs), which dereferences the invalid ERR_PTR address.

The IS_ERR check on the previous line correctly guards __homa_xmit_control but does not guard homa_peer_release.

Fixed; shouldn't release the peer after an error.

#25 lore raw

PATCH v17 10/14 net: homa: create homa_utils.c

In reply to John Ousterhout

This file contains functions for constructing and destructing homa structs.

---
Changes for v16:
* Use cpu_relax when spinning

Changes for v11:
* Move link_mbps variable from struct homa_pacer back to struct homa

Changes for v10:
* Remove log messages after alloc errors

Changes for v9:
* Add support for homa_net objects
* Use new homa_clock abstraction layer
* Various name improvements (e.g. use "alloc" instead of "new" for functions that allocate memory)

Changes for v8:
* Accommodate homa_pacer refactoring

Changes for v7:
* Make Homa a pernet subsystem
* Add support for tx memory accounting
* Remove "lock_slow" functions, which don't add functionality in this patch series
* Use u64 and __u64 properly

---
 net/homa/homa_impl.h  |   6 +++
 net/homa/homa_utils.c | 110 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 116 insertions(+)
 create mode 100644 net/homa/homa_utils.c
net/homa/homa_impl.h +6 -0
index f17c9ecd8056..4726762b688f 100644
@@ -362,13 +362,19 @@ static inline bool homa_make_header_avl(struct sk_buff *skb)
 
 extern unsigned int homa_net_id;
 
+void     homa_destroy(struct homa *homa);
 int      homa_fill_data_interleaved(struct homa_rpc *rpc,
 				    struct sk_buff *skb, struct iov_iter *iter);
+int      homa_init(struct homa *homa);
 int      homa_message_out_fill(struct homa_rpc *rpc,
 			       struct iov_iter *iter, int xmit);
 void     homa_message_out_init(struct homa_rpc *rpc, int length);
+void     homa_net_destroy(struct homa_net *hnet);
+int      homa_net_init(struct homa_net *hnet, struct net *net,
+		       struct homa *homa);
 void     homa_rpc_handoff(struct homa_rpc *rpc);
 int      homa_rpc_tx_end(struct homa_rpc *rpc);
+void     homa_spin(int ns);
 struct sk_buff *homa_tx_data_pkt_alloc(struct homa_rpc *rpc,
 				       struct iov_iter *iter, int offset,
 				       int length, int max_seg_data);
net/homa/homa_utils.c new file +110 -0

110 lines not on this page · raw message

Signature · 1 line
2.43.0
#26 lore raw

PATCH v17 11/14 net: homa: create homa_incoming.c

In reply to John Ousterhout

This file contains most of the code for handling incoming packets, including top-level dispatching code plus specific handlers for each pack type. It also contains code for dispatching fully-received messages to waiting application threads.

---
Changes for v16:
* Use kfree_skb_reason and consume_skb instead of kfree_skb
* Use set_bit/clear_bit/test_bit
* Simplify handling of acks; eliminate akcs and num_acks variables in homa_dispatch_pkts
* Check for wmem in homa_dispatch_pkts (fixes deadlock over wmem)
* Use new homa_lock_preempt() function

Changes for v14:
* Use new homa_rpc_tx_end function
* Fix race in homa_wait_shared (an RPC could get lost if it became ready at the same time that homa_interest_wait returned with an error)
* Handle nonblocking behavior here, rather than in homa_interest.c
* Change API for homa_wait_private to distinguish errors in an RPC from errors that prevented the wait operation from completing.

Changes for v11:
* Cleanup and simplify use of RPC reference counts.
* Cleanup sparse annotations.
* Rework the mechanism for waking up RPCs that stalled waiting for buffer pool space.

Changes for v10:
* Revise sparse annotations to eliminate __context__ definition
* Refactor resend mechanism (new function homa_request_retrans replaces homa_gap_retry)
* Remove log messages after alloc errors
* Fix socket cleanup race

Changes for v9:
* Add support for homa_net objects
* Use new homa_clock abstraction layer
* Various name improvements (e.g. use "alloc" instead of "new" for functions that allocate memory)

Changes for v7:
* API change for homa_rpc_handoff
* Refactor waiting mechanism for incoming packets: simplify wait criteria and use standard Linux mechanisms for waiting, use new homa_interest struct
* Reject unauthorized incoming request messages
* Improve documentation for code that spins (and reduce spin length)
* Use RPC reference counts, eliminate RPC_HANDING_OFF flag
* Replace erroneous use of "safe" list iteration with "rcu" version
* Remove locker argument from locking functions
* Check incoming messages against HOMA_MAX_MESSAGE_LENGTH
* Use u64 and __u64 properly

---
 net/homa/homa_impl.h     |  15 +
 net/homa/homa_incoming.c | 887 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 902 insertions(+)
 create mode 100644 net/homa/homa_incoming.c
net/homa/homa_impl.h +15 -0
index 4726762b688f..779abd7bb1b7 100644
@@ -362,22 +362,37 @@ static inline bool homa_make_header_avl(struct sk_buff *skb)
 
 extern unsigned int homa_net_id;
 
+void     homa_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,
+		      struct homa_rpc *rpc);
+void     homa_add_packet(struct homa_rpc *rpc, struct sk_buff *skb);
+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_fill_data_interleaved(struct homa_rpc *rpc,
 				    struct sk_buff *skb, struct iov_iter *iter);
+struct homa_gap *homa_gap_alloc(struct list_head *next, int start, int end);
 int      homa_init(struct homa *homa);
 int      homa_message_out_fill(struct homa_rpc *rpc,
 			       struct iov_iter *iter, int xmit);
 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);
 int      homa_net_init(struct homa_net *hnet, struct net *net,
 		       struct homa *homa);
+void     homa_request_retrans(struct homa_rpc *rpc);
+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);
 void     homa_spin(int ns);
 struct sk_buff *homa_tx_data_pkt_alloc(struct homa_rpc *rpc,
 				       struct iov_iter *iter, int offset,
 				       int length, int max_seg_data);
+void     homa_rpc_unknown_pkt(struct sk_buff *skb, struct homa_rpc *rpc);
+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,
net/homa/homa_incoming.c new file +887 -0

887 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#27 lore raw

Re: [net-next,v17,11/14] net: homa: create homa_incoming.c

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.

For local reproduction steps see https://netdev-ai.bots.linux.dev/ai-local.html
---
net: homa: create homa_incoming.c

This file contains most of the code for handling incoming packets, including top-level dispatching code plus specific handlers for each pack type. It also contains code for dispatching fully-received messages to waiting application threads.

Quoted 4 lines
net/homa/homa_impl.h +0 -0
index 4726762b688f..779abd7bb1b7 100644

[ ... ]

Quoted 5 lines
net/homa/homa_incoming.c new file +0 -0
new file mode 100644
index 000000000000..f083784921f4

[ ... ]

Quoted 1 line
net/homa/homa_incoming.c new file +0 -0
@@ -0,0 +1,887 @@

[ ... ]

Quoted 80 lines
net/homa/homa_incoming.c new file +80 -0
+/**
+ * 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. This function takes ownership of the packet
+ *         (the packet will either be freed or added to rpc->msgin.packets).
+ */
+void 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;
+	int start = ntohl(h->seg.offset);
+	int length = homa_data_len(skb);
+	enum skb_drop_reason reason;
+	int end = start + length;
+
+	if ((start + length) > rpc->msgin.length) {
+		reason = SKB_DROP_REASON_PKT_TOO_BIG;
+		goto discard;
+	}
+
+	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 discard;
+		}
+		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 discard;
+			}
+			if (end > gap->end) {
+				reason = SKB_DROP_REASON_DUP_FRAG;
+				goto discard;
+			}
+			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 discard;
+			}
+			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) {

net/homa/homa_incoming.c line 189

Quoted 10 lines
net/homa/homa_incoming.c new file +10 -0
+			reason = SKB_DROP_REASON_NOMEM;
+			goto discard;
+		}
+		gap2->time = gap->time;
+		gap->start = end;
+		goto keep;
+	}
+
+discard:
+	kfree_skb_reason(skb, reason);
                           ^^^^^^

Can the 'reason' variable be used uninitialized here? When data has been received sequentially (no gaps), a retransmitted duplicate packet with an offset below recv_end won't match any of the early conditions (it doesn't equal recv_end, it isn't greater than recv_end), so it falls through to the gap traversal loop. With an empty gap list, the loop body never executes and execution continues to the discard label where kfree_skb_reason() is called with an uninitialized reason.

[ ... ]

Quoted 14 lines
net/homa/homa_incoming.c new file +14 -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)
+{

[ ... ]

Quoted 7 lines
net/homa/homa_incoming.c new file +7 -0
+/**
+ * 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)
+{

[ ... ]

Quoted 12 lines
net/homa/homa_incoming.c new file +12 -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

net/homa/homa_incoming.c line 427

Quoted 10 lines
net/homa/homa_incoming.c new file +10 -0
+			 * 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;
+			goto discard;
                    ^^^^^^^^^^^^

This goto is unreachable because it follows the break statement above. More critically, the switch has no default case. Looking at the validation in homa_softirq (which checks 'h->type >= DATA && h->type <= MAX_OP'), the header_lengths array (defined in homa_plumbing.c) has zero entries for types 0x11, 0x15, and 0x16. Packets with these type values pass validation since 'skb->len < 0' is always false.

When such a packet reaches homa_dispatch_pkts, no case matches, execution falls through to 'continue', and the SKB is never freed. Can this leak memory?

[ ... ]

Quoted 18 lines
net/homa/homa_incoming.c new file +18 -0
+/**
+ * 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 lock will be dead on return.
+ */
+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 i, count;
+
+	if (rpc)
+		homa_rpc_end(rpc);

net/homa/homa_incoming.c line 671

Quoted 10 lines
net/homa/homa_incoming.c new file +10 -0
+
+	count = ntohs(h->num_acks);
+	if (count > 0) {
+		if (rpc) {
+			/* Must temporarily release rpc's lock because
+			 * homa_rpc_acked needs to acquire RPC locks.
+			 */
+			homa_rpc_unlock(rpc);
+			for (i = 0; i < count; i++)
+				homa_rpc_acked(hsk, &saddr, &h->acks[i]);
                                                               ^^^^^^^^^^^

Is 'count' validated before accessing h->acks[i] in this loop? The num_acks field comes from the network via ntohs() and can be any value from 0 to 65535. The acks array in struct homa_ack_hdr is declared as 'struct homa_ack acks[HOMA_MAX_ACKS_PER_PKT]' where HOMA_MAX_ACKS_PER_PKT is 5 in net/homa/homa_wire.h.

If a peer sends an ACK packet with num_acks > 5, this code reads beyond the acks[] array boundary in the skb data. The out-of-bounds data is passed to homa_rpc_acked() which dereferences it (reading ack->server_port and ack->client_id). Can this cause protocol state corruption or a kernel crash if the read extends beyond the skb's allocated linear data region?

#28 lore raw

Re: [net-next,v17,11/14] net: homa: create homa_incoming.c

Quoted 124 lines · Paolo Abeni

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.

For local reproduction steps see https://netdev-ai.bots.linux.dev/ai-local.html
---
net: homa: create homa_incoming.c

This file contains most of the code for handling incoming packets, including top-level dispatching code plus specific handlers for each pack type. It also contains code for dispatching fully-received messages to waiting application threads.

Quoted 4 lines
net/homa/homa_impl.h +0 -0
index 4726762b688f..779abd7bb1b7 100644

[ ... ]

Quoted 5 lines
net/homa/homa_incoming.c new file +0 -0
new file mode 100644
index 000000000000..f083784921f4

[ ... ]

Quoted 1 line
net/homa/homa_incoming.c new file +0 -0
@@ -0,0 +1,887 @@

[ ... ]

Quoted 80 lines
net/homa/homa_incoming.c new file +80 -0
+/**
+ * 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. This function takes ownership of the packet
+ *         (the packet will either be freed or added to rpc->msgin.packets).
+ */
+void 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;
+     int start = ntohl(h->seg.offset);
+     int length = homa_data_len(skb);
+     enum skb_drop_reason reason;
+     int end = start + length;
+
+     if ((start + length) > rpc->msgin.length) {
+             reason = SKB_DROP_REASON_PKT_TOO_BIG;
+             goto discard;
+     }
+
+     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 discard;
+             }
+             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 discard;
+                     }
+                     if (end > gap->end) {
+                             reason = SKB_DROP_REASON_DUP_FRAG;
+                             goto discard;
+                     }
+                     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 discard;
+                     }
+                     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) {

net/homa/homa_incoming.c line 189

Quoted 10 lines
net/homa/homa_incoming.c new file +10 -0
+                     reason = SKB_DROP_REASON_NOMEM;
+                     goto discard;
+             }
+             gap2->time = gap->time;
+             gap->start = end;
+             goto keep;
+     }
+
+discard:
+     kfree_skb_reason(skb, reason);
                           ^^^^^^
Quoted 7 lines

Can the 'reason' variable be used uninitialized here? When data has been received sequentially (no gaps), a retransmitted duplicate packet with an offset below recv_end won't match any of the early conditions (it doesn't equal recv_end, it isn't greater than recv_end), so it falls through to the gap traversal loop. With an empty gap list, the loop body never executes and execution continues to the discard label where kfree_skb_reason() is called with an uninitialized reason.

Fixed.

Quoted 61 lines

[ ... ]

Quoted 14 lines
net/homa/homa_incoming.c new file +14 -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)
+{

[ ... ]

Quoted 7 lines
net/homa/homa_incoming.c new file +7 -0
+/**
+ * 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)
+{

[ ... ]

Quoted 12 lines
net/homa/homa_incoming.c new file +12 -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

net/homa/homa_incoming.c line 427

Quoted 10 lines
net/homa/homa_incoming.c new file +10 -0
+                      * 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;
+                     goto discard;
                    ^^^^^^^^^^^^

This goto is unreachable because it follows the break statement above. More critically, the switch has no default case. Looking at the validation in homa_softirq (which checks 'h->type >= DATA && h->type <= MAX_OP'), the header_lengths array (defined in homa_plumbing.c) has zero entries for types 0x11, 0x15, and 0x16. Packets with these type values pass validation since 'skb->len < 0' is always false.

Quoted 3 lines

When such a packet reaches homa_dispatch_pkts, no case matches, execution falls through to 'continue', and the SKB is never freed. Can this leak memory?

Fixed (this was a bug in the script that strips out Homa features not in the current patch series).

Quoted 39 lines

[ ... ]

Quoted 18 lines
net/homa/homa_incoming.c new file +18 -0
+/**
+ * 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 lock will be dead on return.
+ */
+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 i, count;
+
+     if (rpc)
+             homa_rpc_end(rpc);

net/homa/homa_incoming.c line 671

Quoted 10 lines
net/homa/homa_incoming.c new file +10 -0
+
+     count = ntohs(h->num_acks);
+     if (count > 0) {
+             if (rpc) {
+                     /* Must temporarily release rpc's lock because
+                      * homa_rpc_acked needs to acquire RPC locks.
+                      */
+                     homa_rpc_unlock(rpc);
+                     for (i = 0; i < count; i++)
+                             homa_rpc_acked(hsk, &saddr, &h->acks[i]);
                                                               ^^^^^^^^^^^

Is 'count' validated before accessing h->acks[i] in this loop? The num_acks field comes from the network via ntohs() and can be any value from 0 to 65535. The acks array in struct homa_ack_hdr is declared as 'struct homa_ack acks[HOMA_MAX_ACKS_PER_PKT]' where HOMA_MAX_ACKS_PER_PKT is 5 in net/homa/homa_wire.h.

Quoted 5 lines

If a peer sends an ACK packet with num_acks > 5, this code reads beyond the acks[] array boundary in the skb data. The out-of-bounds data is passed to homa_rpc_acked() which dereferences it (reading ack->server_port and ack->client_id). Can this cause protocol state corruption or a kernel crash if the read extends beyond the skb's allocated linear data region?

Fixed.

#29 lore raw

PATCH v17 12/14 net: homa: create homa_timer.c

In reply to John Ousterhout

This file contains code that wakes up periodically to check for missing data, initiate retransmissions, and declare peer nodes "dead".

---
Changes for v14:
* Use new homa_rpc_tx_end function

Changes for v11:
* Cleanup sparse annotations.

Changes for v10:
* Refactor resend mechanism

Changes for v9:
* Reflect changes in socket and peer management
* Minor name changes for clarity

Changes for v7:
* Interface changes to homa_sock_start_scan etc.
* Remove locker argument from locking functions
* Use u64 and __u64 properly

---
 net/homa/homa_impl.h  |   3 +
 net/homa/homa_timer.c | 136 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 139 insertions(+)
 create mode 100644 net/homa/homa_timer.c
net/homa/homa_impl.h +3 -0
index 779abd7bb1b7..9c7e80e49f82 100644
@@ -387,6 +387,9 @@ void     homa_resend_pkt(struct sk_buff *skb, struct homa_rpc *rpc,
 void     homa_rpc_handoff(struct homa_rpc *rpc);
 int      homa_rpc_tx_end(struct homa_rpc *rpc);
 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);
 struct sk_buff *homa_tx_data_pkt_alloc(struct homa_rpc *rpc,
 				       struct iov_iter *iter, int offset,
 				       int length, int max_seg_data);
net/homa/homa_timer.c new file +136 -0

136 lines not on this page · raw message

Signature · 1 line
2.43.0
#30 lore raw

PATCH v17 13/14 net: homa: create homa_plumbing.c

In reply to John Ousterhout

homa_plumbing.c contains functions that connect Homa to the rest of the Linux kernel, such as dispatch tables used by Linux and the top-level functions that Linux invokes from those dispatch tables.

---
Changes for v16:
* Implement HOMAIOCINFO ioctl
* Set hsk->error_msg (for HOMAIOCINFO)
* Use consume_skb and kfree_skb_reason instead of kfree_skb
* Use set_bit, clear_bit, etc. for flag bits
* Remove global_homa variable

Changes for v13:
* Fix bug in is_homa_pkt: didn't properly handle packets where the network header hadn't yet been set.

Changes for v12:
* Fix deadlock in homa_recvmsg (homa_rpc_reap was invoked while holding an RPC lock).

Changes for v11:
* Move link_mbps variable from struct homa_pacer back to struct homa.
* Clean up error handing in homa_load.
* Cleanup and simplify use of RPC reference counts.
* Add explicit padding to struct homa_recvmsg_args to fix problems compiling on 32-bit machines.

Changes for v10:
* Use the destroy function from struct proto properly (fixes bugs in socket cleanup)
* Fix issues from sparse, xmastree, etc.
* Replace __u16 with u16, __u8 with u8, etc.

Changes for v9:
* Add support for homa_net objects
* Various name improvements (e.g. use "alloc" instead of "new" for functions that allocate memory)
* Add BUILD_BUG_ON statements to replace _Static_asserts removed from header files
* Remove unnecessary/unused functions such as homa_get_port, homa_disconnect, and homa_backlog_rcv.

Changes for v8:
* Accommodate homa_pacer and homa_pool refactorings

Changes for v7:
* Remove extraneous code
* Make Homa a pernet subsystem
* Block Homa senders if insufficient tx buffer memory
* Check for missing buffer pool in homa_recvmsg
* Refactor waiting mechanism for incoming packets: simplify wait criteria and use standard Linux mechanisms for waiting
* Implement SO_HOMA_SERVER option for setsockopt
* Rename UNKNOWN packet type to RPC_UNKNOWN
* Remove locker argument from locking functions
* Use u64 and __u64 properly
* Use new homa_make_header_avl function

---
 net/homa/homa_impl.h     |   28 +
 net/homa/homa_plumbing.c | 1259 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 1287 insertions(+)
 create mode 100644 net/homa/homa_plumbing.c
net/homa/homa_impl.h +28 -0
index 9c7e80e49f82..883cd93581c0 100644
@@ -365,27 +365,53 @@ extern unsigned int homa_net_id;
 void     homa_ack_pkt(struct sk_buff *skb, struct homa_sock *hsk,
 		      struct homa_rpc *rpc);
 void     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);
 int      homa_fill_data_interleaved(struct homa_rpc *rpc,
 				    struct sk_buff *skb, struct iov_iter *iter);
 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);
 int      homa_message_out_fill(struct homa_rpc *rpc,
 			       struct iov_iter *iter, int xmit);
 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 net *net,
 		       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, int *addr_len);
 void     homa_request_retrans(struct homa_rpc *rpc);
 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);
+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);
@@ -393,7 +419,9 @@ int      homa_timer_main(void *transport);
 struct sk_buff *homa_tx_data_pkt_alloc(struct homa_rpc *rpc,
 				       struct iov_iter *iter, int offset,
 				       int length, int max_seg_data);
+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,
net/homa/homa_plumbing.c new file +1259 -0

1,259 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#31 lore raw

Re: [net-next,v17,13/14] net: homa: create homa_plumbing.c

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.

For local reproduction steps see https://netdev-ai.bots.linux.dev/ai-local.html
---
net: homa: create homa_plumbing.c

homa_plumbing.c contains functions that connect Homa to the rest of the Linux kernel, such as dispatch tables used by Linux and the top-level functions that Linux invokes from those dispatch tables.

Quoted 3 lines
net/homa/homa_plumbing.c new file +0 -0

[ ... ]

Quoted 25 lines
net/homa/homa_plumbing.c new file +25 -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_info rinfo;
+	struct homa_info hinfo;
+	struct homa_rpc *rpc;
+	int bytes_avl;
+	char *dst;
+
+	if (unlikely(copy_from_user(&hinfo, (void __user *)arg,
+				    sizeof(hinfo)))) {
+		hsk->error_msg = "invalid address for homa_info";
+		return -EFAULT;
+	}
+

net/homa/homa_plumbing.c line 451

Quoted 10 lines
net/homa/homa_plumbing.c new file +10 -0
+	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;
+	list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
                                ^^^^

Is rcu_read_lock() needed around this list_for_each_entry_rcu() loop?

All three other functions that use the same homa_protect_rpcs() + list_for_each_entry_rcu pattern (homa_abort_rpcs in homa_rpc.c, homa_timer in homa_timer.c, and homa_abort_sock_rpcs in homa_rpc.c) bracket the traversal with rcu_read_lock()/rcu_read_unlock().

The homa_protect_rpcs() mechanism prevents RPC reaping via an atomic counter, but doesn't provide RCU read-side protection.

Without rcu_read_lock(), list_for_each_entry_rcu() triggers a lockdep RCU warning, and on PREEMPT_RCU configurations the reader can be preempted during traversal without the RCU subsystem knowing a reader is active, breaking the RCU contract.

Quoted 20 lines
net/homa/homa_plumbing.c new file +20 -0
+		homa_rpc_lock(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)) {
+			if (copy_to_user((void __user *)dst, &rinfo,
+					 sizeof(rinfo))) {
+				homa_unprotect_rpcs(hsk);
+				hsk->error_msg = "couldn't copy homa_rpc_info to user space: invalid or read-only address?";
+				return -EFAULT;
+			}
+			dst += sizeof(rinfo);
+			bytes_avl -= sizeof(rinfo);
+		}
+		hinfo.num_rpcs++;
+	}
+	homa_unprotect_rpcs(hsk);

[ ... ]

Quoted 5 lines
net/homa/homa_plumbing.c new file +5 -0
+/**
+ * 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.
+ *

net/homa/homa_plumbing.c line 518

Quoted 10 lines
net/homa/homa_plumbing.c new file +10 -0
+ * Return: always 0 (success).
+ */
+int homa_socket(struct sock *sk)
+{
+	struct homa_sock *hsk = homa_sk(sk);
+	int result;
+
+	result = homa_sock_init(hsk);
+	if (result != 0) {
+		homa_sock_shutdown(hsk);
                ^^^^^^^^^^^^^^^^^^^

Can this trigger a spinlock bug?

When homa_sock_init() fails because homa_pool_alloc() returns ERR_PTR(-ENOMEM), it returns before spin_lock_init(&hsk->lock) is called in homa_sock_init().

The error path then calls homa_sock_shutdown(hsk), whose first action is homa_sock_lock(hsk) = spin_lock_bh(&hsk->lock) on the never-initialized spinlock.

With CONFIG_DEBUG_SPINLOCK, the lock's magic field (zero from slab allocation) doesn't match SPINLOCK_MAGIC (0xdead4ead), causing spin_bug() to call BUG().

While homa_sock_shutdown() would immediately return after checking !hsk->homa (NULL), the BUG() fires inside spin_lock_bh() before that check is reached.

This is reachable under memory pressure.

Quoted 4 lines
net/homa/homa_plumbing.c new file +4 -0
+		homa_sock_destroy(&hsk->sock);
+	}
+	return result;
+}

[ ... ]

Quoted 18 lines
net/homa/homa_plumbing.c new file +18 -0
+/**
+ * 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;

net/homa/homa_plumbing.c line 622

Quoted 10 lines
net/homa/homa_plumbing.c new file +10 -0
+	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_setsockopt invoked with level not IPPROTO_HOMA";
                                 ^^^^^^^^^^^^^^

This isn't a bug, but the error message says 'homa_setsockopt' instead of 'homa_getsockopt'. This is a copy-paste error from homa_setsockopt().

The error_msg field is returned to applications via the HOMAIOCINFO ioctl, so users debugging socket option failures would see a misleading message pointing to the wrong function.

Quoted 3 lines
net/homa/homa_plumbing.c new file +3 -0
+		return -ENOPROTOOPT;
+	}
+	if (optname == SO_HOMA_RCVBUF) {

[ ... ]

Quoted 13 lines
net/homa/homa_plumbing.c new file +13 -0
+/**
+ * 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.
+ * @addr_len:    Store the length of the sender address here
+ * 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,
+		 int *addr_len)
+{

[ ... ]

net/homa/homa_plumbing.c line 899

Quoted 7 lines
net/homa/homa_plumbing.c new file +7 -0
+	if (rpc->error) {
+		hsk->error_msg = "RPC failed";
+		result = rpc->error;
+	} else {
+		result = rpc->msgin.length;
+	}
+	result = rpc->error ? rpc->error : rpc->msgin.length;
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This isn't a bug, but there's redundant dead-store code here.

The if/else block assigns 'result' to either 'rpc->error' or 'rpc->msgin.length', but the next line immediately overwrites 'result' with the identical ternary expression.

The two 'result = ...' assignments inside the if/else are dead stores that are always overwritten. The if/else block's only surviving side effect is setting 'hsk->error_msg = "RPC failed"' when rpc->error is nonzero.

This appears to be an editing mistake where either the if/else should be the authoritative result assignment (and the ternary deleted), or the ternary should remain and the if/else should be simplified to only set error_msg (removing its result assignments).

Quoted 3 lines
net/homa/homa_plumbing.c new file +3 -0
+
+	/* Collect result information. */
+	control.id = rpc->id;

[ ... ]

net/homa/homa_plumbing.c line 1213

Quoted 11 lines
net/homa/homa_plumbing.c new file +11 -0
+/**
+ * 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_RESTART.
+ */
+enum hrtimer_restart homa_hrtimer(struct hrtimer *timer)
+{
+	wake_up_process(timer_kthread);
+	return HRTIMER_NORESTART;
        ^^^^^^^^^^^^^^^^^^^^^^

The kernel-doc comment states 'Return: Always HRTIMER_RESTART' but the function returns HRTIMER_NORESTART.

The runtime behavior is correct (homa_timer_main re-arms the hrtimer explicitly via hrtimer_start on each loop iteration, so HRTIMER_NORESTART is the intended return value), but the comment contradicts the code.

This misleads readers into believing the timer auto-restarts, when it does not.

Quoted 1 line

+}

#32 lore raw

Re: [net-next,v17,13/14] net: homa: create homa_plumbing.c

Quoted 62 lines · Paolo Abeni

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.

For local reproduction steps see https://netdev-ai.bots.linux.dev/ai-local.html
---
net: homa: create homa_plumbing.c

homa_plumbing.c contains functions that connect Homa to the rest of the Linux kernel, such as dispatch tables used by Linux and the top-level functions that Linux invokes from those dispatch tables.

Quoted 3 lines
net/homa/homa_plumbing.c new file +0 -0

[ ... ]

Quoted 25 lines
net/homa/homa_plumbing.c new file +25 -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_info rinfo;
+     struct homa_info hinfo;
+     struct homa_rpc *rpc;
+     int bytes_avl;
+     char *dst;
+
+     if (unlikely(copy_from_user(&hinfo, (void __user *)arg,
+                                 sizeof(hinfo)))) {
+             hsk->error_msg = "invalid address for homa_info";
+             return -EFAULT;
+     }
+

net/homa/homa_plumbing.c line 451

Quoted 10 lines
net/homa/homa_plumbing.c new file +10 -0
+     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;
+     list_for_each_entry_rcu(rpc, &hsk->active_rpcs, active_links) {
                                ^^^^

Is rcu_read_lock() needed around this list_for_each_entry_rcu() loop?

All three other functions that use the same homa_protect_rpcs() + list_for_each_entry_rcu pattern (homa_abort_rpcs in homa_rpc.c, homa_timer in homa_timer.c, and homa_abort_sock_rpcs in homa_rpc.c) bracket the traversal with rcu_read_lock()/rcu_read_unlock().

Quoted 7 lines

The homa_protect_rpcs() mechanism prevents RPC reaping via an atomic counter, but doesn't provide RCU read-side protection.

Without rcu_read_lock(), list_for_each_entry_rcu() triggers a lockdep RCU warning, and on PREEMPT_RCU configurations the reader can be preempted during traversal without the RCU subsystem knowing a reader is active, breaking the RCU contract.

Fixed (added RCU locking).

Quoted 55 lines
Quoted 21 lines
net/homa/homa_plumbing.c new file +20 -0
+             homa_rpc_lock(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)) {
+                     if (copy_to_user((void __user *)dst, &rinfo,
+                                      sizeof(rinfo))) {
+                             homa_unprotect_rpcs(hsk);
+                             hsk->error_msg = "couldn't copy homa_rpc_info to user space: invalid or read-only address?";
+                             return -EFAULT;
+                     }
+                     dst += sizeof(rinfo);
+                     bytes_avl -= sizeof(rinfo);
+             }
+             hinfo.num_rpcs++;
+     }
+     homa_unprotect_rpcs(hsk);

[ ... ]

Quoted 5 lines
net/homa/homa_plumbing.c new file +5 -0
+/**
+ * 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.
+ *

net/homa/homa_plumbing.c line 518

Quoted 10 lines
net/homa/homa_plumbing.c new file +10 -0
+ * Return: always 0 (success).
+ */
+int homa_socket(struct sock *sk)
+{
+     struct homa_sock *hsk = homa_sk(sk);
+     int result;
+
+     result = homa_sock_init(hsk);
+     if (result != 0) {
+             homa_sock_shutdown(hsk);
                ^^^^^^^^^^^^^^^^^^^

Can this trigger a spinlock bug?

When homa_sock_init() fails because homa_pool_alloc() returns ERR_PTR(-ENOMEM), it returns before spin_lock_init(&hsk->lock) is called in homa_sock_init().

The error path then calls homa_sock_shutdown(hsk), whose first action is homa_sock_lock(hsk) = spin_lock_bh(&hsk->lock) on the never-initialized spinlock.

With CONFIG_DEBUG_SPINLOCK, the lock's magic field (zero from slab allocation) doesn't match SPINLOCK_MAGIC (0xdead4ead), causing spin_bug() to call BUG().

Quoted 5 lines

While homa_sock_shutdown() would immediately return after checking !hsk->homa (NULL), the BUG() fires inside spin_lock_bh() before that check is reached.

This is reachable under memory pressure.

Fixed (no need for additional cleanup after errors).

Quoted 38 lines
Quoted 5 lines
net/homa/homa_plumbing.c new file +4 -0
+             homa_sock_destroy(&hsk->sock);
+     }
+     return result;
+}

[ ... ]

Quoted 18 lines
net/homa/homa_plumbing.c new file +18 -0
+/**
+ * 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;

net/homa/homa_plumbing.c line 622

Quoted 10 lines
net/homa/homa_plumbing.c new file +10 -0
+     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_setsockopt invoked with level not IPPROTO_HOMA";
                                 ^^^^^^^^^^^^^^
Quoted 6 lines

This isn't a bug, but the error message says 'homa_setsockopt' instead of 'homa_getsockopt'. This is a copy-paste error from homa_setsockopt().

The error_msg field is returned to applications via the HOMAIOCINFO ioctl, so users debugging socket option failures would see a misleading message pointing to the wrong function.

Fixed.

Quoted 43 lines
Quoted 4 lines
net/homa/homa_plumbing.c new file +3 -0
+             return -ENOPROTOOPT;
+     }
+     if (optname == SO_HOMA_RCVBUF) {

[ ... ]

Quoted 13 lines
net/homa/homa_plumbing.c new file +13 -0
+/**
+ * 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.
+ * @addr_len:    Store the length of the sender address here
+ * 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,
+              int *addr_len)
+{

[ ... ]

net/homa/homa_plumbing.c line 899

Quoted 7 lines
net/homa/homa_plumbing.c new file +7 -0
+     if (rpc->error) {
+             hsk->error_msg = "RPC failed";
+             result = rpc->error;
+     } else {
+             result = rpc->msgin.length;
+     }
+     result = rpc->error ? rpc->error : rpc->msgin.length;
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This isn't a bug, but there's redundant dead-store code here.

The if/else block assigns 'result' to either 'rpc->error' or 'rpc->msgin.length', but the next line immediately overwrites 'result' with the identical ternary expression.

The two 'result = ...' assignments inside the if/else are dead stores that are always overwritten. The if/else block's only surviving side effect is setting 'hsk->error_msg = "RPC failed"' when rpc->error is nonzero.

Quoted 4 lines

This appears to be an editing mistake where either the if/else should be the authoritative result assignment (and the ternary deleted), or the ternary should remain and the if/else should be simplified to only set error_msg (removing its result assignments).

Fixed.

Quoted 23 lines
Quoted 4 lines
net/homa/homa_plumbing.c new file +3 -0
+
+     /* Collect result information. */
+     control.id = rpc->id;

[ ... ]

net/homa/homa_plumbing.c line 1213

Quoted 11 lines
net/homa/homa_plumbing.c new file +11 -0
+/**
+ * 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_RESTART.
+ */
+enum hrtimer_restart homa_hrtimer(struct hrtimer *timer)
+{
+     wake_up_process(timer_kthread);
+     return HRTIMER_NORESTART;
        ^^^^^^^^^^^^^^^^^^^^^^

The kernel-doc comment states 'Return: Always HRTIMER_RESTART' but the function returns HRTIMER_NORESTART.

Quoted 6 lines

The runtime behavior is correct (homa_timer_main re-arms the hrtimer explicitly via hrtimer_start on each loop iteration, so HRTIMER_NORESTART is the intended return value), but the comment contradicts the code.

This misleads readers into believing the timer auto-restarts, when it does not.

Fixed.

#33 lore raw

PATCH v17 14/14 net: homa: create Makefile and Kconfig

In reply to John Ousterhout

Before this commit the Homa code is "inert": it won't be compiled in kernel builds. This commit adds Homa's Makefile and Kconfig, and also links Homa into net/Makefile and net/Kconfig, so that Homa will be built during kernel builds if enabled (it is disabled by default).

---
 net/Kconfig       |  1 +
 net/Makefile      |  1 +
 net/homa/Kconfig  | 21 +++++++++++++++++++++
 net/homa/Makefile | 15 +++++++++++++++
 4 files changed, 38 insertions(+)
 create mode 100644 net/homa/Kconfig
 create mode 100644 net/homa/Makefile
net/Kconfig +1 -0
index 62266eaf0e95..41bcc80ee9ec 100644
@@ -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"
net/Makefile +1 -0
index 90e3d72bf58b..17e0ba84bd15 100644
@@ -44,6 +44,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/
net/homa/Kconfig new file +21 -0
new file mode 100644
index 000000000000..16fec3fd52ba
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier: BSD-2-Clause or GPL-2.0+
+#
+# Homa transport protocol
+#
+
+menuconfig HOMA
+	tristate "The Homa transport protocol"
+	depends on INET
+	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.
net/homa/Makefile new file +15 -0
new file mode 100644
index 000000000000..1e02be7f69d6
@@ -0,0 +1,15 @@
+# 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_utils.o
Signature · 1 line
2.43.0
#34 lore raw

Re: [PATCH net-next v17 14/14] net: homa: create Makefile and Kconfig

kernel test robot noticed the following build errors:

Hi John,

kernel test robot noticed the following build errors:

[auto build test ERROR on net-next/main]

url:    https://github.com/intel-lab-lkp/linux/commits/John-Ousterhout/net-homa-define-user-visible-API-for-Homa/20260317-070659
base:   net-next/main
patch link:    https://lore.kernel.org/r/20260316223228.2611-15-ouster%40cs.stanford.edu
patch subject: [PATCH net-next v17 14/14] net: homa: create Makefile and Kconfig
config: m68k-allmodconfig (https://download.01.org/0day-ci/archive/20260318/[email protected]/config)
compiler: m68k-linux-gcc (GCC) 15.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260318/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> net/homa/homa_plumbing.c:94:30: error: initialization of 'int (*)(struct sock *, struct msghdr *, size_t,  int)' {aka 'int (*)(struct sock *, struct msghdr *, unsigned int,  int)'} from incompatible pointer type 'int (*)(struct sock *, struct msghdr *, size_t,  int,  int *)' {aka 'int (*)(struct sock *, struct msghdr *, unsigned int,  int,  int *)'} [-Wincompatible-pointer-types]
      94 |         .recvmsg           = homa_recvmsg,
         |                              ^~~~~~~~~~~~
   net/homa/homa_plumbing.c:94:30: note: (near initialization for 'homa_prot.recvmsg')
   In file included from net/homa/homa_plumbing.c:7:
   net/homa/homa_impl.h:402:10: note: 'homa_recvmsg' declared here
     402 | int      homa_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
         |          ^~~~~~~~~~~~
   net/homa/homa_plumbing.c:111:30: error: initialization of 'int (*)(struct sock *, struct msghdr *, size_t,  int)' {aka 'int (*)(struct sock *, struct msghdr *, unsigned int,  int)'} from incompatible pointer type 'int (*)(struct sock *, struct msghdr *, size_t,  int,  int *)' {aka 'int (*)(struct sock *, struct msghdr *, unsigned int,  int,  int *)'} [-Wincompatible-pointer-types]
     111 |         .recvmsg           = homa_recvmsg,
         |                              ^~~~~~~~~~~~
   net/homa/homa_plumbing.c:111:30: note: (near initialization for 'homav6_prot.recvmsg')
   net/homa/homa_impl.h:402:10: note: 'homa_recvmsg' declared here
     402 | int      homa_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
         |          ^~~~~~~~~~~~

vim +94 net/homa/homa_plumbing.c

fda29e883f7618 John Ousterhout 2026-03-16   77  
fda29e883f7618 John Ousterhout 2026-03-16   78  /* This structure also defines functions that handle various operations
fda29e883f7618 John Ousterhout 2026-03-16   79   * on Homa sockets. However, these functions are lower-level than those
fda29e883f7618 John Ousterhout 2026-03-16   80   * in homa_proto_ops: they are specific to the PF_INET or PF_INET6
fda29e883f7618 John Ousterhout 2026-03-16   81   * protocol family, and in many cases they are invoked by functions in
fda29e883f7618 John Ousterhout 2026-03-16   82   * homa_proto_ops. Most of these functions have Homa-specific implementations.
fda29e883f7618 John Ousterhout 2026-03-16   83   */
fda29e883f7618 John Ousterhout 2026-03-16   84  static struct proto homa_prot = {
fda29e883f7618 John Ousterhout 2026-03-16   85  	.name		   = "HOMA",
fda29e883f7618 John Ousterhout 2026-03-16   86  	.owner		   = THIS_MODULE,
fda29e883f7618 John Ousterhout 2026-03-16   87  	.close		   = homa_close,
fda29e883f7618 John Ousterhout 2026-03-16   88  	.connect	   = ip4_datagram_connect,
fda29e883f7618 John Ousterhout 2026-03-16   89  	.init		   = homa_socket,
fda29e883f7618 John Ousterhout 2026-03-16   90  	.destroy	   = homa_sock_destroy,
fda29e883f7618 John Ousterhout 2026-03-16   91  	.setsockopt	   = homa_setsockopt,
fda29e883f7618 John Ousterhout 2026-03-16   92  	.getsockopt	   = homa_getsockopt,
fda29e883f7618 John Ousterhout 2026-03-16   93  	.sendmsg	   = homa_sendmsg,
fda29e883f7618 John Ousterhout 2026-03-16  @94  	.recvmsg	   = homa_recvmsg,
fda29e883f7618 John Ousterhout 2026-03-16   95  	.hash		   = homa_hash,
fda29e883f7618 John Ousterhout 2026-03-16   96  	.unhash		   = homa_unhash,
fda29e883f7618 John Ousterhout 2026-03-16   97  	.obj_size	   = sizeof(struct homa_sock),
fda29e883f7618 John Ousterhout 2026-03-16   98  	.no_autobind       = 1,
fda29e883f7618 John Ousterhout 2026-03-16   99  };

fda29e883f7618 John Ousterhout 2026-03-16 100

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#35 lore raw

Re: [PATCH net-next v17 14/14] net: homa: create Makefile and Kconfig

In reply to John Ousterhout
kernel test robot noticed the following build errors:

Hi John,

kernel test robot noticed the following build errors:

[auto build test ERROR on net-next/main]

url:    https://github.com/intel-lab-lkp/linux/commits/John-Ousterhout/net-homa-define-user-visible-API-for-Homa/20260317-070659
base:   net-next/main
patch link:    https://lore.kernel.org/r/20260316223228.2611-15-ouster%40cs.stanford.edu
patch subject: [PATCH net-next v17 14/14] net: homa: create Makefile and Kconfig
config: sparc64-allmodconfig (https://download.01.org/0day-ci/archive/20260318/[email protected]/config)
compiler: clang version 23.0.0git (https://github.com/llvm/llvm-project 4abb927bacf37f18f6359a41639a6d1b3bffffb5)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260318/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> net/homa/homa_plumbing.c:94:16: error: incompatible function pointer types initializing 'int (*)(struct sock *, struct msghdr *, size_t, int)' (aka 'int (*)(struct sock *, struct msghdr *, unsigned long, int)') with an expression of type 'int (struct sock *, struct msghdr *, size_t, int, int *)' (aka 'int (struct sock *, struct msghdr *, unsigned long, int, int *)') [-Wincompatible-function-pointer-types]

94 | .recvmsg = homa_recvmsg,
| ^~~~~~~~~~~~
net/homa/homa_plumbing.c:111:16: error: incompatible function pointer types initializing 'int (*)(struct sock *, struct msghdr *, size_t, int)' (aka 'int (*)(struct sock *, struct msghdr *, unsigned long, int)') with an expression of type 'int (struct sock *, struct msghdr *, size_t, int, int *)' (aka 'int (struct sock *, struct msghdr *, unsigned long, int, int *)') [-Wincompatible-function-pointer-types]
111 | .recvmsg = homa_recvmsg,
| ^~~~~~~~~~~~
2 errors generated.

vim +94 net/homa/homa_plumbing.c

fda29e883f7618b John Ousterhout 2026-03-16   77  
fda29e883f7618b John Ousterhout 2026-03-16   78  /* This structure also defines functions that handle various operations
fda29e883f7618b John Ousterhout 2026-03-16   79   * on Homa sockets. However, these functions are lower-level than those
fda29e883f7618b John Ousterhout 2026-03-16   80   * in homa_proto_ops: they are specific to the PF_INET or PF_INET6
fda29e883f7618b John Ousterhout 2026-03-16   81   * protocol family, and in many cases they are invoked by functions in
fda29e883f7618b John Ousterhout 2026-03-16   82   * homa_proto_ops. Most of these functions have Homa-specific implementations.
fda29e883f7618b John Ousterhout 2026-03-16   83   */
fda29e883f7618b John Ousterhout 2026-03-16   84  static struct proto homa_prot = {
fda29e883f7618b John Ousterhout 2026-03-16   85  	.name		   = "HOMA",
fda29e883f7618b John Ousterhout 2026-03-16   86  	.owner		   = THIS_MODULE,
fda29e883f7618b John Ousterhout 2026-03-16   87  	.close		   = homa_close,
fda29e883f7618b John Ousterhout 2026-03-16   88  	.connect	   = ip4_datagram_connect,
fda29e883f7618b John Ousterhout 2026-03-16   89  	.init		   = homa_socket,
fda29e883f7618b John Ousterhout 2026-03-16   90  	.destroy	   = homa_sock_destroy,
fda29e883f7618b John Ousterhout 2026-03-16   91  	.setsockopt	   = homa_setsockopt,
fda29e883f7618b John Ousterhout 2026-03-16   92  	.getsockopt	   = homa_getsockopt,
fda29e883f7618b John Ousterhout 2026-03-16   93  	.sendmsg	   = homa_sendmsg,
fda29e883f7618b John Ousterhout 2026-03-16  @94  	.recvmsg	   = homa_recvmsg,
fda29e883f7618b John Ousterhout 2026-03-16   95  	.hash		   = homa_hash,
fda29e883f7618b John Ousterhout 2026-03-16   96  	.unhash		   = homa_unhash,
fda29e883f7618b John Ousterhout 2026-03-16   97  	.obj_size	   = sizeof(struct homa_sock),
fda29e883f7618b John Ousterhout 2026-03-16   98  	.no_autobind       = 1,
fda29e883f7618b John Ousterhout 2026-03-16   99  };

fda29e883f7618b John Ousterhout 2026-03-16 100

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki