Relationship

netstack-network-endpoint-relation-ship.svg
图 1: NetworkEndpoint 关联图
**
NetworkEndpoint 处理与 IP 层协议内容,每个 NetworkEndpoint 的实例会对应某个 IP 层协议,用于处理与该协议相关细节。NetworkProtocol 负责创建 NetworkEndpoint 实例,并通过协议号关联。当链路层收到报文时,根据链路层中协议号选择对应的 NetworkEndpoint 进行处理。

提问:NetworkEndpoint 如何处理多个 IP 地址?

ARP Protocol

Overview

netstack-network-endpoint-arp.svg
图 2: ARP 处理关系图
**
arp.protocol 是 ARP 协议的 NetworkProtocol 实现,ARP 请求与应答主流程如上图。初始 endpoint 实例时,要对其地址管理部分进行初始化操作,如下所示

  1. func (p *protocol) NewEndpoint(nic stack.NetworkInterface, linkAddrCache stack.LinkAddressCache, nud stack.NUDHandler, dispatcher stack.TransportDispatcher) stack.NetworkEndpoint {
  2. e := &endpoint{
  3. protocol: p,
  4. nic: nic,
  5. linkAddrCache: linkAddrCache,
  6. nud: nud,
  7. }
  8. e.AddressableEndpointState.Init(e) // 初始化地址
  9. return e
  10. }

构建发送 ARP 请求的代码如下

  1. // LinkAddressRequest implements stack.LinkAddressResolver.LinkAddressRequest.
  2. func (*protocol) LinkAddressRequest(addr, localAddr tcpip.Address, remoteLinkAddr tcpip.LinkAddress, linkEP stack.LinkEndpoint) *tcpip.Error {
  3. r := &stack.Route{
  4. NetProto: ProtocolNumber,
  5. RemoteLinkAddress: remoteLinkAddr,
  6. }
  7. if len(r.RemoteLinkAddress) == 0 {
  8. r.RemoteLinkAddress = header.EthernetBroadcastAddress
  9. }
  10. // 构建 ARP 报文
  11. pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
  12. ReserveHeaderBytes: int(linkEP.MaxHeaderLength()) + header.ARPSize,
  13. })
  14. h := header.ARP(pkt.NetworkHeader().Push(header.ARPSize))
  15. h.SetIPv4OverEthernet()
  16. h.SetOp(header.ARPRequest)
  17. copy(h.HardwareAddressSender(), linkEP.LinkAddress())
  18. copy(h.ProtocolAddressSender(), localAddr)
  19. copy(h.ProtocolAddressTarget(), addr)
  20. return linkEP.WritePacket(r, nil /* gso */, ProtocolNumber, pkt)
  21. }

Request Handling Procedure

netstack-network-endpoint-address-request-handling.svg
图 3: ARP Request 请求逻辑图

为了将 Stack 对象与链路层实例解耦,定义了 LinkAddressCache 与 NetworkEndpoint 接口,这样对于 ARP 请求的处理,通过上图中橙色线兜一圈后又最终回到了 link.endpoint 进行处理。

link.endpoint 通过匿名包含 stack.AddressableEndpointState 来实现 LinkAddressCache 接口。以 ARP 请求过程中 Stack 对象的 CheckLocalAddress() 方法为例,调用关系入下图所示。
netstack-network-endpoint-addressable-endpoint-state.svg
图 4: AddressableEndpointState
**
AddressableEndpointState 定义如下,不难看出,其核心为 endpoints 域,是 tcpip.Address 实例到 addressState 实例的映射,tcpip.Address 是 string 类型的别名。

  1. // AddressableEndpointState is an implementation of an AddressableEndpoint.
  2. type AddressableEndpointState struct {
  3. networkEndpoint NetworkEndpoint
  4. // Lock ordering (from outer to inner lock ordering):
  5. //
  6. // AddressableEndpointState.mu
  7. // addressState.mu
  8. mu struct {
  9. sync.RWMutex
  10. endpoints map[tcpip.Address]*addressState
  11. primary []*addressState
  12. // groups holds the mapping between group addresses and the number of times
  13. // they have been joined.
  14. groups map[tcpip.Address]uint32
  15. }
  16. }

通过上面的内容,不难理解其 AquireAssignedAddress 方法的逻辑

  1. // AcquireAssignedAddress implements AddressableEndpoint.
  2. func (a *AddressableEndpointState) AcquireAssignedAddress(localAddr tcpip.Address, allowTemp bool, tempPEB PrimaryEndpointBehavior) AddressEndpoint {
  3. a.mu.Lock()
  4. defer a.mu.Unlock()
  5. // 地址存在
  6. if addrState, ok := a.mu.endpoints[localAddr]; ok {
  7. if !addrState.IsAssigned(allowTemp) {
  8. return nil
  9. }
  10. if !addrState.IncRef() { // 引用次数增加
  11. panic(fmt.Sprintf("failed to increase the reference count for address = %s", addrState.addr))
  12. }
  13. return addrState
  14. }
  15. if !allowTemp {
  16. return nil
  17. }
  18. // 地址不存在,创建新地址
  19. addr := localAddr.WithPrefix()
  20. ep, err := a.addAndAcquireAddressLocked(addr, tempPEB, AddressConfigStatic, false /* deprecated */, false /* permanent */)
  21. if err != nil {
  22. // addAndAcquireAddressLocked only returns an error if the address is
  23. // already assigned but we just checked above if the address exists so we
  24. // expect no error.
  25. panic(fmt.Sprintf("a.addAndAcquireAddressLocked(%s, %d, %d, false, false): %s", addr, tempPEB, AddressConfigStatic, err))
  26. }
  27. // From https://golang.org/doc/faq#nil_error:
  28. //
  29. // Under the covers, interfaces are implemented as two elements, a type T and
  30. // a value V.
  31. //
  32. // An interface value is nil only if the V and T are both unset, (T=nil, V is
  33. // not set), In particular, a nil interface will always hold a nil type. If we
  34. // store a nil pointer of type *int inside an interface value, the inner type
  35. // will be *int regardless of the value of the pointer: (T=*int, V=nil). Such
  36. // an interface value will therefore be non-nil even when the pointer value V
  37. // inside is nil.
  38. //
  39. // Since addAndAcquireAddressLocked returns a nil value with a non-nil type,
  40. // we need to explicitly return nil below if ep is (a typed) nil.
  41. if ep == nil {
  42. return nil
  43. }
  44. return ep
  45. }

地址相关结构如下图所示,其中 addressState 代表一个地址状态
netstack-network-endpoint-address-state.svg
图 5: 地址结构关联

IPv4 Protocol

Overview

netstack-network-endpoint-ip-landscape.svg
图 6: IPv4 Endpoint 概览

ipv4.endpoint 由 ipv4.protocol 创建生成,由 IPv4 本身的特性决定,分片处理及路由处理不区分网卡或 IP 地址,因此,这部分内容只需要在 protocol 中统一处理即可。

发送数据时,触发 endpoint 的 WritePacket(s) 方法。在方法中,核心功能为路由查询及分片处理,路由检查需要协议栈配合,代码如下

  1. nicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())
  2. ipt := e.protocol.stack.IPTables()
  3. if ok := ipt.Check(stack.Output, pkt, gso, r, "", nicName); !ok {
  4. // iptables is telling us to drop the packet.
  5. r.Stats().IP.IPTablesOutputDropped.Increment()
  6. return nil
  7. }

路由检查完毕,并且没有错误发生,后续执行 NAT 转换处理,代码如下

  1. if pkt.NatDone {
  2. netHeader := header.IPv4(pkt.NetworkHeader().View())
  3. ep, err := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress())
  4. if err == nil {
  5. route := r.ReverseRoute(netHeader.SourceAddress(), netHeader.DestinationAddress())
  6. ep.HandlePacket(&route, pkt)
  7. return nil
  8. }
  9. }

如果发送的数据包不需要 NAT 操作,处理分片

  1. if e.packetMustBeFragmented(pkt, gso) {
  2. sent, remain, err := e.handleFragments(r, gso, e.nic.MTU(), pkt, func(fragPkt *stack.PacketBuffer) *tcpip.Error {
  3. // TODO(gvisor.dev/issue/3884): Evaluate whether we want to send each
  4. // fragment one by one using WritePacket() (current strategy) or if we
  5. // want to create a PacketBufferList from the fragments and feed it to
  6. // WritePackets(). It'll be faster but cost more memory.
  7. return e.nic.WritePacket(r, gso, ProtocolNumber, fragPkt)
  8. })
  9. r.Stats().IP.PacketsSent.IncrementBy(uint64(sent))
  10. r.Stats().IP.OutgoingPacketErrors.IncrementBy(uint64(remain))
  11. return err
  12. }

最终,通过 nic 发送数据

  1. if err := e.nic.WritePacket(r, gso, ProtocolNumber, pkt); err != nil {
  2. r.Stats().IP.OutgoingPacketErrors.Increment()
  3. return err
  4. }

Link Address Cache

netstack-network-endpoint-link-addr-cache.svg
图 7: linkAddrCache 核心组件
**
linkAddrCache 用于发起 ARP 请求,并缓存 ARP 应答结果。在以太网通信中,IP 层使用 IP 地址作为通信两端的身份标识,但在链路层,需要根据链路层唯一标识来确认通信两端的身份,因此需要引入 ARP 协议。这里需要注意到,链路层并不是只要 MAC 地址一种表达方式,虽然我们后续的讨论仍然围绕 MAC 展开,但要适度考虑其他链路层存在的可能性。linkAddrCache 关键方法 get 代码如下

  1. // get reports any known link address for k.
  2. func (c *linkAddrCache) get(k tcpip.FullAddress, linkRes LinkAddressResolver, localAddr tcpip.Address, linkEP LinkEndpoint, waker *sleep.Waker) (tcpip.LinkAddress, <-chan struct{}, *tcpip.Error) {
  3. if linkRes != nil {
  4. if addr, ok := linkRes.ResolveStaticAddress(k.Addr); ok {
  5. return addr, nil, nil
  6. }
  7. }
  8. c.cache.Lock()
  9. defer c.cache.Unlock()
  10. entry := c.getOrCreateEntryLocked(k)
  11. switch s := entry.s; s {
  12. case ready, failed:
  13. if !time.Now().After(entry.expiration) {
  14. // Not expired.
  15. switch s {
  16. case ready:
  17. return entry.linkAddr, nil, nil
  18. case failed:
  19. return entry.linkAddr, nil, tcpip.ErrNoLinkAddress
  20. default:
  21. panic(fmt.Sprintf("invalid cache entry state: %s", s))
  22. }
  23. }
  24. entry.changeState(incomplete, time.Time{})
  25. fallthrough
  26. case incomplete:
  27. if waker != nil {
  28. if entry.wakers == nil {
  29. entry.wakers = make(map[*sleep.Waker]struct{})
  30. }
  31. entry.wakers[waker] = struct{}{}
  32. }
  33. if entry.done == nil {
  34. // Address resolution needs to be initiated.
  35. if linkRes == nil {
  36. return entry.linkAddr, nil, tcpip.ErrNoLinkAddress
  37. }
  38. entry.done = make(chan struct{})
  39. go c.startAddressResolution(k, linkRes, localAddr, linkEP, entry.done) // S/R-SAFE: link non-savable; wakers dropped synchronously.
  40. }
  41. return entry.linkAddr, entry.done, tcpip.ErrWouldBlock
  42. default:
  43. panic(fmt.Sprintf("invalid cache entry state: %s", s))
  44. }
  45. }

Sleeper & Waker

netstack-network-endpoint-sleeper-waker.svg
图 8: Sleeper & Waker 关系图

Sleeper 中主要包含了三条独立并互相关联的 Waker 链表,如上图所示,从名称中能粗略判断三条链表的作用,在此暂不做详细描述,先看 Sleeper 及 Waker 的定义:

  1. type Sleeper struct {
  2. // sharedList is a "stack" of asserted wakers. They atomically add
  3. // themselves to the front of this list as they become asserted.
  4. sharedList unsafe.Pointer
  5. // localList is a list of asserted wakers that is only accessible to the
  6. // waiter, and thus doesn't have to be accessed atomically. When
  7. // fetching more wakers, the waiter will first go through this list, and
  8. // only when it's empty will it atomically fetch wakers from
  9. // sharedList.
  10. localList *Waker
  11. // allWakers is a list with all wakers that have been added to this
  12. // sleeper. It is used during cleanup to remove associations.
  13. allWakers *Waker
  14. // waitingG holds the G that is sleeping, if any. It is used by wakers
  15. // to determine which G, if any, they should wake.
  16. waitingG uintptr
  17. }
  18. type Waker struct {
  19. _ sync.NoCopy
  20. // s is the sleeper that this waker can wake up. Only one sleeper at a
  21. // time is allowed. This field can have three classes of values:
  22. // nil -- the waker is not asserted: it either is not associated with
  23. // a sleeper, or is queued to a sleeper due to being previously
  24. // asserted. This is the zero value.
  25. // &assertedSleeper -- the waker is asserted.
  26. // otherwise -- the waker is not asserted, and is associated with the
  27. // given sleeper. Once it transitions to asserted state, the
  28. // associated sleeper will be woken.
  29. s unsafe.Pointer
  30. // next is used to form a linked list of asserted wakers in a sleeper.
  31. next *Waker
  32. // allWakersNext is used to form a linked list of all wakers associated
  33. // to a given sleeper.
  34. allWakersNext *Waker
  35. // id is the value to be returned to sleepers when they wake up due to
  36. // this waker being asserted.
  37. id int
  38. }

Add a Waker

netstack-network-endpoint-add-waker.svg
图 9: AddWaker 示意图
**
AddWaker 方法,将一个 Waker 添加到执行本方法的 Sleeper 上。首先,将新 Waker 添加至链表 allWakers 上,然后,对新 Waker 当前指向的 Sleeper 域进行判断,具体如下

  1. // Try to associate the waker with the sleeper. If it's already
  2. // asserted, we simply enqueue it in the "ready" list.
  3. for {
  4. p := (*Sleeper)(atomic.LoadPointer(&w.s))
  5. if p == &assertedSleeper { // 如果 Waker 当前 Sleeper 为 assertedSleeper
  6. s.enqueueAssertedWaker(w)
  7. return
  8. }
  9. // 修改 Waker 指向当前 Sleeper
  10. if atomic.CompareAndSwapPointer(&w.s, usleeper(p), usleeper(s)) {
  11. return
  12. }
  13. }

接着,来看一下 enqueueAssertedWaker 方法

  1. func (s *Sleeper) enqueueAssertedWaker(w *Waker) {
  2. // 将 w 添加进 Sleeper 的 sharedList 中,注意 CAS 操作即可
  3. // Add the new waker to the front of the list.
  4. for {
  5. v := (*Waker)(atomic.LoadPointer(&s.sharedList))
  6. w.next = v
  7. if atomic.CompareAndSwapPointer(&s.sharedList, uwaker(v), uwaker(w)) {
  8. break
  9. }
  10. }
  11. // 无等待状态的 Waker,直接返回即可
  12. // Nothing to do if there isn't a G waiting.
  13. if atomic.LoadUintptr(&s.waitingG) == 0 {
  14. return
  15. }
  16. // Signal to the sleeper that a waker has been asserted.
  17. switch g := atomic.SwapUintptr(&s.waitingG, 0); g {
  18. case 0, preparingG:
  19. default:
  20. // We managed to get a G. Wake it up.
  21. goready(g, 0)
  22. }
  23. }

Assert a Waker

  1. // Assert moves the waker to an asserted state, if it isn't asserted yet. When
  2. // asserted, the waker will cause its matching sleeper to wake up.
  3. func (w *Waker) Assert() {
  4. // Nothing to do if the waker is already asserted. This check allows us
  5. // to complete this case (already asserted) without any interlocked
  6. // operations on x86.
  7. if atomic.LoadPointer(&w.s) == usleeper(&assertedSleeper) {
  8. return
  9. }
  10. // Mark the waker as asserted, and wake up a sleeper if there is one.
  11. switch s := (*Sleeper)(atomic.SwapPointer(&w.s, usleeper(&assertedSleeper))); s {
  12. case nil:
  13. case &assertedSleeper:
  14. default:
  15. // 由于当前 Waker 已被链接至 assertedSleeper,且该 Waker 指向的 Sleeper 也被转移,
  16. // 因此,需要在原 Sleeper 中将当前 Waker 进行处理
  17. s.enqueueAssertedWaker(w)
  18. }
  19. }

Fetch the next Waker

  1. // nextWaker returns the next waker in the notification list, blocking if
  2. // needed.
  3. func (s *Sleeper) nextWaker(block bool) *Waker {
  4. // Attempt to replenish the local list if it's currently empty.
  5. if s.localList == nil {
  6. for atomic.LoadPointer(&s.sharedList) == nil {
  7. // Fail request if caller requested that we
  8. // don't block.
  9. if !block {
  10. return nil
  11. }
  12. // Indicate to wakers that we're about to sleep,
  13. // this allows them to abort the wait by setting
  14. // waitingG back to zero (which we'll notice
  15. // before committing the sleep).
  16. atomic.StoreUintptr(&s.waitingG, preparingG)
  17. // Check if something was queued while we were
  18. // preparing to sleep. We need this interleaving
  19. // to avoid missing wake ups.
  20. if atomic.LoadPointer(&s.sharedList) != nil {
  21. atomic.StoreUintptr(&s.waitingG, 0)
  22. break
  23. }
  24. // Try to commit the sleep and report it to the
  25. // tracer as a select.
  26. //
  27. // gopark puts the caller to sleep and calls
  28. // commitSleep to decide whether to immediately
  29. // wake the caller up or to leave it sleeping.
  30. const traceEvGoBlockSelect = 24
  31. // See:runtime2.go in the go runtime package for
  32. // the values to pass as the waitReason here.
  33. const waitReasonSelect = 9
  34. gopark(commitSleep, &s.waitingG, waitReasonSelect, traceEvGoBlockSelect, 0)
  35. }
  36. // Pull the shared list out and reverse it in the local
  37. // list. Given that wakers push themselves in reverse
  38. // order, we fix things here.
  39. v := (*Waker)(atomic.SwapPointer(&s.sharedList, nil))
  40. for v != nil {
  41. cur := v
  42. v = v.next
  43. cur.next = s.localList
  44. s.localList = cur
  45. }
  46. }
  47. // Remove the waker in the front of the list.
  48. w := s.localList
  49. s.localList = w.next
  50. return w
  51. }

Route

  1. // Route represents a route through the networking stack to a given destination.
  2. type Route struct {
  3. // RemoteAddress is the final destination of the route.
  4. RemoteAddress tcpip.Address
  5. // RemoteLinkAddress is the link-layer (MAC) address of the
  6. // final destination of the route.
  7. RemoteLinkAddress tcpip.LinkAddress
  8. // LocalAddress is the local address where the route starts.
  9. LocalAddress tcpip.Address
  10. // LocalLinkAddress is the link-layer (MAC) address of the
  11. // where the route starts.
  12. LocalLinkAddress tcpip.LinkAddress
  13. // NextHop is the next node in the path to the destination.
  14. NextHop tcpip.Address
  15. // NetProto is the network-layer protocol.
  16. NetProto tcpip.NetworkProtocolNumber
  17. // Loop controls where WritePacket should send packets.
  18. Loop PacketLooping
  19. // nic is the NIC the route goes through.
  20. nic *NIC
  21. // addressEndpoint is the local address this route is associated with.
  22. addressEndpoint AssignableAddressEndpoint
  23. // linkCache is set if link address resolution is enabled for this protocol on
  24. // the route's NIC.
  25. linkCache LinkAddressCache
  26. // linkRes is set if link address resolution is enabled for this protocol on
  27. // the route's NIC.
  28. linkRes LinkAddressResolver
  29. }

路由模块儿用于控制发送数据包的流向,通过数据包的目标地址来选择发送该包的网络接口卡。Route 结构代码中不难发现,它在记录目标地址时,也同时记录了源地址,并且包含了 LinkAddressCache 接口及 LinkAddressResolver 接口,这些的作用是什么呢?

Resolve

  1. func (r *Route) Resolve(waker *sleep.Waker) (<-chan struct{}, *tcpip.Error) {
  2. if !r.IsResolutionRequired() {
  3. // Nothing to do if there is no cache (which does the resolution on cache miss) or
  4. // link address is already known.
  5. return nil, nil
  6. }
  7. nextAddr := r.NextHop
  8. if nextAddr == "" {
  9. // Local link address is already known.
  10. if r.RemoteAddress == r.LocalAddress {
  11. r.RemoteLinkAddress = r.LocalLinkAddress
  12. return nil, nil
  13. }
  14. nextAddr = r.RemoteAddress
  15. }
  16. if neigh := r.nic.neigh; neigh != nil {
  17. entry, ch, err := neigh.entry(nextAddr, r.LocalAddress, r.linkRes, waker)
  18. if err != nil {
  19. return ch, err
  20. }
  21. r.RemoteLinkAddress = entry.LinkAddr
  22. return nil, nil
  23. }
  24. linkAddr, ch, err := r.linkCache.GetLinkAddress(r.nic.ID(), nextAddr, r.LocalAddress, r.NetProto, waker)
  25. if err != nil {
  26. return ch, err
  27. }
  28. r.RemoteLinkAddress = linkAddr
  29. return nil, nil
  30. }

Resolve 方法用于解析路由目标地址对应的链路层地址,在以太网下,会使用 ARP 协议进行解析。为了保证 IP 层性能问题,引入了 neighborCache 对已解析地址进行缓存处理。只有在缓存中不存在的记录才会进行解析。