sending.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. package kcp
  2. import (
  3. "sync"
  4. )
  5. type SendingWindow struct {
  6. start uint32
  7. cap uint32
  8. len uint32
  9. last uint32
  10. data []DataSegment
  11. inuse []bool
  12. prev []uint32
  13. next []uint32
  14. totalInFlightSize uint32
  15. writer SegmentWriter
  16. onPacketLoss func(uint32)
  17. }
  18. func NewSendingWindow(size uint32, writer SegmentWriter, onPacketLoss func(uint32)) *SendingWindow {
  19. window := &SendingWindow{
  20. start: 0,
  21. cap: size,
  22. len: 0,
  23. last: 0,
  24. data: make([]DataSegment, size),
  25. prev: make([]uint32, size),
  26. next: make([]uint32, size),
  27. inuse: make([]bool, size),
  28. writer: writer,
  29. onPacketLoss: onPacketLoss,
  30. }
  31. return window
  32. }
  33. func (this *SendingWindow) Release() {
  34. if this == nil {
  35. return
  36. }
  37. for _, seg := range this.data {
  38. seg.Release()
  39. }
  40. }
  41. func (this *SendingWindow) Len() int {
  42. return int(this.len)
  43. }
  44. func (this *SendingWindow) IsEmpty() bool {
  45. return this.len == 0
  46. }
  47. func (this *SendingWindow) Size() uint32 {
  48. return this.cap
  49. }
  50. func (this *SendingWindow) IsFull() bool {
  51. return this.len == this.cap
  52. }
  53. func (this *SendingWindow) Push(number uint32, data []byte) {
  54. pos := (this.start + this.len) % this.cap
  55. this.data[pos].SetData(data)
  56. this.data[pos].Number = number
  57. this.data[pos].timeout = 0
  58. this.data[pos].transmit = 0
  59. this.inuse[pos] = true
  60. if this.len > 0 {
  61. this.next[this.last] = pos
  62. this.prev[pos] = this.last
  63. }
  64. this.last = pos
  65. this.len++
  66. }
  67. func (this *SendingWindow) FirstNumber() uint32 {
  68. return this.data[this.start].Number
  69. }
  70. func (this *SendingWindow) Clear(una uint32) {
  71. for !this.IsEmpty() && this.data[this.start].Number < una {
  72. this.Remove(0)
  73. }
  74. }
  75. func (this *SendingWindow) Remove(idx uint32) bool {
  76. if this.len == 0 {
  77. return false
  78. }
  79. pos := (this.start + idx) % this.cap
  80. if !this.inuse[pos] {
  81. return false
  82. }
  83. this.inuse[pos] = false
  84. this.totalInFlightSize--
  85. if pos == this.start && pos == this.last {
  86. this.len = 0
  87. this.start = 0
  88. this.last = 0
  89. } else if pos == this.start {
  90. delta := this.next[pos] - this.start
  91. if this.next[pos] < this.start {
  92. delta = this.next[pos] + this.cap - this.start
  93. }
  94. this.start = this.next[pos]
  95. this.len -= delta
  96. } else if pos == this.last {
  97. this.last = this.prev[pos]
  98. } else {
  99. this.next[this.prev[pos]] = this.next[pos]
  100. this.prev[this.next[pos]] = this.prev[pos]
  101. }
  102. return true
  103. }
  104. func (this *SendingWindow) HandleFastAck(number uint32, rto uint32) {
  105. if this.IsEmpty() {
  106. return
  107. }
  108. this.Visit(func(seg *DataSegment) bool {
  109. if number == seg.Number || number-seg.Number > 0x7FFFFFFF {
  110. return false
  111. }
  112. if seg.transmit > 0 && seg.timeout > rto/3 {
  113. seg.timeout -= rto / 3
  114. }
  115. return true
  116. })
  117. }
  118. func (this *SendingWindow) Visit(visitor func(seg *DataSegment) bool) {
  119. for i := this.start; ; i = this.next[i] {
  120. if !visitor(&this.data[i]) || i == this.last {
  121. break
  122. }
  123. }
  124. }
  125. func (this *SendingWindow) Flush(current uint32, rto uint32, maxInFlightSize uint32) {
  126. if this.IsEmpty() {
  127. return
  128. }
  129. var lost uint32
  130. var inFlightSize uint32
  131. this.Visit(func(segment *DataSegment) bool {
  132. if current-segment.timeout >= 0x7FFFFFFF {
  133. return true
  134. }
  135. if segment.transmit == 0 {
  136. // First time
  137. this.totalInFlightSize++
  138. } else {
  139. lost++
  140. }
  141. segment.timeout = current + rto
  142. segment.Timestamp = current
  143. segment.transmit++
  144. this.writer.Write(segment)
  145. inFlightSize++
  146. if inFlightSize >= maxInFlightSize {
  147. return false
  148. }
  149. return true
  150. })
  151. if this.onPacketLoss != nil && inFlightSize > 0 && this.totalInFlightSize != 0 {
  152. rate := lost * 100 / this.totalInFlightSize
  153. this.onPacketLoss(rate)
  154. }
  155. }
  156. type SendingWorker struct {
  157. sync.RWMutex
  158. conn *Connection
  159. window *SendingWindow
  160. firstUnacknowledged uint32
  161. firstUnacknowledgedUpdated bool
  162. nextNumber uint32
  163. remoteNextNumber uint32
  164. controlWindow uint32
  165. fastResend uint32
  166. }
  167. func NewSendingWorker(kcp *Connection) *SendingWorker {
  168. worker := &SendingWorker{
  169. conn: kcp,
  170. fastResend: 2,
  171. remoteNextNumber: 32,
  172. controlWindow: kcp.Config.GetSendingInFlightSize(),
  173. }
  174. worker.window = NewSendingWindow(kcp.Config.GetSendingBufferSize(), worker, worker.OnPacketLoss)
  175. return worker
  176. }
  177. func (this *SendingWorker) Release() {
  178. this.window.Release()
  179. }
  180. func (this *SendingWorker) ProcessReceivingNext(nextNumber uint32) {
  181. this.Lock()
  182. defer this.Unlock()
  183. this.ProcessReceivingNextWithoutLock(nextNumber)
  184. }
  185. func (this *SendingWorker) ProcessReceivingNextWithoutLock(nextNumber uint32) {
  186. this.window.Clear(nextNumber)
  187. this.FindFirstUnacknowledged()
  188. }
  189. // Private: Visible for testing.
  190. func (this *SendingWorker) FindFirstUnacknowledged() {
  191. first := this.firstUnacknowledged
  192. if !this.window.IsEmpty() {
  193. this.firstUnacknowledged = this.window.FirstNumber()
  194. } else {
  195. this.firstUnacknowledged = this.nextNumber
  196. }
  197. if first != this.firstUnacknowledged {
  198. this.firstUnacknowledgedUpdated = true
  199. }
  200. }
  201. // Private: Visible for testing.
  202. func (this *SendingWorker) ProcessAck(number uint32) bool {
  203. // number < this.firstUnacknowledged || number >= this.nextNumber
  204. if number-this.firstUnacknowledged > 0x7FFFFFFF || number-this.nextNumber < 0x7FFFFFFF {
  205. return false
  206. }
  207. removed := this.window.Remove(number - this.firstUnacknowledged)
  208. if removed {
  209. this.FindFirstUnacknowledged()
  210. }
  211. return removed
  212. }
  213. func (this *SendingWorker) ProcessSegment(current uint32, seg *AckSegment, rto uint32) {
  214. defer seg.Release()
  215. this.Lock()
  216. defer this.Unlock()
  217. if this.remoteNextNumber < seg.ReceivingWindow {
  218. this.remoteNextNumber = seg.ReceivingWindow
  219. }
  220. this.ProcessReceivingNextWithoutLock(seg.ReceivingNext)
  221. var maxack uint32
  222. var maxackRemoved bool
  223. for i := 0; i < int(seg.Count); i++ {
  224. number := seg.NumberList[i]
  225. removed := this.ProcessAck(number)
  226. if maxack < number {
  227. maxack = number
  228. maxackRemoved = removed
  229. }
  230. }
  231. if maxackRemoved {
  232. this.window.HandleFastAck(maxack, rto)
  233. if current-seg.Timestamp < 10000 {
  234. this.conn.roundTrip.Update(current-seg.Timestamp, current)
  235. }
  236. }
  237. }
  238. func (this *SendingWorker) Push(b []byte) int {
  239. nBytes := 0
  240. this.Lock()
  241. defer this.Unlock()
  242. for len(b) > 0 && !this.window.IsFull() {
  243. var size int
  244. if len(b) > int(this.conn.mss) {
  245. size = int(this.conn.mss)
  246. } else {
  247. size = len(b)
  248. }
  249. this.window.Push(this.nextNumber, b[:size])
  250. this.nextNumber++
  251. b = b[size:]
  252. nBytes += size
  253. }
  254. return nBytes
  255. }
  256. // Private: Visible for testing.
  257. func (this *SendingWorker) Write(seg Segment) {
  258. dataSeg := seg.(*DataSegment)
  259. dataSeg.Conv = this.conn.conv
  260. dataSeg.SendingNext = this.firstUnacknowledged
  261. dataSeg.Option = 0
  262. if this.conn.State() == StateReadyToClose {
  263. dataSeg.Option = SegmentOptionClose
  264. }
  265. this.conn.output.Write(dataSeg)
  266. }
  267. func (this *SendingWorker) OnPacketLoss(lossRate uint32) {
  268. if !this.conn.Config.Congestion || this.conn.roundTrip.Timeout() == 0 {
  269. return
  270. }
  271. if lossRate >= 15 {
  272. this.controlWindow = 3 * this.controlWindow / 4
  273. } else if lossRate <= 5 {
  274. this.controlWindow += this.controlWindow / 4
  275. }
  276. if this.controlWindow < 16 {
  277. this.controlWindow = 16
  278. }
  279. if this.controlWindow > 2*this.conn.Config.GetSendingInFlightSize() {
  280. this.controlWindow = 2 * this.conn.Config.GetSendingInFlightSize()
  281. }
  282. }
  283. func (this *SendingWorker) Flush(current uint32) {
  284. this.Lock()
  285. defer this.Unlock()
  286. cwnd := this.firstUnacknowledged + this.conn.Config.GetSendingInFlightSize()
  287. if cwnd > this.remoteNextNumber {
  288. cwnd = this.remoteNextNumber
  289. }
  290. if this.conn.Config.Congestion && cwnd > this.firstUnacknowledged+this.controlWindow {
  291. cwnd = this.firstUnacknowledged + this.controlWindow
  292. }
  293. if !this.window.IsEmpty() {
  294. this.window.Flush(current, this.conn.roundTrip.Timeout(), cwnd)
  295. } else if this.firstUnacknowledgedUpdated {
  296. this.conn.Ping(current, CommandPing)
  297. }
  298. this.firstUnacknowledgedUpdated = false
  299. }
  300. func (this *SendingWorker) CloseWrite() {
  301. this.Lock()
  302. defer this.Unlock()
  303. this.window.Clear(0xFFFFFFFF)
  304. }
  305. func (this *SendingWorker) IsEmpty() bool {
  306. this.RLock()
  307. defer this.RUnlock()
  308. return this.window.IsEmpty()
  309. }
  310. func (this *SendingWorker) UpdateNecessary() bool {
  311. return !this.IsEmpty()
  312. }