Relationship
图 1: NetworkEndpoint 关联图
**
NetworkEndpoint 处理与 IP 层协议内容,每个 NetworkEndpoint 的实例会对应某个 IP 层协议,用于处理与该协议相关细节。NetworkProtocol 负责创建 NetworkEndpoint 实例,并通过协议号关联。当链路层收到报文时,根据链路层中协议号选择对应的 NetworkEndpoint 进行处理。
提问:NetworkEndpoint 如何处理多个 IP 地址?
ARP Protocol
Overview
图 2: ARP 处理关系图
**
arp.protocol 是 ARP 协议的 NetworkProtocol 实现,ARP 请求与应答主流程如上图。初始 endpoint 实例时,要对其地址管理部分进行初始化操作,如下所示
func (p *protocol) NewEndpoint(nic stack.NetworkInterface, linkAddrCache stack.LinkAddressCache, nud stack.NUDHandler, dispatcher stack.TransportDispatcher) stack.NetworkEndpoint {e := &endpoint{protocol: p,nic: nic,linkAddrCache: linkAddrCache,nud: nud,}e.AddressableEndpointState.Init(e) // 初始化地址return e}
构建发送 ARP 请求的代码如下
// LinkAddressRequest implements stack.LinkAddressResolver.LinkAddressRequest.func (*protocol) LinkAddressRequest(addr, localAddr tcpip.Address, remoteLinkAddr tcpip.LinkAddress, linkEP stack.LinkEndpoint) *tcpip.Error {r := &stack.Route{NetProto: ProtocolNumber,RemoteLinkAddress: remoteLinkAddr,}if len(r.RemoteLinkAddress) == 0 {r.RemoteLinkAddress = header.EthernetBroadcastAddress}// 构建 ARP 报文pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{ReserveHeaderBytes: int(linkEP.MaxHeaderLength()) + header.ARPSize,})h := header.ARP(pkt.NetworkHeader().Push(header.ARPSize))h.SetIPv4OverEthernet()h.SetOp(header.ARPRequest)copy(h.HardwareAddressSender(), linkEP.LinkAddress())copy(h.ProtocolAddressSender(), localAddr)copy(h.ProtocolAddressTarget(), addr)return linkEP.WritePacket(r, nil /* gso */, ProtocolNumber, pkt)}
Request Handling Procedure
图 3: ARP Request 请求逻辑图
为了将 Stack 对象与链路层实例解耦,定义了 LinkAddressCache 与 NetworkEndpoint 接口,这样对于 ARP 请求的处理,通过上图中橙色线兜一圈后又最终回到了 link.endpoint 进行处理。
link.endpoint 通过匿名包含 stack.AddressableEndpointState 来实现 LinkAddressCache 接口。以 ARP 请求过程中 Stack 对象的 CheckLocalAddress() 方法为例,调用关系入下图所示。
图 4: AddressableEndpointState
**
AddressableEndpointState 定义如下,不难看出,其核心为 endpoints 域,是 tcpip.Address 实例到 addressState 实例的映射,tcpip.Address 是 string 类型的别名。
// AddressableEndpointState is an implementation of an AddressableEndpoint.type AddressableEndpointState struct {networkEndpoint NetworkEndpoint// Lock ordering (from outer to inner lock ordering)://// AddressableEndpointState.mu// addressState.mumu struct {sync.RWMutexendpoints map[tcpip.Address]*addressStateprimary []*addressState// groups holds the mapping between group addresses and the number of times// they have been joined.groups map[tcpip.Address]uint32}}
通过上面的内容,不难理解其 AquireAssignedAddress 方法的逻辑
// AcquireAssignedAddress implements AddressableEndpoint.func (a *AddressableEndpointState) AcquireAssignedAddress(localAddr tcpip.Address, allowTemp bool, tempPEB PrimaryEndpointBehavior) AddressEndpoint {a.mu.Lock()defer a.mu.Unlock()// 地址存在if addrState, ok := a.mu.endpoints[localAddr]; ok {if !addrState.IsAssigned(allowTemp) {return nil}if !addrState.IncRef() { // 引用次数增加panic(fmt.Sprintf("failed to increase the reference count for address = %s", addrState.addr))}return addrState}if !allowTemp {return nil}// 地址不存在,创建新地址addr := localAddr.WithPrefix()ep, err := a.addAndAcquireAddressLocked(addr, tempPEB, AddressConfigStatic, false /* deprecated */, false /* permanent */)if err != nil {// addAndAcquireAddressLocked only returns an error if the address is// already assigned but we just checked above if the address exists so we// expect no error.panic(fmt.Sprintf("a.addAndAcquireAddressLocked(%s, %d, %d, false, false): %s", addr, tempPEB, AddressConfigStatic, err))}// From https://golang.org/doc/faq#nil_error://// Under the covers, interfaces are implemented as two elements, a type T and// a value V.//// An interface value is nil only if the V and T are both unset, (T=nil, V is// not set), In particular, a nil interface will always hold a nil type. If we// store a nil pointer of type *int inside an interface value, the inner type// will be *int regardless of the value of the pointer: (T=*int, V=nil). Such// an interface value will therefore be non-nil even when the pointer value V// inside is nil.//// Since addAndAcquireAddressLocked returns a nil value with a non-nil type,// we need to explicitly return nil below if ep is (a typed) nil.if ep == nil {return nil}return ep}
地址相关结构如下图所示,其中 addressState 代表一个地址状态
图 5: 地址结构关联
IPv4 Protocol
Overview
图 6: IPv4 Endpoint 概览
ipv4.endpoint 由 ipv4.protocol 创建生成,由 IPv4 本身的特性决定,分片处理及路由处理不区分网卡或 IP 地址,因此,这部分内容只需要在 protocol 中统一处理即可。
发送数据时,触发 endpoint 的 WritePacket(s) 方法。在方法中,核心功能为路由查询及分片处理,路由检查需要协议栈配合,代码如下
nicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())ipt := e.protocol.stack.IPTables()if ok := ipt.Check(stack.Output, pkt, gso, r, "", nicName); !ok {// iptables is telling us to drop the packet.r.Stats().IP.IPTablesOutputDropped.Increment()return nil}
路由检查完毕,并且没有错误发生,后续执行 NAT 转换处理,代码如下
if pkt.NatDone {netHeader := header.IPv4(pkt.NetworkHeader().View())ep, err := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress())if err == nil {route := r.ReverseRoute(netHeader.SourceAddress(), netHeader.DestinationAddress())ep.HandlePacket(&route, pkt)return nil}}
如果发送的数据包不需要 NAT 操作,处理分片
if e.packetMustBeFragmented(pkt, gso) {sent, remain, err := e.handleFragments(r, gso, e.nic.MTU(), pkt, func(fragPkt *stack.PacketBuffer) *tcpip.Error {// TODO(gvisor.dev/issue/3884): Evaluate whether we want to send each// fragment one by one using WritePacket() (current strategy) or if we// want to create a PacketBufferList from the fragments and feed it to// WritePackets(). It'll be faster but cost more memory.return e.nic.WritePacket(r, gso, ProtocolNumber, fragPkt)})r.Stats().IP.PacketsSent.IncrementBy(uint64(sent))r.Stats().IP.OutgoingPacketErrors.IncrementBy(uint64(remain))return err}
最终,通过 nic 发送数据
if err := e.nic.WritePacket(r, gso, ProtocolNumber, pkt); err != nil {r.Stats().IP.OutgoingPacketErrors.Increment()return err}
Link Address Cache
图 7: linkAddrCache 核心组件
**
linkAddrCache 用于发起 ARP 请求,并缓存 ARP 应答结果。在以太网通信中,IP 层使用 IP 地址作为通信两端的身份标识,但在链路层,需要根据链路层唯一标识来确认通信两端的身份,因此需要引入 ARP 协议。这里需要注意到,链路层并不是只要 MAC 地址一种表达方式,虽然我们后续的讨论仍然围绕 MAC 展开,但要适度考虑其他链路层存在的可能性。linkAddrCache 关键方法 get 代码如下
// get reports any known link address for k.func (c *linkAddrCache) get(k tcpip.FullAddress, linkRes LinkAddressResolver, localAddr tcpip.Address, linkEP LinkEndpoint, waker *sleep.Waker) (tcpip.LinkAddress, <-chan struct{}, *tcpip.Error) {if linkRes != nil {if addr, ok := linkRes.ResolveStaticAddress(k.Addr); ok {return addr, nil, nil}}c.cache.Lock()defer c.cache.Unlock()entry := c.getOrCreateEntryLocked(k)switch s := entry.s; s {case ready, failed:if !time.Now().After(entry.expiration) {// Not expired.switch s {case ready:return entry.linkAddr, nil, nilcase failed:return entry.linkAddr, nil, tcpip.ErrNoLinkAddressdefault:panic(fmt.Sprintf("invalid cache entry state: %s", s))}}entry.changeState(incomplete, time.Time{})fallthroughcase incomplete:if waker != nil {if entry.wakers == nil {entry.wakers = make(map[*sleep.Waker]struct{})}entry.wakers[waker] = struct{}{}}if entry.done == nil {// Address resolution needs to be initiated.if linkRes == nil {return entry.linkAddr, nil, tcpip.ErrNoLinkAddress}entry.done = make(chan struct{})go c.startAddressResolution(k, linkRes, localAddr, linkEP, entry.done) // S/R-SAFE: link non-savable; wakers dropped synchronously.}return entry.linkAddr, entry.done, tcpip.ErrWouldBlockdefault:panic(fmt.Sprintf("invalid cache entry state: %s", s))}}
Sleeper & Waker
图 8: Sleeper & Waker 关系图
Sleeper 中主要包含了三条独立并互相关联的 Waker 链表,如上图所示,从名称中能粗略判断三条链表的作用,在此暂不做详细描述,先看 Sleeper 及 Waker 的定义:
type Sleeper struct {// sharedList is a "stack" of asserted wakers. They atomically add// themselves to the front of this list as they become asserted.sharedList unsafe.Pointer// localList is a list of asserted wakers that is only accessible to the// waiter, and thus doesn't have to be accessed atomically. When// fetching more wakers, the waiter will first go through this list, and// only when it's empty will it atomically fetch wakers from// sharedList.localList *Waker// allWakers is a list with all wakers that have been added to this// sleeper. It is used during cleanup to remove associations.allWakers *Waker// waitingG holds the G that is sleeping, if any. It is used by wakers// to determine which G, if any, they should wake.waitingG uintptr}type Waker struct {_ sync.NoCopy// s is the sleeper that this waker can wake up. Only one sleeper at a// time is allowed. This field can have three classes of values:// nil -- the waker is not asserted: it either is not associated with// a sleeper, or is queued to a sleeper due to being previously// asserted. This is the zero value.// &assertedSleeper -- the waker is asserted.// otherwise -- the waker is not asserted, and is associated with the// given sleeper. Once it transitions to asserted state, the// associated sleeper will be woken.s unsafe.Pointer// next is used to form a linked list of asserted wakers in a sleeper.next *Waker// allWakersNext is used to form a linked list of all wakers associated// to a given sleeper.allWakersNext *Waker// id is the value to be returned to sleepers when they wake up due to// this waker being asserted.id int}
Add a Waker
图 9: AddWaker 示意图
**
AddWaker 方法,将一个 Waker 添加到执行本方法的 Sleeper 上。首先,将新 Waker 添加至链表 allWakers 上,然后,对新 Waker 当前指向的 Sleeper 域进行判断,具体如下
// Try to associate the waker with the sleeper. If it's already// asserted, we simply enqueue it in the "ready" list.for {p := (*Sleeper)(atomic.LoadPointer(&w.s))if p == &assertedSleeper { // 如果 Waker 当前 Sleeper 为 assertedSleepers.enqueueAssertedWaker(w)return}// 修改 Waker 指向当前 Sleeperif atomic.CompareAndSwapPointer(&w.s, usleeper(p), usleeper(s)) {return}}
接着,来看一下 enqueueAssertedWaker 方法
func (s *Sleeper) enqueueAssertedWaker(w *Waker) {// 将 w 添加进 Sleeper 的 sharedList 中,注意 CAS 操作即可// Add the new waker to the front of the list.for {v := (*Waker)(atomic.LoadPointer(&s.sharedList))w.next = vif atomic.CompareAndSwapPointer(&s.sharedList, uwaker(v), uwaker(w)) {break}}// 无等待状态的 Waker,直接返回即可// Nothing to do if there isn't a G waiting.if atomic.LoadUintptr(&s.waitingG) == 0 {return}// Signal to the sleeper that a waker has been asserted.switch g := atomic.SwapUintptr(&s.waitingG, 0); g {case 0, preparingG:default:// We managed to get a G. Wake it up.goready(g, 0)}}
Assert a Waker
// Assert moves the waker to an asserted state, if it isn't asserted yet. When// asserted, the waker will cause its matching sleeper to wake up.func (w *Waker) Assert() {// Nothing to do if the waker is already asserted. This check allows us// to complete this case (already asserted) without any interlocked// operations on x86.if atomic.LoadPointer(&w.s) == usleeper(&assertedSleeper) {return}// Mark the waker as asserted, and wake up a sleeper if there is one.switch s := (*Sleeper)(atomic.SwapPointer(&w.s, usleeper(&assertedSleeper))); s {case nil:case &assertedSleeper:default:// 由于当前 Waker 已被链接至 assertedSleeper,且该 Waker 指向的 Sleeper 也被转移,// 因此,需要在原 Sleeper 中将当前 Waker 进行处理s.enqueueAssertedWaker(w)}}
Fetch the next Waker
// nextWaker returns the next waker in the notification list, blocking if// needed.func (s *Sleeper) nextWaker(block bool) *Waker {// Attempt to replenish the local list if it's currently empty.if s.localList == nil {for atomic.LoadPointer(&s.sharedList) == nil {// Fail request if caller requested that we// don't block.if !block {return nil}// Indicate to wakers that we're about to sleep,// this allows them to abort the wait by setting// waitingG back to zero (which we'll notice// before committing the sleep).atomic.StoreUintptr(&s.waitingG, preparingG)// Check if something was queued while we were// preparing to sleep. We need this interleaving// to avoid missing wake ups.if atomic.LoadPointer(&s.sharedList) != nil {atomic.StoreUintptr(&s.waitingG, 0)break}// Try to commit the sleep and report it to the// tracer as a select.//// gopark puts the caller to sleep and calls// commitSleep to decide whether to immediately// wake the caller up or to leave it sleeping.const traceEvGoBlockSelect = 24// See:runtime2.go in the go runtime package for// the values to pass as the waitReason here.const waitReasonSelect = 9gopark(commitSleep, &s.waitingG, waitReasonSelect, traceEvGoBlockSelect, 0)}// Pull the shared list out and reverse it in the local// list. Given that wakers push themselves in reverse// order, we fix things here.v := (*Waker)(atomic.SwapPointer(&s.sharedList, nil))for v != nil {cur := vv = v.nextcur.next = s.localLists.localList = cur}}// Remove the waker in the front of the list.w := s.localLists.localList = w.nextreturn w}
Route
// Route represents a route through the networking stack to a given destination.type Route struct {// RemoteAddress is the final destination of the route.RemoteAddress tcpip.Address// RemoteLinkAddress is the link-layer (MAC) address of the// final destination of the route.RemoteLinkAddress tcpip.LinkAddress// LocalAddress is the local address where the route starts.LocalAddress tcpip.Address// LocalLinkAddress is the link-layer (MAC) address of the// where the route starts.LocalLinkAddress tcpip.LinkAddress// NextHop is the next node in the path to the destination.NextHop tcpip.Address// NetProto is the network-layer protocol.NetProto tcpip.NetworkProtocolNumber// Loop controls where WritePacket should send packets.Loop PacketLooping// nic is the NIC the route goes through.nic *NIC// addressEndpoint is the local address this route is associated with.addressEndpoint AssignableAddressEndpoint// linkCache is set if link address resolution is enabled for this protocol on// the route's NIC.linkCache LinkAddressCache// linkRes is set if link address resolution is enabled for this protocol on// the route's NIC.linkRes LinkAddressResolver}
路由模块儿用于控制发送数据包的流向,通过数据包的目标地址来选择发送该包的网络接口卡。Route 结构代码中不难发现,它在记录目标地址时,也同时记录了源地址,并且包含了 LinkAddressCache 接口及 LinkAddressResolver 接口,这些的作用是什么呢?
Resolve
func (r *Route) Resolve(waker *sleep.Waker) (<-chan struct{}, *tcpip.Error) {if !r.IsResolutionRequired() {// Nothing to do if there is no cache (which does the resolution on cache miss) or// link address is already known.return nil, nil}nextAddr := r.NextHopif nextAddr == "" {// Local link address is already known.if r.RemoteAddress == r.LocalAddress {r.RemoteLinkAddress = r.LocalLinkAddressreturn nil, nil}nextAddr = r.RemoteAddress}if neigh := r.nic.neigh; neigh != nil {entry, ch, err := neigh.entry(nextAddr, r.LocalAddress, r.linkRes, waker)if err != nil {return ch, err}r.RemoteLinkAddress = entry.LinkAddrreturn nil, nil}linkAddr, ch, err := r.linkCache.GetLinkAddress(r.nic.ID(), nextAddr, r.LocalAddress, r.NetProto, waker)if err != nil {return ch, err}r.RemoteLinkAddress = linkAddrreturn nil, nil}
Resolve 方法用于解析路由目标地址对应的链路层地址,在以太网下,会使用 ARP 协议进行解析。为了保证 IP 层性能问题,引入了 neighborCache 对已解析地址进行缓存处理。只有在缓存中不存在的记录才会进行解析。
