sending.go 8.9 KB

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