sending.go 8.3 KB

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