main.c 142 KB

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