sending.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 []*alloc.Buffer
  156. }
  157. func NewSendingQueue(size uint32) *SendingQueue {
  158. return &SendingQueue{
  159. start: 0,
  160. cap: size,
  161. list: make([]*alloc.Buffer, 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() *alloc.Buffer {
  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. if this.IsEmpty() {
  183. this.start = 0
  184. }
  185. return seg
  186. }
  187. func (this *SendingQueue) Push(seg *alloc.Buffer) {
  188. if this.IsFull() {
  189. return
  190. }
  191. this.list[(this.start+this.len)%this.cap] = seg
  192. this.len++
  193. }
  194. func (this *SendingQueue) Clear() {
  195. for i := uint32(0); i < this.len; i++ {
  196. this.list[(i+this.start)%this.cap].Release()
  197. this.list[(i+this.start)%this.cap] = nil
  198. }
  199. this.start = 0
  200. this.len = 0
  201. }
  202. func (this *SendingQueue) Len() uint32 {
  203. return this.len
  204. }
  205. type SendingWorker struct {
  206. sync.RWMutex
  207. conn *Connection
  208. window *SendingWindow
  209. queue *SendingQueue
  210. firstUnacknowledged uint32
  211. nextNumber uint32
  212. remoteNextNumber uint32
  213. controlWindow uint32
  214. fastResend uint32
  215. updated bool
  216. }
  217. func NewSendingWorker(kcp *Connection) *SendingWorker {
  218. worker := &SendingWorker{
  219. conn: kcp,
  220. queue: NewSendingQueue(effectiveConfig.GetSendingQueueSize()),
  221. fastResend: 2,
  222. remoteNextNumber: 32,
  223. controlWindow: effectiveConfig.GetSendingInFlightSize(),
  224. }
  225. worker.window = NewSendingWindow(effectiveConfig.GetSendingWindowSize(), worker, worker.OnPacketLoss)
  226. return worker
  227. }
  228. func (this *SendingWorker) ProcessReceivingNext(nextNumber uint32) {
  229. this.Lock()
  230. defer this.Unlock()
  231. this.ProcessReceivingNextWithoutLock(nextNumber)
  232. }
  233. func (this *SendingWorker) ProcessReceivingNextWithoutLock(nextNumber uint32) {
  234. this.window.Clear(nextNumber)
  235. this.FindFirstUnacknowledged()
  236. }
  237. // @Private
  238. func (this *SendingWorker) FindFirstUnacknowledged() {
  239. prevUna := this.firstUnacknowledged
  240. if !this.window.IsEmpty() {
  241. this.firstUnacknowledged = this.window.First().Number
  242. } else {
  243. this.firstUnacknowledged = this.nextNumber
  244. }
  245. if this.firstUnacknowledged != prevUna {
  246. this.updated = true
  247. }
  248. }
  249. // @Private
  250. func (this *SendingWorker) ProcessAck(number uint32) {
  251. // number < this.firstUnacknowledged || number >= this.nextNumber
  252. if number-this.firstUnacknowledged > 0x7FFFFFFF || number-this.nextNumber < 0x7FFFFFFF {
  253. return
  254. }
  255. this.window.Remove(number - this.firstUnacknowledged)
  256. this.FindFirstUnacknowledged()
  257. }
  258. func (this *SendingWorker) FillWindow(current uint32) {
  259. for !this.queue.IsEmpty() && !this.window.IsFull() {
  260. seg := NewDataSegment()
  261. seg.Data = this.queue.Pop()
  262. seg.Number = this.nextNumber
  263. seg.timeout = current
  264. seg.ackSkipped = 0
  265. seg.transmit = 0
  266. this.window.Push(seg)
  267. this.nextNumber++
  268. }
  269. }
  270. func (this *SendingWorker) ProcessSegment(current uint32, seg *AckSegment) {
  271. defer seg.Release()
  272. this.Lock()
  273. defer this.Unlock()
  274. if this.remoteNextNumber < seg.ReceivingWindow {
  275. this.remoteNextNumber = seg.ReceivingWindow
  276. }
  277. this.ProcessReceivingNextWithoutLock(seg.ReceivingNext)
  278. var maxack uint32
  279. for i := 0; i < int(seg.Count); i++ {
  280. timestamp := seg.TimestampList[i]
  281. number := seg.NumberList[i]
  282. if current-timestamp < 10000 {
  283. this.conn.roundTrip.Update(current - timestamp)
  284. }
  285. this.ProcessAck(number)
  286. if maxack < number {
  287. maxack = number
  288. }
  289. }
  290. this.window.HandleFastAck(maxack)
  291. this.FillWindow(current)
  292. }
  293. func (this *SendingWorker) Push(b []byte) int {
  294. nBytes := 0
  295. this.Lock()
  296. defer this.Unlock()
  297. for len(b) > 0 && !this.queue.IsFull() {
  298. var size int
  299. if len(b) > int(this.conn.mss) {
  300. size = int(this.conn.mss)
  301. } else {
  302. size = len(b)
  303. }
  304. this.queue.Push(AllocateBuffer().Clear().Append(b[:size]))
  305. b = b[size:]
  306. nBytes += size
  307. }
  308. return nBytes
  309. }
  310. // @Private
  311. func (this *SendingWorker) Write(seg Segment) {
  312. dataSeg := seg.(*DataSegment)
  313. dataSeg.Conv = this.conn.conv
  314. dataSeg.SendingNext = this.firstUnacknowledged
  315. dataSeg.Option = 0
  316. if this.conn.State() == StateReadyToClose {
  317. dataSeg.Option = SegmentOptionClose
  318. }
  319. this.conn.output.Write(dataSeg)
  320. this.updated = false
  321. }
  322. func (this *SendingWorker) PingNecessary() bool {
  323. this.RLock()
  324. defer this.RUnlock()
  325. return this.updated
  326. }
  327. func (this *SendingWorker) MarkPingNecessary(b bool) {
  328. this.Lock()
  329. defer this.Unlock()
  330. this.updated = b
  331. }
  332. func (this *SendingWorker) OnPacketLoss(lossRate uint32) {
  333. if !effectiveConfig.Congestion || this.conn.roundTrip.Timeout() == 0 {
  334. return
  335. }
  336. if lossRate >= 15 {
  337. this.controlWindow = 3 * this.controlWindow / 4
  338. } else if lossRate <= 5 {
  339. this.controlWindow += this.controlWindow / 4
  340. }
  341. if this.controlWindow < 16 {
  342. this.controlWindow = 16
  343. }
  344. if this.controlWindow > 2*effectiveConfig.GetSendingInFlightSize() {
  345. this.controlWindow = 2 * effectiveConfig.GetSendingInFlightSize()
  346. }
  347. }
  348. func (this *SendingWorker) Flush(current uint32) {
  349. this.Lock()
  350. defer this.Unlock()
  351. cwnd := this.firstUnacknowledged + effectiveConfig.GetSendingInFlightSize()
  352. if cwnd > this.remoteNextNumber {
  353. cwnd = this.remoteNextNumber
  354. }
  355. if effectiveConfig.Congestion && cwnd > this.firstUnacknowledged+this.controlWindow {
  356. cwnd = this.firstUnacknowledged + this.controlWindow
  357. }
  358. this.FillWindow(current)
  359. this.window.Flush(current, this.conn.fastresend, this.conn.roundTrip.Timeout(), cwnd)
  360. }
  361. func (this *SendingWorker) CloseWrite() {
  362. this.Lock()
  363. defer this.Unlock()
  364. this.window.Clear(0xFFFFFFFF)
  365. this.queue.Clear()
  366. }
  367. func (this *SendingWorker) IsEmpty() bool {
  368. this.RLock()
  369. defer this.RUnlock()
  370. return this.window.IsEmpty() && this.queue.IsEmpty()
  371. }