main.c 140 KB

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