sending.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. package kcp
  2. import (
  3. "sync"
  4. "github.com/v2ray/v2ray-core/common/alloc"
  5. )
  6. type SendingWindow struct {
  7. start uint32
  8. cap uint32
  9. len uint32
  10. last uint32
  11. data []*DataSegment
  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. writer: writer,
  28. onPacketLoss: onPacketLoss,
  29. }
  30. return window
  31. }
  32. func (this *SendingWindow) Len() int {
  33. return int(this.len)
  34. }
  35. func (this *SendingWindow) Size() uint32 {
  36. return this.cap
  37. }
  38. func (this *SendingWindow) IsFull() bool {
  39. return this.len == this.cap
  40. }
  41. func (this *SendingWindow) Push(seg *DataSegment) {
  42. pos := (this.start + this.len) % this.cap
  43. this.data[pos] = seg
  44. if this.len > 0 {
  45. this.next[this.last] = pos
  46. this.prev[pos] = this.last
  47. }
  48. this.last = pos
  49. this.len++
  50. }
  51. func (this *SendingWindow) First() *DataSegment {
  52. return this.data[this.start]
  53. }
  54. func (this *SendingWindow) Clear(una uint32) {
  55. for this.Len() > 0 && this.data[this.start].Number < una {
  56. this.Remove(0)
  57. }
  58. }
  59. func (this *SendingWindow) Remove(idx uint32) {
  60. if this.len == 0 {
  61. return
  62. }
  63. pos := (this.start + idx) % this.cap
  64. seg := this.data[pos]
  65. if seg == nil {
  66. return
  67. }
  68. this.totalInFlightSize--
  69. seg.Release()
  70. this.data[pos] = nil
  71. if pos == this.start && pos == this.last {
  72. this.len = 0
  73. this.start = 0
  74. this.last = 0
  75. } else if pos == this.start {
  76. delta := this.next[pos] - this.start
  77. if this.next[pos] < this.start {
  78. delta = this.next[pos] + this.cap - this.start
  79. }
  80. this.start = this.next[pos]
  81. this.len -= delta
  82. } else if pos == this.last {
  83. this.last = this.prev[pos]
  84. } else {
  85. this.next[this.prev[pos]] = this.next[pos]
  86. this.prev[this.next[pos]] = this.prev[pos]
  87. }
  88. }
  89. func (this *SendingWindow) HandleFastAck(number uint32) {
  90. if this.len == 0 {
  91. return
  92. }
  93. for i := this.start; ; i = this.next[i] {
  94. seg := this.data[i]
  95. if _itimediff(number, seg.Number) < 0 {
  96. break
  97. }
  98. if number != seg.Number {
  99. seg.ackSkipped++
  100. }
  101. if i == this.last {
  102. break
  103. }
  104. }
  105. }
  106. func (this *SendingWindow) Flush(current uint32, resend uint32, rto uint32, maxInFlightSize uint32) {
  107. if this.Len() == 0 {
  108. return
  109. }
  110. var lost uint32
  111. var inFlightSize uint32
  112. for i := this.start; ; i = this.next[i] {
  113. segment := this.data[i]
  114. needsend := false
  115. if segment.transmit == 0 {
  116. needsend = true
  117. segment.transmit++
  118. segment.timeout = current + rto
  119. this.totalInFlightSize++
  120. } else if _itimediff(current, segment.timeout) >= 0 {
  121. needsend = true
  122. segment.transmit++
  123. segment.timeout = current + rto
  124. lost++
  125. } else if segment.ackSkipped >= resend {
  126. needsend = true
  127. segment.transmit++
  128. segment.ackSkipped = 0
  129. segment.timeout = current + rto
  130. }
  131. if needsend {
  132. this.writer.Write(segment)
  133. inFlightSize++
  134. if inFlightSize >= maxInFlightSize {
  135. break
  136. }
  137. }
  138. if i == this.last {
  139. break
  140. }
  141. }
  142. if inFlightSize > 0 && this.totalInFlightSize != 0 {
  143. rate := lost * 100 / this.totalInFlightSize
  144. this.onPacketLoss(rate)
  145. }
  146. }
  147. type SendingQueue struct {
  148. start uint32
  149. cap uint32
  150. len uint32
  151. list []*DataSegment
  152. }
  153. func NewSendingQueue(size uint32) *SendingQueue {
  154. return &SendingQueue{
  155. start: 0,
  156. cap: size,
  157. list: make([]*DataSegment, size),
  158. len: 0,
  159. }
  160. }
  161. func (this *SendingQueue) IsFull() bool {
  162. return this.len == this.cap
  163. }
  164. func (this *SendingQueue) IsEmpty() bool {
  165. return this.len == 0
  166. }
  167. func (this *SendingQueue) Pop() *DataSegment {
  168. if this.IsEmpty() {
  169. return nil
  170. }
  171. seg := this.list[this.start]
  172. this.list[this.start] = nil
  173. this.len--
  174. this.start++
  175. if this.start == this.cap {
  176. this.start = 0
  177. }
  178. return seg
  179. }
  180. func (this *SendingQueue) Push(seg *DataSegment) {
  181. if this.IsFull() {
  182. return
  183. }
  184. this.list[(this.start+this.len)%this.cap] = seg
  185. this.len++
  186. }
  187. func (this *SendingQueue) Clear() {
  188. for i := uint32(0); i < this.len; i++ {
  189. this.list[(i+this.start)%this.cap].Release()
  190. this.list[(i+this.start)%this.cap] = nil
  191. }
  192. this.start = 0
  193. this.len = 0
  194. }
  195. func (this *SendingQueue) Len() uint32 {
  196. return this.len
  197. }
  198. type SendingWorker struct {
  199. sync.Mutex
  200. kcp *KCP
  201. window *SendingWindow
  202. queue *SendingQueue
  203. firstUnacknowledged uint32
  204. nextNumber uint32
  205. remoteNextNumber uint32
  206. controlWindow uint32
  207. fastResend uint32
  208. updated bool
  209. }
  210. func NewSendingWorker(kcp *KCP) *SendingWorker {
  211. worker := &SendingWorker{
  212. kcp: kcp,
  213. queue: NewSendingQueue(effectiveConfig.GetSendingQueueSize()),
  214. fastResend: 2,
  215. remoteNextNumber: 32,
  216. controlWindow: effectiveConfig.GetSendingInFlightSize(),
  217. }
  218. worker.window = NewSendingWindow(effectiveConfig.GetSendingWindowSize(), worker, worker.OnPacketLoss)
  219. return worker
  220. }
  221. func (this *SendingWorker) ProcessReceivingNext(nextNumber uint32) {
  222. this.Lock()
  223. defer this.Unlock()
  224. this.window.Clear(nextNumber)
  225. this.FindFirstUnacknowledged()
  226. }
  227. // @Private
  228. func (this *SendingWorker) FindFirstUnacknowledged() {
  229. prevUna := this.firstUnacknowledged
  230. if this.window.Len() > 0 {
  231. this.firstUnacknowledged = this.window.First().Number
  232. } else {
  233. this.firstUnacknowledged = this.nextNumber
  234. }
  235. if this.firstUnacknowledged != prevUna {
  236. this.updated = true
  237. }
  238. }
  239. func (this *SendingWorker) ProcessAck(number uint32) {
  240. if number-this.firstUnacknowledged > this.window.Size() {
  241. return
  242. }
  243. this.Lock()
  244. defer this.Unlock()
  245. this.window.Remove(number - this.firstUnacknowledged)
  246. this.FindFirstUnacknowledged()
  247. }
  248. func (this *SendingWorker) ProcessSegment(seg *AckSegment) {
  249. if this.remoteNextNumber < seg.ReceivingWindow {
  250. this.remoteNextNumber = seg.ReceivingWindow
  251. }
  252. this.ProcessReceivingNext(seg.ReceivingNext)
  253. var maxack uint32
  254. for i := 0; i < int(seg.Count); i++ {
  255. timestamp := seg.TimestampList[i]
  256. number := seg.NumberList[i]
  257. if this.kcp.current-timestamp < 10000 {
  258. this.kcp.update_ack(int32(this.kcp.current - timestamp))
  259. }
  260. this.ProcessAck(number)
  261. if maxack < number {
  262. maxack = number
  263. }
  264. }
  265. this.Lock()
  266. this.window.HandleFastAck(maxack)
  267. this.Unlock()
  268. }
  269. func (this *SendingWorker) Push(b []byte) int {
  270. nBytes := 0
  271. for len(b) > 0 && !this.queue.IsFull() {
  272. var size int
  273. if len(b) > int(this.kcp.mss) {
  274. size = int(this.kcp.mss)
  275. } else {
  276. size = len(b)
  277. }
  278. seg := NewDataSegment()
  279. seg.Data = alloc.NewSmallBuffer().Clear().Append(b[:size])
  280. this.Lock()
  281. this.queue.Push(seg)
  282. this.Unlock()
  283. b = b[size:]
  284. nBytes += size
  285. }
  286. return nBytes
  287. }
  288. func (this *SendingWorker) Write(seg Segment) {
  289. dataSeg := seg.(*DataSegment)
  290. dataSeg.Conv = this.kcp.conv
  291. dataSeg.Timestamp = this.kcp.current
  292. dataSeg.SendingNext = this.firstUnacknowledged
  293. dataSeg.Opt = 0
  294. if this.kcp.state == StateReadyToClose {
  295. dataSeg.Opt = SegmentOptionClose
  296. }
  297. this.kcp.output.Write(dataSeg)
  298. this.updated = false
  299. }
  300. func (this *SendingWorker) PingNecessary() bool {
  301. return this.updated
  302. }
  303. func (this *SendingWorker) OnPacketLoss(lossRate uint32) {
  304. if !effectiveConfig.Congestion || this.kcp.rx_srtt == 0 {
  305. return
  306. }
  307. if lossRate >= 15 {
  308. this.controlWindow = 3 * this.controlWindow / 4
  309. } else if lossRate <= 5 {
  310. this.controlWindow += this.controlWindow / 4
  311. }
  312. if this.controlWindow < 16 {
  313. this.controlWindow = 16
  314. }
  315. if this.controlWindow > 2*effectiveConfig.GetSendingInFlightSize() {
  316. this.controlWindow = 2 * effectiveConfig.GetSendingInFlightSize()
  317. }
  318. }
  319. func (this *SendingWorker) Flush() {
  320. this.Lock()
  321. defer this.Unlock()
  322. cwnd := this.firstUnacknowledged + effectiveConfig.GetSendingInFlightSize()
  323. if cwnd > this.remoteNextNumber {
  324. cwnd = this.remoteNextNumber
  325. }
  326. if effectiveConfig.Congestion && cwnd > this.firstUnacknowledged+this.controlWindow {
  327. cwnd = this.firstUnacknowledged + this.controlWindow
  328. }
  329. for !this.queue.IsEmpty() && !this.window.IsFull() {
  330. seg := this.queue.Pop()
  331. seg.Number = this.nextNumber
  332. seg.timeout = this.kcp.current
  333. seg.ackSkipped = 0
  334. seg.transmit = 0
  335. this.window.Push(seg)
  336. this.nextNumber++
  337. }
  338. this.window.Flush(this.kcp.current, this.kcp.fastresend, this.kcp.rx_rto, cwnd)
  339. }
  340. func (this *SendingWorker) CloseWrite() {
  341. this.Lock()
  342. defer this.Unlock()
  343. this.window.Clear(0xFFFFFFFF)
  344. this.queue.Clear()
  345. }