group.cpp 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145
  1. #include "platform_sys.h"
  2. #include <iterator>
  3. #include "api.h"
  4. #include "group.h"
  5. using namespace std;
  6. using namespace srt::sync;
  7. using namespace srt::groups;
  8. using namespace srt_logging;
  9. // The SRT_DEF_VERSION is defined in core.cpp.
  10. extern const int32_t SRT_DEF_VERSION;
  11. namespace srt {
  12. int32_t CUDTGroup::s_tokenGen = 0;
  13. // [[using locked(this->m_GroupLock)]];
  14. bool CUDTGroup::getBufferTimeBase(CUDT* forthesakeof,
  15. steady_clock::time_point& w_tb,
  16. bool& w_wp,
  17. steady_clock::duration& w_dr)
  18. {
  19. CUDT* master = 0;
  20. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi)
  21. {
  22. CUDT* u = &gi->ps->core();
  23. if (gi->laststatus != SRTS_CONNECTED)
  24. {
  25. HLOGC(gmlog.Debug,
  26. log << "getBufferTimeBase: skipping @" << u->m_SocketID
  27. << ": not connected, state=" << SockStatusStr(gi->laststatus));
  28. continue;
  29. }
  30. if (u == forthesakeof)
  31. continue; // skip the member if it's the target itself
  32. if (!u->m_pRcvBuffer)
  33. continue; // Not initialized yet
  34. master = u;
  35. break; // found
  36. }
  37. // We don't have any sockets in the group, so can't get
  38. // the buffer timebase. This should be then initialized
  39. // the usual way.
  40. if (!master)
  41. return false;
  42. master->m_pRcvBuffer->getInternalTimeBase((w_tb), (w_wp), (w_dr));
  43. // Sanity check
  44. if (is_zero(w_tb))
  45. {
  46. LOGC(gmlog.Error, log << "IPE: existing previously socket has no time base set yet!");
  47. return false; // this will enforce initializing the time base normal way
  48. }
  49. return true;
  50. }
  51. // [[using locked(this->m_GroupLock)]];
  52. bool CUDTGroup::applyGroupSequences(SRTSOCKET target, int32_t& w_snd_isn, int32_t& w_rcv_isn)
  53. {
  54. if (m_bConnected) // You are the first one, no need to change.
  55. {
  56. IF_HEAVY_LOGGING(string update_reason = "what?");
  57. // Find a socket that is declared connected and is not
  58. // the socket that caused the call.
  59. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi)
  60. {
  61. if (gi->id == target)
  62. continue;
  63. CUDT& se = gi->ps->core();
  64. if (!se.m_bConnected)
  65. continue;
  66. // Found it. Get the following sequences:
  67. // For sending, the sequence that is about to be sent next.
  68. // For receiving, the sequence of the latest received packet.
  69. // SndCurrSeqNo is initially set to ISN-1, this next one is
  70. // the sequence that is about to be stamped on the next sent packet
  71. // over that socket. Using this field is safer because it is atomic
  72. // and its affinity is to the same thread as the sending function.
  73. // NOTE: the groupwise scheduling sequence might have been set
  74. // already. If so, it means that it was set by either:
  75. // - the call of this function on the very first conencted socket (see below)
  76. // - the call to `sendBroadcast` or `sendBackup`
  77. // In both cases, we want THIS EXACTLY value to be reported
  78. if (m_iLastSchedSeqNo != -1)
  79. {
  80. w_snd_isn = m_iLastSchedSeqNo;
  81. IF_HEAVY_LOGGING(update_reason = "GROUPWISE snd-seq");
  82. }
  83. else
  84. {
  85. w_snd_isn = se.m_iSndNextSeqNo;
  86. // Write it back to the groupwise scheduling sequence so that
  87. // any next connected socket will take this value as well.
  88. m_iLastSchedSeqNo = w_snd_isn;
  89. IF_HEAVY_LOGGING(update_reason = "existing socket not yet sending");
  90. }
  91. // RcvCurrSeqNo is increased by one because it happens that at the
  92. // synchronization moment it's already past reading and delivery.
  93. // This is redundancy, so the redundant socket is connected at the moment
  94. // when the other one is already transmitting, so skipping one packet
  95. // even if later transmitted is less troublesome than requesting a
  96. // "mistakenly seen as lost" packet.
  97. w_rcv_isn = CSeqNo::incseq(se.m_iRcvCurrSeqNo);
  98. HLOGC(gmlog.Debug,
  99. log << "applyGroupSequences: @" << target << " gets seq from @" << gi->id << " rcv %" << (w_rcv_isn)
  100. << " snd %" << (w_snd_isn) << " as " << update_reason);
  101. return false;
  102. }
  103. }
  104. // If the GROUP (!) is not connected, or no running/pending socket has been found.
  105. // // That is, given socket is the first one.
  106. // The group data should be set up with its own data. They should already be passed here
  107. // in the variables.
  108. //
  109. // Override the schedule sequence of the group in this case because whatever is set now,
  110. // it's not valid.
  111. HLOGC(gmlog.Debug,
  112. log << "applyGroupSequences: no socket found connected and transmitting, @" << target
  113. << " not changing sequences, storing snd-seq %" << (w_snd_isn));
  114. set_currentSchedSequence(w_snd_isn);
  115. return true;
  116. }
  117. // NOTE: This function is now for DEBUG PURPOSES ONLY.
  118. // Except for presenting the extracted data in the logs, there's no use of it now.
  119. void CUDTGroup::debugMasterData(SRTSOCKET slave)
  120. {
  121. // Find at least one connection, which is running. Note that this function is called
  122. // from within a handshake process, so the socket that undergoes this process is at best
  123. // currently in SRT_GST_PENDING state and it's going to be in SRT_GST_IDLE state at the
  124. // time when the connection process is done, until the first reading/writing happens.
  125. ScopedLock cg(m_GroupLock);
  126. IF_LOGGING(SRTSOCKET mpeer = SRT_INVALID_SOCK);
  127. IF_LOGGING(steady_clock::time_point start_time);
  128. bool found = false;
  129. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi)
  130. {
  131. if (gi->sndstate == SRT_GST_RUNNING)
  132. {
  133. // Found it. Get the socket's peer's ID and this socket's
  134. // Start Time. Once it's delivered, this can be used to calculate
  135. // the Master-to-Slave start time difference.
  136. IF_LOGGING(mpeer = gi->ps->m_PeerID);
  137. IF_LOGGING(start_time = gi->ps->core().socketStartTime());
  138. HLOGC(gmlog.Debug,
  139. log << "getMasterData: found RUNNING master @" << gi->id << " - reporting master's peer $" << mpeer
  140. << " starting at " << FormatTime(start_time));
  141. found = true;
  142. break;
  143. }
  144. }
  145. if (!found)
  146. {
  147. // If no running one found, then take the first socket in any other
  148. // state than broken, except the slave. This is for a case when a user
  149. // has prepared one link already, but hasn't sent anything through it yet.
  150. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi)
  151. {
  152. if (gi->sndstate == SRT_GST_BROKEN)
  153. continue;
  154. if (gi->id == slave)
  155. continue;
  156. // Found it. Get the socket's peer's ID and this socket's
  157. // Start Time. Once it's delivered, this can be used to calculate
  158. // the Master-to-Slave start time difference.
  159. IF_LOGGING(mpeer = gi->ps->core().m_PeerID);
  160. IF_LOGGING(start_time = gi->ps->core().socketStartTime());
  161. HLOGC(gmlog.Debug,
  162. log << "getMasterData: found IDLE/PENDING master @" << gi->id << " - reporting master's peer $" << mpeer
  163. << " starting at " << FormatTime(start_time));
  164. found = true;
  165. break;
  166. }
  167. }
  168. if (!found)
  169. {
  170. LOGC(cnlog.Debug, log << CONID() << "NO GROUP MASTER LINK found for group: $" << id());
  171. }
  172. else
  173. {
  174. // The returned master_st is the master's start time. Calculate the
  175. // differene time.
  176. IF_LOGGING(steady_clock::duration master_tdiff = m_tsStartTime - start_time);
  177. LOGC(cnlog.Debug, log << CONID() << "FOUND GROUP MASTER LINK: peer=$" << mpeer
  178. << " - start time diff: " << FormatDuration<DUNIT_S>(master_tdiff));
  179. }
  180. }
  181. // GROUP
  182. CUDTGroup::SocketData* CUDTGroup::add(SocketData data)
  183. {
  184. ScopedLock g(m_GroupLock);
  185. // Change the snd/rcv state of the group member to PENDING.
  186. // Default for SocketData after creation is BROKEN, which just
  187. // after releasing the m_GroupLock could be read and interpreted
  188. // as broken connection and removed before the handshake process
  189. // is done.
  190. data.sndstate = SRT_GST_PENDING;
  191. data.rcvstate = SRT_GST_PENDING;
  192. LOGC(gmlog.Note, log << "group/add: adding member @" << data.id << " into group $" << id());
  193. m_Group.push_back(data);
  194. gli_t end = m_Group.end();
  195. if (m_iMaxPayloadSize == -1)
  196. {
  197. int plsize = (int)data.ps->core().OPT_PayloadSize();
  198. HLOGC(gmlog.Debug,
  199. log << "CUDTGroup::add: taking MAX payload size from socket @" << data.ps->m_SocketID << ": " << plsize
  200. << " " << (plsize ? "(explicit)" : "(unspecified = fallback to 1456)"));
  201. if (plsize == 0)
  202. plsize = SRT_LIVE_MAX_PLSIZE;
  203. // It is stated that the payload size
  204. // is taken from first, and every next one
  205. // will get the same.
  206. m_iMaxPayloadSize = plsize;
  207. }
  208. --end;
  209. return &*end;
  210. }
  211. CUDTGroup::CUDTGroup(SRT_GROUP_TYPE gtype)
  212. : m_Global(CUDT::uglobal())
  213. , m_GroupID(-1)
  214. , m_PeerGroupID(-1)
  215. , m_type(gtype)
  216. , m_listener()
  217. , m_iBusy()
  218. , m_iSndOldestMsgNo(SRT_MSGNO_NONE)
  219. , m_iSndAckedMsgNo(SRT_MSGNO_NONE)
  220. , m_uOPT_MinStabilityTimeout_us(1000 * CSrtConfig::COMM_DEF_MIN_STABILITY_TIMEOUT_MS)
  221. // -1 = "undefined"; will become defined with first added socket
  222. , m_iMaxPayloadSize(-1)
  223. , m_bSynRecving(true)
  224. , m_bSynSending(true)
  225. , m_bTsbPd(true)
  226. , m_bTLPktDrop(true)
  227. , m_iTsbPdDelay_us(0)
  228. // m_*EID and m_*Epolld fields will be initialized
  229. // in the constructor body.
  230. , m_iSndTimeOut(-1)
  231. , m_iRcvTimeOut(-1)
  232. , m_tsStartTime()
  233. , m_tsRcvPeerStartTime()
  234. , m_RcvBaseSeqNo(SRT_SEQNO_NONE)
  235. , m_bOpened(false)
  236. , m_bConnected(false)
  237. , m_bClosing(false)
  238. , m_iLastSchedSeqNo(SRT_SEQNO_NONE)
  239. , m_iLastSchedMsgNo(SRT_MSGNO_NONE)
  240. {
  241. setupMutex(m_GroupLock, "Group");
  242. setupMutex(m_RcvDataLock, "RcvData");
  243. setupCond(m_RcvDataCond, "RcvData");
  244. m_RcvEID = m_Global.m_EPoll.create(&m_RcvEpolld);
  245. m_SndEID = m_Global.m_EPoll.create(&m_SndEpolld);
  246. m_stats.init();
  247. // Set this data immediately during creation before
  248. // two or more sockets start arguing about it.
  249. m_iLastSchedSeqNo = CUDT::generateISN();
  250. }
  251. CUDTGroup::~CUDTGroup()
  252. {
  253. srt_epoll_release(m_RcvEID);
  254. srt_epoll_release(m_SndEID);
  255. releaseMutex(m_GroupLock);
  256. releaseMutex(m_RcvDataLock);
  257. releaseCond(m_RcvDataCond);
  258. }
  259. void CUDTGroup::GroupContainer::erase(CUDTGroup::gli_t it)
  260. {
  261. if (it == m_LastActiveLink)
  262. {
  263. if (m_List.empty())
  264. {
  265. LOGC(gmlog.Error, log << "IPE: GroupContainer is empty and 'erase' is called on it.");
  266. m_LastActiveLink = m_List.end();
  267. return; // this avoids any misunderstandings in iterator checks
  268. }
  269. gli_t bb = m_List.begin();
  270. ++bb;
  271. if (bb == m_List.end()) // means: m_List.size() == 1
  272. {
  273. // One element, this one being deleted, nothing to point to.
  274. m_LastActiveLink = m_List.end();
  275. }
  276. else
  277. {
  278. // Set the link to the previous element IN THE RING.
  279. // We have the position pointer.
  280. // Reverse iterator is automatically decremented.
  281. std::reverse_iterator<gli_t> rt(m_LastActiveLink);
  282. if (rt == m_List.rend())
  283. rt = m_List.rbegin();
  284. m_LastActiveLink = rt.base();
  285. // This operation is safe because we know that:
  286. // - the size of the container is at least 2 (0 and 1 cases are handled above)
  287. // - if m_LastActiveLink == m_List.begin(), `rt` is shifted to the opposite end.
  288. --m_LastActiveLink;
  289. }
  290. }
  291. m_List.erase(it);
  292. --m_SizeCache;
  293. }
  294. void CUDTGroup::setOpt(SRT_SOCKOPT optName, const void* optval, int optlen)
  295. {
  296. HLOGC(gmlog.Debug,
  297. log << "GROUP $" << id() << " OPTION: #" << optName
  298. << " value:" << FormatBinaryString((uint8_t*)optval, optlen));
  299. switch (optName)
  300. {
  301. case SRTO_RCVSYN:
  302. m_bSynRecving = cast_optval<bool>(optval, optlen);
  303. return;
  304. case SRTO_SNDSYN:
  305. m_bSynSending = cast_optval<bool>(optval, optlen);
  306. return;
  307. case SRTO_SNDTIMEO:
  308. m_iSndTimeOut = cast_optval<int>(optval, optlen);
  309. break;
  310. case SRTO_RCVTIMEO:
  311. m_iRcvTimeOut = cast_optval<int>(optval, optlen);
  312. break;
  313. case SRTO_GROUPMINSTABLETIMEO:
  314. {
  315. const int val_ms = cast_optval<int>(optval, optlen);
  316. const int min_timeo_ms = (int) CSrtConfig::COMM_DEF_MIN_STABILITY_TIMEOUT_MS;
  317. if (val_ms < min_timeo_ms)
  318. {
  319. LOGC(qmlog.Error,
  320. log << "group option: SRTO_GROUPMINSTABLETIMEO min allowed value is " << min_timeo_ms << " ms.");
  321. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  322. }
  323. // Search if you already have SRTO_PEERIDLETIMEO set
  324. int idletmo = CSrtConfig::COMM_RESPONSE_TIMEOUT_MS;
  325. vector<ConfigItem>::iterator f =
  326. find_if(m_config.begin(), m_config.end(), ConfigItem::OfType(SRTO_PEERIDLETIMEO));
  327. if (f != m_config.end())
  328. {
  329. f->get(idletmo); // worst case, it will leave it unchanged.
  330. }
  331. if (val_ms > idletmo)
  332. {
  333. LOGC(qmlog.Error,
  334. log << "group option: SRTO_GROUPMINSTABLETIMEO=" << val_ms << " exceeds SRTO_PEERIDLETIMEO=" << idletmo);
  335. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  336. }
  337. m_uOPT_MinStabilityTimeout_us = 1000 * val_ms;
  338. }
  339. break;
  340. default:
  341. break;
  342. }
  343. // All others must be simply stored for setting on a socket.
  344. // If the group is already open and any post-option is about
  345. // to be modified, it must be allowed and applied on all sockets.
  346. if (m_bOpened)
  347. {
  348. // There's at least one socket in the group, so only
  349. // post-options are allowed.
  350. if (!binary_search(srt_post_opt_list, srt_post_opt_list + SRT_SOCKOPT_NPOST, optName))
  351. {
  352. LOGC(gmlog.Error, log << "setsockopt(group): Group is connected, this option can't be altered");
  353. throw CUDTException(MJ_NOTSUP, MN_ISCONNECTED, 0);
  354. }
  355. HLOGC(gmlog.Debug, log << "... SPREADING to existing sockets.");
  356. // This means that there are sockets already, so apply
  357. // this option on them.
  358. std::vector<CUDTSocket*> ps_vec;
  359. {
  360. // Do copy to avoid deadlock. CUDT::setOpt() cannot be called directly inside this loop, because
  361. // CUDT::setOpt() will lock m_ConnectionLock, which should be locked before m_GroupLock.
  362. ScopedLock gg(m_GroupLock);
  363. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi)
  364. {
  365. ps_vec.push_back(gi->ps);
  366. }
  367. }
  368. for (std::vector<CUDTSocket*>::iterator it = ps_vec.begin(); it != ps_vec.end(); ++it)
  369. {
  370. (*it)->core().setOpt(optName, optval, optlen);
  371. }
  372. }
  373. // Store the option regardless if pre or post. This will apply
  374. m_config.push_back(ConfigItem(optName, optval, optlen));
  375. }
  376. static bool getOptDefault(SRT_SOCKOPT optname, void* optval, int& w_optlen);
  377. // unfortunately this is required to properly handle th 'default_opt != opt'
  378. // operation in the below importOption. Not required simultaneously operator==.
  379. static bool operator!=(const struct linger& l1, const struct linger& l2)
  380. {
  381. return l1.l_onoff != l2.l_onoff || l1.l_linger != l2.l_linger;
  382. }
  383. template <class ValueType>
  384. static void importOption(vector<CUDTGroup::ConfigItem>& storage, SRT_SOCKOPT optname, const ValueType& field)
  385. {
  386. ValueType default_opt = ValueType();
  387. int default_opt_size = sizeof(ValueType);
  388. ValueType opt = field;
  389. if (!getOptDefault(optname, (&default_opt), (default_opt_size)) || default_opt != opt)
  390. {
  391. // Store the option when:
  392. // - no default for this option is found
  393. // - the option value retrieved from the field is different than default
  394. storage.push_back(CUDTGroup::ConfigItem(optname, &opt, default_opt_size));
  395. }
  396. }
  397. // This function is called by the same premises as the CUDT::CUDT(const CUDT&) (copy constructor).
  398. // The intention is to rewrite the part that comprises settings from the socket
  399. // into the group. Note that some of the settings concern group, some others concern
  400. // only target socket, and there are also options that can't be set on a socket.
  401. void CUDTGroup::deriveSettings(CUDT* u)
  402. {
  403. // !!! IMPORTANT !!!
  404. //
  405. // This function shall ONLY be called on a newly created group
  406. // for the sake of the newly accepted socket from the group-enabled listener,
  407. // which is lazy-created for the first ever accepted socket.
  408. // Once the group is created, it should stay with the options
  409. // state as initialized here, and be changeable only in case when
  410. // the option is altered on the group.
  411. // SRTO_RCVSYN
  412. m_bSynRecving = u->m_config.bSynRecving;
  413. // SRTO_SNDSYN
  414. m_bSynSending = u->m_config.bSynSending;
  415. // SRTO_RCVTIMEO
  416. m_iRcvTimeOut = u->m_config.iRcvTimeOut;
  417. // SRTO_SNDTIMEO
  418. m_iSndTimeOut = u->m_config.iSndTimeOut;
  419. // SRTO_GROUPMINSTABLETIMEO
  420. m_uOPT_MinStabilityTimeout_us = 1000 * u->m_config.uMinStabilityTimeout_ms;
  421. // Ok, this really is disgusting, but there's only one way
  422. // to properly do it. Would be nice to have some more universal
  423. // connection between an option symbolic name and the internals
  424. // in CUDT class, but until this is done, since now every new
  425. // option will have to be handled both in the CUDT::setOpt/getOpt
  426. // functions, and here as well.
  427. // This is about moving options from listener to the group,
  428. // to be potentially replicated on the socket. So both pre
  429. // and post options apply.
  430. #define IM(option, field) importOption(m_config, option, u->m_config.field)
  431. #define IMF(option, field) importOption(m_config, option, u->field)
  432. IM(SRTO_MSS, iMSS);
  433. IM(SRTO_FC, iFlightFlagSize);
  434. // Nonstandard
  435. importOption(m_config, SRTO_SNDBUF, u->m_config.iSndBufSize * (u->m_config.iMSS - CPacket::UDP_HDR_SIZE));
  436. importOption(m_config, SRTO_RCVBUF, u->m_config.iRcvBufSize * (u->m_config.iMSS - CPacket::UDP_HDR_SIZE));
  437. IM(SRTO_LINGER, Linger);
  438. IM(SRTO_UDP_SNDBUF, iUDPSndBufSize);
  439. IM(SRTO_UDP_RCVBUF, iUDPRcvBufSize);
  440. // SRTO_RENDEZVOUS: impossible to have it set on a listener socket.
  441. // SRTO_SNDTIMEO/RCVTIMEO: groupwise setting
  442. IM(SRTO_CONNTIMEO, tdConnTimeOut);
  443. IM(SRTO_DRIFTTRACER, bDriftTracer);
  444. // Reuseaddr: true by default and should only be true.
  445. IM(SRTO_MAXBW, llMaxBW);
  446. IM(SRTO_INPUTBW, llInputBW);
  447. IM(SRTO_MININPUTBW, llMinInputBW);
  448. IM(SRTO_OHEADBW, iOverheadBW);
  449. IM(SRTO_IPTOS, iIpToS);
  450. IM(SRTO_IPTTL, iIpTTL);
  451. IM(SRTO_TSBPDMODE, bTSBPD);
  452. IM(SRTO_RCVLATENCY, iRcvLatency);
  453. IM(SRTO_PEERLATENCY, iPeerLatency);
  454. IM(SRTO_SNDDROPDELAY, iSndDropDelay);
  455. IM(SRTO_PAYLOADSIZE, zExpPayloadSize);
  456. IMF(SRTO_TLPKTDROP, m_bTLPktDrop);
  457. importOption(m_config, SRTO_STREAMID, u->m_config.sStreamName.str());
  458. IM(SRTO_MESSAGEAPI, bMessageAPI);
  459. IM(SRTO_NAKREPORT, bRcvNakReport);
  460. IM(SRTO_MINVERSION, uMinimumPeerSrtVersion);
  461. IM(SRTO_ENFORCEDENCRYPTION, bEnforcedEnc);
  462. IM(SRTO_IPV6ONLY, iIpV6Only);
  463. IM(SRTO_PEERIDLETIMEO, iPeerIdleTimeout_ms);
  464. importOption(m_config, SRTO_PACKETFILTER, u->m_config.sPacketFilterConfig.str());
  465. importOption(m_config, SRTO_PBKEYLEN, u->m_pCryptoControl->KeyLen());
  466. // Passphrase is empty by default. Decipher the passphrase and
  467. // store as passphrase option
  468. if (u->m_config.CryptoSecret.len)
  469. {
  470. string password((const char*)u->m_config.CryptoSecret.str, u->m_config.CryptoSecret.len);
  471. m_config.push_back(ConfigItem(SRTO_PASSPHRASE, password.c_str(), (int)password.size()));
  472. }
  473. IM(SRTO_KMREFRESHRATE, uKmRefreshRatePkt);
  474. IM(SRTO_KMPREANNOUNCE, uKmPreAnnouncePkt);
  475. string cc = u->m_CongCtl.selected_name();
  476. if (cc != "live")
  477. {
  478. m_config.push_back(ConfigItem(SRTO_CONGESTION, cc.c_str(), (int)cc.size()));
  479. }
  480. // NOTE: This is based on information extracted from the "semi-copy-constructor" of CUDT class.
  481. // Here should be handled all things that are options that modify the socket, but not all options
  482. // are assigned to configurable items.
  483. #undef IM
  484. #undef IMF
  485. }
  486. bool CUDTGroup::applyFlags(uint32_t flags, HandshakeSide)
  487. {
  488. const bool synconmsg = IsSet(flags, SRT_GFLAG_SYNCONMSG);
  489. if (synconmsg)
  490. {
  491. LOGP(gmlog.Error, "GROUP: requested sync on msgno - not supported.");
  492. return false;
  493. }
  494. return true;
  495. }
  496. template <class Type>
  497. struct Value
  498. {
  499. static int fill(void* optval, int, Type value)
  500. {
  501. // XXX assert size >= sizeof(Type) ?
  502. *(Type*)optval = value;
  503. return sizeof(Type);
  504. }
  505. };
  506. template <>
  507. inline int Value<std::string>::fill(void* optval, int len, std::string value)
  508. {
  509. if (size_t(len) < value.size())
  510. return 0;
  511. memcpy(optval, value.c_str(), value.size());
  512. return (int) value.size();
  513. }
  514. template <class V>
  515. inline int fillValue(void* optval, int len, V value)
  516. {
  517. return Value<V>::fill(optval, len, value);
  518. }
  519. static bool getOptDefault(SRT_SOCKOPT optname, void* pw_optval, int& w_optlen)
  520. {
  521. static const linger def_linger = {1, CSrtConfig::DEF_LINGER_S};
  522. switch (optname)
  523. {
  524. default:
  525. return false;
  526. #define RD(value) \
  527. w_optlen = fillValue((pw_optval), w_optlen, value); \
  528. break
  529. case SRTO_KMSTATE:
  530. case SRTO_SNDKMSTATE:
  531. case SRTO_RCVKMSTATE:
  532. RD(SRT_KM_S_UNSECURED);
  533. case SRTO_PBKEYLEN:
  534. RD(16);
  535. case SRTO_MSS:
  536. RD(CSrtConfig::DEF_MSS);
  537. case SRTO_SNDSYN:
  538. RD(true);
  539. case SRTO_RCVSYN:
  540. RD(true);
  541. case SRTO_ISN:
  542. RD(SRT_SEQNO_NONE);
  543. case SRTO_FC:
  544. RD(CSrtConfig::DEF_FLIGHT_SIZE);
  545. case SRTO_SNDBUF:
  546. case SRTO_RCVBUF:
  547. w_optlen = fillValue((pw_optval), w_optlen, CSrtConfig::DEF_BUFFER_SIZE * (CSrtConfig::DEF_MSS - CPacket::UDP_HDR_SIZE));
  548. break;
  549. case SRTO_LINGER:
  550. RD(def_linger);
  551. case SRTO_UDP_SNDBUF:
  552. case SRTO_UDP_RCVBUF:
  553. RD(CSrtConfig::DEF_UDP_BUFFER_SIZE);
  554. case SRTO_RENDEZVOUS:
  555. RD(false);
  556. case SRTO_SNDTIMEO:
  557. RD(-1);
  558. case SRTO_RCVTIMEO:
  559. RD(-1);
  560. case SRTO_REUSEADDR:
  561. RD(true);
  562. case SRTO_MAXBW:
  563. RD(int64_t(-1));
  564. case SRTO_INPUTBW:
  565. RD(int64_t(-1));
  566. case SRTO_OHEADBW:
  567. RD(0);
  568. case SRTO_STATE:
  569. RD(SRTS_INIT);
  570. case SRTO_EVENT:
  571. RD(0);
  572. case SRTO_SNDDATA:
  573. RD(0);
  574. case SRTO_RCVDATA:
  575. RD(0);
  576. case SRTO_IPTTL:
  577. RD(0);
  578. case SRTO_IPTOS:
  579. RD(0);
  580. case SRTO_SENDER:
  581. RD(false);
  582. case SRTO_TSBPDMODE:
  583. RD(false);
  584. case SRTO_LATENCY:
  585. case SRTO_RCVLATENCY:
  586. case SRTO_PEERLATENCY:
  587. RD(SRT_LIVE_DEF_LATENCY_MS);
  588. case SRTO_TLPKTDROP:
  589. RD(true);
  590. case SRTO_SNDDROPDELAY:
  591. RD(-1);
  592. case SRTO_NAKREPORT:
  593. RD(true);
  594. case SRTO_VERSION:
  595. RD(SRT_DEF_VERSION);
  596. case SRTO_PEERVERSION:
  597. RD(0);
  598. case SRTO_CONNTIMEO:
  599. RD(-1);
  600. case SRTO_DRIFTTRACER:
  601. RD(true);
  602. case SRTO_MINVERSION:
  603. RD(0);
  604. case SRTO_STREAMID:
  605. RD(std::string());
  606. case SRTO_CONGESTION:
  607. RD(std::string());
  608. case SRTO_MESSAGEAPI:
  609. RD(true);
  610. case SRTO_PAYLOADSIZE:
  611. RD(0);
  612. case SRTO_GROUPMINSTABLETIMEO:
  613. RD(CSrtConfig::COMM_DEF_MIN_STABILITY_TIMEOUT_MS);
  614. }
  615. #undef RD
  616. return true;
  617. }
  618. void CUDTGroup::getOpt(SRT_SOCKOPT optname, void* pw_optval, int& w_optlen)
  619. {
  620. // Options handled in group
  621. switch (optname)
  622. {
  623. case SRTO_RCVSYN:
  624. *(bool*)pw_optval = m_bSynRecving;
  625. w_optlen = sizeof(bool);
  626. return;
  627. case SRTO_SNDSYN:
  628. *(bool*)pw_optval = m_bSynSending;
  629. w_optlen = sizeof(bool);
  630. return;
  631. default:; // pass on
  632. }
  633. // XXX Suspicous: may require locking of GlobControlLock
  634. // to prevent from deleting a socket in the meantime.
  635. // Deleting a socket requires removing from the group first,
  636. // so after GroupLock this will be either already NULL or
  637. // a valid socket that will only be closed after time in
  638. // the GC, so this is likely safe like all other API functions.
  639. CUDTSocket* ps = 0;
  640. {
  641. // In sockets. All sockets should have all options
  642. // set the same and should represent the group state
  643. // well enough. If there are no sockets, just use default.
  644. // Group lock to protect the container itself.
  645. // Once a socket is extracted, we state it cannot be
  646. // closed without the group send/recv function or closing
  647. // being involved.
  648. ScopedLock lg(m_GroupLock);
  649. if (m_Group.empty())
  650. {
  651. if (!getOptDefault(optname, (pw_optval), (w_optlen)))
  652. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  653. return;
  654. }
  655. ps = m_Group.begin()->ps;
  656. // Release the lock on the group, as it's not necessary,
  657. // as well as it might cause a deadlock when combined
  658. // with the others.
  659. }
  660. if (!ps)
  661. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  662. return ps->core().getOpt(optname, (pw_optval), (w_optlen));
  663. }
  664. SRT_SOCKSTATUS CUDTGroup::getStatus()
  665. {
  666. typedef vector<pair<SRTSOCKET, SRT_SOCKSTATUS> > states_t;
  667. states_t states;
  668. {
  669. ScopedLock cg(m_GroupLock);
  670. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi)
  671. {
  672. switch (gi->sndstate)
  673. {
  674. // Check only sndstate. If this machine is ONLY receiving,
  675. // then rcvstate will turn into SRT_GST_RUNNING, while
  676. // sndstate will remain SRT_GST_IDLE, but still this may only
  677. // happen if the socket is connected.
  678. case SRT_GST_IDLE:
  679. case SRT_GST_RUNNING:
  680. states.push_back(make_pair(gi->id, SRTS_CONNECTED));
  681. break;
  682. case SRT_GST_BROKEN:
  683. states.push_back(make_pair(gi->id, SRTS_BROKEN));
  684. break;
  685. default: // (pending, or whatever will be added in future)
  686. {
  687. // TEMPORARY make a node to note a socket to be checked afterwards
  688. states.push_back(make_pair(gi->id, SRTS_NONEXIST));
  689. }
  690. }
  691. }
  692. }
  693. SRT_SOCKSTATUS pending_state = SRTS_NONEXIST;
  694. for (states_t::iterator i = states.begin(); i != states.end(); ++i)
  695. {
  696. // If at least one socket is connected, the state is connected.
  697. if (i->second == SRTS_CONNECTED)
  698. return SRTS_CONNECTED;
  699. // Second level - pick up the state
  700. if (i->second == SRTS_NONEXIST)
  701. {
  702. // Otherwise find at least one socket, which's state isn't broken.
  703. i->second = m_Global.getStatus(i->first);
  704. if (pending_state == SRTS_NONEXIST)
  705. pending_state = i->second;
  706. }
  707. }
  708. // Return that state as group state
  709. if (pending_state != SRTS_NONEXIST) // did call getStatus at least once and it didn't return NOEXIST
  710. return pending_state;
  711. // If none found, return SRTS_BROKEN.
  712. return SRTS_BROKEN;
  713. }
  714. // [[using locked(m_GroupLock)]];
  715. void CUDTGroup::syncWithSocket(const CUDT& core, const HandshakeSide side)
  716. {
  717. if (side == HSD_RESPONDER)
  718. {
  719. // On the listener side you should synchronize ISN with the incoming
  720. // socket, which is done immediately after creating the socket and
  721. // adding it to the group. On the caller side the ISN is defined in
  722. // the group directly, before any member socket is created.
  723. set_currentSchedSequence(core.ISN());
  724. }
  725. // XXX
  726. // Might need further investigation as to whether this isn't
  727. // wrong for some cases. By having this -1 here the value will be
  728. // laziliy set from the first reading one. It is believed that
  729. // it covers all possible scenarios, that is:
  730. //
  731. // - no readers - no problem!
  732. // - have some readers and a new is attached - this is set already
  733. // - connect multiple links, but none has read yet - you'll be the first.
  734. //
  735. // Previous implementation used setting to: core.m_iPeerISN
  736. resetInitialRxSequence();
  737. // Get the latency (possibly fixed against the opposite side)
  738. // from the first socket (core.m_iTsbPdDelay_ms),
  739. // and set it on the current socket.
  740. set_latency(core.m_iTsbPdDelay_ms * int64_t(1000));
  741. }
  742. void CUDTGroup::close()
  743. {
  744. // Close all descriptors, then delete the group.
  745. vector<SRTSOCKET> ids;
  746. {
  747. ScopedLock glob(CUDT::uglobal().m_GlobControlLock);
  748. ScopedLock g(m_GroupLock);
  749. m_bClosing = true;
  750. // Copy the list of IDs into the array.
  751. for (gli_t ig = m_Group.begin(); ig != m_Group.end(); ++ig)
  752. {
  753. ids.push_back(ig->id);
  754. // Immediately cut ties to this group.
  755. // Just for a case, redispatch the socket, to stay safe.
  756. CUDTSocket* s = CUDT::uglobal().locateSocket_LOCKED(ig->id);
  757. if (!s)
  758. {
  759. HLOGC(smlog.Debug, log << "group/close: IPE(NF): group member @" << ig->id << " already deleted");
  760. continue;
  761. }
  762. // Make the socket closing BEFORE withdrawing its group membership
  763. // because a socket created as a group member cannot be valid
  764. // without the group.
  765. // This is not true in case of non-managed groups, which
  766. // only collect sockets, but also non-managed groups should not
  767. // use common group buffering and tsbpd. Also currently there are
  768. // no other groups than managed one.
  769. s->setClosing();
  770. s->m_GroupOf = NULL;
  771. s->m_GroupMemberData = NULL;
  772. HLOGC(smlog.Debug, log << "group/close: CUTTING OFF @" << ig->id << " (found as @" << s->m_SocketID << ") from the group");
  773. }
  774. // After all sockets that were group members have their ties cut,
  775. // the container can be cleared. Note that sockets won't be now
  776. // removing themselves from the group when closing because they
  777. // are unaware of being group members.
  778. m_Group.clear();
  779. m_PeerGroupID = -1;
  780. set<int> epollid;
  781. {
  782. // Global EPOLL lock must be applied to access any socket's epoll set.
  783. // This is a set of all epoll ids subscribed to it.
  784. ScopedLock elock (CUDT::uglobal().m_EPoll.m_EPollLock);
  785. epollid = m_sPollID; // use move() in C++11
  786. m_sPollID.clear();
  787. }
  788. int no_events = 0;
  789. for (set<int>::iterator i = epollid.begin(); i != epollid.end(); ++i)
  790. {
  791. HLOGC(smlog.Debug, log << "close: CLEARING subscription on E" << (*i) << " of $" << id());
  792. try
  793. {
  794. CUDT::uglobal().m_EPoll.update_usock(*i, id(), &no_events);
  795. }
  796. catch (...)
  797. {
  798. // May catch an API exception, but this isn't an API call to be interrupted.
  799. }
  800. HLOGC(smlog.Debug, log << "close: removing E" << (*i) << " from back-subscribers of $" << id());
  801. }
  802. // NOW, the m_GroupLock is released, then m_GlobControlLock.
  803. // The below code should work with no locks and execute socket
  804. // closing.
  805. }
  806. HLOGC(gmlog.Debug, log << "grp/close: closing $" << m_GroupID << ", closing first " << ids.size() << " sockets:");
  807. // Close all sockets with unlocked GroupLock
  808. for (vector<SRTSOCKET>::iterator i = ids.begin(); i != ids.end(); ++i)
  809. {
  810. try
  811. {
  812. CUDT::uglobal().close(*i);
  813. }
  814. catch (CUDTException&)
  815. {
  816. HLOGC(gmlog.Debug, log << "grp/close: socket @" << *i << " is likely closed already, ignoring");
  817. }
  818. }
  819. HLOGC(gmlog.Debug, log << "grp/close: closing $" << m_GroupID << ": sockets closed, clearing the group:");
  820. // Lock the group again to clear the group data
  821. {
  822. ScopedLock g(m_GroupLock);
  823. if (!m_Group.empty())
  824. {
  825. LOGC(gmlog.Error, log << "grp/close: IPE - after requesting to close all members, still " << m_Group.size()
  826. << " lingering members!");
  827. m_Group.clear();
  828. }
  829. // This takes care of the internal part.
  830. // The external part will be done in Global (CUDTUnited)
  831. }
  832. // Release blocked clients
  833. // XXX This looks like a dead code. Group receiver functions
  834. // do not use any lock on m_RcvDataLock, it is likely a remainder
  835. // of the old, internal impementation.
  836. // CSync::lock_notify_one(m_RcvDataCond, m_RcvDataLock);
  837. }
  838. // [[using locked(m_Global->m_GlobControlLock)]]
  839. // [[using locked(m_GroupLock)]]
  840. void CUDTGroup::send_CheckValidSockets()
  841. {
  842. vector<gli_t> toremove;
  843. for (gli_t d = m_Group.begin(), d_next = d; d != m_Group.end(); d = d_next)
  844. {
  845. ++d_next; // it's now safe to erase d
  846. CUDTSocket* revps = m_Global.locateSocket_LOCKED(d->id);
  847. if (revps != d->ps)
  848. {
  849. // Note: the socket might STILL EXIST, just in the trash, so
  850. // it can't be found by locateSocket. But it can still be bound
  851. // to the group. Just mark it broken from upside so that the
  852. // internal sending procedures will skip it. Removal from the
  853. // group will happen in GC, which will both remove from
  854. // group container and cut backward links to the group.
  855. HLOGC(gmlog.Debug, log << "group/send_CheckValidSockets: socket @" << d->id << " is no longer valid, setting BROKEN in $" << id());
  856. d->sndstate = SRT_GST_BROKEN;
  857. d->rcvstate = SRT_GST_BROKEN;
  858. }
  859. }
  860. }
  861. int CUDTGroup::send(const char* buf, int len, SRT_MSGCTRL& w_mc)
  862. {
  863. switch (m_type)
  864. {
  865. default:
  866. LOGC(gslog.Error, log << "CUDTGroup::send: not implemented for type #" << m_type);
  867. throw CUDTException(MJ_SETUP, MN_INVAL, 0);
  868. case SRT_GTYPE_BROADCAST:
  869. return sendBroadcast(buf, len, (w_mc));
  870. case SRT_GTYPE_BACKUP:
  871. return sendBackup(buf, len, (w_mc));
  872. /* to be implemented
  873. case SRT_GTYPE_BALANCING:
  874. return sendBalancing(buf, len, (w_mc));
  875. case SRT_GTYPE_MULTICAST:
  876. return sendMulticast(buf, len, (w_mc));
  877. */
  878. }
  879. }
  880. int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc)
  881. {
  882. // Avoid stupid errors in the beginning.
  883. if (len <= 0)
  884. {
  885. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  886. }
  887. // NOTE: This is a "vector of list iterators". Every element here
  888. // is an iterator to another container.
  889. // Note that "list" is THE ONLY container in standard C++ library,
  890. // for which NO ITERATORS ARE INVALIDATED after a node at particular
  891. // iterator has been removed, except for that iterator itself.
  892. vector<SRTSOCKET> wipeme;
  893. vector<gli_t> idleLinks;
  894. vector<SRTSOCKET> pendingSockets; // need sock ids as it will be checked out of lock
  895. int32_t curseq = SRT_SEQNO_NONE; // The seqno of the first packet of this message.
  896. int32_t nextseq = SRT_SEQNO_NONE; // The seqno of the first packet of next message.
  897. int rstat = -1;
  898. int stat = 0;
  899. SRT_ATR_UNUSED CUDTException cx(MJ_SUCCESS, MN_NONE, 0);
  900. vector<gli_t> activeLinks;
  901. // First, acquire GlobControlLock to make sure all member sockets still exist
  902. enterCS(m_Global.m_GlobControlLock);
  903. ScopedLock guard(m_GroupLock);
  904. if (m_bClosing)
  905. {
  906. leaveCS(m_Global.m_GlobControlLock);
  907. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  908. }
  909. // Now, still under lock, check if all sockets still can be dispatched
  910. // LOCKED: GlobControlLock, GroupLock (RIGHT ORDER!)
  911. send_CheckValidSockets();
  912. leaveCS(m_Global.m_GlobControlLock);
  913. // LOCKED: GroupLock (only)
  914. // Since this moment GlobControlLock may only be locked if GroupLock is unlocked first.
  915. if (m_bClosing)
  916. {
  917. // No temporary locks here. The group lock is scoped.
  918. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  919. }
  920. // This simply requires the payload to be sent through every socket in the group
  921. for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d)
  922. {
  923. if (d->sndstate != SRT_GST_BROKEN)
  924. {
  925. // Check the socket state prematurely in order not to uselessly
  926. // send over a socket that is broken.
  927. CUDT* const pu = (d->ps)
  928. ? &d->ps->core()
  929. : NULL;
  930. if (!pu || pu->m_bBroken)
  931. {
  932. HLOGC(gslog.Debug,
  933. log << "grp/sendBroadcast: socket @" << d->id << " detected +Broken - transit to BROKEN");
  934. d->sndstate = SRT_GST_BROKEN;
  935. d->rcvstate = SRT_GST_BROKEN;
  936. }
  937. }
  938. // Check socket sndstate before sending
  939. if (d->sndstate == SRT_GST_BROKEN)
  940. {
  941. HLOGC(gslog.Debug,
  942. log << "grp/sendBroadcast: socket in BROKEN state: @" << d->id
  943. << ", sockstatus=" << SockStatusStr(d->ps ? d->ps->getStatus() : SRTS_NONEXIST));
  944. wipeme.push_back(d->id);
  945. continue;
  946. }
  947. if (d->sndstate == SRT_GST_IDLE)
  948. {
  949. SRT_SOCKSTATUS st = SRTS_NONEXIST;
  950. if (d->ps)
  951. st = d->ps->getStatus();
  952. // If the socket is already broken, move it to broken.
  953. if (int(st) >= int(SRTS_BROKEN))
  954. {
  955. HLOGC(gslog.Debug,
  956. log << "CUDTGroup::send.$" << id() << ": @" << d->id << " became " << SockStatusStr(st)
  957. << ", WILL BE CLOSED.");
  958. wipeme.push_back(d->id);
  959. continue;
  960. }
  961. if (st != SRTS_CONNECTED)
  962. {
  963. HLOGC(gslog.Debug,
  964. log << "CUDTGroup::send. @" << d->id << " is still " << SockStatusStr(st) << ", skipping.");
  965. pendingSockets.push_back(d->id);
  966. continue;
  967. }
  968. HLOGC(gslog.Debug, log << "grp/sendBroadcast: socket in IDLE state: @" << d->id << " - will activate it");
  969. // This is idle, we'll take care of them next time
  970. // Might be that:
  971. // - this socket is idle, while some NEXT socket is running
  972. // - we need at least one running socket to work BEFORE activating the idle one.
  973. // - if ALL SOCKETS ARE IDLE, then we simply activate the first from the list,
  974. // and all others will be activated using the ISN from the first one.
  975. idleLinks.push_back(d);
  976. continue;
  977. }
  978. if (d->sndstate == SRT_GST_RUNNING)
  979. {
  980. HLOGC(gslog.Debug,
  981. log << "grp/sendBroadcast: socket in RUNNING state: @" << d->id << " - will send a payload");
  982. activeLinks.push_back(d);
  983. continue;
  984. }
  985. HLOGC(gslog.Debug,
  986. log << "grp/sendBroadcast: socket @" << d->id << " not ready, state: " << StateStr(d->sndstate) << "("
  987. << int(d->sndstate) << ") - NOT sending, SET AS PENDING");
  988. pendingSockets.push_back(d->id);
  989. }
  990. vector<Sendstate> sendstates;
  991. if (w_mc.srctime == 0)
  992. w_mc.srctime = count_microseconds(steady_clock::now().time_since_epoch());
  993. for (vector<gli_t>::iterator snd = activeLinks.begin(); snd != activeLinks.end(); ++snd)
  994. {
  995. gli_t d = *snd;
  996. int erc = 0; // success
  997. // Remaining sndstate is SRT_GST_RUNNING. Send a payload through it.
  998. try
  999. {
  1000. // This must be wrapped in try-catch because on error it throws an exception.
  1001. // Possible return values are only 0, in case when len was passed 0, or a positive
  1002. // >0 value that defines the size of the data that it has sent, that is, in case
  1003. // of Live mode, equal to 'len'.
  1004. stat = d->ps->core().sendmsg2(buf, len, (w_mc));
  1005. }
  1006. catch (CUDTException& e)
  1007. {
  1008. cx = e;
  1009. stat = -1;
  1010. erc = e.getErrorCode();
  1011. }
  1012. if (stat != -1)
  1013. {
  1014. curseq = w_mc.pktseq;
  1015. nextseq = d->ps->core().schedSeqNo();
  1016. }
  1017. const Sendstate cstate = {d->id, &*d, stat, erc};
  1018. sendstates.push_back(cstate);
  1019. d->sndresult = stat;
  1020. d->laststatus = d->ps->getStatus();
  1021. }
  1022. // Ok, we have attempted to send a payload over all links
  1023. // that are currently in the RUNNING state. We know that at
  1024. // least one is successful if we have non-default curseq value.
  1025. // Here we need to activate all links that are found as IDLE.
  1026. // Some portion of logical exclusions:
  1027. //
  1028. // - sockets that were broken in the beginning are already wiped out
  1029. // - broken sockets are checked first, so they can't be simultaneously idle
  1030. // - idle sockets can't get broken because there's no operation done on them
  1031. // - running sockets are the only one that could change sndstate here
  1032. // - running sockets can either remain running or turn to broken
  1033. // In short: Running and Broken sockets can't become idle,
  1034. // although Running sockets can become Broken.
  1035. // There's no certainty here as to whether at least one link was
  1036. // running and it has successfully performed the operation.
  1037. // Might have even happened that we had 2 running links that
  1038. // got broken and 3 other links so far in idle sndstate that just connected
  1039. // at that very moment. In this case we have 3 idle links to activate,
  1040. // but there is no sequence base to overwrite their ISN with. If this
  1041. // happens, then the first link that should be activated goes with
  1042. // whatever ISN it has, whereas every next idle link should use that
  1043. // exactly ISN.
  1044. //
  1045. // If it has additionally happened that the first link got broken at
  1046. // that very moment of sending, the second one has a chance to succeed
  1047. // and therefore take over the leading role in setting the ISN. If the
  1048. // second one fails, too, then the only remaining idle link will simply
  1049. // go with its own original sequence.
  1050. // On the opposite side, if the first packet arriving looks like a jump over,
  1051. // the corresponding LOSSREPORT is sent. For packets that are truly lost,
  1052. // the sender retransmits them, for packets that before ISN, DROPREQ is sent.
  1053. // Now we can go to the idle links and attempt to send the payload
  1054. // also over them.
  1055. // TODO: { sendBroadcast_ActivateIdleLinks
  1056. for (vector<gli_t>::iterator i = idleLinks.begin(); i != idleLinks.end(); ++i)
  1057. {
  1058. gli_t d = *i;
  1059. if (!d->ps->m_GroupOf)
  1060. continue;
  1061. int erc = 0;
  1062. int lastseq = d->ps->core().schedSeqNo();
  1063. if (curseq != SRT_SEQNO_NONE && curseq != lastseq)
  1064. {
  1065. HLOGC(gslog.Debug,
  1066. log << "grp/sendBroadcast: socket @" << d->id << ": override snd sequence %" << lastseq << " with %"
  1067. << curseq << " (diff by " << CSeqNo::seqcmp(curseq, lastseq)
  1068. << "); SENDING PAYLOAD: " << BufferStamp(buf, len));
  1069. d->ps->core().overrideSndSeqNo(curseq);
  1070. }
  1071. else
  1072. {
  1073. HLOGC(gslog.Debug,
  1074. log << "grp/sendBroadcast: socket @" << d->id << ": sequence remains with original value: %"
  1075. << lastseq << "; SENDING PAYLOAD " << BufferStamp(buf, len));
  1076. }
  1077. // Now send and check the status
  1078. // The link could have got broken
  1079. try
  1080. {
  1081. stat = d->ps->core().sendmsg2(buf, len, (w_mc));
  1082. }
  1083. catch (CUDTException& e)
  1084. {
  1085. cx = e;
  1086. stat = -1;
  1087. erc = e.getErrorCode();
  1088. }
  1089. if (stat != -1)
  1090. {
  1091. d->sndstate = SRT_GST_RUNNING;
  1092. // Note: this will override the sequence number
  1093. // for all next iterations in this loop.
  1094. curseq = w_mc.pktseq;
  1095. nextseq = d->ps->core().schedSeqNo();
  1096. HLOGC(gslog.Debug,
  1097. log << "@" << d->id << ":... sending SUCCESSFUL %" << curseq << " MEMBER STATUS: RUNNING");
  1098. }
  1099. d->sndresult = stat;
  1100. d->laststatus = d->ps->getStatus();
  1101. const Sendstate cstate = {d->id, &*d, stat, erc};
  1102. sendstates.push_back(cstate);
  1103. }
  1104. if (nextseq != SRT_SEQNO_NONE)
  1105. {
  1106. HLOGC(gslog.Debug,
  1107. log << "grp/sendBroadcast: $" << id() << ": updating current scheduling sequence %" << nextseq);
  1108. m_iLastSchedSeqNo = nextseq;
  1109. }
  1110. // }
  1111. // { send_CheckBrokenSockets()
  1112. if (!pendingSockets.empty())
  1113. {
  1114. HLOGC(gslog.Debug, log << "grp/sendBroadcast: found pending sockets, polling them.");
  1115. // These sockets if they are in pending state, they should be added to m_SndEID
  1116. // at the connecting stage.
  1117. CEPoll::fmap_t sready;
  1118. if (m_Global.m_EPoll.empty(*m_SndEpolld))
  1119. {
  1120. // Sanity check - weird pending reported.
  1121. LOGC(gslog.Error,
  1122. log << "grp/sendBroadcast: IPE: reported pending sockets, but EID is empty - wiping pending!");
  1123. copy(pendingSockets.begin(), pendingSockets.end(), back_inserter(wipeme));
  1124. }
  1125. else
  1126. {
  1127. {
  1128. InvertedLock ug(m_GroupLock);
  1129. THREAD_PAUSED();
  1130. m_Global.m_EPoll.swait(
  1131. *m_SndEpolld, sready, 0, false /*report by retval*/); // Just check if anything happened
  1132. THREAD_RESUMED();
  1133. }
  1134. if (m_bClosing)
  1135. {
  1136. // No temporary locks here. The group lock is scoped.
  1137. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  1138. }
  1139. HLOGC(gslog.Debug, log << "grp/sendBroadcast: RDY: " << DisplayEpollResults(sready));
  1140. // sockets in EX: should be moved to wipeme.
  1141. for (vector<SRTSOCKET>::iterator i = pendingSockets.begin(); i != pendingSockets.end(); ++i)
  1142. {
  1143. if (CEPoll::isready(sready, *i, SRT_EPOLL_ERR))
  1144. {
  1145. HLOGC(gslog.Debug,
  1146. log << "grp/sendBroadcast: Socket @" << (*i) << " reported FAILURE - moved to wiped.");
  1147. // Failed socket. Move d to wipeme. Remove from eid.
  1148. wipeme.push_back(*i);
  1149. int no_events = 0;
  1150. m_Global.m_EPoll.update_usock(m_SndEID, *i, &no_events);
  1151. }
  1152. }
  1153. // After that, all sockets that have been reported
  1154. // as ready to write should be removed from EID. This
  1155. // will also remove those sockets that have been added
  1156. // as redundant links at the connecting stage and became
  1157. // writable (connected) before this function had a chance
  1158. // to check them.
  1159. m_Global.m_EPoll.clear_ready_usocks(*m_SndEpolld, SRT_EPOLL_CONNECT);
  1160. }
  1161. }
  1162. // Re-check after the waiting lock has been reacquired
  1163. if (m_bClosing)
  1164. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  1165. send_CloseBrokenSockets(wipeme);
  1166. // Re-check after the waiting lock has been reacquired
  1167. if (m_bClosing)
  1168. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  1169. // }
  1170. // { sendBroadcast_CheckBlockedLinks()
  1171. // Alright, we've made an attempt to send a packet over every link.
  1172. // Every operation was done through a non-blocking attempt, so
  1173. // links where sending was blocked have SRT_EASYNCSND error.
  1174. // Links that were successful, have the len value in state.
  1175. // First thing then, find out if at least one link was successful.
  1176. // The first successful link sets the sequence value,
  1177. // the following links derive it. This might be also the first idle
  1178. // link with its random-generated ISN, if there were no active links.
  1179. vector<SocketData*> successful, blocked;
  1180. // This iteration of the state will simply
  1181. // qualify the remaining sockets into three categories:
  1182. //
  1183. // - successful (we only need to know if at least one did)
  1184. // - blocked - if none succeeded, but some blocked, POLL & RETRY.
  1185. // - wipeme - sending failed by any other reason than blocking, remove.
  1186. // Now - sendstates contain directly sockets.
  1187. // In order to update members, you need to have locked:
  1188. // - GlobControlLock to prevent sockets from disappearing or being closed
  1189. // - then GroupLock to latch the validity of m_GroupMemberData field.
  1190. {
  1191. {
  1192. InvertedLock ung (m_GroupLock);
  1193. enterCS(CUDT::uglobal().m_GlobControlLock);
  1194. HLOGC(gslog.Debug, log << "grp/sendBroadcast: Locked GlobControlLock, locking back GroupLock");
  1195. }
  1196. // Under this condition, as an unlock-lock cycle was done on m_GroupLock,
  1197. // the Sendstate::it field shall not be used here!
  1198. for (vector<Sendstate>::iterator is = sendstates.begin(); is != sendstates.end(); ++is)
  1199. {
  1200. CUDTSocket* ps = CUDT::uglobal().locateSocket_LOCKED(is->id);
  1201. // Is the socket valid? If not, simply SKIP IT. Nothing to be done with it,
  1202. // it's already deleted.
  1203. if (!ps)
  1204. continue;
  1205. // Is the socket still group member? If not, SKIP IT. It could only be taken ownership
  1206. // by being explicitly closed and so it's deleted from the container.
  1207. if (!ps->m_GroupOf)
  1208. continue;
  1209. // Now we are certain that m_GroupMemberData is valid.
  1210. SocketData* d = ps->m_GroupMemberData;
  1211. if (is->stat == len)
  1212. {
  1213. HLOGC(gslog.Debug,
  1214. log << "SEND STATE link [" << (is - sendstates.begin()) << "]: SUCCESSFULLY sent " << len
  1215. << " bytes");
  1216. // Successful.
  1217. successful.push_back(d);
  1218. rstat = is->stat;
  1219. continue;
  1220. }
  1221. // Remaining are only failed. Check if again.
  1222. if (is->code == SRT_EASYNCSND)
  1223. {
  1224. blocked.push_back(d);
  1225. continue;
  1226. }
  1227. #if ENABLE_HEAVY_LOGGING
  1228. string errmsg = cx.getErrorString();
  1229. LOGC(gslog.Debug,
  1230. log << "SEND STATE link [" << (is - sendstates.begin()) << "]: FAILURE (result:" << is->stat
  1231. << "): " << errmsg << ". Setting this socket broken status.");
  1232. #endif
  1233. // Turn this link broken
  1234. d->sndstate = SRT_GST_BROKEN;
  1235. }
  1236. // Now you can leave GlobControlLock, while GroupLock is still locked.
  1237. leaveCS(CUDT::uglobal().m_GlobControlLock);
  1238. }
  1239. // Re-check after the waiting lock has been reacquired
  1240. if (m_bClosing)
  1241. {
  1242. HLOGC(gslog.Debug, log << "grp/sendBroadcast: GROUP CLOSED, ABANDONING");
  1243. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  1244. }
  1245. // Good, now let's realize the situation.
  1246. // First, check the most optimistic scenario: at least one link succeeded.
  1247. bool was_blocked = false;
  1248. bool none_succeeded = false;
  1249. if (!successful.empty())
  1250. {
  1251. // Good. All blocked links are now qualified as broken.
  1252. // You had your chance, but I can't leave you here,
  1253. // there will be no further chance to reattempt sending.
  1254. for (vector<SocketData*>::iterator b = blocked.begin(); b != blocked.end(); ++b)
  1255. {
  1256. (*b)->sndstate = SRT_GST_BROKEN;
  1257. }
  1258. blocked.clear();
  1259. }
  1260. else
  1261. {
  1262. none_succeeded = true;
  1263. was_blocked = !blocked.empty();
  1264. }
  1265. int ercode = 0;
  1266. if (was_blocked)
  1267. {
  1268. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false);
  1269. if (!m_bSynSending)
  1270. {
  1271. throw CUDTException(MJ_AGAIN, MN_WRAVAIL, 0);
  1272. }
  1273. HLOGC(gslog.Debug, log << "grp/sendBroadcast: all blocked, trying to common-block on epoll...");
  1274. // XXX TO BE REMOVED. Sockets should be subscribed in m_SndEID at connecting time
  1275. // (both srt_connect and srt_accept).
  1276. // None was successful, but some were blocked. It means that we
  1277. // haven't sent the payload over any link so far, so we still have
  1278. // a chance to retry.
  1279. int modes = SRT_EPOLL_OUT | SRT_EPOLL_ERR;
  1280. for (vector<SocketData*>::iterator b = blocked.begin(); b != blocked.end(); ++b)
  1281. {
  1282. HLOGC(gslog.Debug,
  1283. log << "Will block on blocked socket @" << (*b)->id << " as only blocked socket remained");
  1284. CUDT::uglobal().epoll_add_usock_INTERNAL(m_SndEID, (*b)->ps, &modes);
  1285. }
  1286. int blst = 0;
  1287. CEPoll::fmap_t sready;
  1288. {
  1289. // Lift the group lock for a while, to avoid possible deadlocks.
  1290. InvertedLock ug(m_GroupLock);
  1291. HLOGC(gslog.Debug, log << "grp/sendBroadcast: blocking on any of blocked sockets to allow sending");
  1292. // m_iSndTimeOut is -1 by default, which matches the meaning of waiting forever
  1293. THREAD_PAUSED();
  1294. blst = m_Global.m_EPoll.swait(*m_SndEpolld, sready, m_iSndTimeOut);
  1295. THREAD_RESUMED();
  1296. // NOTE EXCEPTIONS:
  1297. // - EEMPTY: won't happen, we have explicitly added sockets to EID here.
  1298. // - XTIMEOUT: will be propagated as this what should be reported to API
  1299. // This is the only reason why here the errors are allowed to be handled
  1300. // by exceptions.
  1301. }
  1302. // Re-check after the waiting lock has been reacquired
  1303. if (m_bClosing)
  1304. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  1305. if (blst == -1)
  1306. {
  1307. int rno;
  1308. ercode = srt_getlasterror(&rno);
  1309. }
  1310. else
  1311. {
  1312. activeLinks.clear();
  1313. sendstates.clear();
  1314. // Extract gli's from the whole group that have id found in the array.
  1315. // LOCKING INFO:
  1316. // For the moment of lifting m_GroupLock, some sockets could have been closed.
  1317. // But then, we believe they have been also removed from the group container,
  1318. // and this requires locking on GroupLock. We can then stafely state that the
  1319. // group container contains only existing sockets, at worst broken.
  1320. for (gli_t dd = m_Group.begin(); dd != m_Group.end(); ++dd)
  1321. {
  1322. int rdev = CEPoll::ready(sready, dd->id);
  1323. if (rdev & SRT_EPOLL_ERR)
  1324. {
  1325. dd->sndstate = SRT_GST_BROKEN;
  1326. }
  1327. else if (rdev & SRT_EPOLL_OUT)
  1328. activeLinks.push_back(dd);
  1329. }
  1330. for (vector<gli_t>::iterator snd = activeLinks.begin(); snd != activeLinks.end(); ++snd)
  1331. {
  1332. gli_t d = *snd;
  1333. int erc = 0; // success
  1334. // Remaining sndstate is SRT_GST_RUNNING. Send a payload through it.
  1335. try
  1336. {
  1337. // This must be wrapped in try-catch because on error it throws an exception.
  1338. // Possible return values are only 0, in case when len was passed 0, or a positive
  1339. // >0 value that defines the size of the data that it has sent, that is, in case
  1340. // of Live mode, equal to 'len'.
  1341. stat = d->ps->core().sendmsg2(buf, len, (w_mc));
  1342. }
  1343. catch (CUDTException& e)
  1344. {
  1345. cx = e;
  1346. stat = -1;
  1347. erc = e.getErrorCode();
  1348. }
  1349. if (stat != -1)
  1350. curseq = w_mc.pktseq;
  1351. const Sendstate cstate = {d->id, &*d, stat, erc};
  1352. sendstates.push_back(cstate);
  1353. d->sndresult = stat;
  1354. d->laststatus = d->ps->getStatus();
  1355. }
  1356. // This time only check if any were successful.
  1357. // All others are wipeme.
  1358. // NOTE: m_GroupLock is continuously locked - you can safely use Sendstate::it field.
  1359. for (vector<Sendstate>::iterator is = sendstates.begin(); is != sendstates.end(); ++is)
  1360. {
  1361. if (is->stat == len)
  1362. {
  1363. // Successful.
  1364. successful.push_back(is->mb);
  1365. rstat = is->stat;
  1366. was_blocked = false;
  1367. none_succeeded = false;
  1368. continue;
  1369. }
  1370. #if ENABLE_HEAVY_LOGGING
  1371. string errmsg = cx.getErrorString();
  1372. HLOGC(gslog.Debug,
  1373. log << "... (repeat-waited) sending FAILED (" << errmsg
  1374. << "). Setting this socket broken status.");
  1375. #endif
  1376. // Turn this link broken
  1377. is->mb->sndstate = SRT_GST_BROKEN;
  1378. }
  1379. }
  1380. }
  1381. // }
  1382. if (none_succeeded)
  1383. {
  1384. HLOGC(gslog.Debug, log << "grp/sendBroadcast: all links broken (none succeeded to send a payload)");
  1385. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false);
  1386. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true);
  1387. // Reparse error code, if set.
  1388. // It might be set, if the last operation was failed.
  1389. // If any operation succeeded, this will not be executed anyway.
  1390. CodeMajor major = CodeMajor(ercode ? ercode / 1000 : MJ_CONNECTION);
  1391. CodeMinor minor = CodeMinor(ercode ? ercode % 1000 : MN_CONNLOST);
  1392. throw CUDTException(major, minor, 0);
  1393. }
  1394. // Now that at least one link has succeeded, update sending stats.
  1395. m_stats.sent.count(len);
  1396. // Pity that the blocking mode only determines as to whether this function should
  1397. // block or not, but the epoll flags must be updated regardless of the mode.
  1398. // Now fill in the socket table. Check if the size is enough, if not,
  1399. // then set the pointer to NULL and set the correct size.
  1400. // Note that list::size() is linear time, however this shouldn't matter,
  1401. // as with the increased number of links in the redundancy group the
  1402. // impossibility of using that many of them grows exponentally.
  1403. size_t grpsize = m_Group.size();
  1404. if (w_mc.grpdata_size < grpsize)
  1405. {
  1406. w_mc.grpdata = NULL;
  1407. }
  1408. size_t i = 0;
  1409. bool ready_again = false;
  1410. for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d, ++i)
  1411. {
  1412. if (w_mc.grpdata)
  1413. {
  1414. // Enough space to fill
  1415. copyGroupData(*d, (w_mc.grpdata[i]));
  1416. }
  1417. // We perform this loop anyway because we still need to check if any
  1418. // socket is writable. Note that the group lock will hold any write ready
  1419. // updates that are performed just after a single socket update for the
  1420. // group, so if any socket is actually ready at the moment when this
  1421. // is performed, and this one will result in none-write-ready, this will
  1422. // be fixed just after returning from this function.
  1423. ready_again = ready_again || d->ps->writeReady();
  1424. }
  1425. w_mc.grpdata_size = i;
  1426. if (!ready_again)
  1427. {
  1428. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false);
  1429. }
  1430. return rstat;
  1431. }
  1432. int CUDTGroup::getGroupData(SRT_SOCKGROUPDATA* pdata, size_t* psize)
  1433. {
  1434. if (!psize)
  1435. return CUDT::APIError(MJ_NOTSUP, MN_INVAL);
  1436. ScopedLock gl(m_GroupLock);
  1437. return getGroupData_LOCKED(pdata, psize);
  1438. }
  1439. // [[using locked(this->m_GroupLock)]]
  1440. int CUDTGroup::getGroupData_LOCKED(SRT_SOCKGROUPDATA* pdata, size_t* psize)
  1441. {
  1442. SRT_ASSERT(psize != NULL);
  1443. const size_t size = *psize;
  1444. // Rewrite correct size
  1445. *psize = m_Group.size();
  1446. if (!pdata)
  1447. {
  1448. return 0;
  1449. }
  1450. if (m_Group.size() > size)
  1451. {
  1452. // Not enough space to retrieve the data.
  1453. return CUDT::APIError(MJ_NOTSUP, MN_XSIZE);
  1454. }
  1455. size_t i = 0;
  1456. for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d, ++i)
  1457. {
  1458. copyGroupData(*d, (pdata[i]));
  1459. }
  1460. return (int)m_Group.size();
  1461. }
  1462. // [[using locked(this->m_GroupLock)]]
  1463. void CUDTGroup::copyGroupData(const CUDTGroup::SocketData& source, SRT_SOCKGROUPDATA& w_target)
  1464. {
  1465. w_target.id = source.id;
  1466. memcpy((&w_target.peeraddr), &source.peer, source.peer.size());
  1467. w_target.sockstate = source.laststatus;
  1468. w_target.token = source.token;
  1469. // In the internal structure the member state
  1470. // is one per direction. From the user perspective
  1471. // however it is used either in one direction only,
  1472. // in which case the one direction that is active
  1473. // matters, or in both directions, in which case
  1474. // it will be always either both active or both idle.
  1475. if (source.sndstate == SRT_GST_RUNNING || source.rcvstate == SRT_GST_RUNNING)
  1476. {
  1477. w_target.result = 0;
  1478. w_target.memberstate = SRT_GST_RUNNING;
  1479. }
  1480. // Stats can differ per direction only
  1481. // when at least in one direction it's ACTIVE.
  1482. else if (source.sndstate == SRT_GST_BROKEN || source.rcvstate == SRT_GST_BROKEN)
  1483. {
  1484. w_target.result = -1;
  1485. w_target.memberstate = SRT_GST_BROKEN;
  1486. }
  1487. else
  1488. {
  1489. // IDLE or PENDING
  1490. w_target.result = 0;
  1491. w_target.memberstate = source.sndstate;
  1492. }
  1493. w_target.weight = source.weight;
  1494. }
  1495. void CUDTGroup::getGroupCount(size_t& w_size, bool& w_still_alive)
  1496. {
  1497. ScopedLock gg(m_GroupLock);
  1498. // Note: linear time, but no way to avoid it.
  1499. // Fortunately the size of the redundancy group is even
  1500. // in the craziest possible implementation at worst 4 members long.
  1501. size_t group_list_size = 0;
  1502. // In managed group, if all sockets made a failure, all
  1503. // were removed, so the loop won't even run once. In
  1504. // non-managed, simply no socket found here would have a
  1505. // connected status.
  1506. bool still_alive = false;
  1507. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi)
  1508. {
  1509. if (gi->laststatus == SRTS_CONNECTED)
  1510. {
  1511. still_alive = true;
  1512. }
  1513. ++group_list_size;
  1514. }
  1515. // If no socket is found connected, don't update any status.
  1516. w_size = group_list_size;
  1517. w_still_alive = still_alive;
  1518. }
  1519. // [[using locked(m_GroupLock)]]
  1520. void CUDTGroup::fillGroupData(SRT_MSGCTRL& w_out, // MSGCTRL to be written
  1521. const SRT_MSGCTRL& in // MSGCTRL read from the data-providing socket
  1522. )
  1523. {
  1524. // Preserve the data that will be overwritten by assignment
  1525. SRT_SOCKGROUPDATA* grpdata = w_out.grpdata;
  1526. size_t grpdata_size = w_out.grpdata_size;
  1527. w_out = in; // NOTE: This will write NULL to grpdata and 0 to grpdata_size!
  1528. w_out.grpdata = NULL; // Make sure it's done, for any case
  1529. w_out.grpdata_size = 0;
  1530. // User did not wish to read the group data at all.
  1531. if (!grpdata)
  1532. {
  1533. return;
  1534. }
  1535. int st = getGroupData_LOCKED((grpdata), (&grpdata_size));
  1536. // Always write back the size, no matter if the data were filled.
  1537. w_out.grpdata_size = grpdata_size;
  1538. if (st == SRT_ERROR)
  1539. {
  1540. // Keep NULL in grpdata
  1541. return;
  1542. }
  1543. // Write back original data
  1544. w_out.grpdata = grpdata;
  1545. }
  1546. // [[using locked(CUDT::uglobal()->m_GlobControLock)]]
  1547. // [[using locked(m_GroupLock)]]
  1548. struct FLookupSocketWithEvent_LOCKED
  1549. {
  1550. CUDTUnited* glob;
  1551. int evtype;
  1552. FLookupSocketWithEvent_LOCKED(CUDTUnited* g, int event_type)
  1553. : glob(g)
  1554. , evtype(event_type)
  1555. {
  1556. }
  1557. typedef CUDTSocket* result_type;
  1558. pair<CUDTSocket*, bool> operator()(const pair<SRTSOCKET, int>& es)
  1559. {
  1560. CUDTSocket* so = NULL;
  1561. if ((es.second & evtype) == 0)
  1562. return make_pair(so, false);
  1563. so = glob->locateSocket_LOCKED(es.first);
  1564. return make_pair(so, !!so);
  1565. }
  1566. };
  1567. void CUDTGroup::recv_CollectAliveAndBroken(vector<CUDTSocket*>& alive, set<CUDTSocket*>& broken)
  1568. {
  1569. #if ENABLE_HEAVY_LOGGING
  1570. std::ostringstream ds;
  1571. ds << "E(" << m_RcvEID << ") ";
  1572. #define HCLOG(expr) expr
  1573. #else
  1574. #define HCLOG(x) if (false) {}
  1575. #endif
  1576. alive.reserve(m_Group.size());
  1577. HLOGC(grlog.Debug, log << "group/recv: Reviewing member sockets for polling");
  1578. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi)
  1579. {
  1580. if (gi->laststatus == SRTS_CONNECTING)
  1581. {
  1582. HCLOG(ds << "@" << gi->id << "<pending> ");
  1583. continue; // don't read over a failed or pending socket
  1584. }
  1585. if (gi->laststatus >= SRTS_BROKEN)
  1586. {
  1587. broken.insert(gi->ps);
  1588. }
  1589. if (broken.count(gi->ps))
  1590. {
  1591. HCLOG(ds << "@" << gi->id << "<broken> ");
  1592. continue;
  1593. }
  1594. if (gi->laststatus != SRTS_CONNECTED)
  1595. {
  1596. HCLOG(ds << "@" << gi->id << "<unstable:" << SockStatusStr(gi->laststatus) << "> ");
  1597. // Sockets in this state are ignored. We are waiting until it
  1598. // achieves CONNECTING state, then it's added to write.
  1599. // Or gets broken and closed in the next step.
  1600. continue;
  1601. }
  1602. // Don't skip packets that are ahead because if we have a situation
  1603. // that all links are either "elephants" (do not report read readiness)
  1604. // and "kangaroos" (have already delivered an ahead packet) then
  1605. // omitting kangaroos will result in only elephants to be polled for
  1606. // reading. Due to the strict timing requirements and ensurance that
  1607. // TSBPD on every link will result in exactly the same delivery time
  1608. // for a packet of given sequence, having an elephant and kangaroo in
  1609. // one cage means that the elephant is simply a broken or half-broken
  1610. // link (the data are not delivered, but it will get repaired soon,
  1611. // enough for SRT to maintain the connection, but it will still drop
  1612. // packets that didn't arrive in time), in both cases it may
  1613. // potentially block the reading for an indefinite time, while
  1614. // simultaneously a kangaroo might be a link that got some packets
  1615. // dropped, but then it's still capable to deliver packets on time.
  1616. // Note that gi->id might be a socket that was previously being polled
  1617. // on write, when it's attempting to connect, but now it's connected.
  1618. // This will update the socket with the new event set.
  1619. alive.push_back(gi->ps);
  1620. HCLOG(ds << "@" << gi->id << "[READ] ");
  1621. }
  1622. HLOGC(grlog.Debug, log << "group/recv: " << ds.str() << " --> EPOLL/SWAIT");
  1623. #undef HCLOG
  1624. }
  1625. vector<CUDTSocket*> CUDTGroup::recv_WaitForReadReady(const vector<CUDTSocket*>& aliveMembers, set<CUDTSocket*>& w_broken)
  1626. {
  1627. if (aliveMembers.empty())
  1628. {
  1629. LOGC(grlog.Error, log << "group/recv: all links broken");
  1630. throw CUDTException(MJ_CONNECTION, MN_NOCONN, 0);
  1631. }
  1632. for (vector<CUDTSocket*>::const_iterator i = aliveMembers.begin(); i != aliveMembers.end(); ++i)
  1633. {
  1634. // NOT using the official srt_epoll_add_usock because this will do socket dispatching,
  1635. // which requires lock on m_GlobControlLock, while this lock cannot be applied without
  1636. // first unlocking m_GroupLock.
  1637. const int read_modes = SRT_EPOLL_IN | SRT_EPOLL_ERR;
  1638. CUDT::uglobal().epoll_add_usock_INTERNAL(m_RcvEID, *i, &read_modes);
  1639. }
  1640. // Here we need to make an additional check.
  1641. // There might be a possibility that all sockets that
  1642. // were added to the reader group, are ahead. At least
  1643. // surely we don't have a situation that any link contains
  1644. // an ahead-read subsequent packet, because GroupCheckPacketAhead
  1645. // already handled that case.
  1646. //
  1647. // What we can have is that every link has:
  1648. // - no known seq position yet (is not registered in the position map yet)
  1649. // - the position equal to the latest delivered sequence
  1650. // - the ahead position
  1651. // Now the situation is that we don't have any packets
  1652. // waiting for delivery so we need to wait for any to report one.
  1653. // The non-blocking mode would need to simply check the readiness
  1654. // with only immediate report, and read-readiness would have to
  1655. // be done in background.
  1656. // In blocking mode, use m_iRcvTimeOut, which's default value -1
  1657. // means to block indefinitely, also in swait().
  1658. // In non-blocking mode use 0, which means to always return immediately.
  1659. int timeout = m_bSynRecving ? m_iRcvTimeOut : 0;
  1660. int nready = 0;
  1661. // Poll on this descriptor until reading is available, indefinitely.
  1662. CEPoll::fmap_t sready;
  1663. // GlobControlLock is required for dispatching the sockets.
  1664. // Therefore it must be applied only when GroupLock is off.
  1665. {
  1666. // This call may wait indefinite time, so GroupLock must be unlocked.
  1667. InvertedLock ung (m_GroupLock);
  1668. THREAD_PAUSED();
  1669. nready = m_Global.m_EPoll.swait(*m_RcvEpolld, sready, timeout, false /*report by retval*/);
  1670. THREAD_RESUMED();
  1671. // HERE GlobControlLock is locked first, then GroupLock is applied back
  1672. enterCS(CUDT::uglobal().m_GlobControlLock);
  1673. }
  1674. // BOTH m_GlobControlLock AND m_GroupLock are locked here.
  1675. HLOGC(grlog.Debug, log << "group/recv: " << nready << " RDY: " << DisplayEpollResults(sready));
  1676. if (nready == 0)
  1677. {
  1678. // GlobControlLock is applied manually, so unlock manually.
  1679. // GroupLock will be unlocked as per scope.
  1680. leaveCS(CUDT::uglobal().m_GlobControlLock);
  1681. // This can only happen when 0 is passed as timeout and none is ready.
  1682. // And 0 is passed only in non-blocking mode. So this is none ready in
  1683. // non-blocking mode.
  1684. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, false);
  1685. throw CUDTException(MJ_AGAIN, MN_RDAVAIL, 0);
  1686. }
  1687. // Handle sockets of pending connection and with errors.
  1688. // Nice to have something like:
  1689. // broken = FilterIf(sready, [] (auto s)
  1690. // { return s.second == SRT_EPOLL_ERR && (auto cs = g->locateSocket(s.first, ERH_RETURN))
  1691. // ? {cs, true}
  1692. // : {nullptr, false}
  1693. // });
  1694. FilterIf(
  1695. /*FROM*/ sready.begin(),
  1696. sready.end(),
  1697. /*TO*/ std::inserter(w_broken, w_broken.begin()),
  1698. /*VIA*/ FLookupSocketWithEvent_LOCKED(&m_Global, SRT_EPOLL_ERR));
  1699. // If this set is empty, it won't roll even once, therefore output
  1700. // will be surely empty. This will be checked then same way as when
  1701. // reading from every socket resulted in error.
  1702. vector<CUDTSocket*> readReady;
  1703. readReady.reserve(aliveMembers.size());
  1704. for (vector<CUDTSocket*>::const_iterator sockiter = aliveMembers.begin(); sockiter != aliveMembers.end(); ++sockiter)
  1705. {
  1706. CUDTSocket* sock = *sockiter;
  1707. const CEPoll::fmap_t::const_iterator ready_iter = sready.find(sock->m_SocketID);
  1708. if (ready_iter != sready.end())
  1709. {
  1710. if (ready_iter->second & SRT_EPOLL_ERR)
  1711. continue; // broken already
  1712. if ((ready_iter->second & SRT_EPOLL_IN) == 0)
  1713. continue; // not ready for reading
  1714. readReady.push_back(*sockiter);
  1715. }
  1716. else
  1717. {
  1718. // No read-readiness reported by epoll, but probably missed or not yet handled
  1719. // as the receiver buffer is read-ready.
  1720. ScopedLock lg(sock->core().m_RcvBufferLock);
  1721. if (sock->core().m_pRcvBuffer && sock->core().m_pRcvBuffer->isRcvDataReady())
  1722. readReady.push_back(sock);
  1723. }
  1724. }
  1725. leaveCS(CUDT::uglobal().m_GlobControlLock);
  1726. return readReady;
  1727. }
  1728. void CUDTGroup::updateReadState(SRTSOCKET /* not sure if needed */, int32_t sequence)
  1729. {
  1730. bool ready = false;
  1731. ScopedLock lg(m_GroupLock);
  1732. int seqdiff = 0;
  1733. if (m_RcvBaseSeqNo == SRT_SEQNO_NONE)
  1734. {
  1735. // One socket reported readiness, while no reading operation
  1736. // has ever been done. Whatever the sequence number is, it will
  1737. // be taken as a good deal and reading will be accepted.
  1738. ready = true;
  1739. }
  1740. else if ((seqdiff = CSeqNo::seqcmp(sequence, m_RcvBaseSeqNo)) > 0)
  1741. {
  1742. // Case diff == 1: The very next. Surely read-ready.
  1743. // Case diff > 1:
  1744. // We have an ahead packet. There's one strict condition in which
  1745. // we may believe it needs to be delivered - when KANGAROO->HORSE
  1746. // transition is allowed. Stating that the time calculation is done
  1747. // exactly the same way on every link in the redundancy group, when
  1748. // it came to a situation that a packet from one link is ready for
  1749. // extraction while it has jumped over some packet, it has surely
  1750. // happened due to TLPKTDROP, and if it happened on at least one link,
  1751. // we surely don't have this packet ready on any other link.
  1752. // This might prove not exactly true, especially when at the moment
  1753. // when this happens another link may surprisinly receive this lacking
  1754. // packet, so the situation gets suddenly repaired after this function
  1755. // is called, the only result of it would be that it will really get
  1756. // the very next sequence, even though this function doesn't know it
  1757. // yet, but surely in both cases the situation is the same: the medium
  1758. // is ready for reading, no matter what packet will turn out to be
  1759. // returned when reading is done.
  1760. ready = true;
  1761. }
  1762. // When the sequence number is behind the current one,
  1763. // stating that the readines wasn't checked otherwise, the reading
  1764. // function will not retrieve anything ready to read just by this premise.
  1765. // Even though this packet would have to be eventually extracted (and discarded).
  1766. if (ready)
  1767. {
  1768. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, true);
  1769. }
  1770. }
  1771. int32_t CUDTGroup::getRcvBaseSeqNo()
  1772. {
  1773. ScopedLock lg(m_GroupLock);
  1774. return m_RcvBaseSeqNo;
  1775. }
  1776. void CUDTGroup::updateWriteState()
  1777. {
  1778. ScopedLock lg(m_GroupLock);
  1779. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, true);
  1780. }
  1781. /// Validate iPktSeqno is in range
  1782. /// (iBaseSeqno - m_iSeqNoTH/2; iBaseSeqno + m_iSeqNoTH).
  1783. ///
  1784. /// EXPECT_EQ(isValidSeqno(125, 124), true); // behind
  1785. /// EXPECT_EQ(isValidSeqno(125, 125), true); // behind
  1786. /// EXPECT_EQ(isValidSeqno(125, 126), true); // the next in order
  1787. ///
  1788. /// EXPECT_EQ(isValidSeqno(0, 0x3FFFFFFF - 2), true); // ahead, but ok.
  1789. /// EXPECT_EQ(isValidSeqno(0, 0x3FFFFFFF - 1), false); // too far ahead.
  1790. /// EXPECT_EQ(isValidSeqno(0x3FFFFFFF + 2, 0x7FFFFFFF), false); // too far ahead.
  1791. /// EXPECT_EQ(isValidSeqno(0x3FFFFFFF + 3, 0x7FFFFFFF), true); // ahead, but ok.
  1792. /// EXPECT_EQ(isValidSeqno(0x3FFFFFFF, 0x1FFFFFFF + 2), false); // too far (behind)
  1793. /// EXPECT_EQ(isValidSeqno(0x3FFFFFFF, 0x1FFFFFFF + 3), true); // behind, but ok
  1794. /// EXPECT_EQ(isValidSeqno(0x70000000, 0x0FFFFFFF), true); // ahead, but ok
  1795. /// EXPECT_EQ(isValidSeqno(0x70000000, 0x30000000 - 2), false); // too far ahead.
  1796. /// EXPECT_EQ(isValidSeqno(0x70000000, 0x30000000 - 3), true); // ahead, but ok
  1797. /// EXPECT_EQ(isValidSeqno(0x0FFFFFFF, 0), true);
  1798. /// EXPECT_EQ(isValidSeqno(0x0FFFFFFF, 0x7FFFFFFF), true);
  1799. /// EXPECT_EQ(isValidSeqno(0x0FFFFFFF, 0x70000000), false);
  1800. /// EXPECT_EQ(isValidSeqno(0x0FFFFFFF, 0x70000001), false);
  1801. /// EXPECT_EQ(isValidSeqno(0x0FFFFFFF, 0x70000002), true); // behind by 536870910
  1802. /// EXPECT_EQ(isValidSeqno(0x0FFFFFFF, 0x70000003), true);
  1803. ///
  1804. /// @return false if @a iPktSeqno is not inside the valid range; otherwise true.
  1805. static bool isValidSeqno(int32_t iBaseSeqno, int32_t iPktSeqno)
  1806. {
  1807. const int32_t iLenAhead = CSeqNo::seqlen(iBaseSeqno, iPktSeqno);
  1808. if (iLenAhead >= 0 && iLenAhead < CSeqNo::m_iSeqNoTH)
  1809. return true;
  1810. const int32_t iLenBehind = CSeqNo::seqlen(iPktSeqno, iBaseSeqno);
  1811. if (iLenBehind >= 0 && iLenBehind < CSeqNo::m_iSeqNoTH / 2)
  1812. return true;
  1813. return false;
  1814. }
  1815. int CUDTGroup::recv(char* buf, int len, SRT_MSGCTRL& w_mc)
  1816. {
  1817. // First, acquire GlobControlLock to make sure all member sockets still exist
  1818. enterCS(m_Global.m_GlobControlLock);
  1819. ScopedLock guard(m_GroupLock);
  1820. if (m_bClosing)
  1821. {
  1822. // The group could be set closing in the meantime, but if
  1823. // this is only about to be set by another thread, this thread
  1824. // must fist wait for being able to acquire this lock.
  1825. // The group will not be deleted now because it is added usage counter
  1826. // by this call, but will be released once it exits.
  1827. leaveCS(m_Global.m_GlobControlLock);
  1828. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  1829. }
  1830. // Now, still under lock, check if all sockets still can be dispatched
  1831. send_CheckValidSockets();
  1832. leaveCS(m_Global.m_GlobControlLock);
  1833. if (m_bClosing)
  1834. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  1835. // Later iteration over it might be less efficient than
  1836. // by vector, but we'll also often try to check a single id
  1837. // if it was ever seen broken, so that it's skipped.
  1838. set<CUDTSocket*> broken;
  1839. for (;;)
  1840. {
  1841. if (!m_bOpened || !m_bConnected)
  1842. {
  1843. LOGC(grlog.Error,
  1844. log << boolalpha << "grp/recv: $" << id() << ": ABANDONING: opened=" << m_bOpened
  1845. << " connected=" << m_bConnected);
  1846. throw CUDTException(MJ_CONNECTION, MN_NOCONN, 0);
  1847. }
  1848. vector<CUDTSocket*> aliveMembers;
  1849. recv_CollectAliveAndBroken(aliveMembers, broken);
  1850. if (aliveMembers.empty())
  1851. {
  1852. LOGC(grlog.Error, log << "grp/recv: ALL LINKS BROKEN, ABANDONING.");
  1853. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, false);
  1854. throw CUDTException(MJ_CONNECTION, MN_NOCONN, 0);
  1855. }
  1856. vector<CUDTSocket*> readySockets;
  1857. if (m_bSynRecving)
  1858. readySockets = recv_WaitForReadReady(aliveMembers, broken);
  1859. else
  1860. readySockets = aliveMembers;
  1861. if (m_bClosing)
  1862. {
  1863. HLOGC(grlog.Debug, log << "grp/recv: $" << id() << ": GROUP CLOSED, ABANDONING.");
  1864. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  1865. }
  1866. // Find the first readable packet among all member sockets.
  1867. CUDTSocket* socketToRead = NULL;
  1868. CRcvBuffer::PacketInfo infoToRead = {-1, false, time_point()};
  1869. for (vector<CUDTSocket*>::const_iterator si = readySockets.begin(); si != readySockets.end(); ++si)
  1870. {
  1871. CUDTSocket* ps = *si;
  1872. ScopedLock lg(ps->core().m_RcvBufferLock);
  1873. if (m_RcvBaseSeqNo != SRT_SEQNO_NONE)
  1874. {
  1875. // Drop here to make sure the getFirstReadablePacketInfo() below return fresher packet.
  1876. int cnt = ps->core().rcvDropTooLateUpTo(CSeqNo::incseq(m_RcvBaseSeqNo));
  1877. if (cnt > 0)
  1878. {
  1879. HLOGC(grlog.Debug,
  1880. log << "grp/recv: $" << id() << ": @" << ps->m_SocketID << ": dropped " << cnt
  1881. << " packets before reading: m_RcvBaseSeqNo=" << m_RcvBaseSeqNo);
  1882. }
  1883. }
  1884. const CRcvBuffer::PacketInfo info =
  1885. ps->core().m_pRcvBuffer->getFirstReadablePacketInfo(steady_clock::now());
  1886. if (info.seqno == SRT_SEQNO_NONE)
  1887. {
  1888. HLOGC(grlog.Debug, log << "grp/recv: $" << id() << ": @" << ps->m_SocketID << ": Nothing to read.");
  1889. continue;
  1890. }
  1891. // We need to qualify the sequence, just for a case.
  1892. if (m_RcvBaseSeqNo != SRT_SEQNO_NONE && !isValidSeqno(m_RcvBaseSeqNo, info.seqno))
  1893. {
  1894. LOGC(grlog.Error,
  1895. log << "grp/recv: $" << id() << ": @" << ps->m_SocketID << ": SEQUENCE DISCREPANCY: base=%"
  1896. << m_RcvBaseSeqNo << " vs pkt=%" << info.seqno << ", setting ESECFAIL");
  1897. ps->core().m_bBroken = true;
  1898. broken.insert(ps);
  1899. continue;
  1900. }
  1901. if (socketToRead == NULL || CSeqNo::seqcmp(info.seqno, infoToRead.seqno) < 0)
  1902. {
  1903. socketToRead = ps;
  1904. infoToRead = info;
  1905. }
  1906. }
  1907. if (socketToRead == NULL)
  1908. {
  1909. if (m_bSynRecving)
  1910. {
  1911. HLOGC(grlog.Debug,
  1912. log << "grp/recv: $" << id() << ": No links reported any fresher packet, re-polling.");
  1913. continue;
  1914. }
  1915. else
  1916. {
  1917. HLOGC(grlog.Debug,
  1918. log << "grp/recv: $" << id() << ": No links reported any fresher packet, clearing readiness.");
  1919. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, false);
  1920. throw CUDTException(MJ_AGAIN, MN_RDAVAIL, 0);
  1921. }
  1922. }
  1923. else
  1924. {
  1925. HLOGC(grlog.Debug,
  1926. log << "grp/recv: $" << id() << ": Found first readable packet from @" << socketToRead->m_SocketID
  1927. << ": seq=" << infoToRead.seqno << " gap=" << infoToRead.seq_gap
  1928. << " time=" << FormatTime(infoToRead.tsbpd_time));
  1929. }
  1930. const int res = socketToRead->core().receiveMessage((buf), len, (w_mc), CUDTUnited::ERH_RETURN);
  1931. HLOGC(grlog.Debug,
  1932. log << "grp/recv: $" << id() << ": @" << socketToRead->m_SocketID << ": Extracted data with %"
  1933. << w_mc.pktseq << " #" << w_mc.msgno << ": " << (res <= 0 ? "(NOTHING)" : BufferStamp(buf, res)));
  1934. if (res == 0)
  1935. {
  1936. LOGC(grlog.Warn,
  1937. log << "grp/recv: $" << id() << ": @" << socketToRead->m_SocketID << ": Retrying next socket...");
  1938. // This socket will not be socketToRead in the next turn because receiveMessage() return 0 here.
  1939. continue;
  1940. }
  1941. if (res == SRT_ERROR)
  1942. {
  1943. LOGC(grlog.Warn,
  1944. log << "grp/recv: $" << id() << ": @" << socketToRead->m_SocketID << ": " << srt_getlasterror_str()
  1945. << ". Retrying next socket...");
  1946. broken.insert(socketToRead);
  1947. continue;
  1948. }
  1949. fillGroupData((w_mc), w_mc);
  1950. HLOGC(grlog.Debug,
  1951. log << "grp/recv: $" << id() << ": Update m_RcvBaseSeqNo: %" << m_RcvBaseSeqNo << " -> %" << w_mc.pktseq);
  1952. m_RcvBaseSeqNo = w_mc.pktseq;
  1953. // Update stats as per delivery
  1954. m_stats.recv.count(res);
  1955. updateAvgPayloadSize(res);
  1956. bool canReadFurther = false;
  1957. for (vector<CUDTSocket*>::const_iterator si = aliveMembers.begin(); si != aliveMembers.end(); ++si)
  1958. {
  1959. CUDTSocket* ps = *si;
  1960. ScopedLock lg(ps->core().m_RcvBufferLock);
  1961. if (m_RcvBaseSeqNo != SRT_SEQNO_NONE)
  1962. {
  1963. const int cnt = ps->core().rcvDropTooLateUpTo(CSeqNo::incseq(m_RcvBaseSeqNo));
  1964. if (cnt > 0)
  1965. {
  1966. HLOGC(grlog.Debug,
  1967. log << "grp/recv: $" << id() << ": @" << ps->m_SocketID << ": dropped " << cnt
  1968. << " packets after reading: m_RcvBaseSeqNo=" << m_RcvBaseSeqNo);
  1969. }
  1970. }
  1971. if (!ps->core().isRcvBufferReadyNoLock())
  1972. m_Global.m_EPoll.update_events(ps->m_SocketID, ps->core().m_sPollID, SRT_EPOLL_IN, false);
  1973. else
  1974. canReadFurther = true;
  1975. }
  1976. if (!canReadFurther)
  1977. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, false);
  1978. return res;
  1979. }
  1980. LOGC(grlog.Error, log << "grp/recv: UNEXPECTED RUN PATH, ABANDONING.");
  1981. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, false);
  1982. throw CUDTException(MJ_AGAIN, MN_RDAVAIL, 0);
  1983. }
  1984. const char* CUDTGroup::StateStr(CUDTGroup::GroupState st)
  1985. {
  1986. static const char* const states[] = {"PENDING", "IDLE", "RUNNING", "BROKEN"};
  1987. static const size_t size = Size(states);
  1988. static const char* const unknown = "UNKNOWN";
  1989. if (size_t(st) < size)
  1990. return states[st];
  1991. return unknown;
  1992. }
  1993. void CUDTGroup::synchronizeDrift(const srt::CUDT* srcMember)
  1994. {
  1995. SRT_ASSERT(srcMember != NULL);
  1996. ScopedLock glock(m_GroupLock);
  1997. if (m_Group.size() <= 1)
  1998. {
  1999. HLOGC(grlog.Debug, log << "GROUP: synch uDRIFT NOT DONE, no other links");
  2000. return;
  2001. }
  2002. steady_clock::time_point timebase;
  2003. steady_clock::duration udrift(0);
  2004. bool wrap_period = false;
  2005. srcMember->m_pRcvBuffer->getInternalTimeBase((timebase), (wrap_period), (udrift));
  2006. HLOGC(grlog.Debug,
  2007. log << "GROUP: synch uDRIFT=" << FormatDuration(udrift) << " TB=" << FormatTime(timebase) << "("
  2008. << (wrap_period ? "" : "NO ") << "wrap period)");
  2009. // Now that we have the minimum timebase and drift calculated, apply this to every link,
  2010. // INCLUDING THE REPORTER.
  2011. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi)
  2012. {
  2013. // Skip non-connected; these will be synchronized when ready
  2014. if (gi->laststatus != SRTS_CONNECTED)
  2015. continue;
  2016. CUDT& member = gi->ps->core();
  2017. if (srcMember == &member)
  2018. continue;
  2019. member.m_pRcvBuffer->applyGroupDrift(timebase, wrap_period, udrift);
  2020. }
  2021. }
  2022. void CUDTGroup::bstatsSocket(CBytePerfMon* perf, bool clear)
  2023. {
  2024. if (!m_bConnected)
  2025. throw CUDTException(MJ_CONNECTION, MN_NOCONN, 0);
  2026. if (m_bClosing)
  2027. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  2028. const steady_clock::time_point currtime = steady_clock::now();
  2029. memset(perf, 0, sizeof *perf);
  2030. ScopedLock gg(m_GroupLock);
  2031. perf->msTimeStamp = count_milliseconds(currtime - m_tsStartTime);
  2032. perf->pktSentUnique = m_stats.sent.trace.count();
  2033. perf->pktRecvUnique = m_stats.recv.trace.count();
  2034. perf->pktRcvDrop = m_stats.recvDrop.trace.count();
  2035. perf->byteSentUnique = m_stats.sent.trace.bytesWithHdr();
  2036. perf->byteRecvUnique = m_stats.recv.trace.bytesWithHdr();
  2037. perf->byteRcvDrop = m_stats.recvDrop.trace.bytesWithHdr();
  2038. perf->pktSentUniqueTotal = m_stats.sent.total.count();
  2039. perf->pktRecvUniqueTotal = m_stats.recv.total.count();
  2040. perf->pktRcvDropTotal = m_stats.recvDrop.total.count();
  2041. perf->byteSentUniqueTotal = m_stats.sent.total.bytesWithHdr();
  2042. perf->byteRecvUniqueTotal = m_stats.recv.total.bytesWithHdr();
  2043. perf->byteRcvDropTotal = m_stats.recvDrop.total.bytesWithHdr();
  2044. const double interval = static_cast<double>(count_microseconds(currtime - m_stats.tsLastSampleTime));
  2045. perf->mbpsSendRate = double(perf->byteSent) * 8.0 / interval;
  2046. perf->mbpsRecvRate = double(perf->byteRecv) * 8.0 / interval;
  2047. if (clear)
  2048. {
  2049. m_stats.reset();
  2050. }
  2051. }
  2052. /// @brief Compares group members by their weight (higher weight comes first).
  2053. struct FCompareByWeight
  2054. {
  2055. typedef CUDTGroup::gli_t gli_t;
  2056. /// @returns true if the first argument is less than (i.e. is ordered before) the second.
  2057. bool operator()(const gli_t preceding, const gli_t succeeding)
  2058. {
  2059. return preceding->weight > succeeding->weight;
  2060. }
  2061. };
  2062. // [[using maybe_locked(this->m_GroupLock)]]
  2063. BackupMemberState CUDTGroup::sendBackup_QualifyIfStandBy(const gli_t d)
  2064. {
  2065. if (!d->ps)
  2066. return BKUPST_BROKEN;
  2067. const SRT_SOCKSTATUS st = d->ps->getStatus();
  2068. // If the socket is already broken, move it to broken.
  2069. if (int(st) >= int(SRTS_BROKEN))
  2070. {
  2071. HLOGC(gslog.Debug,
  2072. log << "CUDTGroup::send.$" << id() << ": @" << d->id << " became " << SockStatusStr(st)
  2073. << ", WILL BE CLOSED.");
  2074. return BKUPST_BROKEN;
  2075. }
  2076. if (st != SRTS_CONNECTED)
  2077. {
  2078. HLOGC(gslog.Debug, log << "CUDTGroup::send. @" << d->id << " is still " << SockStatusStr(st) << ", skipping.");
  2079. return BKUPST_PENDING;
  2080. }
  2081. return BKUPST_STANDBY;
  2082. }
  2083. // [[using maybe_locked(this->m_GroupLock)]]
  2084. bool CUDTGroup::send_CheckIdle(const gli_t d, vector<SRTSOCKET>& w_wipeme, vector<SRTSOCKET>& w_pendingSockets)
  2085. {
  2086. SRT_SOCKSTATUS st = SRTS_NONEXIST;
  2087. if (d->ps)
  2088. st = d->ps->getStatus();
  2089. // If the socket is already broken, move it to broken.
  2090. if (int(st) >= int(SRTS_BROKEN))
  2091. {
  2092. HLOGC(gslog.Debug,
  2093. log << "CUDTGroup::send.$" << id() << ": @" << d->id << " became " << SockStatusStr(st)
  2094. << ", WILL BE CLOSED.");
  2095. w_wipeme.push_back(d->id);
  2096. return false;
  2097. }
  2098. if (st != SRTS_CONNECTED)
  2099. {
  2100. HLOGC(gslog.Debug, log << "CUDTGroup::send. @" << d->id << " is still " << SockStatusStr(st) << ", skipping.");
  2101. w_pendingSockets.push_back(d->id);
  2102. return false;
  2103. }
  2104. return true;
  2105. }
  2106. #if SRT_DEBUG_BONDING_STATES
  2107. class StabilityTracer
  2108. {
  2109. public:
  2110. StabilityTracer()
  2111. {
  2112. }
  2113. ~StabilityTracer()
  2114. {
  2115. srt::sync::ScopedLock lck(m_mtx);
  2116. m_fout.close();
  2117. }
  2118. void trace(const CUDT& u, const srt::sync::steady_clock::time_point& currtime, uint32_t activation_period_us,
  2119. int64_t stability_tmo_us, const std::string& state, uint16_t weight)
  2120. {
  2121. srt::sync::ScopedLock lck(m_mtx);
  2122. create_file();
  2123. m_fout << srt::sync::FormatTime(currtime) << ",";
  2124. m_fout << u.id() << ",";
  2125. m_fout << weight << ",";
  2126. m_fout << u.peerLatency_us() << ",";
  2127. m_fout << u.SRTT() << ",";
  2128. m_fout << u.RTTVar() << ",";
  2129. m_fout << stability_tmo_us << ",";
  2130. m_fout << count_microseconds(currtime - u.lastRspTime()) << ",";
  2131. m_fout << state << ",";
  2132. m_fout << (srt::sync::is_zero(u.freshActivationStart()) ? -1 : (count_microseconds(currtime - u.freshActivationStart()))) << ",";
  2133. m_fout << activation_period_us << "\n";
  2134. m_fout.flush();
  2135. }
  2136. private:
  2137. void print_header()
  2138. {
  2139. //srt::sync::ScopedLock lck(m_mtx);
  2140. m_fout << "Timepoint,SocketID,weight,usLatency,usRTT,usRTTVar,usStabilityTimeout,usSinceLastResp,State,usSinceActivation,usActivationPeriod\n";
  2141. }
  2142. void create_file()
  2143. {
  2144. if (m_fout.is_open())
  2145. return;
  2146. std::string str_tnow = srt::sync::FormatTimeSys(srt::sync::steady_clock::now());
  2147. str_tnow.resize(str_tnow.size() - 7); // remove trailing ' [SYST]' part
  2148. while (str_tnow.find(':') != std::string::npos) {
  2149. str_tnow.replace(str_tnow.find(':'), 1, 1, '_');
  2150. }
  2151. const std::string fname = "stability_trace_" + str_tnow + ".csv";
  2152. m_fout.open(fname, std::ofstream::out);
  2153. if (!m_fout)
  2154. std::cerr << "IPE: Failed to open " << fname << "!!!\n";
  2155. print_header();
  2156. }
  2157. private:
  2158. srt::sync::Mutex m_mtx;
  2159. std::ofstream m_fout;
  2160. };
  2161. StabilityTracer s_stab_trace;
  2162. #endif
  2163. void CUDTGroup::sendBackup_QualifyMemberStates(SendBackupCtx& w_sendBackupCtx, const steady_clock::time_point& currtime)
  2164. {
  2165. // First, check status of every link - no matter if idle or active.
  2166. for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d)
  2167. {
  2168. if (d->sndstate != SRT_GST_BROKEN)
  2169. {
  2170. // Check the socket state prematurely in order not to uselessly
  2171. // send over a socket that is broken.
  2172. CUDT* const pu = (d->ps)
  2173. ? &d->ps->core()
  2174. : NULL;
  2175. if (!pu || pu->m_bBroken)
  2176. {
  2177. HLOGC(gslog.Debug, log << "grp/sendBackup: socket @" << d->id << " detected +Broken - transit to BROKEN");
  2178. d->sndstate = SRT_GST_BROKEN;
  2179. d->rcvstate = SRT_GST_BROKEN;
  2180. }
  2181. }
  2182. // Check socket sndstate before sending
  2183. if (d->sndstate == SRT_GST_BROKEN)
  2184. {
  2185. HLOGC(gslog.Debug,
  2186. log << "grp/sendBackup: socket in BROKEN state: @" << d->id
  2187. << ", sockstatus=" << SockStatusStr(d->ps ? d->ps->getStatus() : SRTS_NONEXIST));
  2188. sendBackup_AssignBackupState(d->ps->core(), BKUPST_BROKEN, currtime);
  2189. w_sendBackupCtx.recordMemberState(&(*d), BKUPST_BROKEN);
  2190. #if SRT_DEBUG_BONDING_STATES
  2191. s_stab_trace.trace(d->ps->core(), currtime, 0, 0, stateToStr(BKUPST_BROKEN), d->weight);
  2192. #endif
  2193. continue;
  2194. }
  2195. if (d->sndstate == SRT_GST_IDLE)
  2196. {
  2197. const BackupMemberState idle_state = sendBackup_QualifyIfStandBy(d);
  2198. sendBackup_AssignBackupState(d->ps->core(), idle_state, currtime);
  2199. w_sendBackupCtx.recordMemberState(&(*d), idle_state);
  2200. if (idle_state == BKUPST_STANDBY)
  2201. {
  2202. // TODO: Check if this is some abandoned logic.
  2203. sendBackup_CheckIdleTime(d);
  2204. }
  2205. #if SRT_DEBUG_BONDING_STATES
  2206. s_stab_trace.trace(d->ps->core(), currtime, 0, 0, stateToStr(idle_state), d->weight);
  2207. #endif
  2208. continue;
  2209. }
  2210. if (d->sndstate == SRT_GST_RUNNING)
  2211. {
  2212. const BackupMemberState active_state = sendBackup_QualifyActiveState(d, currtime);
  2213. sendBackup_AssignBackupState(d->ps->core(), active_state, currtime);
  2214. w_sendBackupCtx.recordMemberState(&(*d), active_state);
  2215. #if SRT_DEBUG_BONDING_STATES
  2216. s_stab_trace.trace(d->ps->core(), currtime, 0, 0, stateToStr(active_state), d->weight);
  2217. #endif
  2218. continue;
  2219. }
  2220. HLOGC(gslog.Debug,
  2221. log << "grp/sendBackup: socket @" << d->id << " not ready, state: " << StateStr(d->sndstate) << "("
  2222. << int(d->sndstate) << ") - NOT sending, SET AS PENDING");
  2223. // Otherwise connection pending
  2224. sendBackup_AssignBackupState(d->ps->core(), BKUPST_PENDING, currtime);
  2225. w_sendBackupCtx.recordMemberState(&(*d), BKUPST_PENDING);
  2226. #if SRT_DEBUG_BONDING_STATES
  2227. s_stab_trace.trace(d->ps->core(), currtime, 0, 0, stateToStr(BKUPST_PENDING), d->weight);
  2228. #endif
  2229. }
  2230. }
  2231. void CUDTGroup::sendBackup_AssignBackupState(CUDT& sock, BackupMemberState state, const steady_clock::time_point& currtime)
  2232. {
  2233. switch (state)
  2234. {
  2235. case BKUPST_PENDING:
  2236. case BKUPST_STANDBY:
  2237. case BKUPST_BROKEN:
  2238. sock.m_tsFreshActivation = steady_clock::time_point();
  2239. sock.m_tsUnstableSince = steady_clock::time_point();
  2240. sock.m_tsWarySince = steady_clock::time_point();
  2241. break;
  2242. case BKUPST_ACTIVE_FRESH:
  2243. if (is_zero(sock.freshActivationStart()))
  2244. {
  2245. sock.m_tsFreshActivation = currtime;
  2246. }
  2247. sock.m_tsUnstableSince = steady_clock::time_point();
  2248. sock.m_tsWarySince = steady_clock::time_point();;
  2249. break;
  2250. case BKUPST_ACTIVE_STABLE:
  2251. sock.m_tsFreshActivation = steady_clock::time_point();
  2252. sock.m_tsUnstableSince = steady_clock::time_point();
  2253. sock.m_tsWarySince = steady_clock::time_point();
  2254. break;
  2255. case BKUPST_ACTIVE_UNSTABLE:
  2256. if (is_zero(sock.m_tsUnstableSince))
  2257. {
  2258. sock.m_tsUnstableSince = currtime;
  2259. }
  2260. sock.m_tsFreshActivation = steady_clock::time_point();
  2261. sock.m_tsWarySince = steady_clock::time_point();
  2262. break;
  2263. case BKUPST_ACTIVE_UNSTABLE_WARY:
  2264. if (is_zero(sock.m_tsWarySince))
  2265. {
  2266. sock.m_tsWarySince = currtime;
  2267. }
  2268. break;
  2269. default:
  2270. break;
  2271. }
  2272. }
  2273. // [[using locked(this->m_GroupLock)]]
  2274. void CUDTGroup::sendBackup_CheckIdleTime(gli_t w_d)
  2275. {
  2276. // Check if it was fresh set as idle, we had to wait until its sender
  2277. // buffer gets empty so that we can make sure that KEEPALIVE will be the
  2278. // really last sent for longer time.
  2279. CUDT& u = w_d->ps->core();
  2280. if (is_zero(u.m_tsFreshActivation)) // TODO: Check if this condition is ever false
  2281. return;
  2282. CSndBuffer* b = u.m_pSndBuffer;
  2283. if (b && b->getCurrBufSize() == 0)
  2284. {
  2285. HLOGC(gslog.Debug,
  2286. log << "grp/sendBackup: FRESH IDLE LINK reached empty buffer - setting permanent and KEEPALIVE");
  2287. u.m_tsFreshActivation = steady_clock::time_point();
  2288. // Send first immediate keepalive. The link is to be turn to IDLE
  2289. // now so nothing will be sent to it over time and it will start
  2290. // getting KEEPALIVES since now. Send the first one now to increase
  2291. // probability that the link will be recognized as IDLE on the
  2292. // reception side ASAP.
  2293. int32_t arg = 1;
  2294. w_d->ps->core().sendCtrl(UMSG_KEEPALIVE, &arg);
  2295. }
  2296. }
  2297. // [[using locked(this->m_GroupLock)]]
  2298. CUDTGroup::BackupMemberState CUDTGroup::sendBackup_QualifyActiveState(const gli_t d, const time_point currtime)
  2299. {
  2300. const CUDT& u = d->ps->core();
  2301. const uint32_t latency_us = u.peerLatency_us();
  2302. const int32_t min_stability_us = m_uOPT_MinStabilityTimeout_us;
  2303. const int64_t initial_stabtout_us = max<int64_t>(min_stability_us, latency_us);
  2304. const int64_t probing_period_us = initial_stabtout_us + 5 * CUDT::COMM_SYN_INTERVAL_US;
  2305. // RTT and RTTVar values are still being refined during the probing period,
  2306. // therefore the dymanic timeout should not be used during the probing period.
  2307. const bool is_activation_phase = !is_zero(u.freshActivationStart())
  2308. && (count_microseconds(currtime - u.freshActivationStart()) <= probing_period_us);
  2309. // Initial stability timeout is used only in activation phase.
  2310. // Otherwise runtime stability is used, including the WARY state.
  2311. const int64_t stability_tout_us = is_activation_phase
  2312. ? initial_stabtout_us // activation phase
  2313. : min<int64_t>(max<int64_t>(min_stability_us, 2 * u.SRTT() + 4 * u.RTTVar()), latency_us);
  2314. const steady_clock::time_point last_rsp = max(u.freshActivationStart(), u.lastRspTime());
  2315. const steady_clock::duration td_response = currtime - last_rsp;
  2316. // No response for a long time
  2317. if (count_microseconds(td_response) > stability_tout_us)
  2318. {
  2319. return BKUPST_ACTIVE_UNSTABLE;
  2320. }
  2321. enterCS(u.m_StatsLock);
  2322. const int64_t drop_total = u.m_stats.sndr.dropped.total.count();
  2323. leaveCS(u.m_StatsLock);
  2324. const bool have_new_drops = d->pktSndDropTotal != drop_total;
  2325. if (have_new_drops)
  2326. {
  2327. d->pktSndDropTotal = drop_total;
  2328. if (!is_activation_phase)
  2329. return BKUPST_ACTIVE_UNSTABLE;
  2330. }
  2331. // Responsive: either stable, wary or still fresh activated.
  2332. if (is_activation_phase)
  2333. return BKUPST_ACTIVE_FRESH;
  2334. const bool is_wary = !is_zero(u.m_tsWarySince);
  2335. const bool is_wary_probing = is_wary
  2336. && (count_microseconds(currtime - u.m_tsWarySince) <= 4 * u.peerLatency_us());
  2337. const bool is_unstable = !is_zero(u.m_tsUnstableSince);
  2338. // If unstable and not in wary, become wary.
  2339. if (is_unstable && !is_wary)
  2340. return BKUPST_ACTIVE_UNSTABLE_WARY;
  2341. // Still probing for stability.
  2342. if (is_wary_probing)
  2343. return BKUPST_ACTIVE_UNSTABLE_WARY;
  2344. if (is_wary)
  2345. {
  2346. LOGC(gslog.Debug,
  2347. log << "grp/sendBackup: @" << u.id() << " wary->stable after " << count_milliseconds(currtime - u.m_tsWarySince) << " ms");
  2348. }
  2349. return BKUPST_ACTIVE_STABLE;
  2350. }
  2351. // [[using locked(this->m_GroupLock)]]
  2352. bool CUDTGroup::sendBackup_CheckSendStatus(const steady_clock::time_point& currtime SRT_ATR_UNUSED,
  2353. const int send_status,
  2354. const int32_t lastseq,
  2355. const int32_t pktseq,
  2356. CUDT& w_u,
  2357. int32_t& w_curseq,
  2358. int& w_final_stat)
  2359. {
  2360. if (send_status == -1)
  2361. return false; // Sending failed.
  2362. bool send_succeeded = false;
  2363. if (w_curseq == SRT_SEQNO_NONE)
  2364. {
  2365. w_curseq = pktseq;
  2366. }
  2367. else if (w_curseq != lastseq)
  2368. {
  2369. // We believe that all active links use the same seq.
  2370. // But we can do some sanity check.
  2371. LOGC(gslog.Error,
  2372. log << "grp/sendBackup: @" << w_u.m_SocketID << ": IPE: another running link seq discrepancy: %"
  2373. << lastseq << " vs. previous %" << w_curseq << " - fixing");
  2374. // Override must be done with a sequence number greater by one.
  2375. // Example:
  2376. //
  2377. // Link 1 before sending: curr=1114, next=1115
  2378. // After sending it reports pktseq=1115
  2379. //
  2380. // Link 2 before sending: curr=1110, next=1111 (->lastseq before sending)
  2381. // THIS CHECK done after sending:
  2382. // -- w_curseq(1115) != lastseq(1111)
  2383. //
  2384. // NOW: Link 1 after sending is:
  2385. // curr=1115, next=1116
  2386. //
  2387. // The value of w_curseq here = 1115, while overrideSndSeqNo
  2388. // calls setInitialSndSeq(seq), which sets:
  2389. // - curr = seq - 1
  2390. // - next = seq
  2391. //
  2392. // So, in order to set curr=1115, next=1116
  2393. // this must set to 1115+1.
  2394. w_u.overrideSndSeqNo(CSeqNo::incseq(w_curseq));
  2395. }
  2396. // State it as succeeded, though. We don't know if the link
  2397. // is broken until we get the connection broken confirmation,
  2398. // and the instability state may wear off next time.
  2399. send_succeeded = true;
  2400. w_final_stat = send_status;
  2401. return send_succeeded;
  2402. }
  2403. // [[using locked(this->m_GroupLock)]]
  2404. void CUDTGroup::sendBackup_Buffering(const char* buf, const int len, int32_t& w_curseq, SRT_MSGCTRL& w_mc)
  2405. {
  2406. // This is required to rewrite into currentSchedSequence() property
  2407. // as this value will be used as ISN when a new link is connected.
  2408. int32_t oldest_buffer_seq = SRT_SEQNO_NONE;
  2409. if (w_curseq != SRT_SEQNO_NONE)
  2410. {
  2411. HLOGC(gslog.Debug, log << "grp/sendBackup: successfully sent over running link, ADDING TO BUFFER.");
  2412. // Note: the sequence number that was used to send this packet should be
  2413. // recorded here.
  2414. oldest_buffer_seq = addMessageToBuffer(buf, len, (w_mc));
  2415. }
  2416. else
  2417. {
  2418. // We have to predict, which sequence number would have
  2419. // to be placed on the packet about to be sent now. To
  2420. // maintain consistency:
  2421. // 1. If there are any packets in the sender buffer,
  2422. // get the sequence of the last packet, increase it.
  2423. // This must be done even if this contradicts the ISN
  2424. // of all idle links because otherwise packets will get
  2425. // discrepancy.
  2426. if (!m_SenderBuffer.empty())
  2427. {
  2428. BufferedMessage& m = m_SenderBuffer.back();
  2429. w_curseq = CSeqNo::incseq(m.mc.pktseq);
  2430. // Set also this sequence to the current w_mc
  2431. w_mc.pktseq = w_curseq;
  2432. // XXX may need tighter revision when message mode is allowed
  2433. w_mc.msgno = ++MsgNo(m.mc.msgno);
  2434. oldest_buffer_seq = addMessageToBuffer(buf, len, (w_mc));
  2435. }
  2436. // Note that if buffer is empty and w_curseq is (still) SRT_SEQNO_NONE,
  2437. // it will have to try to send first in order to extract the data.
  2438. // Note that if w_curseq is still SRT_SEQNO_NONE at this point, it means
  2439. // that we have the case of the very first packet sending.
  2440. // Otherwise there would be something in the buffer already.
  2441. }
  2442. if (oldest_buffer_seq != SRT_SEQNO_NONE)
  2443. m_iLastSchedSeqNo = oldest_buffer_seq;
  2444. }
  2445. size_t CUDTGroup::sendBackup_TryActivateStandbyIfNeeded(
  2446. const char* buf,
  2447. const int len,
  2448. bool& w_none_succeeded,
  2449. SRT_MSGCTRL& w_mc,
  2450. int32_t& w_curseq,
  2451. int32_t& w_final_stat,
  2452. SendBackupCtx& w_sendBackupCtx,
  2453. CUDTException& w_cx,
  2454. const steady_clock::time_point& currtime)
  2455. {
  2456. const unsigned num_standby = w_sendBackupCtx.countMembersByState(BKUPST_STANDBY);
  2457. if (num_standby == 0)
  2458. {
  2459. return 0;
  2460. }
  2461. const unsigned num_stable = w_sendBackupCtx.countMembersByState(BKUPST_ACTIVE_STABLE);
  2462. const unsigned num_fresh = w_sendBackupCtx.countMembersByState(BKUPST_ACTIVE_FRESH);
  2463. if (num_stable + num_fresh == 0)
  2464. {
  2465. LOGC(gslog.Warn,
  2466. log << "grp/sendBackup: trying to activate a stand-by link (" << num_standby << " available). "
  2467. << "Reason: no stable links"
  2468. );
  2469. }
  2470. else if (w_sendBackupCtx.maxActiveWeight() < w_sendBackupCtx.maxStandbyWeight())
  2471. {
  2472. LOGC(gslog.Warn,
  2473. log << "grp/sendBackup: trying to activate a stand-by link (" << num_standby << " available). "
  2474. << "Reason: max active weight " << w_sendBackupCtx.maxActiveWeight()
  2475. << ", max stand by weight " << w_sendBackupCtx.maxStandbyWeight()
  2476. );
  2477. }
  2478. else
  2479. {
  2480. /*LOGC(gslog.Warn,
  2481. log << "grp/sendBackup: no need to activate (" << num_standby << " available). "
  2482. << "Max active weight " << w_sendBackupCtx.maxActiveWeight()
  2483. << ", max stand by weight " << w_sendBackupCtx.maxStandbyWeight()
  2484. );*/
  2485. return 0;
  2486. }
  2487. int stat = -1;
  2488. size_t num_activated = 0;
  2489. w_sendBackupCtx.sortByWeightAndState();
  2490. typedef vector<BackupMemberStateEntry>::const_iterator const_iter_t;
  2491. for (const_iter_t member = w_sendBackupCtx.memberStates().begin(); member != w_sendBackupCtx.memberStates().end(); ++member)
  2492. {
  2493. if (member->state != BKUPST_STANDBY)
  2494. continue;
  2495. int erc = 0;
  2496. SocketData* d = member->pSocketData;
  2497. // Now send and check the status
  2498. // The link could have got broken
  2499. try
  2500. {
  2501. CUDT& cudt = d->ps->core();
  2502. // Take source rate estimation from an active member (needed for the input rate estimation mode).
  2503. cudt.setRateEstimator(w_sendBackupCtx.getRateEstimate());
  2504. // TODO: At this point all packets that could be sent
  2505. // are located in m_SenderBuffer. So maybe just use sendBackupRexmit()?
  2506. if (w_curseq == SRT_SEQNO_NONE)
  2507. {
  2508. // This marks the fact that the given here packet
  2509. // could not be sent over any link. This includes the
  2510. // situation of sending the very first packet after connection.
  2511. HLOGC(gslog.Debug,
  2512. log << "grp/sendBackup: ... trying @" << d->id << " - sending the VERY FIRST message");
  2513. stat = cudt.sendmsg2(buf, len, (w_mc));
  2514. if (stat != -1)
  2515. {
  2516. // This will be no longer used, but let it stay here.
  2517. // It's because if this is successful, no other links
  2518. // will be tried.
  2519. w_curseq = w_mc.pktseq;
  2520. addMessageToBuffer(buf, len, (w_mc));
  2521. }
  2522. }
  2523. else
  2524. {
  2525. HLOGC(gslog.Debug,
  2526. log << "grp/sendBackup: ... trying @" << d->id << " - resending " << m_SenderBuffer.size()
  2527. << " collected messages...");
  2528. // Note: this will set the currently required packet
  2529. // because it has been just freshly added to the sender buffer
  2530. stat = sendBackupRexmit(cudt, (w_mc));
  2531. }
  2532. ++num_activated;
  2533. }
  2534. catch (CUDTException& e)
  2535. {
  2536. // This will be propagated from internal sendmsg2 call,
  2537. // but that's ok - we want this sending interrupted even in half.
  2538. w_cx = e;
  2539. stat = -1;
  2540. erc = e.getErrorCode();
  2541. }
  2542. d->sndresult = stat;
  2543. d->laststatus = d->ps->getStatus();
  2544. if (stat != -1)
  2545. {
  2546. d->sndstate = SRT_GST_RUNNING;
  2547. sendBackup_AssignBackupState(d->ps->core(), BKUPST_ACTIVE_FRESH, currtime);
  2548. w_sendBackupCtx.updateMemberState(d, BKUPST_ACTIVE_FRESH);
  2549. // Note: this will override the sequence number
  2550. // for all next iterations in this loop.
  2551. w_none_succeeded = false;
  2552. w_final_stat = stat;
  2553. LOGC(gslog.Warn,
  2554. log << "@" << d->id << " FRESH-ACTIVATED");
  2555. // We've activated the link, so that's enough.
  2556. break;
  2557. }
  2558. // Failure - move to broken those that could not be activated
  2559. bool isblocked SRT_ATR_UNUSED = true;
  2560. if (erc != SRT_EASYNCSND)
  2561. {
  2562. isblocked = false;
  2563. sendBackup_AssignBackupState(d->ps->core(), BKUPST_BROKEN, currtime);
  2564. w_sendBackupCtx.updateMemberState(d, BKUPST_BROKEN);
  2565. }
  2566. // If we found a blocked link, leave it alone, however
  2567. // still try to send something over another link
  2568. LOGC(gslog.Warn,
  2569. log << "@" << d->id << " FAILED (" << (isblocked ? "blocked" : "ERROR")
  2570. << "), trying to activate another link.");
  2571. }
  2572. return num_activated;
  2573. }
  2574. // [[using locked(this->m_GroupLock)]]
  2575. void CUDTGroup::sendBackup_CheckPendingSockets(SendBackupCtx& w_sendBackupCtx, const steady_clock::time_point& currtime)
  2576. {
  2577. if (w_sendBackupCtx.countMembersByState(BKUPST_PENDING) == 0)
  2578. return;
  2579. HLOGC(gslog.Debug, log << "grp/send*: checking pending sockets.");
  2580. // These sockets if they are in pending state, should be added to m_SndEID
  2581. // at the connecting stage.
  2582. CEPoll::fmap_t sready;
  2583. if (m_Global.m_EPoll.empty(*m_SndEpolld))
  2584. {
  2585. // Sanity check - weird pending reported.
  2586. LOGC(gslog.Error, log << "grp/send*: IPE: reported pending sockets, but EID is empty - wiping pending!");
  2587. return;
  2588. }
  2589. {
  2590. InvertedLock ug(m_GroupLock);
  2591. m_Global.m_EPoll.swait(
  2592. *m_SndEpolld, sready, 0, false /*report by retval*/); // Just check if anything has happened
  2593. }
  2594. if (m_bClosing)
  2595. {
  2596. HLOGC(gslog.Debug, log << "grp/send...: GROUP CLOSED, ABANDONING");
  2597. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  2598. }
  2599. // Some sockets could have been closed in the meantime.
  2600. if (m_Global.m_EPoll.empty(*m_SndEpolld))
  2601. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  2602. HLOGC(gslog.Debug, log << "grp/send*: RDY: " << DisplayEpollResults(sready));
  2603. typedef vector<BackupMemberStateEntry>::const_iterator const_iter_t;
  2604. for (const_iter_t member = w_sendBackupCtx.memberStates().begin(); member != w_sendBackupCtx.memberStates().end(); ++member)
  2605. {
  2606. if (member->state != BKUPST_PENDING)
  2607. continue;
  2608. const SRTSOCKET sockid = member->pSocketData->id;
  2609. if (!CEPoll::isready(sready, sockid, SRT_EPOLL_ERR))
  2610. continue;
  2611. HLOGC(gslog.Debug, log << "grp/send*: Socket @" << sockid << " reported FAILURE - qualifying as broken.");
  2612. w_sendBackupCtx.updateMemberState(member->pSocketData, BKUPST_BROKEN);
  2613. if (member->pSocketData->ps)
  2614. sendBackup_AssignBackupState(member->pSocketData->ps->core(), BKUPST_BROKEN, currtime);
  2615. const int no_events = 0;
  2616. m_Global.m_EPoll.update_usock(m_SndEID, sockid, &no_events);
  2617. }
  2618. // After that, all sockets that have been reported
  2619. // as ready to write should be removed from EID. This
  2620. // will also remove those sockets that have been added
  2621. // as redundant links at the connecting stage and became
  2622. // writable (connected) before this function had a chance
  2623. // to check them.
  2624. m_Global.m_EPoll.clear_ready_usocks(*m_SndEpolld, SRT_EPOLL_OUT);
  2625. }
  2626. // [[using locked(this->m_GroupLock)]]
  2627. void CUDTGroup::sendBackup_CheckUnstableSockets(SendBackupCtx& w_sendBackupCtx, const steady_clock::time_point& currtime)
  2628. {
  2629. const unsigned num_stable = w_sendBackupCtx.countMembersByState(BKUPST_ACTIVE_STABLE);
  2630. if (num_stable == 0)
  2631. return;
  2632. const unsigned num_unstable = w_sendBackupCtx.countMembersByState(BKUPST_ACTIVE_UNSTABLE);
  2633. const unsigned num_wary = w_sendBackupCtx.countMembersByState(BKUPST_ACTIVE_UNSTABLE_WARY);
  2634. if (num_unstable + num_wary == 0)
  2635. return;
  2636. HLOGC(gslog.Debug, log << "grp/send*: checking unstable sockets.");
  2637. typedef vector<BackupMemberStateEntry>::const_iterator const_iter_t;
  2638. for (const_iter_t member = w_sendBackupCtx.memberStates().begin(); member != w_sendBackupCtx.memberStates().end(); ++member)
  2639. {
  2640. if (member->state != BKUPST_ACTIVE_UNSTABLE && member->state != BKUPST_ACTIVE_UNSTABLE_WARY)
  2641. continue;
  2642. CUDT& sock = member->pSocketData->ps->core();
  2643. if (is_zero(sock.m_tsUnstableSince))
  2644. {
  2645. LOGC(gslog.Error, log << "grp/send* IPE: Socket @" << member->socketID
  2646. << " is qualified as unstable, but does not have the 'unstable since' timestamp. Still marking for closure.");
  2647. }
  2648. const int unstable_for_ms = (int)count_milliseconds(currtime - sock.m_tsUnstableSince);
  2649. if (unstable_for_ms < sock.peerIdleTimeout_ms())
  2650. continue;
  2651. // Requesting this socket to be broken with the next CUDT::checkExpTimer() call.
  2652. sock.breakAsUnstable();
  2653. LOGC(gslog.Warn, log << "grp/send*: Socket @" << member->socketID << " is unstable for " << unstable_for_ms
  2654. << "ms - requesting breakage.");
  2655. //w_sendBackupCtx.updateMemberState(member->pSocketData, BKUPST_BROKEN);
  2656. //if (member->pSocketData->ps)
  2657. // sendBackup_AssignBackupState(member->pSocketData->ps->core(), BKUPST_BROKEN, currtime);
  2658. }
  2659. }
  2660. // [[using locked(this->m_GroupLock)]]
  2661. void CUDTGroup::send_CloseBrokenSockets(vector<SRTSOCKET>& w_wipeme)
  2662. {
  2663. if (!w_wipeme.empty())
  2664. {
  2665. InvertedLock ug(m_GroupLock);
  2666. // With unlocked GroupLock, we can now lock GlobControlLock.
  2667. // This is needed prevent any of them be deleted from the container
  2668. // at the same time.
  2669. ScopedLock globlock(CUDT::uglobal().m_GlobControlLock);
  2670. for (vector<SRTSOCKET>::iterator p = w_wipeme.begin(); p != w_wipeme.end(); ++p)
  2671. {
  2672. CUDTSocket* s = CUDT::uglobal().locateSocket_LOCKED(*p);
  2673. // If the socket has been just moved to ClosedSockets, it means that
  2674. // the object still exists, but it will be no longer findable.
  2675. if (!s)
  2676. continue;
  2677. HLOGC(gslog.Debug,
  2678. log << "grp/send...: BROKEN SOCKET @" << (*p) << " - CLOSING, to be removed from group.");
  2679. // As per sending, make it also broken so that scheduled
  2680. // packets will be also abandoned.
  2681. s->setClosed();
  2682. }
  2683. }
  2684. HLOGC(gslog.Debug, log << "grp/send...: - wiped " << w_wipeme.size() << " broken sockets");
  2685. // We'll need you again.
  2686. w_wipeme.clear();
  2687. }
  2688. // [[using locked(this->m_GroupLock)]]
  2689. void CUDTGroup::sendBackup_CloseBrokenSockets(SendBackupCtx& w_sendBackupCtx)
  2690. {
  2691. if (w_sendBackupCtx.countMembersByState(BKUPST_BROKEN) == 0)
  2692. return;
  2693. InvertedLock ug(m_GroupLock);
  2694. // With unlocked GroupLock, we can now lock GlobControlLock.
  2695. // This is needed prevent any of them be deleted from the container
  2696. // at the same time.
  2697. ScopedLock globlock(CUDT::uglobal().m_GlobControlLock);
  2698. typedef vector<BackupMemberStateEntry>::const_iterator const_iter_t;
  2699. for (const_iter_t member = w_sendBackupCtx.memberStates().begin(); member != w_sendBackupCtx.memberStates().end(); ++member)
  2700. {
  2701. if (member->state != BKUPST_BROKEN)
  2702. continue;
  2703. // m_GroupLock is unlocked, therefore member->pSocketData can't be used.
  2704. const SRTSOCKET sockid = member->socketID;
  2705. CUDTSocket* s = CUDT::uglobal().locateSocket_LOCKED(sockid);
  2706. // If the socket has been just moved to ClosedSockets, it means that
  2707. // the object still exists, but it will be no longer findable.
  2708. if (!s)
  2709. continue;
  2710. LOGC(gslog.Debug,
  2711. log << "grp/send...: BROKEN SOCKET @" << sockid << " - CLOSING, to be removed from group.");
  2712. // As per sending, make it also broken so that scheduled
  2713. // packets will be also abandoned.
  2714. s->setBrokenClosed();
  2715. }
  2716. // TODO: all broken members are to be removed from the context now???
  2717. }
  2718. // [[using locked(this->m_GroupLock)]]
  2719. void CUDTGroup::sendBackup_RetryWaitBlocked(SendBackupCtx& w_sendBackupCtx,
  2720. int& w_final_stat,
  2721. bool& w_none_succeeded,
  2722. SRT_MSGCTRL& w_mc,
  2723. CUDTException& w_cx)
  2724. {
  2725. // In contradiction to broadcast sending, backup sending must check
  2726. // the blocking state in total first. We need this information through
  2727. // epoll because we didn't use all sockets to send the data hence the
  2728. // blocked socket information would not be complete.
  2729. // Don't do this check if sending has succeeded over at least one
  2730. // stable link. This procedure is to wait for at least one write-ready
  2731. // link.
  2732. //
  2733. // If sending succeeded also over at least one unstable link (you only have
  2734. // unstable links and none other or others just got broken), continue sending
  2735. // anyway.
  2736. // This procedure is for a case when the packet could not be sent
  2737. // over any link (hence "none succeeded"), but there are some unstable
  2738. // links and no parallel links. We need to WAIT for any of the links
  2739. // to become available for sending.
  2740. // Note: A link is added in unstableLinks if sending has failed with SRT_ESYNCSND.
  2741. const unsigned num_unstable = w_sendBackupCtx.countMembersByState(BKUPST_ACTIVE_UNSTABLE);
  2742. const unsigned num_wary = w_sendBackupCtx.countMembersByState(BKUPST_ACTIVE_UNSTABLE_WARY);
  2743. if ((num_unstable + num_wary == 0) || !w_none_succeeded)
  2744. return;
  2745. HLOGC(gslog.Debug, log << "grp/sendBackup: no successfull sending: "
  2746. << (num_unstable + num_wary) << " unstable links - waiting to retry sending...");
  2747. // Note: GroupLock is set already, skip locks and checks
  2748. getGroupData_LOCKED((w_mc.grpdata), (&w_mc.grpdata_size));
  2749. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false);
  2750. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true);
  2751. if (m_Global.m_EPoll.empty(*m_SndEpolld))
  2752. {
  2753. // wipeme wiped, pending sockets checked, it can only mean that
  2754. // all sockets are broken.
  2755. HLOGC(gslog.Debug, log << "grp/sendBackup: epolld empty - all sockets broken?");
  2756. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  2757. }
  2758. if (!m_bSynSending)
  2759. {
  2760. HLOGC(gslog.Debug, log << "grp/sendBackup: non-blocking mode - exit with no-write-ready");
  2761. throw CUDTException(MJ_AGAIN, MN_WRAVAIL, 0);
  2762. }
  2763. // Here is the situation that the only links left here are:
  2764. // - those that failed to send (already closed and wiped out)
  2765. // - those that got blockade on sending
  2766. // At least, there was so far no socket through which we could
  2767. // successfully send anything.
  2768. // As a last resort in this situation, try to wait for any links
  2769. // remaining in the group to become ready to write.
  2770. CEPoll::fmap_t sready;
  2771. int brdy;
  2772. // This keeps the number of links that existed at the entry.
  2773. // Simply notify all dead links, regardless as to whether the number
  2774. // of group members decreases below. If the number of corpses reaches
  2775. // this number, consider the group connection broken.
  2776. const size_t nlinks = m_Group.size();
  2777. size_t ndead = 0;
  2778. RetryWaitBlocked:
  2779. {
  2780. // Some sockets could have been closed in the meantime.
  2781. if (m_Global.m_EPoll.empty(*m_SndEpolld))
  2782. {
  2783. HLOGC(gslog.Debug, log << "grp/sendBackup: no more sockets available for sending - group broken");
  2784. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  2785. }
  2786. InvertedLock ug(m_GroupLock);
  2787. HLOGC(gslog.Debug,
  2788. log << "grp/sendBackup: swait call to get at least one link alive up to " << m_iSndTimeOut << "us");
  2789. THREAD_PAUSED();
  2790. brdy = m_Global.m_EPoll.swait(*m_SndEpolld, (sready), m_iSndTimeOut);
  2791. THREAD_RESUMED();
  2792. if (brdy == 0) // SND timeout exceeded
  2793. {
  2794. throw CUDTException(MJ_AGAIN, MN_WRAVAIL, 0);
  2795. }
  2796. HLOGC(gslog.Debug, log << "grp/sendBackup: swait exited with " << brdy << " ready sockets:");
  2797. // Check if there's anything in the "error" section.
  2798. // This must be cleared here before the lock on group is set again.
  2799. // (This loop will not fire neither once if no failed sockets found).
  2800. for (CEPoll::fmap_t::const_iterator i = sready.begin(); i != sready.end(); ++i)
  2801. {
  2802. if (i->second & SRT_EPOLL_ERR)
  2803. {
  2804. SRTSOCKET id = i->first;
  2805. CUDTSocket* s = m_Global.locateSocket(id, CUDTUnited::ERH_RETURN); // << LOCKS m_GlobControlLock!
  2806. if (s)
  2807. {
  2808. HLOGC(gslog.Debug,
  2809. log << "grp/sendBackup: swait/ex on @" << (id)
  2810. << " while waiting for any writable socket - CLOSING");
  2811. CUDT::uglobal().close(s); // << LOCKS m_GlobControlLock, then GroupLock!
  2812. }
  2813. else
  2814. {
  2815. HLOGC(gslog.Debug, log << "grp/sendBackup: swait/ex on @" << (id) << " - WAS DELETED IN THE MEANTIME");
  2816. }
  2817. ++ndead;
  2818. }
  2819. }
  2820. HLOGC(gslog.Debug, log << "grp/sendBackup: swait/?close done, re-acquiring GroupLock");
  2821. }
  2822. // GroupLock is locked back
  2823. // Re-check after the waiting lock has been reacquired
  2824. if (m_bClosing)
  2825. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  2826. if (brdy == -1 || ndead >= nlinks)
  2827. {
  2828. LOGC(gslog.Error,
  2829. log << "grp/sendBackup: swait=>" << brdy << " nlinks=" << nlinks << " ndead=" << ndead
  2830. << " - looxlike all links broken");
  2831. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false);
  2832. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true);
  2833. // You can safely throw here - nothing to fill in when all sockets down.
  2834. // (timeout was reported by exception in the swait call).
  2835. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  2836. }
  2837. // Ok, now check if we have at least one write-ready.
  2838. // Note that the procedure of activation of a new link in case of
  2839. // no stable links found embraces also rexmit-sending and status
  2840. // check as well, including blocked status.
  2841. // Find which one it was. This is so rare case that we can
  2842. // suffer linear search.
  2843. int nwaiting = 0;
  2844. int nactivated SRT_ATR_UNUSED = 0;
  2845. int stat = -1;
  2846. for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d)
  2847. {
  2848. // We are waiting only for active members
  2849. if (d->sndstate != SRT_GST_RUNNING)
  2850. {
  2851. HLOGC(gslog.Debug,
  2852. log << "grp/sendBackup: member @" << d->id << " state is not RUNNING - SKIPPING from retry/waiting");
  2853. continue;
  2854. }
  2855. // Skip if not writable in this run
  2856. if (!CEPoll::isready(sready, d->id, SRT_EPOLL_OUT))
  2857. {
  2858. ++nwaiting;
  2859. HLOGC(gslog.Debug, log << "grp/sendBackup: @" << d->id << " NOT ready:OUT, added as waiting");
  2860. continue;
  2861. }
  2862. try
  2863. {
  2864. // Note: this will set the currently required packet
  2865. // because it has been just freshly added to the sender buffer
  2866. stat = sendBackupRexmit(d->ps->core(), (w_mc));
  2867. ++nactivated;
  2868. }
  2869. catch (CUDTException& e)
  2870. {
  2871. // This will be propagated from internal sendmsg2 call,
  2872. // but that's ok - we want this sending interrupted even in half.
  2873. w_cx = e;
  2874. stat = -1;
  2875. }
  2876. d->sndresult = stat;
  2877. d->laststatus = d->ps->getStatus();
  2878. if (stat == -1)
  2879. {
  2880. // This link is no longer waiting.
  2881. continue;
  2882. }
  2883. w_final_stat = stat;
  2884. d->sndstate = SRT_GST_RUNNING;
  2885. w_none_succeeded = false;
  2886. const steady_clock::time_point currtime = steady_clock::now();
  2887. sendBackup_AssignBackupState(d->ps->core(), BKUPST_ACTIVE_UNSTABLE_WARY, currtime);
  2888. w_sendBackupCtx.updateMemberState(&(*d), BKUPST_ACTIVE_UNSTABLE_WARY);
  2889. HLOGC(gslog.Debug, log << "grp/sendBackup: after waiting, ACTIVATED link @" << d->id);
  2890. break;
  2891. }
  2892. // If we have no links successfully activated, but at least
  2893. // one link "not ready for writing", continue waiting for at
  2894. // least one link ready.
  2895. if (stat == -1 && nwaiting > 0)
  2896. {
  2897. HLOGC(gslog.Debug, log << "grp/sendBackup: still have " << nwaiting << " waiting and none succeeded, REPEAT");
  2898. goto RetryWaitBlocked;
  2899. }
  2900. }
  2901. // [[using locked(this->m_GroupLock)]]
  2902. void CUDTGroup::sendBackup_SilenceRedundantLinks(SendBackupCtx& w_sendBackupCtx, const steady_clock::time_point& currtime)
  2903. {
  2904. // The most important principle is to keep the data being sent constantly,
  2905. // even if it means temporarily full redundancy.
  2906. // A member can be silenced only if there is at least one stable memebr.
  2907. const unsigned num_stable = w_sendBackupCtx.countMembersByState(BKUPST_ACTIVE_STABLE);
  2908. if (num_stable == 0)
  2909. return;
  2910. // INPUT NEEDED:
  2911. // - stable member with maximum weight
  2912. uint16_t max_weight_stable = 0;
  2913. SRTSOCKET stableSocketId = SRT_INVALID_SOCK; // SocketID of a stable link with higher weight
  2914. w_sendBackupCtx.sortByWeightAndState();
  2915. //LOGC(gslog.Debug, log << "grp/silenceRedundant: links after sort: " << w_sendBackupCtx.printMembers());
  2916. typedef vector<BackupMemberStateEntry>::const_iterator const_iter_t;
  2917. for (const_iter_t member = w_sendBackupCtx.memberStates().begin(); member != w_sendBackupCtx.memberStates().end(); ++member)
  2918. {
  2919. if (!isStateActive(member->state))
  2920. continue;
  2921. const bool haveHigherWeightStable = stableSocketId != SRT_INVALID_SOCK;
  2922. const uint16_t weight = member->pSocketData->weight;
  2923. if (member->state == BKUPST_ACTIVE_STABLE)
  2924. {
  2925. // silence stable link if it is not the first stable
  2926. if (!haveHigherWeightStable)
  2927. {
  2928. max_weight_stable = (int) weight;
  2929. stableSocketId = member->socketID;
  2930. continue;
  2931. }
  2932. else
  2933. {
  2934. LOGC(gslog.Note, log << "grp/sendBackup: silencing stable member @" << member->socketID << " (weight " << weight
  2935. << ") in favor of @" << stableSocketId << " (weight " << max_weight_stable << ")");
  2936. }
  2937. }
  2938. else if (haveHigherWeightStable && weight <= max_weight_stable)
  2939. {
  2940. LOGC(gslog.Note, log << "grp/sendBackup: silencing member @" << member->socketID << " (weight " << weight
  2941. << " " << stateToStr(member->state)
  2942. << ") in favor of @" << stableSocketId << " (weight " << max_weight_stable << ")");
  2943. }
  2944. else
  2945. {
  2946. continue;
  2947. }
  2948. // TODO: Move to a separate function sendBackup_SilenceMember
  2949. SocketData* d = member->pSocketData;
  2950. CUDT& u = d->ps->core();
  2951. sendBackup_AssignBackupState(u, BKUPST_STANDBY, currtime);
  2952. w_sendBackupCtx.updateMemberState(d, BKUPST_STANDBY);
  2953. if (d->sndstate != SRT_GST_RUNNING)
  2954. {
  2955. LOGC(gslog.Error,
  2956. log << "grp/sendBackup: IPE: misidentified a non-running link @" << d->id << " as active");
  2957. continue;
  2958. }
  2959. d->sndstate = SRT_GST_IDLE;
  2960. }
  2961. }
  2962. int CUDTGroup::sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc)
  2963. {
  2964. if (len <= 0)
  2965. {
  2966. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  2967. }
  2968. // Only live streaming is supported
  2969. if (len > SRT_LIVE_MAX_PLSIZE)
  2970. {
  2971. LOGC(gslog.Error, log << "grp/send(backup): buffer size=" << len << " exceeds maximum allowed in live mode");
  2972. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  2973. }
  2974. // [[using assert(this->m_pSndBuffer != nullptr)]];
  2975. // First, acquire GlobControlLock to make sure all member sockets still exist
  2976. enterCS(m_Global.m_GlobControlLock);
  2977. ScopedLock guard(m_GroupLock);
  2978. if (m_bClosing)
  2979. {
  2980. leaveCS(m_Global.m_GlobControlLock);
  2981. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  2982. }
  2983. // Now, still under lock, check if all sockets still can be dispatched
  2984. send_CheckValidSockets();
  2985. leaveCS(m_Global.m_GlobControlLock);
  2986. steady_clock::time_point currtime = steady_clock::now();
  2987. SendBackupCtx sendBackupCtx; // default initialized as empty
  2988. // TODO: reserve? sendBackupCtx.memberStates.reserve(m_Group.size());
  2989. sendBackup_QualifyMemberStates((sendBackupCtx), currtime);
  2990. int32_t curseq = SRT_SEQNO_NONE;
  2991. size_t nsuccessful = 0;
  2992. SRT_ATR_UNUSED CUDTException cx(MJ_SUCCESS, MN_NONE, 0); // TODO: Delete then?
  2993. uint16_t maxActiveWeight = 0; // Maximum weight of active links.
  2994. // The number of bytes sent or -1 for error will be stored in group_send_result
  2995. int group_send_result = sendBackup_SendOverActive(buf, len, w_mc, currtime, (curseq), (nsuccessful), (maxActiveWeight), (sendBackupCtx), (cx));
  2996. bool none_succeeded = (nsuccessful == 0);
  2997. // Save current payload in group's sender buffer.
  2998. sendBackup_Buffering(buf, len, (curseq), (w_mc));
  2999. sendBackup_TryActivateStandbyIfNeeded(buf, len, (none_succeeded),
  3000. (w_mc),
  3001. (curseq),
  3002. (group_send_result),
  3003. (sendBackupCtx),
  3004. (cx), currtime);
  3005. sendBackup_CheckPendingSockets((sendBackupCtx), currtime);
  3006. sendBackup_CheckUnstableSockets((sendBackupCtx), currtime);
  3007. //LOGC(gslog.Debug, log << "grp/sendBackup: links after all checks: " << sendBackupCtx.printMembers());
  3008. // Re-check after the waiting lock has been reacquired
  3009. if (m_bClosing)
  3010. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  3011. sendBackup_CloseBrokenSockets((sendBackupCtx));
  3012. // Re-check after the waiting lock has been reacquired
  3013. if (m_bClosing)
  3014. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  3015. // If all links out of the unstable-running links are blocked (SRT_EASYNCSND),
  3016. // perform epoll wait on them. In this situation we know that
  3017. // there are no idle blocked links because IDLE LINK CAN'T BE BLOCKED,
  3018. // no matter what. It's because the link may only be blocked if
  3019. // the sender buffer of this socket is full, and it can't be
  3020. // full if it wasn't used so far.
  3021. //
  3022. // This means that in case when we have no stable links, we
  3023. // need to try out any link that can accept the rexmit-load.
  3024. // We'll check link stability at the next sending attempt.
  3025. sendBackup_RetryWaitBlocked((sendBackupCtx), (group_send_result), (none_succeeded), (w_mc), (cx));
  3026. sendBackup_SilenceRedundantLinks((sendBackupCtx), currtime);
  3027. // (closing condition checked inside this call)
  3028. if (none_succeeded)
  3029. {
  3030. HLOGC(gslog.Debug, log << "grp/sendBackup: all links broken (none succeeded to send a payload)");
  3031. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false);
  3032. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true);
  3033. // Reparse error code, if set.
  3034. // It might be set, if the last operation was failed.
  3035. // If any operation succeeded, this will not be executed anyway.
  3036. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0);
  3037. }
  3038. // At least one link has succeeded, update sending stats.
  3039. m_stats.sent.count(len);
  3040. // Now fill in the socket table. Check if the size is enough, if not,
  3041. // then set the pointer to NULL and set the correct size.
  3042. // Note that list::size() is linear time, however this shouldn't matter,
  3043. // as with the increased number of links in the redundancy group the
  3044. // impossibility of using that many of them grows exponentally.
  3045. const size_t grpsize = m_Group.size();
  3046. if (w_mc.grpdata_size < grpsize)
  3047. {
  3048. w_mc.grpdata = NULL;
  3049. }
  3050. size_t i = 0;
  3051. bool ready_again = false;
  3052. HLOGC(gslog.Debug, log << "grp/sendBackup: copying group data");
  3053. for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d, ++i)
  3054. {
  3055. if (w_mc.grpdata)
  3056. {
  3057. // Enough space to fill
  3058. copyGroupData(*d, (w_mc.grpdata[i]));
  3059. }
  3060. // We perform this loop anyway because we still need to check if any
  3061. // socket is writable. Note that the group lock will hold any write ready
  3062. // updates that are performed just after a single socket update for the
  3063. // group, so if any socket is actually ready at the moment when this
  3064. // is performed, and this one will result in none-write-ready, this will
  3065. // be fixed just after returning from this function.
  3066. ready_again = ready_again || d->ps->writeReady();
  3067. }
  3068. w_mc.grpdata_size = i;
  3069. if (!ready_again)
  3070. {
  3071. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false);
  3072. }
  3073. HLOGC(gslog.Debug,
  3074. log << "grp/sendBackup: successfully sent " << group_send_result << " bytes, "
  3075. << (ready_again ? "READY for next" : "NOT READY to send next"));
  3076. return group_send_result;
  3077. }
  3078. // [[using locked(this->m_GroupLock)]]
  3079. int32_t CUDTGroup::addMessageToBuffer(const char* buf, size_t len, SRT_MSGCTRL& w_mc)
  3080. {
  3081. if (m_iSndAckedMsgNo == SRT_MSGNO_NONE)
  3082. {
  3083. // Very first packet, just set the msgno.
  3084. m_iSndAckedMsgNo = w_mc.msgno;
  3085. m_iSndOldestMsgNo = w_mc.msgno;
  3086. HLOGC(gslog.Debug, log << "addMessageToBuffer: initial message no #" << w_mc.msgno);
  3087. }
  3088. else if (m_iSndOldestMsgNo != m_iSndAckedMsgNo)
  3089. {
  3090. int offset = MsgNo(m_iSndAckedMsgNo) - MsgNo(m_iSndOldestMsgNo);
  3091. HLOGC(gslog.Debug,
  3092. log << "addMessageToBuffer: new ACK-ed messages: #(" << m_iSndOldestMsgNo << "-" << m_iSndAckedMsgNo
  3093. << ") - going to remove");
  3094. if (offset > int(m_SenderBuffer.size()))
  3095. {
  3096. LOGC(gslog.Error,
  3097. log << "addMessageToBuffer: IPE: offset=" << offset << " exceeds buffer size=" << m_SenderBuffer.size()
  3098. << " - CLEARING");
  3099. m_SenderBuffer.clear();
  3100. }
  3101. else
  3102. {
  3103. HLOGC(gslog.Debug,
  3104. log << "addMessageToBuffer: erasing " << offset << "/" << m_SenderBuffer.size()
  3105. << " group-senderbuffer ACKED messages for #" << m_iSndOldestMsgNo << " - #" << m_iSndAckedMsgNo);
  3106. m_SenderBuffer.erase(m_SenderBuffer.begin(), m_SenderBuffer.begin() + offset);
  3107. }
  3108. // Position at offset is not included
  3109. m_iSndOldestMsgNo = m_iSndAckedMsgNo;
  3110. HLOGC(gslog.Debug,
  3111. log << "addMessageToBuffer: ... after: oldest #" << m_iSndOldestMsgNo);
  3112. }
  3113. m_SenderBuffer.resize(m_SenderBuffer.size() + 1);
  3114. BufferedMessage& bm = m_SenderBuffer.back();
  3115. bm.mc = w_mc;
  3116. bm.copy(buf, len);
  3117. HLOGC(gslog.Debug,
  3118. log << "addMessageToBuffer: #" << w_mc.msgno << " size=" << len << " !" << BufferStamp(buf, len));
  3119. return m_SenderBuffer.front().mc.pktseq;
  3120. }
  3121. int CUDTGroup::sendBackup_SendOverActive(const char* buf, int len, SRT_MSGCTRL& w_mc, const steady_clock::time_point& currtime, int32_t& w_curseq,
  3122. size_t& w_nsuccessful, uint16_t& w_maxActiveWeight, SendBackupCtx& w_sendBackupCtx, CUDTException& w_cx)
  3123. {
  3124. if (w_mc.srctime == 0)
  3125. w_mc.srctime = count_microseconds(currtime.time_since_epoch());
  3126. SRT_ASSERT(w_nsuccessful == 0);
  3127. SRT_ASSERT(w_maxActiveWeight == 0);
  3128. int group_send_result = SRT_ERROR;
  3129. // TODO: implement iterator over active links
  3130. typedef vector<BackupMemberStateEntry>::const_iterator const_iter_t;
  3131. for (const_iter_t member = w_sendBackupCtx.memberStates().begin(); member != w_sendBackupCtx.memberStates().end(); ++member)
  3132. {
  3133. if (!isStateActive(member->state))
  3134. continue;
  3135. SocketData* d = member->pSocketData;
  3136. int erc = SRT_SUCCESS;
  3137. // Remaining sndstate is SRT_GST_RUNNING. Send a payload through it.
  3138. CUDT& u = d->ps->core();
  3139. const int32_t lastseq = u.schedSeqNo();
  3140. int sndresult = SRT_ERROR;
  3141. try
  3142. {
  3143. // This must be wrapped in try-catch because on error it throws an exception.
  3144. // Possible return values are only 0, in case when len was passed 0, or a positive
  3145. // >0 value that defines the size of the data that it has sent, that is, in case
  3146. // of Live mode, equal to 'len'.
  3147. sndresult = u.sendmsg2(buf, len, (w_mc));
  3148. }
  3149. catch (CUDTException& e)
  3150. {
  3151. w_cx = e;
  3152. erc = e.getErrorCode();
  3153. sndresult = SRT_ERROR;
  3154. }
  3155. const bool send_succeeded = sendBackup_CheckSendStatus(
  3156. currtime,
  3157. sndresult,
  3158. lastseq,
  3159. w_mc.pktseq,
  3160. (u),
  3161. (w_curseq),
  3162. (group_send_result));
  3163. if (send_succeeded)
  3164. {
  3165. ++w_nsuccessful;
  3166. w_maxActiveWeight = max(w_maxActiveWeight, d->weight);
  3167. if (u.m_pSndBuffer)
  3168. w_sendBackupCtx.setRateEstimate(u.m_pSndBuffer->getRateEstimator());
  3169. }
  3170. else if (erc == SRT_EASYNCSND)
  3171. {
  3172. sendBackup_AssignBackupState(u, BKUPST_ACTIVE_UNSTABLE, currtime);
  3173. w_sendBackupCtx.updateMemberState(d, BKUPST_ACTIVE_UNSTABLE);
  3174. }
  3175. d->sndresult = sndresult;
  3176. d->laststatus = d->ps->getStatus();
  3177. }
  3178. return group_send_result;
  3179. }
  3180. // [[using locked(this->m_GroupLock)]]
  3181. int CUDTGroup::sendBackupRexmit(CUDT& core, SRT_MSGCTRL& w_mc)
  3182. {
  3183. // This should resend all packets
  3184. if (m_SenderBuffer.empty())
  3185. {
  3186. LOGC(gslog.Fatal, log << "IPE: sendBackupRexmit: sender buffer empty");
  3187. // Although act as if it was successful, otherwise you'll get connection break
  3188. return 0;
  3189. }
  3190. // using [[assert !m_SenderBuffer.empty()]];
  3191. // Send everything you currently have in the sender buffer.
  3192. // The receiver will reject packets that it currently has.
  3193. // Start from the oldest.
  3194. CPacket packet;
  3195. set<int> results;
  3196. int stat = -1;
  3197. // Make sure that the link has correctly synchronized sequence numbers.
  3198. // Note that sequence numbers should be recorded in mc.
  3199. int32_t curseq = m_SenderBuffer[0].mc.pktseq;
  3200. size_t skip_initial = 0;
  3201. if (curseq != core.schedSeqNo())
  3202. {
  3203. const int distance = CSeqNo::seqoff(core.schedSeqNo(), curseq);
  3204. if (distance < 0)
  3205. {
  3206. // This may happen in case when the link to be activated is already running.
  3207. // Getting sequences backwards is not allowed, as sending them makes no
  3208. // sense - they are already ACK-ed or are behind the ISN. Instead, skip all
  3209. // packets that are in the past towards the scheduling sequence.
  3210. skip_initial = -distance;
  3211. LOGC(gslog.Warn,
  3212. log << "sendBackupRexmit: OVERRIDE attempt. Link seqno %" << core.schedSeqNo() << ", trying to send from seqno %" << curseq
  3213. << " - DENIED; skip " << skip_initial << " pkts, " << m_SenderBuffer.size() << " pkts in buffer");
  3214. }
  3215. else
  3216. {
  3217. // In case when the next planned sequence on this link is behind
  3218. // the firstmost sequence in the backup buffer, synchronize the
  3219. // sequence with it first so that they go hand-in-hand with
  3220. // sequences already used by the link from which packets were
  3221. // copied to the backup buffer.
  3222. IF_HEAVY_LOGGING(int32_t old = core.schedSeqNo());
  3223. const bool su SRT_ATR_UNUSED = core.overrideSndSeqNo(curseq);
  3224. HLOGC(gslog.Debug,
  3225. log << "sendBackupRexmit: OVERRIDING seq %" << old << " with %" << curseq
  3226. << (su ? " - succeeded" : " - FAILED!"));
  3227. }
  3228. }
  3229. if (skip_initial >= m_SenderBuffer.size())
  3230. {
  3231. LOGC(gslog.Warn,
  3232. log << "sendBackupRexmit: All packets were skipped. Nothing to send %" << core.schedSeqNo() << ", trying to send from seqno %" << curseq
  3233. << " - DENIED; skip " << skip_initial << " packets");
  3234. return 0; // can't return any other state, nothing was sent
  3235. }
  3236. senderBuffer_t::iterator i = m_SenderBuffer.begin() + skip_initial;
  3237. // Send everything - including the packet freshly added to the buffer
  3238. for (; i != m_SenderBuffer.end(); ++i)
  3239. {
  3240. // NOTE: an exception from here will interrupt the loop
  3241. // and will be caught in the upper level.
  3242. stat = core.sendmsg2(i->data, (int)i->size, (i->mc));
  3243. if (stat == -1)
  3244. {
  3245. // Stop sending if one sending ended up with error
  3246. LOGC(gslog.Warn,
  3247. log << "sendBackupRexmit: sending from buffer stopped at %" << core.schedSeqNo() << " and FAILED");
  3248. return -1;
  3249. }
  3250. }
  3251. // Copy the contents of the last item being updated.
  3252. w_mc = m_SenderBuffer.back().mc;
  3253. HLOGC(gslog.Debug, log << "sendBackupRexmit: pre-sent collected %" << curseq << " - %" << w_mc.pktseq);
  3254. return stat;
  3255. }
  3256. // [[using locked(CUDTGroup::m_GroupLock)]];
  3257. void CUDTGroup::ackMessage(int32_t msgno)
  3258. {
  3259. // The message id could not be identified, skip.
  3260. if (msgno == SRT_MSGNO_CONTROL)
  3261. {
  3262. HLOGC(gslog.Debug, log << "ackMessage: msgno not found in ACK-ed sequence");
  3263. return;
  3264. }
  3265. // It's impossible to get the exact message position as the
  3266. // message is allowed also to span for multiple packets.
  3267. // Search since the oldest packet until you hit the first
  3268. // packet with this message number.
  3269. // First, you need to decrease the message number by 1. It's
  3270. // because the sequence number being ACK-ed can be in the middle
  3271. // of the message, while it doesn't acknowledge that the whole
  3272. // message has been received. Decrease the message number so that
  3273. // partial-message-acknowledgement does not swipe the whole message,
  3274. // part of which may need to be retransmitted over a backup link.
  3275. int offset = MsgNo(msgno) - MsgNo(m_iSndAckedMsgNo);
  3276. if (offset <= 0)
  3277. {
  3278. HLOGC(gslog.Debug, log << "ackMessage: already acked up to msgno=" << msgno);
  3279. return;
  3280. }
  3281. HLOGC(gslog.Debug, log << "ackMessage: updated to #" << msgno);
  3282. // Update last acked. Will be picked up when adding next message.
  3283. m_iSndAckedMsgNo = msgno;
  3284. }
  3285. void CUDTGroup::processKeepalive(CUDTGroup::SocketData* gli)
  3286. {
  3287. // received keepalive for that group member
  3288. // In backup group it means that the link went IDLE.
  3289. if (m_type == SRT_GTYPE_BACKUP)
  3290. {
  3291. if (gli->rcvstate == SRT_GST_RUNNING)
  3292. {
  3293. gli->rcvstate = SRT_GST_IDLE;
  3294. HLOGC(gslog.Debug, log << "GROUP: received KEEPALIVE in @" << gli->id << " - link turning rcv=IDLE");
  3295. }
  3296. // When received KEEPALIVE, the sending state should be also
  3297. // turned IDLE, if the link isn't temporarily activated. The
  3298. // temporarily activated link will not be measured stability anyway,
  3299. // while this should clear out the problem when the transmission is
  3300. // stopped and restarted after a while. This will simply set the current
  3301. // link as IDLE on the sender when the peer sends a keepalive because the
  3302. // data stopped coming in and it can't send ACKs therefore.
  3303. //
  3304. // This also shouldn't be done for the temporary activated links because
  3305. // stability timeout could be exceeded for them by a reason that, for example,
  3306. // the packets come with the past sequences (as they are being synchronized
  3307. // the sequence per being IDLE and empty buffer), so a large portion of initial
  3308. // series of packets may come with past sequence, delaying this way with ACK,
  3309. // which may result not only with exceeded stability timeout (which fortunately
  3310. // isn't being measured in this case), but also with receiveing keepalive
  3311. // (therefore we also don't reset the link to IDLE in the temporary activation period).
  3312. if (gli->sndstate == SRT_GST_RUNNING && is_zero(gli->ps->core().m_tsFreshActivation))
  3313. {
  3314. gli->sndstate = SRT_GST_IDLE;
  3315. HLOGC(gslog.Debug,
  3316. log << "GROUP: received KEEPALIVE in @" << gli->id << " active=PAST - link turning snd=IDLE");
  3317. }
  3318. }
  3319. }
  3320. void CUDTGroup::internalKeepalive(SocketData* gli)
  3321. {
  3322. // This is in response to AGENT SENDING keepalive. This means that there's
  3323. // no transmission in either direction, but the KEEPALIVE packet from the
  3324. // other party could have been missed. This is to ensure that the IDLE state
  3325. // is recognized early enough, before any sequence discrepancy can happen.
  3326. if (m_type == SRT_GTYPE_BACKUP && gli->rcvstate == SRT_GST_RUNNING)
  3327. {
  3328. gli->rcvstate = SRT_GST_IDLE;
  3329. // Prevent sending KEEPALIVE again in group-sending
  3330. gli->ps->core().m_tsFreshActivation = steady_clock::time_point();
  3331. HLOGC(gslog.Debug, log << "GROUP: EXP-requested KEEPALIVE in @" << gli->id << " - link turning IDLE");
  3332. }
  3333. }
  3334. CUDTGroup::BufferedMessageStorage CUDTGroup::BufferedMessage::storage(SRT_LIVE_MAX_PLSIZE /*, 1000*/);
  3335. // Forwarder needed due to class definition order
  3336. int32_t CUDTGroup::generateISN()
  3337. {
  3338. return CUDT::generateISN();
  3339. }
  3340. void CUDTGroup::setGroupConnected()
  3341. {
  3342. if (!m_bConnected)
  3343. {
  3344. // Switch to connected state and give appropriate signal
  3345. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_CONNECT, true);
  3346. m_bConnected = true;
  3347. }
  3348. }
  3349. void CUDTGroup::updateLatestRcv(CUDTSocket* s)
  3350. {
  3351. // Currently only Backup groups use connected idle links.
  3352. if (m_type != SRT_GTYPE_BACKUP)
  3353. return;
  3354. HLOGC(grlog.Debug,
  3355. log << "updateLatestRcv: BACKUP group, updating from active link @" << s->m_SocketID << " with %"
  3356. << s->core().m_iRcvLastAck);
  3357. CUDT* source = &s->core();
  3358. vector<CUDT*> targets;
  3359. UniqueLock lg(m_GroupLock);
  3360. // Sanity check for a case when getting a deleted socket
  3361. if (!s->m_GroupOf)
  3362. return;
  3363. // Under a group lock, we block execution of removal of the socket
  3364. // from the group, so if m_GroupOf is not NULL, we are granted
  3365. // that m_GroupMemberData is valid.
  3366. SocketData* current = s->m_GroupMemberData;
  3367. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi)
  3368. {
  3369. // Skip the socket that has reported packet reception
  3370. if (&*gi == current)
  3371. {
  3372. HLOGC(grlog.Debug, log << "grp: NOT updating rcv-seq on self @" << gi->id);
  3373. continue;
  3374. }
  3375. // Don't update the state if the link is:
  3376. // - PENDING - because it's not in the connected state, wait for it.
  3377. // - RUNNING - because in this case it should have its own line of sequences
  3378. // - BROKEN - because it doesn't make sense anymore, about to be removed
  3379. if (gi->rcvstate != SRT_GST_IDLE)
  3380. {
  3381. HLOGC(grlog.Debug,
  3382. log << "grp: NOT updating rcv-seq on @" << gi->id
  3383. << " - link state:" << srt_log_grp_state[gi->rcvstate]);
  3384. continue;
  3385. }
  3386. // Sanity check
  3387. if (!gi->ps->core().m_bConnected)
  3388. {
  3389. HLOGC(grlog.Debug, log << "grp: IPE: NOT updating rcv-seq on @" << gi->id << " - IDLE BUT NOT CONNECTED");
  3390. continue;
  3391. }
  3392. targets.push_back(&gi->ps->core());
  3393. }
  3394. lg.unlock();
  3395. // Do this on the unlocked group because this
  3396. // operation will need receiver lock, so it might
  3397. // risk a deadlock.
  3398. for (size_t i = 0; i < targets.size(); ++i)
  3399. {
  3400. targets[i]->updateIdleLinkFrom(source);
  3401. }
  3402. }
  3403. void CUDTGroup::activateUpdateEvent(bool still_have_items)
  3404. {
  3405. // This function actually reacts on the fact that a socket
  3406. // was deleted from the group. This might make the group empty.
  3407. if (!still_have_items) // empty, or removal of unknown socket attempted - set error on group
  3408. {
  3409. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN | SRT_EPOLL_OUT | SRT_EPOLL_ERR, true);
  3410. }
  3411. else
  3412. {
  3413. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_UPDATE, true);
  3414. }
  3415. }
  3416. void CUDTGroup::addEPoll(int eid)
  3417. {
  3418. enterCS(m_Global.m_EPoll.m_EPollLock);
  3419. m_sPollID.insert(eid);
  3420. leaveCS(m_Global.m_EPoll.m_EPollLock);
  3421. bool any_read = false;
  3422. bool any_write = false;
  3423. bool any_broken = false;
  3424. bool any_pending = false;
  3425. {
  3426. // Check all member sockets
  3427. ScopedLock gl(m_GroupLock);
  3428. // We only need to know if there is any socket that is
  3429. // ready to get a payload and ready to receive from.
  3430. for (gli_t i = m_Group.begin(); i != m_Group.end(); ++i)
  3431. {
  3432. if (i->sndstate == SRT_GST_IDLE || i->sndstate == SRT_GST_RUNNING)
  3433. {
  3434. any_write |= i->ps->writeReady();
  3435. }
  3436. if (i->rcvstate == SRT_GST_IDLE || i->rcvstate == SRT_GST_RUNNING)
  3437. {
  3438. any_read |= i->ps->readReady();
  3439. }
  3440. if (i->ps->broken())
  3441. any_broken |= true;
  3442. else
  3443. any_pending |= true;
  3444. }
  3445. }
  3446. // This is stupid, but we don't have any other interface to epoll
  3447. // internals. Actually we don't have to check if id() is in m_sPollID
  3448. // because we know it is, as we just added it. But it's not performance
  3449. // critical, sockets are not being often added during transmission.
  3450. if (any_read)
  3451. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, true);
  3452. if (any_write)
  3453. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, true);
  3454. // Set broken if none is non-broken (pending, read-ready or write-ready)
  3455. if (any_broken && !any_pending)
  3456. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true);
  3457. }
  3458. void CUDTGroup::removeEPollEvents(const int eid)
  3459. {
  3460. // clear IO events notifications;
  3461. // since this happens after the epoll ID has been removed, they cannot be set again
  3462. set<int> remove;
  3463. remove.insert(eid);
  3464. m_Global.m_EPoll.update_events(id(), remove, SRT_EPOLL_IN | SRT_EPOLL_OUT, false);
  3465. }
  3466. void CUDTGroup::removeEPollID(const int eid)
  3467. {
  3468. enterCS(m_Global.m_EPoll.m_EPollLock);
  3469. m_sPollID.erase(eid);
  3470. leaveCS(m_Global.m_EPoll.m_EPollLock);
  3471. }
  3472. void CUDTGroup::updateFailedLink()
  3473. {
  3474. ScopedLock lg(m_GroupLock);
  3475. // Check all members if they are in the pending
  3476. // or connected state.
  3477. int nhealthy = 0;
  3478. for (gli_t i = m_Group.begin(); i != m_Group.end(); ++i)
  3479. {
  3480. if (i->sndstate < SRT_GST_BROKEN)
  3481. nhealthy++;
  3482. }
  3483. if (!nhealthy)
  3484. {
  3485. // No healthy links, set ERR on epoll.
  3486. HLOGC(gmlog.Debug, log << "group/updateFailedLink: All sockets broken");
  3487. m_Global.m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN | SRT_EPOLL_OUT | SRT_EPOLL_ERR, true);
  3488. }
  3489. else
  3490. {
  3491. HLOGC(gmlog.Debug, log << "group/updateFailedLink: Still " << nhealthy << " links in the group");
  3492. }
  3493. }
  3494. #if ENABLE_HEAVY_LOGGING
  3495. // [[using maybe_locked(CUDT::uglobal()->m_GlobControlLock)]]
  3496. void CUDTGroup::debugGroup()
  3497. {
  3498. ScopedLock gg(m_GroupLock);
  3499. HLOGC(gmlog.Debug, log << "GROUP MEMBER STATUS - $" << id());
  3500. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi)
  3501. {
  3502. HLOGC(gmlog.Debug,
  3503. log << " ... id { agent=@" << gi->id << " peer=@" << gi->ps->m_PeerID
  3504. << " } address { agent=" << gi->agent.str() << " peer=" << gi->peer.str() << "} "
  3505. << " state {snd=" << StateStr(gi->sndstate) << " rcv=" << StateStr(gi->rcvstate) << "}");
  3506. }
  3507. }
  3508. #endif
  3509. } // namespace srt