main.c 143 KB

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