main.c 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426
  1. /*
  2. * Copyright 2011 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 2 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <curses.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <stdbool.h>
  16. #include <stdint.h>
  17. #include <unistd.h>
  18. #include <sys/time.h>
  19. #include <time.h>
  20. #include <math.h>
  21. #include <stdarg.h>
  22. #include <assert.h>
  23. #include <signal.h>
  24. #ifndef WIN32
  25. #include <sys/resource.h>
  26. #endif
  27. #include <ccan/opt/opt.h>
  28. #include <jansson.h>
  29. #include <curl/curl.h>
  30. #include <libgen.h>
  31. #include "compat.h"
  32. #include "miner.h"
  33. #include "findnonce.h"
  34. #include "bench_block.h"
  35. #include "ocl.h"
  36. #include "uthash.h"
  37. #include "adl.h"
  38. #if defined(unix)
  39. #include <errno.h>
  40. #include <fcntl.h>
  41. #include <unistd.h>
  42. #include <sys/wait.h>
  43. #include <sys/types.h>
  44. #endif
  45. #ifdef __linux /* Linux specific policy and affinity management */
  46. #include <sched.h>
  47. static inline void drop_policy(void)
  48. {
  49. struct sched_param param;
  50. #ifdef SCHED_BATCH
  51. #ifdef SCHED_IDLE
  52. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  53. #endif
  54. sched_setscheduler(0, SCHED_BATCH, &param);
  55. #endif
  56. }
  57. static inline void affine_to_cpu(int id, int cpu)
  58. {
  59. cpu_set_t set;
  60. CPU_ZERO(&set);
  61. CPU_SET(cpu, &set);
  62. sched_setaffinity(0, sizeof(&set), &set);
  63. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  64. }
  65. #else
  66. static inline void drop_policy(void)
  67. {
  68. }
  69. static inline void affine_to_cpu(int id, int cpu)
  70. {
  71. }
  72. #endif
  73. enum workio_commands {
  74. WC_GET_WORK,
  75. WC_SUBMIT_WORK,
  76. WC_DIE,
  77. };
  78. struct workio_cmd {
  79. enum workio_commands cmd;
  80. struct thr_info *thr;
  81. union {
  82. struct work *work;
  83. } u;
  84. bool lagging;
  85. };
  86. enum sha256_algos {
  87. ALGO_C, /* plain C */
  88. ALGO_4WAY, /* parallel SSE2 */
  89. ALGO_VIA, /* VIA padlock */
  90. ALGO_CRYPTOPP, /* Crypto++ (C) */
  91. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  92. ALGO_SSE2_32, /* SSE2 for x86_32 */
  93. ALGO_SSE2_64, /* SSE2 for x86_64 */
  94. ALGO_SSE4_64, /* SSE4 for x86_64 */
  95. };
  96. enum pool_strategy {
  97. POOL_FAILOVER,
  98. POOL_ROUNDROBIN,
  99. POOL_ROTATE,
  100. POOL_LOADBALANCE,
  101. };
  102. #define TOP_STRATEGY (POOL_LOADBALANCE)
  103. struct strategies {
  104. const char *s;
  105. } strategies[] = {
  106. { "Failover" },
  107. { "Round Robin" },
  108. { "Rotate" },
  109. { "Load Balance" },
  110. };
  111. static size_t max_name_len = 0;
  112. static char *name_spaces_pad = NULL;
  113. static const char *algo_names[] = {
  114. [ALGO_C] = "c",
  115. #ifdef WANT_SSE2_4WAY
  116. [ALGO_4WAY] = "4way",
  117. #endif
  118. #ifdef WANT_VIA_PADLOCK
  119. [ALGO_VIA] = "via",
  120. #endif
  121. [ALGO_CRYPTOPP] = "cryptopp",
  122. #ifdef WANT_CRYPTOPP_ASM32
  123. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  124. #endif
  125. #ifdef WANT_X8632_SSE2
  126. [ALGO_SSE2_32] = "sse2_32",
  127. #endif
  128. #ifdef WANT_X8664_SSE2
  129. [ALGO_SSE2_64] = "sse2_64",
  130. #endif
  131. #ifdef WANT_X8664_SSE4
  132. [ALGO_SSE4_64] = "sse4_64",
  133. #endif
  134. };
  135. typedef void (*sha256_func)();
  136. static const sha256_func sha256_funcs[] = {
  137. [ALGO_C] = (sha256_func)scanhash_c,
  138. #ifdef WANT_SSE2_4WAY
  139. [ALGO_4WAY] = (sha256_func)ScanHash_4WaySSE2,
  140. #endif
  141. #ifdef WANT_VIA_PADLOCK
  142. [ALGO_VIA] = (sha256_func)scanhash_via,
  143. #endif
  144. [ALGO_CRYPTOPP] = (sha256_func)scanhash_cryptopp,
  145. #ifdef WANT_CRYPTOPP_ASM32
  146. [ALGO_CRYPTOPP_ASM32] = (sha256_func)scanhash_asm32,
  147. #endif
  148. #ifdef WANT_X8632_SSE2
  149. [ALGO_SSE2_32] = (sha256_func)scanhash_sse2_32,
  150. #endif
  151. #ifdef WANT_X8664_SSE2
  152. [ALGO_SSE2_64] = (sha256_func)scanhash_sse2_64,
  153. #endif
  154. #ifdef WANT_X8664_SSE4
  155. [ALGO_SSE4_64] = (sha256_func)scanhash_sse4_64
  156. #endif
  157. };
  158. static char packagename[255];
  159. bool opt_debug = false;
  160. bool opt_protocol = false;
  161. static bool want_longpoll = true;
  162. static bool have_longpoll = false;
  163. static bool want_per_device_stats = false;
  164. bool use_syslog = false;
  165. static bool opt_quiet = false;
  166. static bool opt_realquiet = false;
  167. static bool opt_loginput = false;
  168. static int opt_retries = -1;
  169. static int opt_fail_pause = 5;
  170. static int fail_pause = 5;
  171. static int opt_log_interval = 5;
  172. bool opt_log_output = false;
  173. static bool opt_dynamic = true;
  174. static int opt_queue = 1;
  175. int opt_vectors;
  176. int opt_worksize;
  177. int opt_scantime = 60;
  178. int opt_bench_algo = -1;
  179. static const bool opt_time = true;
  180. static bool opt_restart = true;
  181. #if defined(WANT_X8664_SSE2) && defined(__SSE2__)
  182. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  183. #elif defined(WANT_X8632_SSE2) && defined(__SSE2__)
  184. static enum sha256_algos opt_algo = ALGO_SSE2_32;
  185. #else
  186. static enum sha256_algos opt_algo = ALGO_C;
  187. #endif
  188. static int nDevs;
  189. static int opt_g_threads = 2;
  190. static int opt_device;
  191. static int total_devices;
  192. static bool gpu_devices[16];
  193. static int gpu_threads;
  194. static bool forced_n_threads;
  195. static int opt_n_threads;
  196. static int mining_threads;
  197. static int num_processors;
  198. static int scan_intensity;
  199. static bool use_curses = true;
  200. static bool opt_submit_stale;
  201. static bool opt_nogpu;
  202. static bool opt_usecpu;
  203. static int opt_shares;
  204. static bool opt_fail_only;
  205. bool opt_autofan;
  206. bool opt_autoengine;
  207. char *opt_kernel_path;
  208. char *cgminer_path;
  209. #define QUIET (opt_quiet || opt_realquiet)
  210. struct thr_info *thr_info;
  211. static int work_thr_id;
  212. int longpoll_thr_id;
  213. static int stage_thr_id;
  214. static int watchdog_thr_id;
  215. static int input_thr_id;
  216. static int gpur_thr_id;
  217. static int cpur_thr_id;
  218. static int total_threads;
  219. struct work_restart *work_restart = NULL;
  220. static pthread_mutex_t hash_lock;
  221. static pthread_mutex_t qd_lock;
  222. static pthread_mutex_t stgd_lock;
  223. static pthread_mutex_t curses_lock;
  224. static pthread_rwlock_t blk_lock;
  225. static double total_mhashes_done;
  226. static struct timeval total_tv_start, total_tv_end;
  227. pthread_mutex_t control_lock;
  228. int hw_errors;
  229. static int total_accepted, total_rejected;
  230. static int total_getworks, total_stale, total_discarded;
  231. static int total_queued;
  232. static unsigned int new_blocks;
  233. enum block_change {
  234. BLOCK_NONE,
  235. BLOCK_LP,
  236. BLOCK_DETECT,
  237. BLOCK_FIRST,
  238. };
  239. static enum block_change block_changed = BLOCK_FIRST;
  240. static unsigned int local_work;
  241. static unsigned int total_go, total_ro;
  242. #define MAX_POOLS (32)
  243. static struct pool *pools[MAX_POOLS];
  244. static struct pool *currentpool = NULL;
  245. static int total_pools;
  246. static enum pool_strategy pool_strategy = POOL_FAILOVER;
  247. static int opt_rotate_period;
  248. static int total_urls, total_users, total_passes, total_userpasses;
  249. static bool curses_active = false;
  250. static char current_block[37];
  251. static char *current_hash;
  252. static char datestamp[40];
  253. static char blocktime[30];
  254. struct block {
  255. char hash[37];
  256. UT_hash_handle hh;
  257. };
  258. static struct block *blocks = NULL;
  259. static char *opt_kernel = NULL;
  260. #if defined(unix)
  261. static char *opt_stderr_cmd = NULL;
  262. #endif // defined(unix)
  263. enum cl_kernel chosen_kernel;
  264. static bool ping = true;
  265. struct sigaction termhandler, inthandler;
  266. struct thread_q *getq;
  267. static int total_work;
  268. struct work *staged_work = NULL;
  269. static int staged_clones;
  270. struct schedtime {
  271. bool enable;
  272. struct tm tm;
  273. };
  274. struct schedtime schedstart;
  275. struct schedtime schedstop;
  276. bool sched_paused;
  277. static bool time_before(struct tm *tm1, struct tm *tm2)
  278. {
  279. if (tm1->tm_hour < tm2->tm_hour)
  280. return true;
  281. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  282. return true;
  283. return false;
  284. }
  285. static bool should_run(void)
  286. {
  287. struct timeval tv;
  288. struct tm tm;
  289. if (!schedstart.enable && !schedstop.enable)
  290. return true;
  291. gettimeofday(&tv, NULL);
  292. localtime_r(&tv.tv_sec, &tm);
  293. if (schedstart.enable) {
  294. if (!schedstop.enable) {
  295. if (time_before(&tm, &schedstart.tm))
  296. return false;
  297. /* This is a once off event with no stop time set */
  298. schedstart.enable = false;
  299. return true;
  300. }
  301. if (time_before(&schedstart.tm, &schedstop.tm)) {
  302. if (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm))
  303. return true;
  304. return false;
  305. } /* Times are reversed */
  306. if (time_before(&tm, &schedstart.tm)) {
  307. if (time_before(&tm, &schedstop.tm))
  308. return true;
  309. return false;
  310. }
  311. return true;
  312. }
  313. /* only schedstop.enable == true */
  314. if (!time_before(&tm, &schedstop.tm))
  315. return false;
  316. return true;
  317. }
  318. void get_datestamp(char *f, struct timeval *tv)
  319. {
  320. struct tm tm;
  321. localtime_r(&tv->tv_sec, &tm);
  322. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  323. tm.tm_year + 1900,
  324. tm.tm_mon + 1,
  325. tm.tm_mday,
  326. tm.tm_hour,
  327. tm.tm_min,
  328. tm.tm_sec);
  329. }
  330. void get_timestamp(char *f, struct timeval *tv)
  331. {
  332. struct tm tm;
  333. localtime_r(&tv->tv_sec, &tm);
  334. sprintf(f, "[%02d:%02d:%02d]",
  335. tm.tm_hour,
  336. tm.tm_min,
  337. tm.tm_sec);
  338. }
  339. static void applog_and_exit(const char *fmt, ...)
  340. {
  341. va_list ap;
  342. va_start(ap, fmt);
  343. vapplog(LOG_ERR, fmt, ap);
  344. va_end(ap);
  345. exit(1);
  346. }
  347. static void add_pool(void)
  348. {
  349. struct pool *pool;
  350. pool = calloc(sizeof(struct pool), 1);
  351. if (!pool) {
  352. applog(LOG_ERR, "Failed to malloc pool in add_pool");
  353. exit (1);
  354. }
  355. pool->pool_no = pool->prio = total_pools;
  356. pools[total_pools++] = pool;
  357. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL))) {
  358. applog(LOG_ERR, "Failed to pthread_mutex_init in add_pool");
  359. exit (1);
  360. }
  361. /* Make sure the pool doesn't think we've been idle since time 0 */
  362. pool->tv_idle.tv_sec = ~0UL;
  363. }
  364. /* Pool variant of test and set */
  365. static bool pool_tset(struct pool *pool, bool *var)
  366. {
  367. bool ret;
  368. mutex_lock(&pool->pool_lock);
  369. ret = *var;
  370. *var = true;
  371. mutex_unlock(&pool->pool_lock);
  372. return ret;
  373. }
  374. static bool pool_tclear(struct pool *pool, bool *var)
  375. {
  376. bool ret;
  377. mutex_lock(&pool->pool_lock);
  378. ret = *var;
  379. *var = false;
  380. mutex_unlock(&pool->pool_lock);
  381. return ret;
  382. }
  383. static struct pool *current_pool(void)
  384. {
  385. struct pool *pool;
  386. mutex_lock(&control_lock);
  387. pool = currentpool;
  388. mutex_unlock(&control_lock);
  389. return pool;
  390. }
  391. // Algo benchmark, crash-prone, system independent stage
  392. static double bench_algo_stage3(
  393. enum sha256_algos algo
  394. )
  395. {
  396. // Use a random work block pulled from a pool
  397. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  398. struct work work __attribute__((aligned(128)));
  399. size_t bench_size = sizeof(work);
  400. size_t work_size = sizeof(bench_block);
  401. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  402. memset(&work, 0, sizeof(work));
  403. memcpy(&work, &bench_block, min_size);
  404. struct work_restart dummy;
  405. work_restart = &dummy;
  406. struct timeval end;
  407. struct timeval start;
  408. uint32_t max_nonce = (1<<22);
  409. unsigned long hashes_done = 0;
  410. gettimeofday(&start, 0);
  411. #if defined(WANT_VIA_PADLOCK)
  412. // For some reason, the VIA padlock hasher has a different API ...
  413. if (ALGO_VIA==algo) {
  414. (void)scanhash_via(
  415. 0,
  416. work.data,
  417. work.target,
  418. max_nonce,
  419. &hashes_done,
  420. work.blk.nonce
  421. );
  422. } else
  423. #endif
  424. {
  425. sha256_func func = sha256_funcs[algo];
  426. (*func)(
  427. 0,
  428. work.midstate,
  429. work.data + 64,
  430. work.hash1,
  431. work.hash,
  432. work.target,
  433. max_nonce,
  434. &hashes_done,
  435. work.blk.nonce
  436. );
  437. }
  438. gettimeofday(&end, 0);
  439. work_restart = NULL;
  440. uint64_t usec_end = ((uint64_t)end.tv_sec)*1000*1000 + end.tv_usec;
  441. uint64_t usec_start = ((uint64_t)start.tv_sec)*1000*1000 + start.tv_usec;
  442. uint64_t usec_elapsed = usec_end - usec_start;
  443. double rate = -1.0;
  444. if (0<usec_elapsed) {
  445. rate = (1.0*hashes_done)/usec_elapsed;
  446. }
  447. return rate;
  448. }
  449. #if defined(unix)
  450. // Change non-blocking status on a file descriptor
  451. static void set_non_blocking(
  452. int fd,
  453. int yes
  454. )
  455. {
  456. int flags = fcntl(fd, F_GETFL, 0);
  457. if (flags<0) {
  458. perror("fcntl(GET) failed");
  459. exit(1);
  460. }
  461. flags = yes ? (flags|O_NONBLOCK) : (flags&~O_NONBLOCK);
  462. int r = fcntl(fd, F_SETFL, flags);
  463. if (r<0) {
  464. perror("fcntl(SET) failed");
  465. exit(1);
  466. }
  467. }
  468. #endif // defined(unix)
  469. // Algo benchmark, crash-safe, system-dependent stage
  470. static double bench_algo_stage2(
  471. enum sha256_algos algo
  472. )
  473. {
  474. // Here, the gig is to safely run a piece of code that potentially
  475. // crashes. Unfortunately, the Right Way (tm) to do this is rather
  476. // heavily platform dependent :(
  477. double rate = -1.23457;
  478. #if defined(unix)
  479. // Make a pipe: [readFD, writeFD]
  480. int pfd[2];
  481. int r = pipe(pfd);
  482. if (r<0) {
  483. perror("pipe - failed to create pipe for --algo auto");
  484. exit(1);
  485. }
  486. // Make pipe non blocking
  487. set_non_blocking(pfd[0], 1);
  488. set_non_blocking(pfd[1], 1);
  489. // Don't allow a crashing child to kill the main process
  490. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  491. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  492. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  493. perror("signal - failed to edit signal mask for --algo auto");
  494. exit(1);
  495. }
  496. // Fork a child to do the actual benchmarking
  497. pid_t child_pid = fork();
  498. if (child_pid<0) {
  499. perror("fork - failed to create a child process for --algo auto");
  500. exit(1);
  501. }
  502. // Do the dangerous work in the child, knowing we might crash
  503. if (0==child_pid) {
  504. // TODO: some umask trickery to prevent coredumps
  505. // Benchmark this algorithm
  506. double r = bench_algo_stage3(algo);
  507. // We survived, send result to parent and bail
  508. int loop_count = 0;
  509. while (1) {
  510. ssize_t bytes_written = write(pfd[1], &r, sizeof(r));
  511. int try_again = (0==bytes_written || (bytes_written<0 && EAGAIN==errno));
  512. int success = (sizeof(r)==(size_t)bytes_written);
  513. if (success)
  514. break;
  515. if (!try_again) {
  516. perror("write - child failed to write benchmark result to pipe");
  517. exit(1);
  518. }
  519. if (5<loop_count) {
  520. applog(LOG_ERR, "child tried %d times to communicate with parent, giving up", loop_count);
  521. exit(1);
  522. }
  523. ++loop_count;
  524. sleep(1);
  525. }
  526. exit(0);
  527. }
  528. // Parent waits for a result from child
  529. int loop_count = 0;
  530. while (1) {
  531. // Wait for child to die
  532. int status;
  533. int r = waitpid(child_pid, &status, WNOHANG);
  534. if ((child_pid==r) || (r<0 && ECHILD==errno)) {
  535. // Child died somehow. Grab result and bail
  536. double tmp;
  537. ssize_t bytes_read = read(pfd[0], &tmp, sizeof(tmp));
  538. if (sizeof(tmp)==(size_t)bytes_read)
  539. rate = tmp;
  540. break;
  541. } else if (r<0) {
  542. perror("bench_algo: waitpid failed. giving up.");
  543. exit(1);
  544. }
  545. // Give up on child after a ~60s
  546. if (60<loop_count) {
  547. kill(child_pid, SIGKILL);
  548. waitpid(child_pid, &status, 0);
  549. break;
  550. }
  551. // Wait a bit longer
  552. ++loop_count;
  553. sleep(1);
  554. }
  555. // Close pipe
  556. r = close(pfd[0]);
  557. if (r<0) {
  558. perror("close - failed to close read end of pipe for --algo auto");
  559. exit(1);
  560. }
  561. r = close(pfd[1]);
  562. if (r<0) {
  563. perror("close - failed to close read end of pipe for --algo auto");
  564. exit(1);
  565. }
  566. #elif defined(WIN32)
  567. // Get handle to current exe
  568. HINSTANCE module = GetModuleHandle(0);
  569. if (!module) {
  570. applog(LOG_ERR, "failed to retrieve module handle");
  571. exit(1);
  572. }
  573. // Create a unique name
  574. char unique_name[32];
  575. snprintf(
  576. unique_name,
  577. sizeof(unique_name)-1,
  578. "cgminer-%p",
  579. (void*)module
  580. );
  581. // Create and init a chunked of shared memory
  582. HANDLE map_handle = CreateFileMapping(
  583. INVALID_HANDLE_VALUE, // use paging file
  584. NULL, // default security attributes
  585. PAGE_READWRITE, // read/write access
  586. 0, // size: high 32-bits
  587. 4096, // size: low 32-bits
  588. unique_name // name of map object
  589. );
  590. if (NULL==map_handle) {
  591. applog(LOG_ERR, "could not create shared memory");
  592. exit(1);
  593. }
  594. void *shared_mem = MapViewOfFile(
  595. map_handle, // object to map view of
  596. FILE_MAP_WRITE, // read/write access
  597. 0, // high offset: map from
  598. 0, // low offset: beginning
  599. 0 // default: map entire file
  600. );
  601. if (NULL==shared_mem) {
  602. applog(LOG_ERR, "could not map shared memory");
  603. exit(1);
  604. }
  605. SetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name);
  606. CopyMemory(shared_mem, &rate, sizeof(rate));
  607. // Get path to current exe
  608. char cmd_line[256 + MAX_PATH];
  609. const size_t n = sizeof(cmd_line)-200;
  610. DWORD size = GetModuleFileName(module, cmd_line, n);
  611. if (0==size) {
  612. applog(LOG_ERR, "failed to retrieve module path");
  613. exit(1);
  614. }
  615. // Construct new command line based on that
  616. char *p = strlen(cmd_line) + cmd_line;
  617. sprintf(p, " --bench-algo %d", algo);
  618. SetEnvironmentVariable("CGMINER_BENCH_ALGO", "1");
  619. // Launch a debug copy of cgminer
  620. STARTUPINFO startup_info;
  621. PROCESS_INFORMATION process_info;
  622. ZeroMemory(&startup_info, sizeof(startup_info));
  623. ZeroMemory(&process_info, sizeof(process_info));
  624. startup_info.cb = sizeof(startup_info);
  625. BOOL ok = CreateProcess(
  626. NULL, // No module name (use command line)
  627. cmd_line, // Command line
  628. NULL, // Process handle not inheritable
  629. NULL, // Thread handle not inheritable
  630. FALSE, // Set handle inheritance to FALSE
  631. DEBUG_ONLY_THIS_PROCESS,// We're going to debug the child
  632. NULL, // Use parent's environment block
  633. NULL, // Use parent's starting directory
  634. &startup_info, // Pointer to STARTUPINFO structure
  635. &process_info // Pointer to PROCESS_INFORMATION structure
  636. );
  637. if (!ok) {
  638. applog(LOG_ERR, "CreateProcess failed with error %d\n", GetLastError() );
  639. exit(1);
  640. }
  641. // Debug the child (only clean way to catch exceptions)
  642. while (1) {
  643. // Wait for child to do something
  644. DEBUG_EVENT debug_event;
  645. ZeroMemory(&debug_event, sizeof(debug_event));
  646. BOOL ok = WaitForDebugEvent(&debug_event, 60 * 1000);
  647. if (!ok)
  648. break;
  649. // Decide if event is "normal"
  650. int go_on =
  651. CREATE_PROCESS_DEBUG_EVENT== debug_event.dwDebugEventCode ||
  652. CREATE_THREAD_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  653. EXIT_THREAD_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  654. EXCEPTION_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  655. LOAD_DLL_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  656. OUTPUT_DEBUG_STRING_EVENT == debug_event.dwDebugEventCode ||
  657. UNLOAD_DLL_DEBUG_EVENT == debug_event.dwDebugEventCode;
  658. if (!go_on)
  659. break;
  660. // Some exceptions are also "normal", apparently.
  661. if (EXCEPTION_DEBUG_EVENT== debug_event.dwDebugEventCode) {
  662. int go_on =
  663. EXCEPTION_BREAKPOINT== debug_event.u.Exception.ExceptionRecord.ExceptionCode;
  664. if (!go_on)
  665. break;
  666. }
  667. // If nothing unexpected happened, let child proceed
  668. ContinueDebugEvent(
  669. debug_event.dwProcessId,
  670. debug_event.dwThreadId,
  671. DBG_CONTINUE
  672. );
  673. }
  674. // Clean up child process
  675. TerminateProcess(process_info.hProcess, 1);
  676. CloseHandle(process_info.hProcess);
  677. CloseHandle(process_info.hThread);
  678. // Reap return value and cleanup
  679. CopyMemory(&rate, shared_mem, sizeof(rate));
  680. (void)UnmapViewOfFile(shared_mem);
  681. (void)CloseHandle(map_handle);
  682. #else
  683. // Not linux, not unix, not WIN32 ... do our best
  684. rate = bench_algo_stage3(algo);
  685. #endif // defined(unix)
  686. // Done
  687. return rate;
  688. }
  689. static void bench_algo(
  690. double *best_rate,
  691. enum sha256_algos *best_algo,
  692. enum sha256_algos algo
  693. )
  694. {
  695. size_t n = max_name_len - strlen(algo_names[algo]);
  696. memset(name_spaces_pad, ' ', n);
  697. name_spaces_pad[n] = 0;
  698. applog(
  699. LOG_ERR,
  700. "\"%s\"%s : benchmarking algorithm ...",
  701. algo_names[algo],
  702. name_spaces_pad
  703. );
  704. double rate = bench_algo_stage2(algo);
  705. if (rate<0.0) {
  706. applog(
  707. LOG_ERR,
  708. "\"%s\"%s : algorithm fails on this platform",
  709. algo_names[algo],
  710. name_spaces_pad
  711. );
  712. } else {
  713. applog(
  714. LOG_ERR,
  715. "\"%s\"%s : algorithm runs at %.5f MH/s",
  716. algo_names[algo],
  717. name_spaces_pad,
  718. rate
  719. );
  720. if (*best_rate<rate) {
  721. *best_rate = rate;
  722. *best_algo = algo;
  723. }
  724. }
  725. }
  726. // Figure out the longest algorithm name
  727. static void init_max_name_len()
  728. {
  729. size_t i;
  730. size_t nb_names = sizeof(algo_names)/sizeof(algo_names[0]);
  731. for (i=0; i<nb_names; ++i) {
  732. const char *p = algo_names[i];
  733. size_t name_len = p ? strlen(p) : 0;
  734. if (max_name_len<name_len)
  735. max_name_len = name_len;
  736. }
  737. name_spaces_pad = (char*) malloc(max_name_len+16);
  738. if (0==name_spaces_pad) {
  739. perror("malloc failed");
  740. exit(1);
  741. }
  742. }
  743. // Pick the fastest CPU hasher
  744. static enum sha256_algos pick_fastest_algo()
  745. {
  746. double best_rate = -1.0;
  747. enum sha256_algos best_algo = 0;
  748. applog(LOG_ERR, "benchmarking all sha256 algorithms ...");
  749. bench_algo(&best_rate, &best_algo, ALGO_C);
  750. #if defined(WANT_SSE2_4WAY)
  751. bench_algo(&best_rate, &best_algo, ALGO_4WAY);
  752. #endif
  753. #if defined(WANT_VIA_PADLOCK)
  754. bench_algo(&best_rate, &best_algo, ALGO_VIA);
  755. #endif
  756. bench_algo(&best_rate, &best_algo, ALGO_CRYPTOPP);
  757. #if defined(WANT_CRYPTOPP_ASM32)
  758. bench_algo(&best_rate, &best_algo, ALGO_CRYPTOPP_ASM32);
  759. #endif
  760. #if defined(WANT_X8632_SSE2)
  761. bench_algo(&best_rate, &best_algo, ALGO_SSE2_32);
  762. #endif
  763. #if defined(WANT_X8664_SSE2)
  764. bench_algo(&best_rate, &best_algo, ALGO_SSE2_64);
  765. #endif
  766. #if defined(WANT_X8664_SSE4)
  767. bench_algo(&best_rate, &best_algo, ALGO_SSE4_64);
  768. #endif
  769. size_t n = max_name_len - strlen(algo_names[best_algo]);
  770. memset(name_spaces_pad, ' ', n);
  771. name_spaces_pad[n] = 0;
  772. applog(
  773. LOG_ERR,
  774. "\"%s\"%s : is fastest algorithm at %.5f MH/s",
  775. algo_names[best_algo],
  776. name_spaces_pad,
  777. best_rate
  778. );
  779. return best_algo;
  780. }
  781. /* FIXME: Use asprintf for better errors. */
  782. static char *set_algo(const char *arg, enum sha256_algos *algo)
  783. {
  784. enum sha256_algos i;
  785. if (!strcmp(arg, "auto")) {
  786. *algo = pick_fastest_algo();
  787. return NULL;
  788. }
  789. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  790. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  791. *algo = i;
  792. return NULL;
  793. }
  794. }
  795. return "Unknown algorithm";
  796. }
  797. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  798. {
  799. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  800. }
  801. static char *set_int_range(const char *arg, int *i, int min, int max)
  802. {
  803. char *err = opt_set_intval(arg, i);
  804. if (err)
  805. return err;
  806. if (*i < min || *i > max)
  807. return "Value out of range";
  808. return NULL;
  809. }
  810. static char *set_int_0_to_9999(const char *arg, int *i)
  811. {
  812. return set_int_range(arg, i, 0, 9999);
  813. }
  814. static char *forced_int_1010(const char *arg, int *i)
  815. {
  816. opt_dynamic = false;
  817. return set_int_range(arg, i, -10, 10);
  818. }
  819. static char *force_nthreads_int(const char *arg, int *i)
  820. {
  821. forced_n_threads = true;
  822. return set_int_range(arg, i, 0, 9999);
  823. }
  824. static char *set_int_0_to_10(const char *arg, int *i)
  825. {
  826. return set_int_range(arg, i, 0, 10);
  827. }
  828. static char *set_int_0_to_100(const char *arg, int *i)
  829. {
  830. return set_int_range(arg, i, 0, 100);
  831. }
  832. static char *set_int_1_to_10(const char *arg, int *i)
  833. {
  834. return set_int_range(arg, i, 1, 10);
  835. }
  836. static char *set_devices(const char *arg, int *i)
  837. {
  838. char *err = opt_set_intval(arg, i);
  839. if (err)
  840. return err;
  841. if (*i < 0 || *i > 15)
  842. return "Invalid GPU device number";
  843. total_devices++;
  844. gpu_devices[*i] = true;
  845. return NULL;
  846. }
  847. static char *set_loadbalance(enum pool_strategy *strategy)
  848. {
  849. *strategy = POOL_LOADBALANCE;
  850. return NULL;
  851. }
  852. static char *set_rotate(const char *arg, int *i)
  853. {
  854. pool_strategy = POOL_ROTATE;
  855. return set_int_range(arg, i, 0, 9999);
  856. }
  857. static char *set_rr(enum pool_strategy *strategy)
  858. {
  859. *strategy = POOL_ROUNDROBIN;
  860. return NULL;
  861. }
  862. static char *set_url(char *arg)
  863. {
  864. struct pool *pool;
  865. total_urls++;
  866. if (total_urls > total_pools)
  867. add_pool();
  868. pool = pools[total_urls - 1];
  869. opt_set_charp(arg, &pool->rpc_url);
  870. if (strncmp(arg, "http://", 7) &&
  871. strncmp(arg, "https://", 8)) {
  872. char *httpinput;
  873. httpinput = malloc(255);
  874. if (!httpinput)
  875. quit(1, "Failed to malloc httpinput");
  876. strcpy(httpinput, "http://");
  877. strncat(httpinput, arg, 248);
  878. pool->rpc_url = httpinput;
  879. }
  880. return NULL;
  881. }
  882. static char *set_user(const char *arg)
  883. {
  884. struct pool *pool;
  885. if (total_userpasses)
  886. return "Use only user + pass or userpass, but not both";
  887. total_users++;
  888. if (total_users > total_pools)
  889. add_pool();
  890. pool = pools[total_users - 1];
  891. opt_set_charp(arg, &pool->rpc_user);
  892. return NULL;
  893. }
  894. static char *set_pass(const char *arg)
  895. {
  896. struct pool *pool;
  897. if (total_userpasses)
  898. return "Use only user + pass or userpass, but not both";
  899. total_passes++;
  900. if (total_passes > total_pools)
  901. add_pool();
  902. pool = pools[total_passes - 1];
  903. opt_set_charp(arg, &pool->rpc_pass);
  904. return NULL;
  905. }
  906. static char *set_userpass(const char *arg)
  907. {
  908. struct pool *pool;
  909. if (total_users || total_passes)
  910. return "Use only user + pass or userpass, but not both";
  911. total_userpasses++;
  912. if (total_userpasses > total_pools)
  913. add_pool();
  914. pool = pools[total_userpasses - 1];
  915. opt_set_charp(arg, &pool->rpc_userpass);
  916. return NULL;
  917. }
  918. static char *set_vector(const char *arg, int *i)
  919. {
  920. char *err = opt_set_intval(arg, i);
  921. if (err)
  922. return err;
  923. if (*i != 1 && *i != 2 && *i != 4)
  924. return "Valid vectors are 1, 2 or 4";
  925. return NULL;
  926. }
  927. static char *enable_debug(bool *flag)
  928. {
  929. *flag = true;
  930. /* Turn out verbose output, too. */
  931. opt_log_output = true;
  932. return NULL;
  933. }
  934. static char *set_schedtime(const char *arg, struct schedtime *st)
  935. {
  936. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  937. return "Invalid time set, should be HH:MM";
  938. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  939. return "Invalid time set.";
  940. st->enable = true;
  941. return NULL;
  942. }
  943. #ifdef HAVE_ADL
  944. static char *set_gpu_engine(char *arg)
  945. {
  946. int i, val = 0, device = 0;
  947. char *nextptr;
  948. nextptr = strtok(arg, ",");
  949. if (nextptr == NULL)
  950. return "Invalid parameters for set gpu engine";
  951. val = atoi(nextptr);
  952. if (val <= 0 || val >= 9999)
  953. return "Invalid value passed to set_gpu_engine";
  954. gpus[device++].gpu_engine = val;
  955. while ((nextptr = strtok(NULL, ",")) != NULL) {
  956. val = atoi(nextptr);
  957. if (val <= 0 || val >= 9999)
  958. return "Invalid value passed to set_gpu_engine";
  959. gpus[device++].gpu_engine = val;
  960. }
  961. for (i = device; i < 16; i++)
  962. gpus[i].gpu_engine = val;
  963. return NULL;
  964. }
  965. static char *set_gpu_fan(char *arg)
  966. {
  967. int i, val = 0, device = 0;
  968. char *nextptr;
  969. nextptr = strtok(arg, ",");
  970. if (nextptr == NULL)
  971. return "Invalid parameters for set gpu fan";
  972. val = atoi(nextptr);
  973. if (val < 0 || val > 100)
  974. return "Invalid value passed to set_gpu_fan";
  975. gpus[device++].gpu_fan = val;
  976. while ((nextptr = strtok(NULL, ",")) != NULL) {
  977. val = atoi(nextptr);
  978. if (val < 0 || val > 100)
  979. return "Invalid value passed to set_gpu_fan";
  980. gpus[device++].gpu_fan = val;
  981. }
  982. for (i = device; i < 16; i++)
  983. gpus[i].gpu_fan = val;
  984. return NULL;
  985. }
  986. static char *set_gpu_memclock(char *arg)
  987. {
  988. int i, val = 0, device = 0;
  989. char *nextptr;
  990. nextptr = strtok(arg, ",");
  991. if (nextptr == NULL)
  992. return "Invalid parameters for set gpu memclock";
  993. val = atoi(nextptr);
  994. if (val <= 0 || val >= 9999)
  995. return "Invalid value passed to set_gpu_memclock";
  996. gpus[device++].gpu_memclock = val;
  997. while ((nextptr = strtok(NULL, ",")) != NULL) {
  998. val = atoi(nextptr);
  999. if (val <= 0 || val >= 9999)
  1000. return "Invalid value passed to set_gpu_memclock";
  1001. gpus[device++].gpu_memclock = val;
  1002. }
  1003. for (i = device; i < 16; i++)
  1004. gpus[i].gpu_memclock = val;
  1005. return NULL;
  1006. }
  1007. static char *set_gpu_powertune(char *arg)
  1008. {
  1009. int i, val = 0, device = 0;
  1010. char *nextptr;
  1011. nextptr = strtok(arg, ",");
  1012. if (nextptr == NULL)
  1013. return "Invalid parameters for set gpu powertune";
  1014. val = atoi(nextptr);
  1015. if (val < -99 || val > 99)
  1016. return "Invalid value passed to set_gpu_powertune";
  1017. gpus[device++].gpu_powertune = val;
  1018. while ((nextptr = strtok(NULL, ",")) != NULL) {
  1019. val = atoi(nextptr);
  1020. if (val < -99 || val > 99)
  1021. return "Invalid value passed to set_gpu_powertune";
  1022. gpus[device++].gpu_powertune = val;
  1023. }
  1024. for (i = device; i < 16; i++)
  1025. gpus[i].gpu_powertune = val;
  1026. return NULL;
  1027. }
  1028. static char *set_gpu_vddc(char *arg)
  1029. {
  1030. int i, device = 0;
  1031. float val = 0;
  1032. char *nextptr;
  1033. nextptr = strtok(arg, ",");
  1034. if (nextptr == NULL)
  1035. return "Invalid parameters for set gpu vddc";
  1036. val = atof(nextptr);
  1037. if (val <= 0 || val >= 9999)
  1038. return "Invalid value passed to set_gpu_vddc";
  1039. gpus[device++].gpu_vddc = val;
  1040. while ((nextptr = strtok(NULL, ",")) != NULL) {
  1041. val = atoi(nextptr);
  1042. if (val <= 0 || val >= 9999)
  1043. return "Invalid value passed to set_gpu_vddc";
  1044. gpus[device++].gpu_vddc = val;
  1045. }
  1046. for (i = device; i < 16; i++)
  1047. gpus[i].gpu_vddc = val;
  1048. return NULL;
  1049. }
  1050. #endif
  1051. /* These options are available from config file or commandline */
  1052. static struct opt_table opt_config_table[] = {
  1053. OPT_WITH_ARG("--algo|-a",
  1054. set_algo, show_algo, &opt_algo,
  1055. "Specify sha256 implementation for CPU mining:\n"
  1056. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1057. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1058. #ifdef WANT_SSE2_4WAY
  1059. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1060. #endif
  1061. #ifdef WANT_VIA_PADLOCK
  1062. "\n\tvia\t\tVIA padlock implementation"
  1063. #endif
  1064. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1065. #ifdef WANT_CRYPTOPP_ASM32
  1066. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1067. #endif
  1068. #ifdef WANT_X8632_SSE2
  1069. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1070. #endif
  1071. #ifdef WANT_X8664_SSE2
  1072. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1073. #endif
  1074. #ifdef WANT_X8664_SSE4
  1075. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1076. #endif
  1077. ),
  1078. #ifdef HAVE_ADL
  1079. OPT_WITHOUT_ARG("--auto-fan",
  1080. opt_set_bool, &opt_autofan,
  1081. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  1082. OPT_WITHOUT_ARG("--auto-gpu",
  1083. opt_set_bool, &opt_autoengine,
  1084. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  1085. #endif
  1086. OPT_WITH_ARG("--bench-algo|-b",
  1087. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  1088. opt_hidden),
  1089. OPT_WITH_ARG("--cpu-threads|-t",
  1090. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1091. "Number of miner CPU threads"),
  1092. OPT_WITHOUT_ARG("--debug|-D",
  1093. enable_debug, &opt_debug,
  1094. "Enable debug output"),
  1095. #ifdef HAVE_OPENCL
  1096. OPT_WITH_ARG("--device|-d",
  1097. set_devices, NULL, &opt_device,
  1098. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  1099. OPT_WITHOUT_ARG("--disable-gpu|-G",
  1100. opt_set_bool, &opt_nogpu,
  1101. "Disable GPU mining even if suitable devices exist"),
  1102. OPT_WITHOUT_ARG("--enable-cpu|-C",
  1103. opt_set_bool, &opt_usecpu,
  1104. "Enable CPU mining with GPU mining (default: no CPU mining if suitable GPUs exist)"),
  1105. OPT_WITHOUT_ARG("--failover-only",
  1106. opt_set_bool, &opt_fail_only,
  1107. "Don't leak work to backup pools when primary pool is lagging"),
  1108. OPT_WITH_ARG("--gpu-threads|-g",
  1109. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  1110. "Number of threads per GPU (1 - 10)"),
  1111. #ifdef HAVE_ADL
  1112. OPT_WITH_ARG("--gpu-engine",
  1113. set_gpu_engine, NULL, NULL,
  1114. "Set the GPU engine (over)clock in Mhz - one value for all or separate by commas for per card."),
  1115. OPT_WITH_ARG("--gpu-fan",
  1116. set_gpu_fan, NULL, NULL,
  1117. "Set the GPU fan percentage - one value for all or separate by commas for per card."),
  1118. OPT_WITH_ARG("--gpu-memclock",
  1119. set_gpu_memclock, NULL, NULL,
  1120. "Set the GPU memory (over)clock in Mhz - one value for all or separate by commas for per card."),
  1121. OPT_WITH_ARG("--gpu-powertune",
  1122. set_gpu_powertune, NULL, NULL,
  1123. "Set the GPU powertune percentage - one value for all or separate by commas for per card."),
  1124. OPT_WITH_ARG("--gpu-vddc",
  1125. set_gpu_vddc, NULL, NULL,
  1126. "Set the GPU voltage in Volts - one value for all or separate by commas for per card."),
  1127. #endif
  1128. OPT_WITH_ARG("--intensity|-I",
  1129. forced_int_1010, NULL, &scan_intensity,
  1130. "Intensity of GPU scanning (-10 -> 10, default: dynamic to maintain desktop interactivity)"),
  1131. OPT_WITH_ARG("--kernel-path|-K",
  1132. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1133. "Specify a path to where the kernel .cl files are"),
  1134. OPT_WITH_ARG("--kernel|-k",
  1135. opt_set_charp, NULL, &opt_kernel,
  1136. "Select kernel to use (poclbm or phatk - default: auto)"),
  1137. #endif
  1138. OPT_WITHOUT_ARG("--load-balance",
  1139. set_loadbalance, &pool_strategy,
  1140. "Change multipool strategy from failover to even load balance"),
  1141. OPT_WITH_ARG("--log|-l",
  1142. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1143. "Interval in seconds between log output"),
  1144. #if defined(unix)
  1145. OPT_WITH_ARG("--monitor|-m",
  1146. opt_set_charp, NULL, &opt_stderr_cmd,
  1147. "Use custom pipe cmd for output messages"),
  1148. #endif // defined(unix)
  1149. OPT_WITHOUT_ARG("--no-longpoll",
  1150. opt_set_invbool, &want_longpoll,
  1151. "Disable X-Long-Polling support"),
  1152. #ifdef HAVE_OPENCL
  1153. OPT_WITHOUT_ARG("--no-restart",
  1154. opt_set_invbool, &opt_restart,
  1155. "Do not attempt to restart GPUs that hang"),
  1156. #endif
  1157. OPT_WITH_ARG("--pass|-p",
  1158. set_pass, NULL, NULL,
  1159. "Password for bitcoin JSON-RPC server"),
  1160. OPT_WITHOUT_ARG("--per-device-stats",
  1161. opt_set_bool, &want_per_device_stats,
  1162. "Force verbose mode and output per-device statistics"),
  1163. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1164. opt_set_bool, &opt_protocol,
  1165. "Verbose dump of protocol-level activities"),
  1166. OPT_WITH_ARG("--queue|-Q",
  1167. set_int_0_to_10, opt_show_intval, &opt_queue,
  1168. "Minimum number of work items to have queued (0 - 10)"),
  1169. OPT_WITHOUT_ARG("--quiet|-q",
  1170. opt_set_bool, &opt_quiet,
  1171. "Disable logging output, display status and errors"),
  1172. OPT_WITHOUT_ARG("--real-quiet",
  1173. opt_set_bool, &opt_realquiet,
  1174. "Disable all output"),
  1175. OPT_WITH_ARG("--retries|-r",
  1176. opt_set_intval, opt_show_intval, &opt_retries,
  1177. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  1178. OPT_WITH_ARG("--retry-pause|-R",
  1179. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  1180. "Number of seconds to pause, between retries"),
  1181. OPT_WITH_ARG("--rotate",
  1182. set_rotate, opt_show_intval, &opt_rotate_period,
  1183. "Change multipool strategy from failover to regularly rotate at N minutes"),
  1184. OPT_WITHOUT_ARG("--round-robin",
  1185. set_rr, &pool_strategy,
  1186. "Change multipool strategy from failover to round robin on failure"),
  1187. OPT_WITH_ARG("--scan-time|-s",
  1188. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1189. "Upper bound on time spent scanning current work, in seconds"),
  1190. OPT_WITH_ARG("--sched-start",
  1191. set_schedtime, NULL, &schedstart,
  1192. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  1193. OPT_WITH_ARG("--sched-stop",
  1194. set_schedtime, NULL, &schedstop,
  1195. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  1196. OPT_WITH_ARG("--shares",
  1197. opt_set_intval, NULL, &opt_shares,
  1198. "Quit after mining N shares (default: unlimited)"),
  1199. OPT_WITHOUT_ARG("--submit-stale",
  1200. opt_set_bool, &opt_submit_stale,
  1201. "Submit shares even if they would normally be considered stale"),
  1202. #ifdef HAVE_SYSLOG_H
  1203. OPT_WITHOUT_ARG("--syslog",
  1204. opt_set_bool, &use_syslog,
  1205. "Use system log for output messages (default: standard error)"),
  1206. #endif
  1207. #ifdef HAVE_ADL
  1208. OPT_WITH_ARG("--temp-hysteresis",
  1209. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  1210. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  1211. OPT_WITH_ARG("--temp-overheat",
  1212. set_int_0_to_100, opt_show_intval, &opt_overheattemp,
  1213. "Set the overheat temperature when automatically managing fan and GPU speeds"),
  1214. OPT_WITH_ARG("--temp-target",
  1215. set_int_0_to_100, opt_show_intval, &opt_targettemp,
  1216. "Set the target temperature when automatically managing fan and GPU speeds"),
  1217. #endif
  1218. OPT_WITHOUT_ARG("--text-only|-T",
  1219. opt_set_invbool, &use_curses,
  1220. "Disable ncurses formatted screen output"),
  1221. OPT_WITH_ARG("--url|-o",
  1222. set_url, NULL, NULL,
  1223. "URL for bitcoin JSON-RPC server"),
  1224. OPT_WITH_ARG("--user|-u",
  1225. set_user, NULL, NULL,
  1226. "Username for bitcoin JSON-RPC server"),
  1227. #ifdef HAVE_OPENCL
  1228. OPT_WITH_ARG("--vectors|-v",
  1229. set_vector, NULL, &opt_vectors,
  1230. "Override detected optimal vector width (1, 2 or 4)"),
  1231. #endif
  1232. OPT_WITHOUT_ARG("--verbose",
  1233. opt_set_bool, &opt_log_output,
  1234. "Log verbose output to stderr as well as status output"),
  1235. #ifdef HAVE_OPENCL
  1236. OPT_WITH_ARG("--worksize|-w",
  1237. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  1238. "Override detected optimal worksize"),
  1239. #endif
  1240. OPT_WITH_ARG("--userpass|-O",
  1241. set_userpass, NULL, NULL,
  1242. "Username:Password pair for bitcoin JSON-RPC server"),
  1243. OPT_ENDTABLE
  1244. };
  1245. static char *parse_config(json_t *config)
  1246. {
  1247. static char err_buf[200];
  1248. json_t *val;
  1249. struct opt_table *opt;
  1250. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1251. char *p, *name;
  1252. /* We don't handle subtables. */
  1253. assert(!(opt->type & OPT_SUBTABLE));
  1254. /* Pull apart the option name(s). */
  1255. name = strdup(opt->names);
  1256. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  1257. char *err;
  1258. /* Ignore short options. */
  1259. if (p[1] != '-')
  1260. continue;
  1261. val = json_object_get(config, p+2);
  1262. if (!val)
  1263. continue;
  1264. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  1265. err = opt->cb_arg(json_string_value(val),
  1266. opt->u.arg);
  1267. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  1268. err = opt->cb(opt->u.arg);
  1269. } else {
  1270. err = "Invalid value";
  1271. }
  1272. if (err) {
  1273. sprintf(err_buf, "Parsing JSON option %s: %s",
  1274. p, err);
  1275. return err_buf;
  1276. }
  1277. }
  1278. free(name);
  1279. }
  1280. return NULL;
  1281. }
  1282. static char *load_config(const char *arg, void *unused)
  1283. {
  1284. json_error_t err;
  1285. json_t *config;
  1286. config = json_load_file(arg, 0, &err);
  1287. if (!json_is_object(config))
  1288. return "JSON decode of file failed";
  1289. /* Parse the config now, so we can override it. That can keep pointers
  1290. * so don't free config object. */
  1291. return parse_config(config);
  1292. }
  1293. #ifdef HAVE_OPENCL
  1294. static char *print_ndevs_and_exit(int *ndevs)
  1295. {
  1296. printf("%i GPU devices detected\n", *ndevs);
  1297. fflush(stdout);
  1298. exit(*ndevs);
  1299. }
  1300. #endif
  1301. extern const char *opt_argv0;
  1302. static char *opt_verusage_and_exit(const char *extra)
  1303. {
  1304. printf("%s\n"
  1305. #ifdef HAVE_OPENCL
  1306. "Built with CPU and GPU mining support.\n"
  1307. #else
  1308. "Built with CPU mining support only.\n"
  1309. #endif
  1310. , packagename);
  1311. printf("%s", opt_usage(opt_argv0, extra));
  1312. fflush(stdout);
  1313. exit(0);
  1314. }
  1315. /* These options are available from commandline only */
  1316. static struct opt_table opt_cmdline_table[] = {
  1317. OPT_WITH_ARG("--config|-c",
  1318. load_config, NULL, NULL,
  1319. "Load a JSON-format configuration file\n"
  1320. "See example-cfg.json for an example configuration."),
  1321. OPT_WITHOUT_ARG("--help|-h",
  1322. opt_verusage_and_exit, NULL,
  1323. "Print this message"),
  1324. #ifdef HAVE_OPENCL
  1325. OPT_WITHOUT_ARG("--ndevs|-n",
  1326. print_ndevs_and_exit, &nDevs,
  1327. "Enumerate number of detected GPUs and exit"),
  1328. #endif
  1329. OPT_WITHOUT_ARG("--version|-V",
  1330. opt_version_and_exit, packagename,
  1331. "Display version and exit"),
  1332. OPT_ENDTABLE
  1333. };
  1334. static bool jobj_binary(const json_t *obj, const char *key,
  1335. void *buf, size_t buflen)
  1336. {
  1337. const char *hexstr;
  1338. json_t *tmp;
  1339. tmp = json_object_get(obj, key);
  1340. if (unlikely(!tmp)) {
  1341. applog(LOG_ERR, "JSON key '%s' not found", key);
  1342. return false;
  1343. }
  1344. hexstr = json_string_value(tmp);
  1345. if (unlikely(!hexstr)) {
  1346. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1347. return false;
  1348. }
  1349. if (!hex2bin(buf, hexstr, buflen))
  1350. return false;
  1351. return true;
  1352. }
  1353. static bool work_decode(const json_t *val, struct work *work)
  1354. {
  1355. if (unlikely(!jobj_binary(val, "midstate",
  1356. work->midstate, sizeof(work->midstate)))) {
  1357. applog(LOG_ERR, "JSON inval midstate");
  1358. goto err_out;
  1359. }
  1360. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  1361. applog(LOG_ERR, "JSON inval data");
  1362. goto err_out;
  1363. }
  1364. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  1365. applog(LOG_ERR, "JSON inval hash1");
  1366. goto err_out;
  1367. }
  1368. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  1369. applog(LOG_ERR, "JSON inval target");
  1370. goto err_out;
  1371. }
  1372. memset(work->hash, 0, sizeof(work->hash));
  1373. gettimeofday(&work->tv_staged, NULL);
  1374. return true;
  1375. err_out:
  1376. return false;
  1377. }
  1378. static inline int dev_from_id(int thr_id)
  1379. {
  1380. return thr_info[thr_id].cgpu->cpu_gpu;
  1381. }
  1382. /* Make the change in the recent value adjust dynamically when the difference
  1383. * is large, but damp it when the values are closer together. This allows the
  1384. * value to change quickly, but not fluctuate too dramatically when it has
  1385. * stabilised. */
  1386. static void decay_time(double *f, double fadd)
  1387. {
  1388. double ratio = 0;
  1389. if (likely(*f > 0)) {
  1390. ratio = fadd / *f;
  1391. if (ratio > 1)
  1392. ratio = 1 / ratio;
  1393. }
  1394. if (ratio > 0.9)
  1395. *f = (fadd * 0.1 + *f) / 1.1;
  1396. else
  1397. *f = (fadd + *f * 0.1) / 1.1;
  1398. }
  1399. static int requests_staged(void)
  1400. {
  1401. int ret;
  1402. mutex_lock(&stgd_lock);
  1403. ret = HASH_COUNT(staged_work);
  1404. mutex_unlock(&stgd_lock);
  1405. return ret;
  1406. }
  1407. static WINDOW *mainwin, *statuswin, *logwin;
  1408. static double total_secs = 0.1;
  1409. static char statusline[256];
  1410. static int cpucursor, gpucursor, logstart, logcursor;
  1411. struct cgpu_info gpus[16]; /* Maximum number apparently possible */
  1412. static struct cgpu_info *cpus;
  1413. static inline void unlock_curses(void)
  1414. {
  1415. mutex_unlock(&curses_lock);
  1416. }
  1417. static inline void lock_curses(void)
  1418. {
  1419. mutex_lock(&curses_lock);
  1420. }
  1421. static bool curses_active_locked(void)
  1422. {
  1423. bool ret;
  1424. lock_curses();
  1425. ret = curses_active;
  1426. if (!ret)
  1427. unlock_curses();
  1428. return ret;
  1429. }
  1430. static void text_print_status(int thr_id)
  1431. {
  1432. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1433. #ifdef HAVE_ADL
  1434. if (cgpu->has_adl) {
  1435. int gpu = cgpu->cpu_gpu;
  1436. printf("GPU %d: [%.1f °C] [%.1f/%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  1437. cgpu->cpu_gpu, gpu_temp(gpu), cgpu->rolling,
  1438. cgpu->total_mhashes / total_secs, cgpu->getworks,
  1439. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1440. cgpu->efficiency, cgpu->utility);
  1441. } else
  1442. #endif
  1443. printf(" %sPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  1444. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->rolling,
  1445. cgpu->total_mhashes / total_secs, cgpu->getworks,
  1446. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1447. cgpu->efficiency, cgpu->utility);
  1448. }
  1449. /* Must be called with curses mutex lock held and curses_active */
  1450. static void curses_print_status(void)
  1451. {
  1452. struct pool *pool = current_pool();
  1453. wattron(statuswin, A_BOLD);
  1454. mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  1455. if (opt_n_threads)
  1456. wprintw(statuswin, " CPU Algo: %s", algo_names[opt_algo]);
  1457. wattroff(statuswin, A_BOLD);
  1458. mvwhline(statuswin, 1, 0, '-', 80);
  1459. mvwprintw(statuswin, 2, 0, " %s", statusline);
  1460. wclrtoeol(statuswin);
  1461. mvwprintw(statuswin, 3, 0, " TQ: %d ST: %d SS: %d DW: %d NB: %d LW: %d GF: %d RF: %d I: %d",
  1462. total_queued, requests_staged(), total_stale, total_discarded, new_blocks,
  1463. local_work, total_go, total_ro, scan_intensity);
  1464. wclrtoeol(statuswin);
  1465. if (pool_strategy == POOL_LOADBALANCE && total_pools > 1)
  1466. mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s LP",
  1467. have_longpoll ? "": "out");
  1468. else
  1469. mvwprintw(statuswin, 4, 0, " Connected to %s with%s LP as user %s",
  1470. pool->rpc_url, have_longpoll ? "": "out", pool->rpc_user);
  1471. wclrtoeol(statuswin);
  1472. mvwprintw(statuswin, 5, 0, " Block: %s... Started: %s", current_hash, blocktime);
  1473. mvwhline(statuswin, 6, 0, '-', 80);
  1474. mvwhline(statuswin, logstart - 1, 0, '-', 80);
  1475. mvwprintw(statuswin, gpucursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1476. opt_g_threads ? "[G]PU management " : "");
  1477. /* The window will be updated once we're done with all the devices */
  1478. wnoutrefresh(statuswin);
  1479. }
  1480. static void curses_print_devstatus(int thr_id)
  1481. {
  1482. if (thr_id >= 0 && thr_id < gpu_threads) {
  1483. int gpu = dev_from_id(thr_id);
  1484. struct cgpu_info *cgpu = &gpus[gpu];
  1485. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1486. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1487. mvwprintw(statuswin, gpucursor + gpu, 0, " GPU %d: ", gpu);
  1488. #ifdef HAVE_ADL
  1489. if (cgpu->has_adl)
  1490. wprintw(statuswin, "[%.1f °C] ", gpu_temp(gpu));
  1491. #endif
  1492. if (cgpu->status == LIFE_DEAD)
  1493. wprintw(statuswin, "[DEAD ");
  1494. else if (cgpu->status == LIFE_SICK)
  1495. wprintw(statuswin, "[SICK ");
  1496. else if (!gpu_devices[gpu])
  1497. wprintw(statuswin, "[DISABLED ");
  1498. else
  1499. wprintw(statuswin, "[%.1f", cgpu->rolling);
  1500. wprintw(statuswin, "/%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m] ",
  1501. cgpu->total_mhashes / total_secs,
  1502. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1503. cgpu->efficiency, cgpu->utility);
  1504. wclrtoeol(statuswin);
  1505. } else if (thr_id >= gpu_threads) {
  1506. int cpu = dev_from_id(thr_id);
  1507. struct cgpu_info *cgpu = &cpus[cpu];
  1508. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1509. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1510. mvwprintw(statuswin, cpucursor + cpu, 0, " CPU %d: [%.2f/%.2f Mh/s] [Q:%d A:%d R:%d E:%.0f%% U:%.2f/m] ",
  1511. cpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  1512. cgpu->getworks, cgpu->accepted, cgpu->rejected,
  1513. cgpu->efficiency, cgpu->utility);
  1514. wclrtoeol(statuswin);
  1515. }
  1516. wnoutrefresh(statuswin);
  1517. }
  1518. static void print_status(int thr_id)
  1519. {
  1520. if (!curses_active)
  1521. text_print_status(thr_id);
  1522. }
  1523. /* Check for window resize. Called with curses mutex locked */
  1524. static inline bool change_logwinsize(void)
  1525. {
  1526. int x, y, logx, logy;
  1527. getmaxyx(mainwin, y, x);
  1528. getmaxyx(logwin, logy, logx);
  1529. y -= logcursor;
  1530. /* Detect screen size change */
  1531. if ((x != logx || y != logy) && x >= 80 && y >= 25) {
  1532. wresize(logwin, y, x);
  1533. return true;
  1534. }
  1535. return false;
  1536. }
  1537. /* For mandatory printing when mutex is already locked */
  1538. static void wlog(const char *f, ...)
  1539. {
  1540. va_list ap;
  1541. va_start(ap, f);
  1542. vw_printw(logwin, f, ap);
  1543. va_end(ap);
  1544. }
  1545. /* Mandatory printing */
  1546. void wlogprint(const char *f, ...)
  1547. {
  1548. va_list ap;
  1549. if (curses_active_locked()) {
  1550. va_start(ap, f);
  1551. vw_printw(logwin, f, ap);
  1552. va_end(ap);
  1553. wrefresh(logwin);
  1554. unlock_curses();
  1555. }
  1556. }
  1557. void log_curses(int prio, const char *f, va_list ap)
  1558. {
  1559. if (opt_quiet && prio != LOG_ERR)
  1560. return;
  1561. if (curses_active_locked()) {
  1562. if (!opt_loginput) {
  1563. vw_printw(logwin, f, ap);
  1564. wrefresh(logwin);
  1565. }
  1566. unlock_curses();
  1567. } else
  1568. vprintf(f, ap);
  1569. }
  1570. static void clear_logwin(void)
  1571. {
  1572. if (curses_active_locked()) {
  1573. wclear(logwin);
  1574. wrefresh(logwin);
  1575. unlock_curses();
  1576. }
  1577. }
  1578. static bool submit_upstream_work(const struct work *work)
  1579. {
  1580. char *hexstr = NULL;
  1581. json_t *val, *res;
  1582. char s[345], sd[345];
  1583. bool rc = false;
  1584. int thr_id = work->thr_id;
  1585. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1586. CURL *curl = curl_easy_init();
  1587. struct pool *pool = work->pool;
  1588. bool rolltime;
  1589. if (unlikely(!curl)) {
  1590. applog(LOG_ERR, "CURL initialisation failed");
  1591. return rc;
  1592. }
  1593. /* build hex string */
  1594. hexstr = bin2hex(work->data, sizeof(work->data));
  1595. if (unlikely(!hexstr)) {
  1596. applog(LOG_ERR, "submit_upstream_work OOM");
  1597. goto out_nofree;
  1598. }
  1599. /* build JSON-RPC request */
  1600. sprintf(s,
  1601. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  1602. hexstr);
  1603. sprintf(sd,
  1604. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  1605. hexstr);
  1606. if (opt_debug)
  1607. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  1608. /* issue JSON-RPC request */
  1609. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool);
  1610. if (unlikely(!val)) {
  1611. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  1612. if (!pool_tset(pool, &pool->submit_fail)) {
  1613. total_ro++;
  1614. pool->remotefail_occasions++;
  1615. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  1616. }
  1617. goto out;
  1618. } else if (pool_tclear(pool, &pool->submit_fail))
  1619. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  1620. res = json_object_get(val, "result");
  1621. /* Theoretically threads could race when modifying accepted and
  1622. * rejected values but the chance of two submits completing at the
  1623. * same time is zero so there is no point adding extra locking */
  1624. if (json_is_true(res)) {
  1625. cgpu->accepted++;
  1626. total_accepted++;
  1627. pool->accepted++;
  1628. if (opt_debug)
  1629. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  1630. if (!QUIET) {
  1631. if (total_pools > 1)
  1632. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d pool %d",
  1633. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  1634. else
  1635. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d",
  1636. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  1637. }
  1638. if (opt_shares && total_accepted >= opt_shares) {
  1639. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  1640. kill_work();
  1641. goto out;
  1642. }
  1643. } else {
  1644. cgpu->rejected++;
  1645. total_rejected++;
  1646. pool->rejected++;
  1647. if (opt_debug)
  1648. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  1649. if (!QUIET) {
  1650. if (total_pools > 1)
  1651. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d pool %d",
  1652. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  1653. else
  1654. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d",
  1655. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  1656. }
  1657. }
  1658. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1659. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1660. if (!opt_realquiet)
  1661. print_status(thr_id);
  1662. if (!want_per_device_stats) {
  1663. #ifdef HAVE_ADL
  1664. if (cgpu->has_adl) {
  1665. int gpu = cgpu->cpu_gpu;
  1666. applog(LOG_INFO, "GPU %d %.1f°C Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  1667. gpu, gpu_temp(gpu), cgpu->getworks, cgpu->accepted,
  1668. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  1669. } else
  1670. #endif
  1671. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  1672. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  1673. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  1674. }
  1675. json_decref(val);
  1676. rc = true;
  1677. out:
  1678. free(hexstr);
  1679. out_nofree:
  1680. curl_easy_cleanup(curl);
  1681. return rc;
  1682. }
  1683. static const char *rpc_req =
  1684. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  1685. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  1686. static inline struct pool *select_pool(bool lagging)
  1687. {
  1688. static int rotating_pool = 0;
  1689. struct pool *pool, *cp;
  1690. cp = current_pool();
  1691. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  1692. pool = cp;
  1693. else
  1694. pool = NULL;
  1695. while (!pool) {
  1696. if (++rotating_pool >= total_pools)
  1697. rotating_pool = 0;
  1698. pool = pools[rotating_pool];
  1699. if ((!pool->idle && pool->enabled) || pool == cp)
  1700. break;
  1701. pool = NULL;
  1702. }
  1703. return pool;
  1704. }
  1705. static bool get_upstream_work(struct work *work, bool lagging)
  1706. {
  1707. struct pool *pool;
  1708. json_t *val;
  1709. bool rc = false;
  1710. CURL *curl;
  1711. curl = curl_easy_init();
  1712. if (unlikely(!curl)) {
  1713. applog(LOG_ERR, "CURL initialisation failed");
  1714. return rc;
  1715. }
  1716. pool = select_pool(lagging);
  1717. if (opt_debug)
  1718. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  1719. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1720. false, false, &work->rolltime, pool);
  1721. if (unlikely(!val)) {
  1722. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  1723. goto out;
  1724. }
  1725. rc = work_decode(json_object_get(val, "result"), work);
  1726. work->pool = pool;
  1727. total_getworks++;
  1728. pool->getwork_requested++;
  1729. if (work->thr)
  1730. work->thr->cgpu->getworks++;
  1731. json_decref(val);
  1732. out:
  1733. curl_easy_cleanup(curl);
  1734. return rc;
  1735. }
  1736. static struct work *make_work(void)
  1737. {
  1738. struct work *work = calloc(1, sizeof(struct work));
  1739. if (unlikely(!work))
  1740. quit(1, "Failed to calloc work in make_work");
  1741. work->id = total_work++;
  1742. return work;
  1743. }
  1744. static void free_work(struct work *work)
  1745. {
  1746. free(work);
  1747. }
  1748. static void workio_cmd_free(struct workio_cmd *wc)
  1749. {
  1750. if (!wc)
  1751. return;
  1752. switch (wc->cmd) {
  1753. case WC_SUBMIT_WORK:
  1754. free_work(wc->u.work);
  1755. break;
  1756. default: /* do nothing */
  1757. break;
  1758. }
  1759. memset(wc, 0, sizeof(*wc)); /* poison */
  1760. free(wc);
  1761. }
  1762. static void disable_curses(void)
  1763. {
  1764. if (curses_active_locked()) {
  1765. curses_active = false;
  1766. leaveok(logwin, false);
  1767. leaveok(statuswin, false);
  1768. leaveok(mainwin, false);
  1769. nocbreak();
  1770. echo();
  1771. delwin(logwin);
  1772. delwin(statuswin);
  1773. delwin(mainwin);
  1774. endwin();
  1775. refresh();
  1776. #ifdef WIN32
  1777. // Move the cursor to after curses output.
  1778. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  1779. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1780. COORD coord;
  1781. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  1782. coord.X = 0;
  1783. coord.Y = csbi.dwSize.Y - 1;
  1784. SetConsoleCursorPosition(hout, coord);
  1785. }
  1786. #endif
  1787. unlock_curses();
  1788. }
  1789. }
  1790. static void print_summary(void);
  1791. void kill_work(void)
  1792. {
  1793. struct workio_cmd *wc;
  1794. struct thr_info *thr;
  1795. unsigned int i;
  1796. disable_curses();
  1797. applog(LOG_INFO, "Received kill message");
  1798. /* Kill the watchdog thread */
  1799. thr = &thr_info[watchdog_thr_id];
  1800. if (thr->pth)
  1801. pthread_cancel(*thr->pth);
  1802. /* Stop the mining threads*/
  1803. for (i = 0; i < mining_threads; i++) {
  1804. thr = &thr_info[i];
  1805. if (!thr->pth)
  1806. continue;
  1807. tq_freeze(thr->q);
  1808. /* No need to check if this succeeds or not */
  1809. pthread_cancel(*thr->pth);
  1810. }
  1811. /* Stop the others */
  1812. thr = &thr_info[stage_thr_id];
  1813. if (thr->pth)
  1814. pthread_cancel(*thr->pth);
  1815. thr = &thr_info[longpoll_thr_id];
  1816. if (thr->pth)
  1817. pthread_cancel(*thr->pth);
  1818. wc = calloc(1, sizeof(*wc));
  1819. if (unlikely(!wc)) {
  1820. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  1821. /* We're just trying to die anyway, so forget graceful */
  1822. exit (1);
  1823. }
  1824. wc->cmd = WC_DIE;
  1825. wc->thr = 0;
  1826. if (opt_debug)
  1827. applog(LOG_DEBUG, "Pushing die request to work thread");
  1828. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1829. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  1830. exit (1);
  1831. }
  1832. thr = &thr_info[work_thr_id];
  1833. if (thr->pth)
  1834. pthread_cancel(*thr->pth);
  1835. }
  1836. void quit(int status, const char *format, ...);
  1837. static void sighandler(int sig)
  1838. {
  1839. /* Restore signal handlers so we can still quit if kill_work fails */
  1840. sigaction(SIGTERM, &termhandler, NULL);
  1841. sigaction(SIGINT, &inthandler, NULL);
  1842. kill_work();
  1843. quit(sig, "Received interrupt signal.");
  1844. }
  1845. static void *get_work_thread(void *userdata)
  1846. {
  1847. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1848. struct work *ret_work;
  1849. int failures = 0;
  1850. pthread_detach(pthread_self());
  1851. ret_work = make_work();
  1852. if (wc->thr)
  1853. ret_work->thr = wc->thr;
  1854. else
  1855. ret_work->thr = NULL;
  1856. /* obtain new work from bitcoin via JSON-RPC */
  1857. while (!get_upstream_work(ret_work, wc->lagging)) {
  1858. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1859. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  1860. free_work(ret_work);
  1861. kill_work();
  1862. goto out;
  1863. }
  1864. /* pause, then restart work-request loop */
  1865. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  1866. fail_pause);
  1867. sleep(fail_pause);
  1868. fail_pause += opt_fail_pause;
  1869. }
  1870. fail_pause = opt_fail_pause;
  1871. if (opt_debug)
  1872. applog(LOG_DEBUG, "Pushing work to requesting thread");
  1873. /* send work to requesting thread */
  1874. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  1875. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  1876. kill_work();
  1877. free_work(ret_work);
  1878. }
  1879. out:
  1880. workio_cmd_free(wc);
  1881. return NULL;
  1882. }
  1883. static bool workio_get_work(struct workio_cmd *wc)
  1884. {
  1885. pthread_t get_thread;
  1886. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  1887. applog(LOG_ERR, "Failed to create get_work_thread");
  1888. return false;
  1889. }
  1890. return true;
  1891. }
  1892. static bool stale_work(struct work *work)
  1893. {
  1894. struct timeval now;
  1895. bool ret = false;
  1896. char *hexstr;
  1897. gettimeofday(&now, NULL);
  1898. if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_scantime)
  1899. return true;
  1900. hexstr = bin2hex(work->data, 18);
  1901. if (unlikely(!hexstr)) {
  1902. applog(LOG_ERR, "submit_work_thread OOM");
  1903. return ret;
  1904. }
  1905. if (strcmp(hexstr, current_block))
  1906. ret = true;
  1907. free(hexstr);
  1908. return ret;
  1909. }
  1910. static void *submit_work_thread(void *userdata)
  1911. {
  1912. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1913. struct work *work = wc->u.work;
  1914. struct pool *pool = work->pool;
  1915. int failures = 0;
  1916. pthread_detach(pthread_self());
  1917. if (!opt_submit_stale && stale_work(work)) {
  1918. applog(LOG_WARNING, "Stale share detected, discarding");
  1919. total_stale++;
  1920. pool->stale_shares++;
  1921. goto out;
  1922. }
  1923. /* submit solution to bitcoin via JSON-RPC */
  1924. while (!submit_upstream_work(work)) {
  1925. if (!opt_submit_stale && stale_work(work)) {
  1926. applog(LOG_WARNING, "Stale share detected, discarding");
  1927. total_stale++;
  1928. pool->stale_shares++;
  1929. break;
  1930. }
  1931. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1932. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1933. kill_work();
  1934. break;
  1935. }
  1936. /* pause, then restart work-request loop */
  1937. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1938. fail_pause);
  1939. sleep(fail_pause);
  1940. fail_pause += opt_fail_pause;
  1941. }
  1942. fail_pause = opt_fail_pause;
  1943. out:
  1944. workio_cmd_free(wc);
  1945. return NULL;
  1946. }
  1947. static bool workio_submit_work(struct workio_cmd *wc)
  1948. {
  1949. pthread_t submit_thread;
  1950. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1951. applog(LOG_ERR, "Failed to create submit_work_thread");
  1952. return false;
  1953. }
  1954. return true;
  1955. }
  1956. /* Find the pool that currently has the highest priority */
  1957. static struct pool *priority_pool(int choice)
  1958. {
  1959. struct pool *ret = NULL;
  1960. int i;
  1961. for (i = 0; i < total_pools; i++) {
  1962. struct pool *pool = pools[i];
  1963. if (pool->prio == choice) {
  1964. ret = pool;
  1965. break;
  1966. }
  1967. }
  1968. if (unlikely(!ret)) {
  1969. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1970. return pools[choice];
  1971. }
  1972. return ret;
  1973. }
  1974. static void restart_longpoll(void);
  1975. static void switch_pools(struct pool *selected)
  1976. {
  1977. struct pool *pool, *last_pool;
  1978. int i, pool_no;
  1979. mutex_lock(&control_lock);
  1980. last_pool = currentpool;
  1981. pool_no = currentpool->pool_no;
  1982. /* Switch selected to pool number 0 and move the rest down */
  1983. if (selected) {
  1984. if (selected->prio != 0) {
  1985. for (i = 0; i < total_pools; i++) {
  1986. pool = pools[i];
  1987. if (pool->prio < selected->prio)
  1988. pool->prio++;
  1989. }
  1990. selected->prio = 0;
  1991. }
  1992. }
  1993. switch (pool_strategy) {
  1994. /* Both of these set to the master pool */
  1995. case POOL_FAILOVER:
  1996. case POOL_LOADBALANCE:
  1997. for (i = 0; i < total_pools; i++) {
  1998. pool = priority_pool(i);
  1999. if (!pool->idle && pool->enabled) {
  2000. pool_no = pool->pool_no;
  2001. break;
  2002. }
  2003. }
  2004. break;
  2005. /* Both of these simply increment and cycle */
  2006. case POOL_ROUNDROBIN:
  2007. case POOL_ROTATE:
  2008. if (selected) {
  2009. pool_no = selected->pool_no;
  2010. break;
  2011. }
  2012. pool_no++;
  2013. if (pool_no >= total_pools)
  2014. pool_no = 0;
  2015. break;
  2016. default:
  2017. break;
  2018. }
  2019. currentpool = pools[pool_no];
  2020. pool = currentpool;
  2021. mutex_unlock(&control_lock);
  2022. if (pool != last_pool) {
  2023. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  2024. /* Only switch longpoll if the new pool also supports LP */
  2025. if (pool->hdr_path)
  2026. restart_longpoll();
  2027. }
  2028. /* Reset the queued amount to allow more to be queued for the new pool */
  2029. mutex_lock(&qd_lock);
  2030. total_queued = 0;
  2031. mutex_unlock(&qd_lock);
  2032. }
  2033. static void discard_work(struct work *work)
  2034. {
  2035. if (!work->clone && !work->rolls && !work->mined) {
  2036. if (work->pool)
  2037. work->pool->discarded_work++;
  2038. total_discarded++;
  2039. if (opt_debug)
  2040. applog(LOG_DEBUG, "Discarded work");
  2041. } else if (opt_debug)
  2042. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2043. free_work(work);
  2044. }
  2045. /* This is overkill, but at least we'll know accurately how much work is
  2046. * queued to prevent ever being left without work */
  2047. static void inc_queued(void)
  2048. {
  2049. mutex_lock(&qd_lock);
  2050. total_queued++;
  2051. mutex_unlock(&qd_lock);
  2052. }
  2053. static void dec_queued(void)
  2054. {
  2055. mutex_lock(&qd_lock);
  2056. if (total_queued > 0)
  2057. total_queued--;
  2058. mutex_unlock(&qd_lock);
  2059. }
  2060. static int requests_queued(void)
  2061. {
  2062. int ret;
  2063. mutex_lock(&qd_lock);
  2064. ret = total_queued;
  2065. mutex_unlock(&qd_lock);
  2066. return ret;
  2067. }
  2068. static int discard_stale(void)
  2069. {
  2070. struct work *work, *tmp;
  2071. int i, stale = 0;
  2072. mutex_lock(&stgd_lock);
  2073. HASH_ITER(hh, staged_work, work, tmp) {
  2074. if (stale_work(work)) {
  2075. HASH_DEL(staged_work, work);
  2076. if (work->clone)
  2077. --staged_clones;
  2078. discard_work(work);
  2079. stale++;
  2080. }
  2081. }
  2082. mutex_unlock(&stgd_lock);
  2083. if (opt_debug)
  2084. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  2085. /* Dec queued outside the loop to not have recursive locks */
  2086. for (i = 0; i < stale; i++)
  2087. dec_queued();
  2088. return stale;
  2089. }
  2090. static bool queue_request(struct thr_info *thr, bool needed);
  2091. static void restart_threads(void)
  2092. {
  2093. int i, stale;
  2094. /* Discard staged work that is now stale */
  2095. stale = discard_stale();
  2096. for (i = 0; i < stale; i++)
  2097. queue_request(NULL, true);
  2098. for (i = 0; i < mining_threads; i++)
  2099. work_restart[i].restart = 1;
  2100. }
  2101. static void set_curblock(char *hexstr, unsigned char *hash)
  2102. {
  2103. unsigned char hash_swap[32];
  2104. char *old_hash = NULL;
  2105. struct timeval tv_now;
  2106. /* Don't free current_hash directly to avoid dereferencing it when
  2107. * we might be accessing its data elsewhere */
  2108. if (current_hash)
  2109. old_hash = current_hash;
  2110. strcpy(current_block, hexstr);
  2111. gettimeofday(&tv_now, NULL);
  2112. get_timestamp(blocktime, &tv_now);
  2113. swap256(hash_swap, hash);
  2114. current_hash = bin2hex(hash_swap, 16);
  2115. if (unlikely(!current_hash))
  2116. quit (1, "set_curblock OOM");
  2117. if (old_hash)
  2118. free(old_hash);
  2119. }
  2120. static void test_work_current(struct work *work)
  2121. {
  2122. struct block *s;
  2123. char *hexstr;
  2124. hexstr = bin2hex(work->data, 18);
  2125. if (unlikely(!hexstr)) {
  2126. applog(LOG_ERR, "stage_thread OOM");
  2127. return;
  2128. }
  2129. /* Search to see if this block exists yet and if not, consider it a
  2130. * new block and set the current block details to this one */
  2131. rd_lock(&blk_lock);
  2132. HASH_FIND_STR(blocks, hexstr, s);
  2133. rd_unlock(&blk_lock);
  2134. if (!s) {
  2135. s = calloc(sizeof(struct block), 1);
  2136. if (unlikely(!s))
  2137. quit (1, "test_work_current OOM");
  2138. strcpy(s->hash, hexstr);
  2139. wr_lock(&blk_lock);
  2140. HASH_ADD_STR(blocks, hash, s);
  2141. wr_unlock(&blk_lock);
  2142. set_curblock(hexstr, work->data);
  2143. new_blocks++;
  2144. if (block_changed != BLOCK_LP && block_changed != BLOCK_FIRST) {
  2145. block_changed = BLOCK_DETECT;
  2146. if (have_longpoll)
  2147. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  2148. else
  2149. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  2150. } else
  2151. block_changed = BLOCK_NONE;
  2152. restart_threads();
  2153. }
  2154. free(hexstr);
  2155. }
  2156. static int tv_sort(struct work *worka, struct work *workb)
  2157. {
  2158. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  2159. }
  2160. static bool hash_push(struct work *work)
  2161. {
  2162. bool rc = true;
  2163. mutex_lock(&getq->mutex);
  2164. if (likely(!getq->frozen)) {
  2165. HASH_ADD_INT(staged_work, id, work);
  2166. HASH_SORT(staged_work, tv_sort);
  2167. if (work->clone)
  2168. ++staged_clones;
  2169. } else
  2170. rc = false;
  2171. pthread_cond_signal(&getq->cond);
  2172. mutex_unlock(&getq->mutex);
  2173. return rc;
  2174. }
  2175. static void *stage_thread(void *userdata)
  2176. {
  2177. struct thr_info *mythr = userdata;
  2178. bool ok = true;
  2179. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2180. while (ok) {
  2181. struct work *work = NULL;
  2182. if (opt_debug)
  2183. applog(LOG_DEBUG, "Popping work to stage thread");
  2184. work = tq_pop(mythr->q, NULL);
  2185. if (unlikely(!work)) {
  2186. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  2187. ok = false;
  2188. break;
  2189. }
  2190. test_work_current(work);
  2191. if (opt_debug)
  2192. applog(LOG_DEBUG, "Pushing work to getwork queue");
  2193. if (unlikely(!hash_push(work))) {
  2194. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  2195. continue;
  2196. }
  2197. }
  2198. tq_freeze(mythr->q);
  2199. return NULL;
  2200. }
  2201. int curses_int(const char *query)
  2202. {
  2203. int ret;
  2204. char *cvar;
  2205. cvar = curses_input(query);
  2206. ret = atoi(cvar);
  2207. free(cvar);
  2208. return ret;
  2209. }
  2210. static bool input_pool(bool live);
  2211. static int active_pools(void)
  2212. {
  2213. int ret = 0;
  2214. int i;
  2215. for (i = 0; i < total_pools; i++) {
  2216. if ((pools[i])->enabled)
  2217. ret++;
  2218. }
  2219. return ret;
  2220. }
  2221. static void display_pool_summary(struct pool *pool)
  2222. {
  2223. double efficiency = 0.0;
  2224. if (curses_active_locked()) {
  2225. wlog("Pool: %s\n", pool->rpc_url);
  2226. wlog("%s long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  2227. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  2228. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  2229. wlog(" Accepted shares: %d\n", pool->accepted);
  2230. wlog(" Rejected shares: %d\n", pool->rejected);
  2231. if (pool->accepted || pool->rejected)
  2232. wlog(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  2233. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  2234. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2235. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  2236. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  2237. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  2238. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2239. wrefresh(logwin);
  2240. unlock_curses();
  2241. }
  2242. }
  2243. /* We can't remove the memory used for this struct pool because there may
  2244. * still be work referencing it. We just remove it from the pools list */
  2245. static void remove_pool(struct pool *pool)
  2246. {
  2247. int i, last_pool = total_pools - 1;
  2248. struct pool *other;
  2249. /* Boost priority of any lower prio than this one */
  2250. for (i = 0; i < total_pools; i++) {
  2251. other = pools[i];
  2252. if (other->prio > pool->prio)
  2253. other->prio--;
  2254. }
  2255. if (pool->pool_no < last_pool) {
  2256. /* Swap the last pool for this one */
  2257. (pools[last_pool])->pool_no = pool->pool_no;
  2258. pools[pool->pool_no] = pools[last_pool];
  2259. }
  2260. /* Give it an invalid number */
  2261. pool->pool_no = total_pools;
  2262. total_pools--;
  2263. }
  2264. static void display_pools(void)
  2265. {
  2266. struct pool *pool;
  2267. int selected, i;
  2268. char input;
  2269. opt_loginput = true;
  2270. immedok(logwin, true);
  2271. updated:
  2272. clear_logwin();
  2273. for (i = 0; i < total_pools; i++) {
  2274. pool = pools[i];
  2275. if (pool == current_pool())
  2276. wattron(logwin, A_BOLD);
  2277. if (!pool->enabled)
  2278. wattron(logwin, A_DIM);
  2279. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  2280. pool->pool_no,
  2281. pool->enabled? "Enabled" : "Disabled",
  2282. pool->idle? "Dead" : "Alive",
  2283. pool->prio,
  2284. pool->rpc_url, pool->rpc_user);
  2285. wattroff(logwin, A_BOLD | A_DIM);
  2286. }
  2287. retry:
  2288. wlogprint("\nCurrent pool management strategy: %s\n",
  2289. strategies[pool_strategy]);
  2290. if (pool_strategy == POOL_ROTATE)
  2291. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  2292. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  2293. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  2294. wlogprint("Or press any other key to continue\n");
  2295. input = getch();
  2296. if (!strncasecmp(&input, "a", 1)) {
  2297. input_pool(true);
  2298. goto updated;
  2299. } else if (!strncasecmp(&input, "r", 1)) {
  2300. if (total_pools <= 1) {
  2301. wlogprint("Cannot remove last pool");
  2302. goto retry;
  2303. }
  2304. selected = curses_int("Select pool number");
  2305. if (selected < 0 || selected >= total_pools) {
  2306. wlogprint("Invalid selection\n");
  2307. goto retry;
  2308. }
  2309. pool = pools[selected];
  2310. if (pool == current_pool())
  2311. switch_pools(NULL);
  2312. if (pool == current_pool()) {
  2313. wlogprint("Unable to remove pool due to activity\n");
  2314. goto retry;
  2315. }
  2316. pool->enabled = false;
  2317. remove_pool(pool);
  2318. goto updated;
  2319. } else if (!strncasecmp(&input, "s", 1)) {
  2320. selected = curses_int("Select pool number");
  2321. if (selected < 0 || selected >= total_pools) {
  2322. wlogprint("Invalid selection\n");
  2323. goto retry;
  2324. }
  2325. pool = pools[selected];
  2326. pool->enabled = true;
  2327. switch_pools(pool);
  2328. goto updated;
  2329. } else if (!strncasecmp(&input, "d", 1)) {
  2330. if (active_pools() <= 1) {
  2331. wlogprint("Cannot disable last pool");
  2332. goto retry;
  2333. }
  2334. selected = curses_int("Select pool number");
  2335. if (selected < 0 || selected >= total_pools) {
  2336. wlogprint("Invalid selection\n");
  2337. goto retry;
  2338. }
  2339. pool = pools[selected];
  2340. pool->enabled = false;
  2341. if (pool == current_pool())
  2342. switch_pools(NULL);
  2343. goto updated;
  2344. } else if (!strncasecmp(&input, "e", 1)) {
  2345. selected = curses_int("Select pool number");
  2346. if (selected < 0 || selected >= total_pools) {
  2347. wlogprint("Invalid selection\n");
  2348. goto retry;
  2349. }
  2350. pool = pools[selected];
  2351. pool->enabled = true;
  2352. if (pool->prio < current_pool()->prio)
  2353. switch_pools(pool);
  2354. goto updated;
  2355. } else if (!strncasecmp(&input, "c", 1)) {
  2356. for (i = 0; i <= TOP_STRATEGY; i++)
  2357. wlogprint("%d: %s\n", i, strategies[i]);
  2358. selected = curses_int("Select strategy number type");
  2359. if (selected < 0 || selected > TOP_STRATEGY) {
  2360. wlogprint("Invalid selection\n");
  2361. goto retry;
  2362. }
  2363. if (selected == POOL_ROTATE) {
  2364. opt_rotate_period = curses_int("Select interval in minutes");
  2365. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  2366. opt_rotate_period = 0;
  2367. wlogprint("Invalid selection\n");
  2368. goto retry;
  2369. }
  2370. }
  2371. pool_strategy = selected;
  2372. switch_pools(NULL);
  2373. goto updated;
  2374. } else if (!strncasecmp(&input, "i", 1)) {
  2375. selected = curses_int("Select pool number");
  2376. if (selected < 0 || selected >= total_pools) {
  2377. wlogprint("Invalid selection\n");
  2378. goto retry;
  2379. }
  2380. pool = pools[selected];
  2381. display_pool_summary(pool);
  2382. goto retry;
  2383. }
  2384. clear_logwin();
  2385. immedok(logwin, false);
  2386. opt_loginput = false;
  2387. }
  2388. static void display_options(void)
  2389. {
  2390. int selected;
  2391. char input;
  2392. opt_loginput = true;
  2393. immedok(logwin, true);
  2394. retry:
  2395. clear_logwin();
  2396. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  2397. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n[R]PC debug:%s\n[L]og interval:%d\n",
  2398. opt_debug ? "on" : "off",
  2399. want_per_device_stats? "on" : "off",
  2400. opt_quiet ? "on" : "off",
  2401. opt_log_output ? "on" : "off",
  2402. opt_protocol ? "on" : "off",
  2403. opt_log_interval);
  2404. wlogprint("Select an option or any other key to return\n");
  2405. input = getch();
  2406. if (!strncasecmp(&input, "q", 1)) {
  2407. opt_quiet ^= true;
  2408. clear_logwin();
  2409. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  2410. } else if (!strncasecmp(&input, "v", 1)) {
  2411. opt_log_output ^= true;
  2412. if (opt_log_output)
  2413. opt_quiet = false;
  2414. clear_logwin();
  2415. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2416. } else if (!strncasecmp(&input, "n", 1)) {
  2417. opt_log_output = false;
  2418. opt_debug = false;
  2419. opt_quiet = false;
  2420. opt_protocol = false;
  2421. want_per_device_stats = false;
  2422. clear_logwin();
  2423. wlogprint("Output mode reset to normal\n");
  2424. } else if (!strncasecmp(&input, "d", 1)) {
  2425. opt_debug ^= true;
  2426. opt_log_output = opt_debug;
  2427. if (opt_debug)
  2428. opt_quiet = false;
  2429. clear_logwin();
  2430. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2431. } else if (!strncasecmp(&input, "p", 1)) {
  2432. want_per_device_stats ^= true;
  2433. opt_log_output = want_per_device_stats;
  2434. clear_logwin();
  2435. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  2436. } else if (!strncasecmp(&input, "r", 1)) {
  2437. opt_protocol ^= true;
  2438. if (opt_protocol)
  2439. opt_quiet = false;
  2440. clear_logwin();
  2441. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2442. } else if (!strncasecmp(&input, "c", 1))
  2443. clear_logwin();
  2444. else if (!strncasecmp(&input, "l", 1)) {
  2445. selected = curses_int("Interval in seconds");
  2446. if (selected < 0 || selected > 9999) {
  2447. wlogprint("Invalid selection\n");
  2448. goto retry;
  2449. }
  2450. opt_log_interval = selected;
  2451. clear_logwin();
  2452. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2453. } else if (!strncasecmp(&input, "s", 1)) {
  2454. opt_realquiet = true;
  2455. clear_logwin();
  2456. } else clear_logwin();
  2457. immedok(logwin, false);
  2458. opt_loginput = false;
  2459. }
  2460. static void set_options(void)
  2461. {
  2462. int selected;
  2463. char input;
  2464. opt_loginput = true;
  2465. immedok(logwin, true);
  2466. retry:
  2467. clear_logwin();
  2468. wlogprint("\n[D]ynamic mode: %s\n[L]ongpoll: %s\n",
  2469. opt_dynamic ? "On" : "Off", want_longpoll ? "On" : "Off");
  2470. if (opt_dynamic)
  2471. wlogprint("[I]ntensity: Dynamic\n");
  2472. else
  2473. wlogprint("[I]ntensity: %d\n", scan_intensity);
  2474. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[R]etries: %d\n[P]ause: %d\n",
  2475. opt_queue, opt_scantime, opt_retries, opt_fail_pause);
  2476. wlogprint("Select an option or any other key to return\n");
  2477. input = getch();
  2478. if (!strncasecmp(&input, "q", 1)) {
  2479. selected = curses_int("Extra work items to queue");
  2480. if (selected < 0 || selected > 9999) {
  2481. wlogprint("Invalid selection\n");
  2482. goto retry;
  2483. }
  2484. opt_queue = selected;
  2485. goto retry;
  2486. } else if (!strncasecmp(&input, "d", 1)) {
  2487. opt_dynamic ^= true;
  2488. goto retry;
  2489. } else if (!strncasecmp(&input, "l", 1)) {
  2490. want_longpoll ^= true;
  2491. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2492. restart_longpoll();
  2493. goto retry;
  2494. } else if (!strncasecmp(&input, "i", 1)) {
  2495. selected = curses_int("Set GPU scan intensity (-10 -> 10)");
  2496. if (selected < -10 || selected > 10) {
  2497. wlogprint("Invalid selection\n");
  2498. goto retry;
  2499. }
  2500. opt_dynamic = false;
  2501. scan_intensity = selected;
  2502. goto retry;
  2503. } else if (!strncasecmp(&input, "s", 1)) {
  2504. selected = curses_int("Set scantime in seconds");
  2505. if (selected < 0 || selected > 9999) {
  2506. wlogprint("Invalid selection\n");
  2507. goto retry;
  2508. }
  2509. opt_scantime = selected;
  2510. goto retry;
  2511. } else if (!strncasecmp(&input, "r", 1)) {
  2512. selected = curses_int("Retries before failing (-1 infinite)");
  2513. if (selected < -1 || selected > 9999) {
  2514. wlogprint("Invalid selection\n");
  2515. goto retry;
  2516. }
  2517. opt_retries = selected;
  2518. goto retry;
  2519. } else if (!strncasecmp(&input, "p", 1)) {
  2520. selected = curses_int("Seconds to pause before network retries");
  2521. if (selected < 1 || selected > 9999) {
  2522. wlogprint("Invalid selection\n");
  2523. goto retry;
  2524. }
  2525. opt_fail_pause = selected;
  2526. goto retry;
  2527. }
  2528. clear_logwin();
  2529. immedok(logwin, false);
  2530. opt_loginput = false;
  2531. }
  2532. #ifdef HAVE_OPENCL
  2533. static void reinit_device(struct cgpu_info *cgpu);
  2534. static void manage_gpu(void)
  2535. {
  2536. struct thr_info *thr;
  2537. int selected, gpu, i;
  2538. char checkin[40];
  2539. char input;
  2540. if (!opt_g_threads)
  2541. return;
  2542. opt_loginput = true;
  2543. immedok(logwin, true);
  2544. clear_logwin();
  2545. retry:
  2546. for (gpu = 0; gpu < nDevs; gpu++) {
  2547. struct cgpu_info *cgpu = &gpus[gpu];
  2548. wlog("GPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  2549. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  2550. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  2551. cgpu->efficiency, cgpu->utility);
  2552. #ifdef HAVE_ADL
  2553. if (gpus[gpu].has_adl) {
  2554. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  2555. float temp = 0, vddc = 0;
  2556. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  2557. wlog("Temp: %.1f °C\nFan Speed: %d%% (%d RPM)\nEngine Clock: %d MHz\n"
  2558. "Memory Clock: %d Mhz\nVddc: %.3f V\nActivity: %d%%\nPowertune: %d%%\n",
  2559. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  2560. }
  2561. #endif
  2562. wlog("Last initialised: %s\n", cgpu->init);
  2563. for (i = 0; i < mining_threads; i++) {
  2564. thr = &thr_info[i];
  2565. if (thr->cgpu != cgpu)
  2566. continue;
  2567. get_datestamp(checkin, &thr->last);
  2568. wlog("Thread %d: %.1f Mh/s %s ", i, thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled");
  2569. switch (cgpu->status) {
  2570. default:
  2571. case LIFE_WELL:
  2572. wlog("ALIVE");
  2573. break;
  2574. case LIFE_SICK:
  2575. wlog("SICK reported in %s", checkin);
  2576. break;
  2577. case LIFE_DEAD:
  2578. wlog("DEAD reported in %s", checkin);
  2579. break;
  2580. }
  2581. wlog("\n");
  2582. }
  2583. wlog("\n");
  2584. }
  2585. wlogprint("[E]nable [D]isable [R]estart GPU %s\n",adl_active ? "[C]hange settings" : "");
  2586. wlogprint("Or press any other key to continue\n");
  2587. input = getch();
  2588. if (!strncasecmp(&input, "e", 1)) {
  2589. selected = curses_int("Select GPU to enable");
  2590. if (selected < 0 || selected >= nDevs) {
  2591. wlogprint("Invalid selection\n");
  2592. goto retry;
  2593. }
  2594. if (gpu_devices[selected]) {
  2595. wlogprint("Device already enabled\n");
  2596. goto retry;
  2597. }
  2598. gpu_devices[selected] = true;
  2599. for (i = 0; i < gpu_threads; i++) {
  2600. if (dev_from_id(i) != selected)
  2601. continue;
  2602. thr = &thr_info[i];
  2603. if (opt_debug)
  2604. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  2605. tq_push(thr->q, &ping);
  2606. }
  2607. } if (!strncasecmp(&input, "d", 1)) {
  2608. selected = curses_int("Select GPU to disable");
  2609. if (selected < 0 || selected >= nDevs) {
  2610. wlogprint("Invalid selection\n");
  2611. goto retry;
  2612. }
  2613. if (!gpu_devices[selected]) {
  2614. wlogprint("Device already disabled\n");
  2615. goto retry;
  2616. }
  2617. gpu_devices[selected] = false;
  2618. } else if (!strncasecmp(&input, "r", 1)) {
  2619. selected = curses_int("Select GPU to attempt to restart");
  2620. if (selected < 0 || selected >= nDevs) {
  2621. wlogprint("Invalid selection\n");
  2622. goto retry;
  2623. }
  2624. wlogprint("Attempting to restart threads of GPU %d\n", selected);
  2625. reinit_device(&gpus[selected]);
  2626. } else if (adl_active && (!strncasecmp(&input, "c", 1))) {
  2627. selected = curses_int("Select GPU to change settings on");
  2628. if (selected < 0 || selected >= nDevs) {
  2629. wlogprint("Invalid selection\n");
  2630. goto retry;
  2631. }
  2632. change_gpusettings(selected);
  2633. }
  2634. clear_logwin();
  2635. immedok(logwin, false);
  2636. opt_loginput = false;
  2637. }
  2638. #else
  2639. static void manage_gpu(void)
  2640. {
  2641. }
  2642. #endif
  2643. static void *input_thread(void *userdata)
  2644. {
  2645. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2646. if (!curses_active)
  2647. return NULL;
  2648. while (1) {
  2649. char input;
  2650. input = getch();
  2651. if (!strncasecmp(&input, "q", 1)) {
  2652. kill_work();
  2653. return NULL;
  2654. } else if (!strncasecmp(&input, "d", 1))
  2655. display_options();
  2656. else if (!strncasecmp(&input, "p", 1))
  2657. display_pools();
  2658. else if (!strncasecmp(&input, "s", 1))
  2659. set_options();
  2660. else if (!strncasecmp(&input, "g", 1))
  2661. manage_gpu();
  2662. if (opt_realquiet) {
  2663. disable_curses();
  2664. break;
  2665. }
  2666. }
  2667. return NULL;
  2668. }
  2669. static void *workio_thread(void *userdata)
  2670. {
  2671. struct thr_info *mythr = userdata;
  2672. bool ok = true;
  2673. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2674. while (ok) {
  2675. struct workio_cmd *wc;
  2676. if (opt_debug)
  2677. applog(LOG_DEBUG, "Popping work to work thread");
  2678. /* wait for workio_cmd sent to us, on our queue */
  2679. wc = tq_pop(mythr->q, NULL);
  2680. if (unlikely(!wc)) {
  2681. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  2682. ok = false;
  2683. break;
  2684. }
  2685. /* process workio_cmd */
  2686. switch (wc->cmd) {
  2687. case WC_GET_WORK:
  2688. ok = workio_get_work(wc);
  2689. break;
  2690. case WC_SUBMIT_WORK:
  2691. ok = workio_submit_work(wc);
  2692. break;
  2693. case WC_DIE:
  2694. default:
  2695. ok = false;
  2696. break;
  2697. }
  2698. }
  2699. tq_freeze(mythr->q);
  2700. return NULL;
  2701. }
  2702. static void thread_reportin(struct thr_info *thr)
  2703. {
  2704. gettimeofday(&thr->last, NULL);
  2705. thr->cgpu->status = LIFE_WELL;
  2706. thr->getwork = false;
  2707. }
  2708. static inline void thread_reportout(struct thr_info *thr)
  2709. {
  2710. thr->getwork = true;
  2711. }
  2712. static void hashmeter(int thr_id, struct timeval *diff,
  2713. unsigned long hashes_done)
  2714. {
  2715. struct timeval temp_tv_end, total_diff;
  2716. double secs;
  2717. double local_secs;
  2718. double utility, efficiency = 0.0;
  2719. static double local_mhashes_done = 0;
  2720. static double rolling = 0;
  2721. double local_mhashes = (double)hashes_done / 1000000.0;
  2722. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2723. bool showlog = false;
  2724. /* Update the last time this thread reported in */
  2725. if (thr_id >= 0)
  2726. gettimeofday(&thr_info[thr_id].last, NULL);
  2727. /* Don't bother calculating anything if we're not displaying it */
  2728. if (opt_realquiet || !opt_log_interval)
  2729. return;
  2730. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  2731. /* So we can call hashmeter from a non worker thread */
  2732. if (thr_id >= 0) {
  2733. struct thr_info *thr = &thr_info[thr_id];
  2734. double thread_rolling = 0.0;
  2735. int i;
  2736. if (opt_debug)
  2737. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  2738. thr_id, hashes_done, hashes_done / secs);
  2739. /* Rolling average for each thread and each device */
  2740. decay_time(&thr->rolling, local_mhashes / secs);
  2741. for (i = 0; i < mining_threads; i++) {
  2742. struct thr_info *th = &thr_info[i];
  2743. if (th->cgpu == cgpu)
  2744. thread_rolling += th->rolling;
  2745. }
  2746. decay_time(&cgpu->rolling, thread_rolling);
  2747. cgpu->total_mhashes += local_mhashes;
  2748. // If needed, output detailed, per-device stats
  2749. if (want_per_device_stats) {
  2750. struct timeval now;
  2751. struct timeval elapsed;
  2752. gettimeofday(&now, NULL);
  2753. timeval_subtract(&elapsed, &now, &thr->cgpu->last_message_tv);
  2754. if (opt_log_interval <= elapsed.tv_sec) {
  2755. struct cgpu_info *cgpu = thr->cgpu;
  2756. cgpu->last_message_tv = now;
  2757. #ifdef HAVE_ADL
  2758. if (cgpu->has_adl) {
  2759. int gpu = cgpu->cpu_gpu;
  2760. sprintf(
  2761. statusline,
  2762. "[GPU%d %.1f °C (%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  2763. cgpu->cpu_gpu,
  2764. gpu_temp(gpu),
  2765. opt_log_interval,
  2766. cgpu->rolling,
  2767. cgpu->total_mhashes / total_secs,
  2768. cgpu->getworks,
  2769. cgpu->accepted,
  2770. cgpu->rejected,
  2771. cgpu->hw_errors,
  2772. cgpu->efficiency,
  2773. cgpu->utility
  2774. );
  2775. } else
  2776. #endif
  2777. sprintf(
  2778. statusline,
  2779. "[%sPU%d (%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  2780. cgpu->is_gpu ? "G" : "C",
  2781. cgpu->cpu_gpu,
  2782. opt_log_interval,
  2783. cgpu->rolling,
  2784. cgpu->total_mhashes / total_secs,
  2785. cgpu->getworks,
  2786. cgpu->accepted,
  2787. cgpu->rejected,
  2788. cgpu->hw_errors,
  2789. cgpu->efficiency,
  2790. cgpu->utility
  2791. );
  2792. if (!curses_active) {
  2793. printf("%s \r", statusline);
  2794. fflush(stdout);
  2795. } else
  2796. applog(LOG_INFO, "%s", statusline);
  2797. }
  2798. }
  2799. }
  2800. /* Totals are updated by all threads so can race without locking */
  2801. mutex_lock(&hash_lock);
  2802. gettimeofday(&temp_tv_end, NULL);
  2803. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  2804. total_mhashes_done += local_mhashes;
  2805. local_mhashes_done += local_mhashes;
  2806. if (total_diff.tv_sec < opt_log_interval)
  2807. /* Only update the total every opt_log_interval seconds */
  2808. goto out_unlock;
  2809. showlog = true;
  2810. gettimeofday(&total_tv_end, NULL);
  2811. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  2812. decay_time(&rolling, local_mhashes_done / local_secs);
  2813. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  2814. total_secs = (double)total_diff.tv_sec +
  2815. ((double)total_diff.tv_usec / 1000000.0);
  2816. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2817. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2818. sprintf(statusline, "[%s(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  2819. want_per_device_stats ? "ALL " : "",
  2820. opt_log_interval, rolling, total_mhashes_done / total_secs,
  2821. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  2822. local_mhashes_done = 0;
  2823. out_unlock:
  2824. mutex_unlock(&hash_lock);
  2825. if (showlog) {
  2826. if (!curses_active) {
  2827. printf("%s \r", statusline);
  2828. fflush(stdout);
  2829. } else
  2830. applog(LOG_INFO, "%s", statusline);
  2831. }
  2832. }
  2833. static bool pool_active(struct pool *pool, bool pinging)
  2834. {
  2835. bool ret = false;
  2836. json_t *val;
  2837. CURL *curl;
  2838. bool rolltime;
  2839. curl = curl_easy_init();
  2840. if (unlikely(!curl)) {
  2841. applog(LOG_ERR, "CURL initialisation failed");
  2842. return false;
  2843. }
  2844. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  2845. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2846. true, false, &rolltime, pool);
  2847. if (val) {
  2848. struct work *work = make_work();
  2849. bool rc;
  2850. rc = work_decode(json_object_get(val, "result"), work);
  2851. if (rc) {
  2852. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  2853. pool->pool_no, pool->rpc_url);
  2854. work->pool = pool;
  2855. work->rolltime = rolltime;
  2856. if (opt_debug)
  2857. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  2858. tq_push(thr_info[stage_thr_id].q, work);
  2859. total_getworks++;
  2860. pool->getwork_requested++;
  2861. inc_queued();
  2862. ret = true;
  2863. gettimeofday(&pool->tv_idle, NULL);
  2864. } else {
  2865. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  2866. pool->pool_no, pool->rpc_url);
  2867. free_work(work);
  2868. }
  2869. json_decref(val);
  2870. } else {
  2871. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  2872. pool->pool_no, pool->rpc_url);
  2873. if (!pinging)
  2874. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  2875. }
  2876. curl_easy_cleanup(curl);
  2877. return ret;
  2878. }
  2879. static void pool_died(struct pool *pool)
  2880. {
  2881. if (!pool_tset(pool, &pool->idle)) {
  2882. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2883. gettimeofday(&pool->tv_idle, NULL);
  2884. switch_pools(NULL);
  2885. }
  2886. }
  2887. static void pool_resus(struct pool *pool)
  2888. {
  2889. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  2890. if (pool->prio < current_pool()->prio && pool_strategy == POOL_FAILOVER)
  2891. switch_pools(NULL);
  2892. }
  2893. static bool queue_request(struct thr_info *thr, bool needed)
  2894. {
  2895. struct workio_cmd *wc;
  2896. int rq = requests_queued();
  2897. if (rq >= mining_threads + staged_clones)
  2898. return true;
  2899. /* fill out work request message */
  2900. wc = calloc(1, sizeof(*wc));
  2901. if (unlikely(!wc)) {
  2902. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  2903. return false;
  2904. }
  2905. wc->cmd = WC_GET_WORK;
  2906. if (thr)
  2907. wc->thr = thr;
  2908. else
  2909. wc->thr = NULL;
  2910. /* If we're queueing work faster than we can stage it, consider the
  2911. * system lagging and allow work to be gathered from another pool if
  2912. * possible */
  2913. if (rq && needed && !requests_staged() && !opt_fail_only)
  2914. wc->lagging = true;
  2915. if (opt_debug)
  2916. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  2917. /* send work request to workio thread */
  2918. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2919. applog(LOG_ERR, "Failed to tq_push in queue_request");
  2920. workio_cmd_free(wc);
  2921. return false;
  2922. }
  2923. inc_queued();
  2924. return true;
  2925. }
  2926. struct work *hash_pop(const struct timespec *abstime)
  2927. {
  2928. struct work *work = NULL;
  2929. int rc;
  2930. mutex_lock(&getq->mutex);
  2931. if (HASH_COUNT(staged_work))
  2932. goto pop;
  2933. if (abstime)
  2934. rc = pthread_cond_timedwait(&getq->cond, &getq->mutex, abstime);
  2935. else
  2936. rc = pthread_cond_wait(&getq->cond, &getq->mutex);
  2937. if (rc)
  2938. goto out;
  2939. if (!HASH_COUNT(staged_work))
  2940. goto out;
  2941. pop:
  2942. work = staged_work;
  2943. HASH_DEL(staged_work, work);
  2944. if (work->clone)
  2945. --staged_clones;
  2946. out:
  2947. mutex_unlock(&getq->mutex);
  2948. return work;
  2949. }
  2950. static inline bool should_roll(struct work *work)
  2951. {
  2952. int rs;
  2953. rs = requests_staged();
  2954. if (rs >= mining_threads)
  2955. return false;
  2956. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE || !rs)
  2957. return true;
  2958. return false;
  2959. }
  2960. static inline bool can_roll(struct work *work)
  2961. {
  2962. return (work->pool && !stale_work(work) && work->rolltime &&
  2963. work->rolls < 11 && !work->clone);
  2964. }
  2965. static void roll_work(struct work *work)
  2966. {
  2967. uint32_t *work_ntime;
  2968. uint32_t ntime;
  2969. work_ntime = (uint32_t *)(work->data + 68);
  2970. ntime = be32toh(*work_ntime);
  2971. ntime++;
  2972. *work_ntime = htobe32(ntime);
  2973. local_work++;
  2974. work->rolls++;
  2975. work->blk.nonce = 0;
  2976. if (opt_debug)
  2977. applog(LOG_DEBUG, "Successfully rolled work");
  2978. }
  2979. /* Recycle the work at a higher starting res_nonce if we know the thread we're
  2980. * giving it to will not finish scanning it. We keep the master copy to be
  2981. * recycled more rapidly and discard the clone to avoid repeating work */
  2982. static bool divide_work(struct timeval *now, struct work *work, uint32_t hash_div)
  2983. {
  2984. uint64_t hash_inc;
  2985. if (work->clone)
  2986. return false;
  2987. hash_inc = MAXTHREADS / hash_div * 2;
  2988. if ((uint64_t)work->blk.nonce + hash_inc < MAXTHREADS) {
  2989. /* Okay we can divide it up */
  2990. work->blk.nonce += hash_inc;
  2991. work->cloned = true;
  2992. local_work++;
  2993. if (opt_debug)
  2994. applog(LOG_DEBUG, "Successfully divided work");
  2995. return true;
  2996. } else if (can_roll(work) && should_roll(work)) {
  2997. roll_work(work);
  2998. return true;
  2999. }
  3000. return false;
  3001. }
  3002. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  3003. const int thr_id, uint32_t hash_div)
  3004. {
  3005. struct timespec abstime = {};
  3006. struct timeval now;
  3007. struct work *work_heap;
  3008. struct pool *pool;
  3009. bool ret = false;
  3010. int failures = 0;
  3011. /* Tell the watchdog thread this thread is waiting on getwork and
  3012. * should not be restarted */
  3013. thread_reportout(thr);
  3014. retry:
  3015. pool = current_pool();
  3016. if (unlikely((!requested || requests_queued() < opt_queue) && !queue_request(thr, true))) {
  3017. applog(LOG_WARNING, "Failed to queue_request in get_work");
  3018. goto out;
  3019. }
  3020. if (!requests_staged()) {
  3021. if (can_roll(work)) {
  3022. roll_work(work);
  3023. ret = true;
  3024. goto out;
  3025. }
  3026. if (requested && requests_queued() >= mining_threads &&
  3027. !pool_tset(pool, &pool->lagging)) {
  3028. applog(LOG_WARNING, "Pool %d not providing work fast enough",
  3029. pool->pool_no);
  3030. pool->getfail_occasions++;
  3031. total_go++;
  3032. }
  3033. }
  3034. requested = false;
  3035. gettimeofday(&now, NULL);
  3036. abstime.tv_sec = now.tv_sec + 60;
  3037. if (opt_debug)
  3038. applog(LOG_DEBUG, "Popping work from get queue to get work");
  3039. /* wait for 1st response, or get cached response */
  3040. work_heap = hash_pop(&abstime);
  3041. if (unlikely(!work_heap)) {
  3042. /* Attempt to switch pools if this one times out */
  3043. pool_died(pool);
  3044. goto retry;
  3045. }
  3046. if (stale_work(work_heap)) {
  3047. dec_queued();
  3048. discard_work(work_heap);
  3049. goto retry;
  3050. }
  3051. pool = work_heap->pool;
  3052. /* If we make it here we have succeeded in getting fresh work */
  3053. if (!work_heap->mined) {
  3054. pool_tclear(pool, &pool->lagging);
  3055. if (pool_tclear(pool, &pool->idle))
  3056. pool_resus(pool);
  3057. }
  3058. memcpy(work, work_heap, sizeof(*work));
  3059. /* Copy the res nonce back so we know to start at a higher baseline
  3060. * should we divide the same work up again. Make the work we're
  3061. * handing out be clone */
  3062. if (divide_work(&now, work_heap, hash_div)) {
  3063. if (opt_debug)
  3064. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  3065. hash_push(work_heap);
  3066. work->clone = true;
  3067. } else {
  3068. dec_queued();
  3069. free_work(work_heap);
  3070. }
  3071. ret = true;
  3072. out:
  3073. if (unlikely(ret == false)) {
  3074. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  3075. applog(LOG_ERR, "Failed %d times to get_work");
  3076. return ret;
  3077. }
  3078. applog(LOG_DEBUG, "Retrying after %d seconds", fail_pause);
  3079. sleep(fail_pause);
  3080. fail_pause += opt_fail_pause;
  3081. goto retry;
  3082. }
  3083. fail_pause = opt_fail_pause;
  3084. work->thr_id = thr_id;
  3085. thread_reportin(thr);
  3086. if (ret)
  3087. work->mined = true;
  3088. return ret;
  3089. }
  3090. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  3091. {
  3092. struct workio_cmd *wc;
  3093. /* fill out work request message */
  3094. wc = calloc(1, sizeof(*wc));
  3095. if (unlikely(!wc)) {
  3096. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  3097. return false;
  3098. }
  3099. wc->u.work = make_work();
  3100. wc->cmd = WC_SUBMIT_WORK;
  3101. wc->thr = thr;
  3102. memcpy(wc->u.work, work_in, sizeof(*work_in));
  3103. if (opt_debug)
  3104. applog(LOG_DEBUG, "Pushing submit work to work thread");
  3105. /* send solution to workio thread */
  3106. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3107. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  3108. goto err_out;
  3109. }
  3110. return true;
  3111. err_out:
  3112. workio_cmd_free(wc);
  3113. return false;
  3114. }
  3115. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  3116. {
  3117. work->data[64+12+0] = (nonce>>0) & 0xff;
  3118. work->data[64+12+1] = (nonce>>8) & 0xff;
  3119. work->data[64+12+2] = (nonce>>16) & 0xff;
  3120. work->data[64+12+3] = (nonce>>24) & 0xff;
  3121. /* Do one last check before attempting to submit the work */
  3122. if (!fulltest(work->data + 64, work->target))
  3123. return true;
  3124. return submit_work_sync(thr, work);
  3125. }
  3126. static void *miner_thread(void *userdata)
  3127. {
  3128. struct work *work = make_work();
  3129. struct thr_info *mythr = userdata;
  3130. const int thr_id = mythr->id;
  3131. uint32_t max_nonce = 0xffffff, total_hashes = 0;
  3132. unsigned long hashes_done = max_nonce;
  3133. bool needs_work = true;
  3134. /* Try to cycle approximately 5 times before each log update */
  3135. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  3136. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3137. bool requested = false;
  3138. uint32_t nonce_inc = max_nonce, hash_div = 1;
  3139. double hash_divfloat = 1.0;
  3140. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3141. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  3142. * and if that fails, then SCHED_BATCH. No need for this to be an
  3143. * error if it fails */
  3144. setpriority(PRIO_PROCESS, 0, 19);
  3145. drop_policy();
  3146. /* Cpu affinity only makes sense if the number of threads is a multiple
  3147. * of the number of CPUs */
  3148. if (!(opt_n_threads % num_processors))
  3149. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  3150. /* Invalidate pool so it fails can_roll() test */
  3151. work->pool = NULL;
  3152. while (1) {
  3153. struct timeval tv_workstart, tv_start, tv_end, diff;
  3154. uint64_t max64;
  3155. bool rc;
  3156. if (needs_work) {
  3157. gettimeofday(&tv_workstart, NULL);
  3158. /* obtain new work from internal workio thread */
  3159. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3160. applog(LOG_ERR, "work retrieval failed, exiting "
  3161. "mining thread %d", thr_id);
  3162. goto out;
  3163. }
  3164. needs_work = requested = false;
  3165. total_hashes = 0;
  3166. max_nonce = work->blk.nonce + hashes_done;
  3167. }
  3168. hashes_done = 0;
  3169. gettimeofday(&tv_start, NULL);
  3170. /* scan nonces for a proof-of-work hash */
  3171. switch (opt_algo) {
  3172. case ALGO_C:
  3173. rc = scanhash_c(thr_id, work->midstate, work->data + 64,
  3174. work->hash1, work->hash, work->target,
  3175. max_nonce, &hashes_done,
  3176. work->blk.nonce);
  3177. break;
  3178. #ifdef WANT_X8632_SSE2
  3179. case ALGO_SSE2_32: {
  3180. unsigned int rc5 =
  3181. scanhash_sse2_32(thr_id, work->midstate, work->data + 64,
  3182. work->hash1, work->hash,
  3183. work->target,
  3184. max_nonce, &hashes_done,
  3185. work->blk.nonce);
  3186. rc = (rc5 == -1) ? false : true;
  3187. }
  3188. break;
  3189. #endif
  3190. #ifdef WANT_X8664_SSE2
  3191. case ALGO_SSE2_64: {
  3192. unsigned int rc5 =
  3193. scanhash_sse2_64(thr_id, work->midstate, work->data + 64,
  3194. work->hash1, work->hash,
  3195. work->target,
  3196. max_nonce, &hashes_done,
  3197. work->blk.nonce);
  3198. rc = (rc5 == -1) ? false : true;
  3199. }
  3200. break;
  3201. #endif
  3202. #ifdef WANT_X8664_SSE4
  3203. case ALGO_SSE4_64: {
  3204. unsigned int rc5 =
  3205. scanhash_sse4_64(thr_id, work->midstate, work->data + 64,
  3206. work->hash1, work->hash,
  3207. work->target,
  3208. max_nonce, &hashes_done,
  3209. work->blk.nonce);
  3210. rc = (rc5 == -1) ? false : true;
  3211. }
  3212. break;
  3213. #endif
  3214. #ifdef WANT_SSE2_4WAY
  3215. case ALGO_4WAY: {
  3216. unsigned int rc4 =
  3217. ScanHash_4WaySSE2(thr_id, work->midstate, work->data + 64,
  3218. work->hash1, work->hash,
  3219. work->target,
  3220. max_nonce, &hashes_done,
  3221. work->blk.nonce);
  3222. rc = (rc4 == -1) ? false : true;
  3223. }
  3224. break;
  3225. #endif
  3226. #ifdef WANT_VIA_PADLOCK
  3227. case ALGO_VIA:
  3228. rc = scanhash_via(thr_id, work->data, work->target,
  3229. max_nonce, &hashes_done,
  3230. work->blk.nonce);
  3231. break;
  3232. #endif
  3233. case ALGO_CRYPTOPP:
  3234. rc = scanhash_cryptopp(thr_id, work->midstate, work->data + 64,
  3235. work->hash1, work->hash, work->target,
  3236. max_nonce, &hashes_done,
  3237. work->blk.nonce);
  3238. break;
  3239. #ifdef WANT_CRYPTOPP_ASM32
  3240. case ALGO_CRYPTOPP_ASM32:
  3241. rc = scanhash_asm32(thr_id, work->midstate, work->data + 64,
  3242. work->hash1, work->hash, work->target,
  3243. max_nonce, &hashes_done,
  3244. work->blk.nonce);
  3245. break;
  3246. #endif
  3247. default:
  3248. /* should never happen */
  3249. goto out;
  3250. }
  3251. /* record scanhash elapsed time */
  3252. gettimeofday(&tv_end, NULL);
  3253. timeval_subtract(&diff, &tv_end, &tv_start);
  3254. hashes_done -= work->blk.nonce;
  3255. hashmeter(thr_id, &diff, hashes_done);
  3256. total_hashes += hashes_done;
  3257. work->blk.nonce += hashes_done;
  3258. /* adjust max_nonce to meet target cycle time */
  3259. if (diff.tv_usec > 500000)
  3260. diff.tv_sec++;
  3261. if (diff.tv_sec && diff.tv_sec != cycle) {
  3262. uint64_t next_inc = ((uint64_t)hashes_done * (uint64_t)cycle) / (uint64_t)diff.tv_sec;
  3263. if (next_inc > (uint64_t)nonce_inc / 2 * 3)
  3264. next_inc = nonce_inc / 2 * 3;
  3265. nonce_inc = next_inc;
  3266. } else if (!diff.tv_sec)
  3267. nonce_inc = hashes_done * 2;
  3268. if (nonce_inc < 4)
  3269. nonce_inc = 0xffffff;
  3270. max64 = work->blk.nonce + nonce_inc;
  3271. if (max64 > 0xfffffffaULL)
  3272. max64 = 0xfffffffaULL;
  3273. max_nonce = max64;
  3274. /* if nonce found, submit work */
  3275. if (unlikely(rc)) {
  3276. if (opt_debug)
  3277. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  3278. if (unlikely(!submit_work_sync(mythr, work))) {
  3279. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  3280. break;
  3281. }
  3282. work->blk.nonce += 4;
  3283. }
  3284. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3285. if (!requested && (diff.tv_sec >= request_interval)) {
  3286. thread_reportout(mythr);
  3287. if (unlikely(!queue_request(mythr, false))) {
  3288. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  3289. goto out;
  3290. }
  3291. thread_reportin(mythr);
  3292. requested = true;
  3293. }
  3294. if (diff.tv_sec > opt_scantime) {
  3295. decay_time(&hash_divfloat , (double)((MAXTHREADS / total_hashes) ? : 1));
  3296. hash_div = hash_divfloat;
  3297. needs_work = true;
  3298. } else if (work_restart[thr_id].restart || stale_work(work) ||
  3299. work->blk.nonce >= MAXTHREADS - hashes_done)
  3300. needs_work = true;
  3301. if (unlikely(mythr->pause)) {
  3302. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3303. mythr->rolling = mythr->cgpu->rolling = 0;
  3304. if (opt_debug)
  3305. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  3306. thread_reportout(mythr);
  3307. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3308. thread_reportin(mythr);
  3309. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3310. }
  3311. }
  3312. out:
  3313. thread_reportin(mythr);
  3314. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3315. tq_freeze(mythr->q);
  3316. return NULL;
  3317. }
  3318. enum {
  3319. STAT_SLEEP_INTERVAL = 1,
  3320. STAT_CTR_INTERVAL = 10000000,
  3321. FAILURE_INTERVAL = 30,
  3322. };
  3323. #ifdef HAVE_OPENCL
  3324. static _clState *clStates[16];
  3325. static cl_int queue_poclbm_kernel(_clState *clState, dev_blk_ctx *blk)
  3326. {
  3327. cl_kernel *kernel = &clState->kernel;
  3328. cl_int status = 0;
  3329. int num = 0;
  3330. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  3331. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  3332. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  3333. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  3334. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  3335. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  3336. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  3337. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  3338. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  3339. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3340. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3341. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3342. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3343. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3344. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  3345. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  3346. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  3347. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  3348. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  3349. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  3350. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  3351. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  3352. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  3353. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  3354. (void *)&clState->outputBuffer);
  3355. return status;
  3356. }
  3357. static cl_int queue_phatk_kernel(_clState *clState, dev_blk_ctx *blk)
  3358. {
  3359. cl_uint vwidth = clState->preferred_vwidth;
  3360. cl_kernel *kernel = &clState->kernel;
  3361. cl_int status = 0;
  3362. int i, num = 0;
  3363. uint *nonces;
  3364. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  3365. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  3366. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  3367. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  3368. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  3369. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  3370. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  3371. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  3372. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  3373. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3374. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3375. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3376. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3377. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3378. nonces = alloca(sizeof(uint) * vwidth);
  3379. for (i = 0; i < vwidth; i++)
  3380. nonces[i] = blk->nonce + i;
  3381. status |= clSetKernelArg(*kernel, num++, vwidth * sizeof(uint), (void *)nonces);
  3382. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  3383. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  3384. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4_2);
  3385. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal0);
  3386. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW18);
  3387. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW19);
  3388. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW31);
  3389. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW32);
  3390. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  3391. (void *)&clState->outputBuffer);
  3392. return status;
  3393. }
  3394. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  3395. unsigned int *hashes, size_t *globalThreads,
  3396. unsigned int minthreads)
  3397. {
  3398. *threads = 1 << (15 + scan_intensity);
  3399. if (*threads < minthreads)
  3400. *threads = minthreads;
  3401. *globalThreads = *threads;
  3402. *hashes = *threads * vectors;
  3403. }
  3404. static void *gpuminer_thread(void *userdata)
  3405. {
  3406. cl_int (*queue_kernel_parameters)(_clState *, dev_blk_ctx *);
  3407. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  3408. struct timeval tv_start, tv_end, diff, tv_workstart;
  3409. struct thr_info *mythr = userdata;
  3410. const int thr_id = mythr->id;
  3411. uint32_t *res, *blank_res;
  3412. double gpu_ms_average = 7;
  3413. int gpu = dev_from_id(thr_id);
  3414. size_t globalThreads[1];
  3415. size_t localThreads[1];
  3416. cl_int status;
  3417. _clState *clState = clStates[thr_id];
  3418. const cl_kernel *kernel = &clState->kernel;
  3419. struct work *work = make_work();
  3420. unsigned int threads;
  3421. unsigned const int vectors = clState->preferred_vwidth;
  3422. unsigned int hashes;
  3423. unsigned int hashes_done = 0;
  3424. /* Request the next work item at 2/3 of the scantime */
  3425. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3426. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  3427. bool requested = false;
  3428. uint32_t total_hashes = 0, hash_div = 1;
  3429. switch (chosen_kernel) {
  3430. case KL_POCLBM:
  3431. queue_kernel_parameters = &queue_poclbm_kernel;
  3432. break;
  3433. case KL_PHATK:
  3434. default:
  3435. queue_kernel_parameters = &queue_phatk_kernel;
  3436. break;
  3437. }
  3438. if (opt_dynamic) {
  3439. /* Minimise impact on desktop if we want dynamic mode */
  3440. setpriority(PRIO_PROCESS, 0, 19);
  3441. drop_policy();
  3442. }
  3443. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3444. res = calloc(BUFFERSIZE, 1);
  3445. blank_res = calloc(BUFFERSIZE, 1);
  3446. if (!res || !blank_res) {
  3447. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  3448. goto out;
  3449. }
  3450. gettimeofday(&tv_start, NULL);
  3451. localThreads[0] = clState->work_size;
  3452. set_threads_hashes(vectors, &threads, &hashes, &globalThreads[0],
  3453. localThreads[0]);
  3454. diff.tv_sec = 0;
  3455. gettimeofday(&tv_end, NULL);
  3456. work->pool = NULL;
  3457. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  3458. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3459. if (unlikely(status != CL_SUCCESS))
  3460. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3461. mythr->cgpu->status = LIFE_WELL;
  3462. if (opt_debug)
  3463. applog(LOG_DEBUG, "Popping ping in gpuminer thread");
  3464. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  3465. gettimeofday(&tv_workstart, NULL);
  3466. /* obtain new work from internal workio thread */
  3467. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3468. applog(LOG_ERR, "work retrieval failed, exiting "
  3469. "gpu mining thread %d", thr_id);
  3470. goto out;
  3471. }
  3472. requested = false;
  3473. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3474. work->blk.nonce = 0;
  3475. while (1) {
  3476. struct timeval tv_gpustart, tv_gpuend;
  3477. suseconds_t gpu_us;
  3478. gettimeofday(&tv_gpustart, NULL);
  3479. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  3480. /* This finish flushes the readbuffer set with CL_FALSE later */
  3481. clFinish(clState->commandQueue);
  3482. gettimeofday(&tv_gpuend, NULL);
  3483. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  3484. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  3485. decay_time(&gpu_ms_average, gpu_us / 1000);
  3486. if (opt_dynamic) {
  3487. /* Try to not let the GPU be out for longer than 6ms, but
  3488. * increase intensity when the system is idle, unless
  3489. * dynamic is disabled. */
  3490. if (gpu_ms_average > 7) {
  3491. if (scan_intensity > -10)
  3492. scan_intensity--;
  3493. } else if (gpu_ms_average < 3) {
  3494. if (scan_intensity < 10)
  3495. scan_intensity++;
  3496. }
  3497. }
  3498. set_threads_hashes(vectors, &threads, &hashes, globalThreads, localThreads[0]);
  3499. if (diff.tv_sec > opt_scantime ||
  3500. work->blk.nonce >= MAXTHREADS - hashes ||
  3501. work_restart[thr_id].restart ||
  3502. stale_work(work)) {
  3503. /* Ignore any reads since we're getting new work and queue a clean buffer */
  3504. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3505. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3506. if (unlikely(status != CL_SUCCESS))
  3507. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3508. memset(res, 0, BUFFERSIZE);
  3509. gettimeofday(&tv_workstart, NULL);
  3510. if (opt_debug)
  3511. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  3512. /* obtain new work from internal workio thread */
  3513. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3514. applog(LOG_ERR, "work retrieval failed, exiting "
  3515. "gpu mining thread %d", thr_id);
  3516. goto out;
  3517. }
  3518. requested = false;
  3519. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3520. work_restart[thr_id].restart = 0;
  3521. /* Flushes the writebuffer set with CL_FALSE above */
  3522. clFinish(clState->commandQueue);
  3523. }
  3524. status = queue_kernel_parameters(clState, &work->blk);
  3525. if (unlikely(status != CL_SUCCESS))
  3526. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  3527. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  3528. if (res[FOUND]) {
  3529. /* Clear the buffer again */
  3530. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3531. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3532. if (unlikely(status != CL_SUCCESS))
  3533. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3534. if (opt_debug)
  3535. applog(LOG_DEBUG, "GPU %d found something?", gpu);
  3536. postcalc_hash_async(mythr, work, res);
  3537. memset(res, 0, BUFFERSIZE);
  3538. clFinish(clState->commandQueue);
  3539. }
  3540. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  3541. globalThreads, localThreads, 0, NULL, NULL);
  3542. if (unlikely(status != CL_SUCCESS))
  3543. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  3544. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3545. BUFFERSIZE, res, 0, NULL, NULL);
  3546. if (unlikely(status != CL_SUCCESS))
  3547. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  3548. gettimeofday(&tv_end, NULL);
  3549. timeval_subtract(&diff, &tv_end, &tv_start);
  3550. hashes_done += hashes;
  3551. total_hashes += hashes;
  3552. work->blk.nonce += hashes;
  3553. if (diff.tv_sec >= cycle) {
  3554. hashmeter(thr_id, &diff, hashes_done);
  3555. gettimeofday(&tv_start, NULL);
  3556. hashes_done = 0;
  3557. }
  3558. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3559. if (!requested) {
  3560. #if 0
  3561. if (diff.tv_sec > request_interval)
  3562. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  3563. #endif
  3564. if (diff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  3565. thread_reportout(mythr);
  3566. if (unlikely(!queue_request(mythr, false))) {
  3567. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  3568. goto out;
  3569. }
  3570. thread_reportin(mythr);
  3571. requested = true;
  3572. }
  3573. }
  3574. if (unlikely(!gpu_devices[gpu] || mythr->pause)) {
  3575. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3576. mythr->rolling = mythr->cgpu->rolling = 0;
  3577. if (opt_debug)
  3578. applog(LOG_DEBUG, "Popping wakeup ping in gpuminer thread");
  3579. thread_reportout(mythr);
  3580. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3581. thread_reportin(mythr);
  3582. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3583. }
  3584. }
  3585. out:
  3586. clReleaseCommandQueue(clState->commandQueue);
  3587. clReleaseKernel(clState->kernel);
  3588. clReleaseProgram(clState->program);
  3589. clReleaseContext(clState->context);
  3590. thread_reportin(mythr);
  3591. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3592. tq_freeze(mythr->q);
  3593. return NULL;
  3594. }
  3595. #endif /* HAVE_OPENCL */
  3596. /* Stage another work item from the work returned in a longpoll */
  3597. static void convert_to_work(json_t *val, bool rolltime)
  3598. {
  3599. struct work *work;
  3600. bool rc;
  3601. work = make_work();
  3602. rc= work_decode(json_object_get(val, "result"), work);
  3603. if (unlikely(!rc)) {
  3604. applog(LOG_ERR, "Could not convert longpoll data to work");
  3605. return;
  3606. }
  3607. work->pool = current_pool();
  3608. work->rolltime = rolltime;
  3609. if (opt_debug)
  3610. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  3611. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  3612. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  3613. else if (opt_debug)
  3614. applog(LOG_DEBUG, "Converted longpoll data to work");
  3615. }
  3616. static void *longpoll_thread(void *userdata)
  3617. {
  3618. struct thr_info *mythr = userdata;
  3619. CURL *curl = NULL;
  3620. char *copy_start, *hdr_path, *lp_url = NULL;
  3621. bool need_slash = false;
  3622. int failures = 0;
  3623. struct pool *pool = current_pool();
  3624. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3625. pthread_detach(pthread_self());
  3626. curl = curl_easy_init();
  3627. if (unlikely(!curl)) {
  3628. applog(LOG_ERR, "CURL initialisation failed");
  3629. goto out;
  3630. }
  3631. tq_pop(mythr->q, NULL);
  3632. if (!pool->hdr_path) {
  3633. applog(LOG_WARNING, "No long-poll found on this server");
  3634. goto out;
  3635. }
  3636. hdr_path = pool->hdr_path;
  3637. /* full URL */
  3638. if (strstr(hdr_path, "://")) {
  3639. lp_url = hdr_path;
  3640. hdr_path = NULL;
  3641. }
  3642. /* absolute path, on current server */
  3643. else {
  3644. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3645. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3646. need_slash = true;
  3647. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3648. if (!lp_url)
  3649. goto out;
  3650. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3651. }
  3652. have_longpoll = true;
  3653. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  3654. while (1) {
  3655. struct timeval start, end;
  3656. bool rolltime;
  3657. json_t *val;
  3658. gettimeofday(&start, NULL);
  3659. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  3660. false, true, &rolltime, pool);
  3661. if (likely(val)) {
  3662. /* Keep track of who ordered a restart_threads to make
  3663. * sure it's only done once per new block */
  3664. if (block_changed != BLOCK_DETECT) {
  3665. block_changed = BLOCK_LP;
  3666. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  3667. } else {
  3668. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  3669. block_changed = BLOCK_NONE;
  3670. }
  3671. convert_to_work(val, rolltime);
  3672. failures = 0;
  3673. json_decref(val);
  3674. } else {
  3675. /* Some pools regularly drop the longpoll request so
  3676. * only see this as longpoll failure if it happens
  3677. * immediately and just restart it the rest of the
  3678. * time. */
  3679. gettimeofday(&end, NULL);
  3680. if (end.tv_sec - start.tv_sec > 30)
  3681. continue;
  3682. if (failures++ < 10) {
  3683. sleep(30);
  3684. applog(LOG_WARNING,
  3685. "longpoll failed for %s, sleeping for 30s", lp_url);
  3686. } else {
  3687. applog(LOG_ERR,
  3688. "longpoll failed for %s, ending thread", lp_url);
  3689. goto out;
  3690. }
  3691. }
  3692. }
  3693. out:
  3694. have_longpoll = false;
  3695. tq_freeze(mythr->q);
  3696. if (curl)
  3697. curl_easy_cleanup(curl);
  3698. return NULL;
  3699. }
  3700. static void stop_longpoll(void)
  3701. {
  3702. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3703. tq_freeze(thr->q);
  3704. if (thr->pth)
  3705. pthread_cancel(*thr->pth);
  3706. have_longpoll = false;
  3707. }
  3708. static void start_longpoll(void)
  3709. {
  3710. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3711. tq_thaw(thr->q);
  3712. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  3713. quit(1, "longpoll thread create failed");
  3714. if (opt_debug)
  3715. applog(LOG_DEBUG, "Pushing ping to longpoll thread");
  3716. tq_push(thr_info[longpoll_thr_id].q, &ping);
  3717. }
  3718. static void restart_longpoll(void)
  3719. {
  3720. stop_longpoll();
  3721. if (want_longpoll)
  3722. start_longpoll();
  3723. }
  3724. static void *reinit_cpu(void *userdata)
  3725. {
  3726. pthread_detach(pthread_self());
  3727. #if 0
  3728. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  3729. int cpu = cgpu->cpu_gpu;
  3730. long thr_id = ....(long)userdata;
  3731. struct thr_info *thr = &thr_info[thr_id];
  3732. int cpu = dev_from_id(thr_id);
  3733. cpus[cpu].alive = false;
  3734. thr->rolling = thr->cgpu->rolling = 0;
  3735. tq_freeze(thr->q);
  3736. if (!pthread_cancel(*thr->pth))
  3737. pthread_join(*thr->pth, NULL);
  3738. free(thr->q);
  3739. thr->q = tq_new();
  3740. if (!thr->q)
  3741. quit(1, "Failed to tq_new in reinit_cputhread");
  3742. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  3743. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  3744. applog(LOG_ERR, "thread %d create failed", thr_id);
  3745. return NULL;
  3746. }
  3747. tq_push(thr->q, &ping);
  3748. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3749. #endif
  3750. return NULL;
  3751. }
  3752. #ifdef HAVE_OPENCL
  3753. /* We have only one thread that ever re-initialises GPUs, thus if any GPU
  3754. * init command fails due to a completely wedged GPU, the thread will never
  3755. * return, unable to harm other GPUs. If it does return, it means we only had
  3756. * a soft failure and then the reinit_gpu thread is ready to tackle another
  3757. * GPU */
  3758. static void *reinit_gpu(void *userdata)
  3759. {
  3760. struct thr_info *mythr = userdata;
  3761. struct cgpu_info *cgpu;
  3762. struct thr_info *thr;
  3763. struct timeval now;
  3764. char name[256];
  3765. int thr_id;
  3766. int gpu;
  3767. pthread_detach(pthread_self());
  3768. select_cgpu:
  3769. cgpu = tq_pop(mythr->q, NULL);
  3770. if (!cgpu)
  3771. goto out;
  3772. if (clDevicesNum() != nDevs) {
  3773. applog(LOG_WARNING, "Hardware not reporting same number of active devices, will not attempt to restart GPU");
  3774. goto out;
  3775. }
  3776. gpu = cgpu->cpu_gpu;
  3777. gpu_devices[gpu] = false;
  3778. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3779. if (dev_from_id(thr_id) != gpu)
  3780. continue;
  3781. thr = &thr_info[thr_id];
  3782. thr->rolling = thr->cgpu->rolling = 0;
  3783. /* Reports the last time we tried to revive a sick GPU */
  3784. gettimeofday(&thr->sick, NULL);
  3785. if (!pthread_cancel(*thr->pth)) {
  3786. applog(LOG_WARNING, "Thread %d still exists, killing it off", thr_id);
  3787. } else
  3788. applog(LOG_WARNING, "Thread %d no longer exists", thr_id);
  3789. }
  3790. gpu_devices[gpu] = true;
  3791. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3792. if (dev_from_id(thr_id) != gpu)
  3793. continue;
  3794. thr = &thr_info[thr_id];
  3795. /* Lose this ram cause we may get stuck here! */
  3796. //tq_freeze(thr->q);
  3797. thr->q = tq_new();
  3798. if (!thr->q)
  3799. quit(1, "Failed to tq_new in reinit_gpu");
  3800. /* Lose this ram cause we may dereference in the dying thread! */
  3801. //free(clState);
  3802. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  3803. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  3804. if (!clStates[thr_id]) {
  3805. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  3806. goto select_cgpu;
  3807. }
  3808. applog(LOG_INFO, "initCl() finished. Found %s", name);
  3809. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  3810. applog(LOG_ERR, "thread %d create failed", thr_id);
  3811. return NULL;
  3812. }
  3813. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3814. }
  3815. gettimeofday(&now, NULL);
  3816. get_datestamp(cgpu->init, &now);
  3817. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3818. if (dev_from_id(thr_id) != gpu)
  3819. continue;
  3820. thr = &thr_info[thr_id];
  3821. tq_push(thr->q, &ping);
  3822. }
  3823. goto select_cgpu;
  3824. out:
  3825. return NULL;
  3826. }
  3827. #else
  3828. static void *reinit_gpu(void *userdata)
  3829. {
  3830. }
  3831. #endif
  3832. static void reinit_device(struct cgpu_info *cgpu)
  3833. {
  3834. if (cgpu->is_gpu)
  3835. tq_push(thr_info[gpur_thr_id].q, cgpu);
  3836. else
  3837. tq_push(thr_info[cpur_thr_id].q, cgpu);
  3838. }
  3839. /* Determine which are the first threads belonging to a device and if they're
  3840. * active */
  3841. static bool active_device(int thr_id)
  3842. {
  3843. if (thr_id < gpu_threads) {
  3844. if (thr_id >= total_devices)
  3845. return false;
  3846. if (!gpu_devices[dev_from_id(thr_id)])
  3847. return false;
  3848. } else if (thr_id > gpu_threads + num_processors)
  3849. return false;
  3850. return true;
  3851. }
  3852. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  3853. * the screen at regular intervals, and restarts threads if they appear to have
  3854. * died. */
  3855. static void *watchdog_thread(void *userdata)
  3856. {
  3857. const unsigned int interval = opt_log_interval / 2 ? : 1;
  3858. static struct timeval rotate_tv;
  3859. struct timeval zero_tv;
  3860. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3861. memset(&zero_tv, 0, sizeof(struct timeval));
  3862. gettimeofday(&rotate_tv, NULL);
  3863. while (1) {
  3864. int i;
  3865. struct timeval now;
  3866. sleep(interval);
  3867. if (requests_queued() < opt_queue)
  3868. queue_request(NULL, false);
  3869. hashmeter(-1, &zero_tv, 0);
  3870. if (curses_active_locked()) {
  3871. change_logwinsize();
  3872. curses_print_status();
  3873. for (i = 0; i < mining_threads; i++)
  3874. curses_print_devstatus(i);
  3875. clearok(statuswin, true);
  3876. doupdate();
  3877. unlock_curses();
  3878. }
  3879. gettimeofday(&now, NULL);
  3880. for (i = 0; i < total_pools; i++) {
  3881. struct pool *pool = pools[i];
  3882. if (!pool->enabled)
  3883. continue;
  3884. /* Test pool is idle once every minute */
  3885. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  3886. gettimeofday(&pool->tv_idle, NULL);
  3887. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  3888. pool_resus(pool);
  3889. }
  3890. }
  3891. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  3892. gettimeofday(&rotate_tv, NULL);
  3893. switch_pools(NULL);
  3894. }
  3895. if (!sched_paused && !should_run()) {
  3896. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  3897. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3898. if (!schedstart.enable) {
  3899. quit(0, "Terminating execution as planned");
  3900. break;
  3901. }
  3902. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  3903. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3904. sched_paused = true;
  3905. for (i = 0; i < mining_threads; i++) {
  3906. struct thr_info *thr;
  3907. thr = &thr_info[i];
  3908. thr->pause = true;
  3909. }
  3910. } else if (sched_paused && should_run()) {
  3911. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  3912. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3913. if (schedstop.enable)
  3914. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  3915. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3916. sched_paused = false;
  3917. for (i = 0; i < mining_threads; i++) {
  3918. struct thr_info *thr;
  3919. thr = &thr_info[i];
  3920. /* Don't touch disabled GPUs */
  3921. if (thr->cgpu->is_gpu && !gpu_devices[thr->cgpu->cpu_gpu])
  3922. continue;
  3923. thr->pause = false;
  3924. tq_push(thr->q, &ping);
  3925. }
  3926. }
  3927. for (i = 0; i < gpu_threads; i++) {
  3928. struct thr_info *thr;
  3929. int gpu;
  3930. /* Use only one thread per device to determine if the GPU is healthy */
  3931. if (i >= nDevs)
  3932. break;
  3933. thr = &thr_info[i];
  3934. gpu = thr->cgpu->cpu_gpu;
  3935. #ifdef HAVE_ADL
  3936. if (adl_active)
  3937. gpu_autotune(gpu);
  3938. if (opt_debug && gpus[gpu].has_adl) {
  3939. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  3940. float temp = 0, vddc = 0;
  3941. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  3942. applog(LOG_DEBUG, "%.1f°C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  3943. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  3944. }
  3945. #endif
  3946. /* Thread is waiting on getwork or disabled */
  3947. if (thr->getwork || !gpu_devices[gpu])
  3948. continue;
  3949. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  3950. applog(LOG_ERR, "Thread %d recovered, GPU %d declared WELL!", i, gpu);
  3951. gpus[gpu].status = LIFE_WELL;
  3952. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  3953. thr->rolling = thr->cgpu->rolling = 0;
  3954. gpus[gpu].status = LIFE_SICK;
  3955. applog(LOG_ERR, "Thread %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  3956. gettimeofday(&thr->sick, NULL);
  3957. if (opt_restart) {
  3958. applog(LOG_ERR, "Attempting to restart GPU");
  3959. reinit_device(thr->cgpu);
  3960. }
  3961. } else if (now.tv_sec - thr->last.tv_sec > 600 && gpus[i].status == LIFE_SICK) {
  3962. gpus[gpu].status = LIFE_DEAD;
  3963. applog(LOG_ERR, "Thread %d not responding for more than 10 minutes, GPU %d declared DEAD!", i, gpu);
  3964. } else if (now.tv_sec - thr->sick.tv_sec > 60 && gpus[i].status == LIFE_SICK) {
  3965. /* Attempt to restart a GPU once every minute */
  3966. gettimeofday(&thr->sick, NULL);
  3967. if (opt_restart)
  3968. reinit_device(thr->cgpu);
  3969. }
  3970. }
  3971. }
  3972. return NULL;
  3973. }
  3974. static void log_print_status(int thr_id)
  3975. {
  3976. struct cgpu_info *cgpu;
  3977. cgpu = thr_info[thr_id].cgpu;
  3978. #ifdef HAVE_ADL
  3979. if (cgpu->has_adl) {
  3980. int gpu = cgpu->cpu_gpu;
  3981. applog(LOG_WARNING, " GPU %d: [%.1f °C] [%.1f/%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  3982. gpu, gpu_temp(gpu), cgpu->rolling,
  3983. cgpu->total_mhashes / total_secs, cgpu->getworks,
  3984. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  3985. cgpu->efficiency, cgpu->utility);
  3986. } else
  3987. #endif
  3988. applog(LOG_WARNING, " %sPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  3989. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->rolling,
  3990. cgpu->total_mhashes / total_secs, cgpu->getworks,
  3991. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  3992. cgpu->efficiency, cgpu->utility);
  3993. }
  3994. static void print_summary(void)
  3995. {
  3996. struct timeval diff;
  3997. int hours, mins, secs, i;
  3998. double utility, efficiency = 0.0;
  3999. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  4000. hours = diff.tv_sec / 3600;
  4001. mins = (diff.tv_sec % 3600) / 60;
  4002. secs = diff.tv_sec % 60;
  4003. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  4004. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4005. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  4006. applog(LOG_WARNING, "Started at %s", datestamp);
  4007. if (opt_n_threads)
  4008. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  4009. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  4010. if (total_secs)
  4011. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  4012. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  4013. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  4014. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  4015. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  4016. if (total_accepted || total_rejected)
  4017. applog(LOG_WARNING, "Reject ratio: %.1f", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  4018. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  4019. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  4020. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  4021. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  4022. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  4023. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  4024. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  4025. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  4026. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  4027. if (total_pools > 1) {
  4028. for (i = 0; i < total_pools; i++) {
  4029. struct pool *pool = pools[i];
  4030. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  4031. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  4032. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  4033. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  4034. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  4035. if (pool->accepted || pool->rejected)
  4036. applog(LOG_WARNING, " Reject ratio: %.1f", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4037. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  4038. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  4039. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  4040. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  4041. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  4042. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  4043. }
  4044. }
  4045. applog(LOG_WARNING, "Summary of per device statistics:\n");
  4046. for (i = 0; i < mining_threads; i++) {
  4047. if (active_device(i))
  4048. log_print_status(i);
  4049. }
  4050. if (opt_shares)
  4051. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  4052. fflush(stdout);
  4053. fflush(stderr);
  4054. if (opt_shares > total_accepted)
  4055. quit(1, "Did not successfully mine as many shares as were requested.");
  4056. }
  4057. void quit(int status, const char *format, ...)
  4058. {
  4059. va_list ap;
  4060. disable_curses();
  4061. if (!opt_realquiet && successful_connect)
  4062. print_summary();
  4063. if (format) {
  4064. va_start(ap, format);
  4065. vfprintf(stderr, format, ap);
  4066. va_end(ap);
  4067. }
  4068. fprintf(stderr, "\n");
  4069. fflush(stderr);
  4070. exit(status);
  4071. }
  4072. char *curses_input(const char *query)
  4073. {
  4074. char *input;
  4075. echo();
  4076. input = malloc(255);
  4077. if (!input)
  4078. quit(1, "Failed to malloc input");
  4079. leaveok(logwin, false);
  4080. wlogprint("%s: ", query);
  4081. wgetnstr(logwin, input, 255);
  4082. if (!strlen(input))
  4083. strcpy(input, "-1");
  4084. leaveok(logwin, true);
  4085. noecho();
  4086. return input;
  4087. }
  4088. static bool input_pool(bool live)
  4089. {
  4090. char *url = NULL, *user = NULL, *pass = NULL;
  4091. struct pool *pool = NULL;
  4092. bool ret = false;
  4093. immedok(logwin, true);
  4094. if (total_pools == MAX_POOLS) {
  4095. wlogprint("Reached maximum number of pools.\n");
  4096. goto out;
  4097. }
  4098. wlogprint("Input server details.\n");
  4099. url = curses_input("URL");
  4100. if (!url)
  4101. goto out;
  4102. if (strncmp(url, "http://", 7) &&
  4103. strncmp(url, "https://", 8)) {
  4104. char *httpinput;
  4105. httpinput = malloc(255);
  4106. if (!httpinput)
  4107. quit(1, "Failed to malloc httpinput");
  4108. strcpy(httpinput, "http://");
  4109. strncat(httpinput, url, 248);
  4110. free(url);
  4111. url = httpinput;
  4112. }
  4113. user = curses_input("Username");
  4114. if (!user)
  4115. goto out;
  4116. pass = curses_input("Password");
  4117. if (!pass)
  4118. goto out;
  4119. pool = calloc(sizeof(struct pool), 1);
  4120. if (!pool)
  4121. quit(1, "Failed to realloc pools in input_pool");
  4122. pool->pool_no = total_pools;
  4123. pool->prio = total_pools;
  4124. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  4125. quit (1, "Failed to pthread_mutex_init in input_pool");
  4126. pool->rpc_url = url;
  4127. pool->rpc_user = user;
  4128. pool->rpc_pass = pass;
  4129. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4130. if (!pool->rpc_userpass)
  4131. quit(1, "Failed to malloc userpass");
  4132. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4133. pool->tv_idle.tv_sec = ~0UL;
  4134. /* Test the pool is not idle if we're live running, otherwise
  4135. * it will be tested separately */
  4136. ret = true;
  4137. pool->enabled = true;
  4138. if (live && !pool_active(pool, false))
  4139. pool->idle = true;
  4140. pools[total_pools++] = pool;
  4141. out:
  4142. immedok(logwin, false);
  4143. if (!ret) {
  4144. if (url)
  4145. free(url);
  4146. if (user)
  4147. free(user);
  4148. if (pass)
  4149. free(pass);
  4150. if (pool)
  4151. free(pool);
  4152. }
  4153. return ret;
  4154. }
  4155. #if defined(unix)
  4156. static void fork_monitor()
  4157. {
  4158. // Make a pipe: [readFD, writeFD]
  4159. int pfd[2];
  4160. int r = pipe(pfd);
  4161. if (r<0) {
  4162. perror("pipe - failed to create pipe for --monitor");
  4163. exit(1);
  4164. }
  4165. // Make stderr write end of pipe
  4166. fflush(stderr);
  4167. r = dup2(pfd[1], 2);
  4168. if (r<0) {
  4169. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  4170. exit(1);
  4171. }
  4172. r = close(pfd[1]);
  4173. if (r<0) {
  4174. perror("close - failed to close write end of pipe for --monitor");
  4175. exit(1);
  4176. }
  4177. // Don't allow a dying monitor to kill the main process
  4178. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  4179. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  4180. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  4181. perror("signal - failed to edit signal mask for --monitor");
  4182. exit(1);
  4183. }
  4184. // Fork a child process
  4185. r = fork();
  4186. if (r<0) {
  4187. perror("fork - failed to fork child process for --monitor");
  4188. exit(1);
  4189. }
  4190. // Child: launch monitor command
  4191. if (0==r) {
  4192. // Make stdin read end of pipe
  4193. r = dup2(pfd[0], 0);
  4194. if (r<0) {
  4195. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  4196. exit(1);
  4197. }
  4198. close(pfd[0]);
  4199. if (r<0) {
  4200. perror("close - in child, failed to close read end of pipe for --monitor");
  4201. exit(1);
  4202. }
  4203. // Launch user specified command
  4204. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  4205. perror("execl - in child failed to exec user specified command for --monitor");
  4206. exit(1);
  4207. }
  4208. // Parent: clean up unused fds and bail
  4209. r = close(pfd[0]);
  4210. if (r<0) {
  4211. perror("close - failed to close read end of pipe for --monitor");
  4212. exit(1);
  4213. }
  4214. }
  4215. #endif // defined(unix)
  4216. static void enable_curses(void) {
  4217. int x,y;
  4218. lock_curses();
  4219. if (curses_active) {
  4220. unlock_curses();
  4221. return;
  4222. }
  4223. mainwin = initscr();
  4224. getmaxyx(mainwin, y, x);
  4225. statuswin = newwin(logstart, x, 0, 0);
  4226. leaveok(statuswin, true);
  4227. logwin = newwin(y - logcursor, 0, logcursor, 0);
  4228. idlok(logwin, true);
  4229. scrollok(logwin, true);
  4230. leaveok(logwin, true);
  4231. cbreak();
  4232. noecho();
  4233. curses_active = true;
  4234. unlock_curses();
  4235. }
  4236. int main (int argc, char *argv[])
  4237. {
  4238. unsigned int i, pools_active = 0;
  4239. struct block *block, *tmpblock;
  4240. struct work *work, *tmpwork;
  4241. struct sigaction handler;
  4242. struct thr_info *thr;
  4243. char name[256];
  4244. /* This dangerous functions tramples random dynamically allocated
  4245. * variables so do it before anything at all */
  4246. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  4247. quit(1, "Failed to curl_global_init");
  4248. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  4249. quit(1, "Failed to pthread_mutex_init");
  4250. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  4251. quit(1, "Failed to pthread_mutex_init");
  4252. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  4253. quit(1, "Failed to pthread_mutex_init");
  4254. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  4255. quit(1, "Failed to pthread_mutex_init");
  4256. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  4257. quit(1, "Failed to pthread_mutex_init");
  4258. if (unlikely(pthread_rwlock_init(&blk_lock, NULL)))
  4259. quit(1, "Failed to pthread_rwlock_init");
  4260. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  4261. init_max_name_len();
  4262. handler.sa_handler = &sighandler;
  4263. sigaction(SIGTERM, &handler, &termhandler);
  4264. sigaction(SIGINT, &handler, &inthandler);
  4265. opt_kernel_path = alloca(PATH_MAX);
  4266. strcpy(opt_kernel_path, CGMINER_PREFIX);
  4267. cgminer_path = alloca(PATH_MAX);
  4268. strcpy(cgminer_path, dirname(argv[0]));
  4269. strcat(cgminer_path, "/");
  4270. // Hack to make cgminer silent when called recursively on WIN32
  4271. int skip_to_bench = 0;
  4272. #if defined(WIN32)
  4273. char buf[32];
  4274. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  4275. skip_to_bench = 1;
  4276. #endif // defined(WIN32)
  4277. block = calloc(sizeof(struct block), 1);
  4278. if (unlikely(!block))
  4279. quit (1, "main OOM");
  4280. for (i = 0; i < 36; i++)
  4281. strcat(block->hash, "0");
  4282. HASH_ADD_STR(blocks, hash, block);
  4283. strcpy(current_block, block->hash);
  4284. // Reckon number of cores in the box
  4285. #if defined(WIN32)
  4286. DWORD system_am;
  4287. DWORD process_am;
  4288. BOOL ok = GetProcessAffinityMask(
  4289. GetCurrentProcess(),
  4290. &system_am,
  4291. &process_am
  4292. );
  4293. if (!ok) {
  4294. applog(LOG_ERR, "couldn't figure out number of processors :(");
  4295. num_processors = 1;
  4296. } else {
  4297. size_t n = 32;
  4298. num_processors = 0;
  4299. while (n--)
  4300. if (process_am & (1<<n))
  4301. ++num_processors;
  4302. }
  4303. #else
  4304. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  4305. #endif /* !WIN32 */
  4306. opt_n_threads = num_processors;
  4307. #ifdef HAVE_OPENCL
  4308. if (!skip_to_bench) {
  4309. for (i = 0; i < 16; i++)
  4310. gpu_devices[i] = false;
  4311. nDevs = clDevicesNum();
  4312. if (nDevs < 0) {
  4313. applog(LOG_ERR, "clDevicesNum returned error, none usable");
  4314. nDevs = 0;
  4315. }
  4316. }
  4317. #endif
  4318. /* parse command line */
  4319. opt_register_table(opt_config_table,
  4320. "Options for both config file and command line");
  4321. opt_register_table(opt_cmdline_table,
  4322. "Options for command line only");
  4323. opt_parse(&argc, argv, applog_and_exit);
  4324. if (argc != 1)
  4325. quit(1, "Unexpected extra commandline arguments");
  4326. applog(LOG_WARNING, "Started %s", packagename);
  4327. if (opt_nogpu)
  4328. nDevs = 0;
  4329. if (nDevs && !opt_usecpu)
  4330. opt_n_threads = 0;
  4331. strcat(opt_kernel_path, "/");
  4332. if (want_per_device_stats)
  4333. opt_log_output = true;
  4334. if (0<=opt_bench_algo) {
  4335. double rate = bench_algo_stage3(opt_bench_algo);
  4336. if (!skip_to_bench) {
  4337. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  4338. } else {
  4339. // Write result to shared memory for parent
  4340. #if defined(WIN32)
  4341. char unique_name[64];
  4342. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  4343. HANDLE map_handle = CreateFileMapping(
  4344. INVALID_HANDLE_VALUE, // use paging file
  4345. NULL, // default security attributes
  4346. PAGE_READWRITE, // read/write access
  4347. 0, // size: high 32-bits
  4348. 4096, // size: low 32-bits
  4349. unique_name // name of map object
  4350. );
  4351. if (NULL!=map_handle) {
  4352. void *shared_mem = MapViewOfFile(
  4353. map_handle, // object to map view of
  4354. FILE_MAP_WRITE, // read/write access
  4355. 0, // high offset: map from
  4356. 0, // low offset: beginning
  4357. 0 // default: map entire file
  4358. );
  4359. if (NULL!=shared_mem)
  4360. CopyMemory(shared_mem, &rate, sizeof(rate));
  4361. (void)UnmapViewOfFile(shared_mem);
  4362. }
  4363. (void)CloseHandle(map_handle);
  4364. }
  4365. #endif
  4366. }
  4367. exit(0);
  4368. }
  4369. if (opt_kernel) {
  4370. if (strcmp(opt_kernel, "poclbm") && strcmp(opt_kernel, "phatk"))
  4371. quit(1, "Invalid kernel name specified - must be poclbm or phatk");
  4372. if (!strcmp(opt_kernel, "poclbm"))
  4373. chosen_kernel = KL_POCLBM;
  4374. else
  4375. chosen_kernel = KL_PHATK;
  4376. } else
  4377. chosen_kernel = KL_NONE;
  4378. gpu_threads = nDevs * opt_g_threads;
  4379. if (total_devices) {
  4380. if (total_devices > nDevs)
  4381. quit(1, "More devices specified than exist");
  4382. for (i = 0; i < 16; i++)
  4383. if (gpu_devices[i] && i + 1 > nDevs)
  4384. quit (1, "Command line options set a device that doesn't exist");
  4385. } else {
  4386. for (i = 0; i < nDevs; i++)
  4387. gpu_devices[i] = true;
  4388. total_devices = nDevs;
  4389. }
  4390. if (!gpu_threads && !forced_n_threads) {
  4391. /* Maybe they turned GPU off; restore default CPU threads. */
  4392. opt_n_threads = num_processors;
  4393. }
  4394. if (!opt_n_threads && ! gpu_threads)
  4395. quit(1, "All devices disabled, cannot mine!");
  4396. logcursor = 8;
  4397. gpucursor = logcursor;
  4398. cpucursor = gpucursor + nDevs;
  4399. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  4400. logcursor = logstart + 1;
  4401. if (opt_realquiet)
  4402. use_curses = false;
  4403. if (!total_pools) {
  4404. enable_curses();
  4405. applog(LOG_WARNING, "Need to specify at least one pool server.");
  4406. if (!input_pool(false))
  4407. quit(1, "Pool setup failed");
  4408. if (!use_curses)
  4409. disable_curses();
  4410. }
  4411. for (i = 0; i < total_pools; i++) {
  4412. struct pool *pool = pools[i];
  4413. if (!pool->rpc_userpass) {
  4414. if (!pool->rpc_user || !pool->rpc_pass)
  4415. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  4416. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4417. if (!pool->rpc_userpass)
  4418. quit(1, "Failed to malloc userpass");
  4419. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4420. } else {
  4421. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  4422. if (!pool->rpc_user)
  4423. quit(1, "Failed to malloc user");
  4424. strcpy(pool->rpc_user, pool->rpc_userpass);
  4425. pool->rpc_user = strtok(pool->rpc_user, ":");
  4426. if (!pool->rpc_user)
  4427. quit(1, "Failed to find colon delimiter in userpass");
  4428. }
  4429. }
  4430. /* Set the currentpool to pool 0 */
  4431. currentpool = pools[0];
  4432. #ifdef HAVE_SYSLOG_H
  4433. if (use_syslog)
  4434. openlog(PACKAGE, LOG_PID, LOG_USER);
  4435. #endif
  4436. #if defined(unix)
  4437. if (opt_stderr_cmd)
  4438. fork_monitor();
  4439. #endif // defined(unix)
  4440. mining_threads = opt_n_threads + gpu_threads;
  4441. total_threads = mining_threads + 7;
  4442. work_restart = calloc(total_threads, sizeof(*work_restart));
  4443. if (!work_restart)
  4444. quit(1, "Failed to calloc work_restart");
  4445. thr_info = calloc(total_threads, sizeof(*thr));
  4446. if (!thr_info)
  4447. quit(1, "Failed to calloc thr_info");
  4448. /* init workio thread info */
  4449. work_thr_id = mining_threads;
  4450. thr = &thr_info[work_thr_id];
  4451. thr->id = work_thr_id;
  4452. thr->q = tq_new();
  4453. if (!thr->q)
  4454. quit(1, "Failed to tq_new");
  4455. /* start work I/O thread */
  4456. if (thr_info_create(thr, NULL, workio_thread, thr))
  4457. quit(1, "workio thread create failed");
  4458. /* init longpoll thread info */
  4459. longpoll_thr_id = mining_threads + 1;
  4460. thr = &thr_info[longpoll_thr_id];
  4461. thr->id = longpoll_thr_id;
  4462. thr->q = tq_new();
  4463. if (!thr->q)
  4464. quit(1, "Failed to tq_new");
  4465. if (opt_n_threads ) {
  4466. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  4467. if (unlikely(!cpus))
  4468. quit(1, "Failed to calloc cpus");
  4469. }
  4470. stage_thr_id = mining_threads + 3;
  4471. thr = &thr_info[stage_thr_id];
  4472. thr->q = tq_new();
  4473. if (!thr->q)
  4474. quit(1, "Failed to tq_new");
  4475. /* start stage thread */
  4476. if (thr_info_create(thr, NULL, stage_thread, thr))
  4477. quit(1, "stage thread create failed");
  4478. pthread_detach(*thr->pth);
  4479. /* Create a unique get work queue */
  4480. getq = tq_new();
  4481. if (!getq)
  4482. quit(1, "Failed to create getq");
  4483. /* Test each pool to see if we can retrieve and use work and for what
  4484. * it supports */
  4485. for (i = 0; i < total_pools; i++) {
  4486. struct pool *pool;
  4487. pool = pools[i];
  4488. pool->enabled = true;
  4489. if (pool_active(pool, false)) {
  4490. if (!currentpool)
  4491. currentpool = pool;
  4492. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  4493. pools_active++;
  4494. } else {
  4495. if (pool == currentpool)
  4496. currentpool = NULL;
  4497. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  4498. pool->idle = true;
  4499. }
  4500. }
  4501. if (!pools_active) {
  4502. enable_curses();
  4503. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  4504. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  4505. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  4506. for (i = 0; i < total_pools; i++) {
  4507. struct pool *pool;
  4508. pool = pools[i];
  4509. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  4510. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  4511. }
  4512. curses_input("Press enter to exit");
  4513. quit(0, "No servers could be used! Exiting.");
  4514. }
  4515. /* If we want longpoll, enable it for the chosen default pool, or, if
  4516. * the pool does not support longpoll, find the first one that does
  4517. * and use its longpoll support */
  4518. if (want_longpoll) {
  4519. if (currentpool->hdr_path)
  4520. start_longpoll();
  4521. else {
  4522. for (i = 0; i < total_pools; i++) {
  4523. struct pool *pool;
  4524. pool = pools[i];
  4525. if (pool->hdr_path) {
  4526. struct pool *temp = currentpool;
  4527. currentpool = pool;
  4528. start_longpoll();
  4529. /* Not real blocking, but good enough */
  4530. sleep(1);
  4531. currentpool = temp;
  4532. break;
  4533. }
  4534. }
  4535. }
  4536. }
  4537. gettimeofday(&total_tv_start, NULL);
  4538. gettimeofday(&total_tv_end, NULL);
  4539. get_datestamp(datestamp, &total_tv_start);
  4540. #ifdef HAVE_OPENCL
  4541. init_adl(nDevs);
  4542. bool failmessage = false;
  4543. /* start GPU mining threads */
  4544. for (i = 0; i < nDevs * opt_g_threads; i++) {
  4545. int gpu = i % nDevs;
  4546. struct cgpu_info *cgpu;
  4547. struct timeval now;
  4548. gpus[gpu].is_gpu = 1;
  4549. gpus[gpu].cpu_gpu = gpu;
  4550. thr = &thr_info[i];
  4551. thr->id = i;
  4552. cgpu = thr->cgpu = &gpus[gpu];
  4553. thr->q = tq_new();
  4554. if (!thr->q)
  4555. quit(1, "tq_new failed in starting gpu mining threads");
  4556. /* Enable threads for devices set not to mine but disable
  4557. * their queue in case we wish to enable them later*/
  4558. if (gpu_devices[gpu]) {
  4559. if (opt_debug)
  4560. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  4561. tq_push(thr->q, &ping);
  4562. }
  4563. applog(LOG_INFO, "Init GPU thread %i", i);
  4564. clStates[i] = initCl(gpu, name, sizeof(name));
  4565. if (!clStates[i]) {
  4566. enable_curses();
  4567. applog(LOG_ERR, "Failed to init GPU thread %d, disabling device %d", i, gpu);
  4568. if (!failmessage) {
  4569. char *buf;
  4570. applog(LOG_ERR, "The most common reason for this failure is cgminer being unable to read the kernel .cl files");
  4571. applog(LOG_ERR, "Alternatively if it has failed on different GPUs, restarting might help.");
  4572. failmessage = true;
  4573. buf = curses_input("Press enter to continue");
  4574. if (buf)
  4575. free(buf);
  4576. }
  4577. gpu_devices[gpu] = false;
  4578. continue;
  4579. }
  4580. applog(LOG_INFO, "initCl() finished. Found %s", name);
  4581. gettimeofday(&now, NULL);
  4582. get_datestamp(cgpu->init, &now);
  4583. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  4584. quit(1, "thread %d create failed", i);
  4585. }
  4586. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  4587. #else
  4588. opt_g_threads = 0;
  4589. #endif
  4590. /* start CPU mining threads */
  4591. for (i = gpu_threads; i < mining_threads; i++) {
  4592. int cpu = (i - gpu_threads) % num_processors;
  4593. thr = &thr_info[i];
  4594. thr->id = i;
  4595. cpus[cpu].cpu_gpu = cpu;
  4596. thr->cgpu = &cpus[cpu];
  4597. thr->q = tq_new();
  4598. if (!thr->q)
  4599. quit(1, "tq_new failed in starting cpu mining threads");
  4600. thread_reportin(thr);
  4601. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  4602. quit(1, "thread %d create failed", i);
  4603. }
  4604. applog(LOG_INFO, "%d cpu miner threads started, "
  4605. "using SHA256 '%s' algorithm.",
  4606. opt_n_threads,
  4607. algo_names[opt_algo]);
  4608. if (use_curses)
  4609. enable_curses();
  4610. watchdog_thr_id = mining_threads + 2;
  4611. thr = &thr_info[watchdog_thr_id];
  4612. /* start wakeup thread */
  4613. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  4614. quit(1, "wakeup thread create failed");
  4615. /* Create curses input thread for keyboard input */
  4616. input_thr_id = mining_threads + 4;
  4617. thr = &thr_info[input_thr_id];
  4618. if (thr_info_create(thr, NULL, input_thread, thr))
  4619. quit(1, "input thread create failed");
  4620. pthread_detach(*thr->pth);
  4621. /* Create reinit cpu thread */
  4622. cpur_thr_id = mining_threads + 5;
  4623. thr = &thr_info[cpur_thr_id];
  4624. thr->q = tq_new();
  4625. if (!thr->q)
  4626. quit(1, "tq_new failed for cpur_thr_id");
  4627. if (thr_info_create(thr, NULL, reinit_cpu, thr))
  4628. quit(1, "reinit_cpu thread create failed");
  4629. /* Create reinit gpu thread */
  4630. gpur_thr_id = mining_threads + 6;
  4631. thr = &thr_info[gpur_thr_id];
  4632. thr->q = tq_new();
  4633. if (!thr->q)
  4634. quit(1, "tq_new failed for gpur_thr_id");
  4635. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  4636. quit(1, "reinit_gpu thread create failed");
  4637. /* main loop - simply wait for workio thread to exit */
  4638. pthread_join(*thr_info[work_thr_id].pth, NULL);
  4639. applog(LOG_INFO, "workio thread dead, exiting.");
  4640. gettimeofday(&total_tv_end, NULL);
  4641. disable_curses();
  4642. if (!opt_realquiet && successful_connect)
  4643. print_summary();
  4644. #ifdef HAVE_OPENCL
  4645. clear_adl(nDevs);
  4646. #endif
  4647. if (opt_n_threads)
  4648. free(cpus);
  4649. HASH_ITER(hh, staged_work, work, tmpwork) {
  4650. HASH_DEL(staged_work, work);
  4651. free_work(work);
  4652. }
  4653. HASH_ITER(hh, blocks, block, tmpblock) {
  4654. HASH_DEL(blocks, block);
  4655. free(block);
  4656. }
  4657. curl_global_cleanup();
  4658. return 0;
  4659. }