sending.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 number-seg.Number > 0x7FFFFFFF {
  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 current-segment.timeout < 0x7FFFFFFF {
  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. segment.Timestamp = current
  133. this.writer.Write(segment)
  134. inFlightSize++
  135. if inFlightSize >= maxInFlightSize {
  136. break
  137. }
  138. }
  139. if i == this.last {
  140. break
  141. }
  142. }
  143. if inFlightSize > 0 && this.totalInFlightSize != 0 {
  144. rate := lost * 100 / this.totalInFlightSize
  145. this.onPacketLoss(rate)
  146. }
  147. }
  148. type SendingQueue struct {
  149. start uint32
  150. cap uint32
  151. len uint32
  152. list []*DataSegment
  153. }
  154. func NewSendingQueue(size uint32) *SendingQueue {
  155. return &SendingQueue{
  156. start: 0,
  157. cap: size,
  158. list: make([]*DataSegment, size),
  159. len: 0,
  160. }
  161. }
  162. func (this *SendingQueue) IsFull() bool {
  163. return this.len == this.cap
  164. }
  165. func (this *SendingQueue) IsEmpty() bool {
  166. return this.len == 0
  167. }
  168. func (this *SendingQueue) Pop() *DataSegment {
  169. if this.IsEmpty() {
  170. return nil
  171. }
  172. seg := this.list[this.start]
  173. this.list[this.start] = nil
  174. this.len--
  175. this.start++
  176. if this.start == this.cap {
  177. this.start = 0
  178. }
  179. return seg
  180. }
  181. func (this *SendingQueue) Push(seg *DataSegment) {
  182. if this.IsFull() {
  183. return
  184. }
  185. this.list[(this.start+this.len)%this.cap] = seg
  186. this.len++
  187. }
  188. func (this *SendingQueue) Clear() {
  189. for i := uint32(0); i < this.len; i++ {
  190. this.list[(i+this.start)%this.cap].Release()
  191. this.list[(i+this.start)%this.cap] = nil
  192. }
  193. this.start = 0
  194. this.len = 0
  195. }
  196. func (this *SendingQueue) Len() uint32 {
  197. return this.len
  198. }
  199. type SendingWorker struct {
  200. sync.Mutex
  201. conn *Connection
  202. window *SendingWindow
  203. queue *SendingQueue
  204. firstUnacknowledged uint32
  205. nextNumber uint32
  206. remoteNextNumber uint32
  207. controlWindow uint32
  208. fastResend uint32
  209. updated bool
  210. }
  211. func NewSendingWorker(kcp *Connection) *SendingWorker {
  212. worker := &SendingWorker{
  213. conn: kcp,
  214. queue: NewSendingQueue(effectiveConfig.GetSendingQueueSize()),
  215. fastResend: 2,
  216. remoteNextNumber: 32,
  217. controlWindow: effectiveConfig.GetSendingInFlightSize(),
  218. }
  219. worker.window = NewSendingWindow(effectiveConfig.GetSendingWindowSize(), worker, worker.OnPacketLoss)
  220. return worker
  221. }
  222. func (this *SendingWorker) ProcessReceivingNext(nextNumber uint32) {
  223. this.Lock()
  224. defer this.Unlock()
  225. this.ProcessReceivingNextWithoutLock(nextNumber)
  226. }
  227. func (this *SendingWorker) ProcessReceivingNextWithoutLock(nextNumber uint32) {
  228. this.window.Clear(nextNumber)
  229. this.FindFirstUnacknowledged()
  230. }
  231. // @Private
  232. func (this *SendingWorker) FindFirstUnacknowledged() {
  233. prevUna := this.firstUnacknowledged
  234. if this.window.Len() > 0 {
  235. this.firstUnacknowledged = this.window.First().Number
  236. } else {
  237. this.firstUnacknowledged = this.nextNumber
  238. }
  239. if this.firstUnacknowledged != prevUna {
  240. this.updated = true
  241. }
  242. }
  243. // @Private
  244. func (this *SendingWorker) ProcessAck(number uint32) {
  245. if number-this.firstUnacknowledged > this.window.Size() {
  246. return
  247. }
  248. this.window.Remove(number - this.firstUnacknowledged)
  249. this.FindFirstUnacknowledged()
  250. }
  251. func (this *SendingWorker) ProcessSegment(current uint32, seg *AckSegment) {
  252. this.Lock()
  253. defer this.Unlock()
  254. if this.remoteNextNumber < seg.ReceivingWindow {
  255. this.remoteNextNumber = seg.ReceivingWindow
  256. }
  257. this.ProcessReceivingNextWithoutLock(seg.ReceivingNext)
  258. var maxack uint32
  259. for i := 0; i < int(seg.Count); i++ {
  260. timestamp := seg.TimestampList[i]
  261. number := seg.NumberList[i]
  262. if current-timestamp < 10000 {
  263. this.conn.roundTrip.Update(current - timestamp)
  264. }
  265. this.ProcessAck(number)
  266. if maxack < number {
  267. maxack = number
  268. }
  269. }
  270. this.window.HandleFastAck(maxack)
  271. }
  272. func (this *SendingWorker) Push(b []byte) int {
  273. nBytes := 0
  274. this.Lock()
  275. defer this.Unlock()
  276. for len(b) > 0 && !this.queue.IsFull() {
  277. var size int
  278. if len(b) > int(this.conn.mss) {
  279. size = int(this.conn.mss)
  280. } else {
  281. size = len(b)
  282. }
  283. seg := NewDataSegment()
  284. seg.Data = alloc.NewSmallBuffer().Clear().Append(b[:size])
  285. this.queue.Push(seg)
  286. b = b[size:]
  287. nBytes += size
  288. }
  289. return nBytes
  290. }
  291. // @Private
  292. func (this *SendingWorker) Write(seg Segment) {
  293. dataSeg := seg.(*DataSegment)
  294. dataSeg.Conv = this.conn.conv
  295. dataSeg.SendingNext = this.firstUnacknowledged
  296. dataSeg.Opt = 0
  297. if this.conn.State() == StateReadyToClose {
  298. dataSeg.Opt = SegmentOptionClose
  299. }
  300. this.conn.output.Write(dataSeg)
  301. this.updated = false
  302. }
  303. func (this *SendingWorker) PingNecessary() bool {
  304. return this.updated
  305. }
  306. func (this *SendingWorker) OnPacketLoss(lossRate uint32) {
  307. if !effectiveConfig.Congestion || this.conn.roundTrip.Timeout() == 0 {
  308. return
  309. }
  310. if lossRate >= 15 {
  311. this.controlWindow = 3 * this.controlWindow / 4
  312. } else if lossRate <= 5 {
  313. this.controlWindow += this.controlWindow / 4
  314. }
  315. if this.controlWindow < 16 {
  316. this.controlWindow = 16
  317. }
  318. if this.controlWindow > 2*effectiveConfig.GetSendingInFlightSize() {
  319. this.controlWindow = 2 * effectiveConfig.GetSendingInFlightSize()
  320. }
  321. }
  322. func (this *SendingWorker) Flush(current uint32) {
  323. this.Lock()
  324. defer this.Unlock()
  325. cwnd := this.firstUnacknowledged + effectiveConfig.GetSendingInFlightSize()
  326. if cwnd > this.remoteNextNumber {
  327. cwnd = this.remoteNextNumber
  328. }
  329. if effectiveConfig.Congestion && cwnd > this.firstUnacknowledged+this.controlWindow {
  330. cwnd = this.firstUnacknowledged + this.controlWindow
  331. }
  332. for !this.queue.IsEmpty() && !this.window.IsFull() {
  333. seg := this.queue.Pop()
  334. seg.Number = this.nextNumber
  335. seg.timeout = current
  336. seg.ackSkipped = 0
  337. seg.transmit = 0
  338. this.window.Push(seg)
  339. this.nextNumber++
  340. }
  341. this.window.Flush(current, this.conn.fastresend, this.conn.roundTrip.Timeout(), cwnd)
  342. }
  343. func (this *SendingWorker) CloseWrite() {
  344. this.Lock()
  345. defer this.Unlock()
  346. this.window.Clear(0xFFFFFFFF)
  347. this.queue.Clear()
  348. }