main.c 144 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606
  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 <openssl/sha.h>
  32. #include "compat.h"
  33. #include "miner.h"
  34. #include "findnonce.h"
  35. #include "bench_block.h"
  36. #include "ocl.h"
  37. #include "uthash.h"
  38. #include "adl.h"
  39. #if defined(unix)
  40. #include <errno.h>
  41. #include <fcntl.h>
  42. #include <unistd.h>
  43. #include <sys/wait.h>
  44. #include <sys/types.h>
  45. #endif
  46. #ifdef __linux /* Linux specific policy and affinity management */
  47. #include <sched.h>
  48. static inline void drop_policy(void)
  49. {
  50. struct sched_param param;
  51. #ifdef SCHED_BATCH
  52. #ifdef SCHED_IDLE
  53. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  54. #endif
  55. sched_setscheduler(0, SCHED_BATCH, &param);
  56. #endif
  57. }
  58. static inline void affine_to_cpu(int id, int cpu)
  59. {
  60. cpu_set_t set;
  61. CPU_ZERO(&set);
  62. CPU_SET(cpu, &set);
  63. sched_setaffinity(0, sizeof(&set), &set);
  64. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  65. }
  66. #else
  67. static inline void drop_policy(void)
  68. {
  69. }
  70. static inline void affine_to_cpu(int id, int cpu)
  71. {
  72. }
  73. #endif
  74. enum workio_commands {
  75. WC_GET_WORK,
  76. WC_SUBMIT_WORK,
  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. int gp = gpu_fanpercent(gpu);
  1561. if (gt != -1)
  1562. tailsprintf(buf, "%.1fC ", gt);
  1563. if (gf != -1)
  1564. tailsprintf(buf, "%dRPM ", gf);
  1565. else if (gp != -1)
  1566. tailsprintf(buf, "%d%% ", gp);
  1567. if (gt > -1 || gf > -1 || gp > -1)
  1568. tailsprintf(buf, "| ");
  1569. }
  1570. #endif
  1571. tailsprintf(buf, "(%ds):%.1f (avg):%.1f Mh/s | A:%d R:%d HW:%d U:%.2f/m",
  1572. opt_log_interval,
  1573. cgpu->rolling,
  1574. cgpu->total_mhashes / total_secs,
  1575. cgpu->accepted,
  1576. cgpu->rejected,
  1577. cgpu->hw_errors,
  1578. cgpu->utility);
  1579. }
  1580. static void text_print_status(int thr_id)
  1581. {
  1582. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1583. char logline[255];
  1584. get_statline(logline, cgpu);
  1585. printf("%s\n", logline);
  1586. }
  1587. /* Must be called with curses mutex lock held and curses_active */
  1588. static void curses_print_status(void)
  1589. {
  1590. struct pool *pool = current_pool();
  1591. wattron(statuswin, A_BOLD);
  1592. mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  1593. if (opt_n_threads)
  1594. wprintw(statuswin, " CPU Algo: %s", algo_names[opt_algo]);
  1595. wattroff(statuswin, A_BOLD);
  1596. mvwhline(statuswin, 1, 0, '-', 80);
  1597. mvwprintw(statuswin, 2, 0, " %s", statusline);
  1598. wclrtoeol(statuswin);
  1599. mvwprintw(statuswin, 3, 0, " TQ: %d ST: %d SS: %d DW: %d NB: %d LW: %d GF: %d RF: %d I: %d",
  1600. total_queued, requests_staged(), total_stale, total_discarded, new_blocks,
  1601. local_work, total_go, total_ro, scan_intensity);
  1602. wclrtoeol(statuswin);
  1603. if (pool_strategy == POOL_LOADBALANCE && total_pools > 1)
  1604. mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s LP",
  1605. have_longpoll ? "": "out");
  1606. else
  1607. mvwprintw(statuswin, 4, 0, " Connected to %s with%s LP as user %s",
  1608. pool->rpc_url, have_longpoll ? "": "out", pool->rpc_user);
  1609. wclrtoeol(statuswin);
  1610. mvwprintw(statuswin, 5, 0, " Block: %s... Started: %s", current_hash, blocktime);
  1611. mvwhline(statuswin, 6, 0, '-', 80);
  1612. mvwhline(statuswin, logstart - 1, 0, '-', 80);
  1613. mvwprintw(statuswin, gpucursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1614. opt_g_threads ? "[G]PU management " : "");
  1615. /* The window will be updated once we're done with all the devices */
  1616. wnoutrefresh(statuswin);
  1617. }
  1618. static void curses_print_devstatus(int thr_id)
  1619. {
  1620. if (thr_id >= 0 && thr_id < gpu_threads) {
  1621. int gpu = dev_from_id(thr_id);
  1622. struct cgpu_info *cgpu = &gpus[gpu];
  1623. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1624. mvwprintw(statuswin, gpucursor + gpu, 0, " GPU %d: ", gpu);
  1625. #ifdef HAVE_ADL
  1626. if (cgpu->has_adl) {
  1627. float gt = gpu_temp(gpu);
  1628. int gf = gpu_fanspeed(gpu);
  1629. int gp = gpu_fanpercent(gpu);
  1630. if (gt != -1)
  1631. wprintw(statuswin, "%.1fC ", gt);
  1632. if (gf != -1)
  1633. wprintw(statuswin, "%4dRPM ", gf);
  1634. else if (gp != -1)
  1635. wprintw(statuswin, "%2d%% ", gp);
  1636. if (gt > -1 || gf > -1 || gp > -1)
  1637. wprintw(statuswin, "| ");
  1638. }
  1639. #endif
  1640. if (cgpu->status == LIFE_DEAD)
  1641. wprintw(statuswin, "DEAD ");
  1642. else if (cgpu->status == LIFE_SICK)
  1643. wprintw(statuswin, "SICK ");
  1644. else if (!gpu_devices[gpu])
  1645. wprintw(statuswin, "DISABLED ");
  1646. else
  1647. wprintw(statuswin, "%.1f", cgpu->rolling);
  1648. wprintw(statuswin, "/%.1fMh/s | A:%d R:%d HW:%d U:%.2f/m",
  1649. cgpu->total_mhashes / total_secs,
  1650. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1651. cgpu->utility);
  1652. wclrtoeol(statuswin);
  1653. } else if (thr_id >= gpu_threads) {
  1654. int cpu = dev_from_id(thr_id);
  1655. struct cgpu_info *cgpu = &cpus[cpu];
  1656. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1657. mvwprintw(statuswin, cpucursor + cpu, 0, " CPU %d: %.2f/%.2fMh/s | A:%d R:%d U:%.2f/m",
  1658. cpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  1659. cgpu->accepted, cgpu->rejected,
  1660. cgpu->utility);
  1661. wclrtoeol(statuswin);
  1662. }
  1663. wnoutrefresh(statuswin);
  1664. }
  1665. static void print_status(int thr_id)
  1666. {
  1667. if (!curses_active)
  1668. text_print_status(thr_id);
  1669. }
  1670. /* Check for window resize. Called with curses mutex locked */
  1671. static inline bool change_logwinsize(void)
  1672. {
  1673. int x, y, logx, logy;
  1674. getmaxyx(mainwin, y, x);
  1675. getmaxyx(logwin, logy, logx);
  1676. y -= logcursor;
  1677. /* Detect screen size change */
  1678. if ((x != logx || y != logy) && x >= 80 && y >= 25) {
  1679. wresize(logwin, y, x);
  1680. return true;
  1681. }
  1682. return false;
  1683. }
  1684. /* For mandatory printing when mutex is already locked */
  1685. static void wlog(const char *f, ...)
  1686. {
  1687. va_list ap;
  1688. va_start(ap, f);
  1689. vw_printw(logwin, f, ap);
  1690. va_end(ap);
  1691. }
  1692. /* Mandatory printing */
  1693. void wlogprint(const char *f, ...)
  1694. {
  1695. va_list ap;
  1696. if (curses_active_locked()) {
  1697. va_start(ap, f);
  1698. vw_printw(logwin, f, ap);
  1699. va_end(ap);
  1700. wrefresh(logwin);
  1701. unlock_curses();
  1702. }
  1703. }
  1704. void log_curses(int prio, const char *f, va_list ap)
  1705. {
  1706. if (opt_quiet && prio != LOG_ERR)
  1707. return;
  1708. if (curses_active_locked()) {
  1709. if (!opt_loginput || prio == LOG_ERR || prio == LOG_WARNING) {
  1710. vw_printw(logwin, f, ap);
  1711. wrefresh(logwin);
  1712. }
  1713. unlock_curses();
  1714. } else
  1715. vprintf(f, ap);
  1716. }
  1717. void clear_logwin(void)
  1718. {
  1719. if (curses_active_locked()) {
  1720. wclear(logwin);
  1721. wrefresh(logwin);
  1722. unlock_curses();
  1723. }
  1724. }
  1725. /* regenerate the full work->hash value */
  1726. void regeneratehash(const struct work *work)
  1727. {
  1728. uint32_t *data32 = (uint32_t *)(work->data);
  1729. unsigned char swap[128];
  1730. uint32_t *swap32 = (uint32_t *)swap;
  1731. unsigned char hash1[SHA256_DIGEST_LENGTH];
  1732. int i;
  1733. for (i = 0; i < 80/4; i++)
  1734. swap32[i] = swab32(data32[i]);
  1735. SHA256(swap, 80, hash1);
  1736. SHA256(hash1, SHA256_DIGEST_LENGTH, (unsigned char *)(work->hash));
  1737. }
  1738. static bool submit_upstream_work(const struct work *work)
  1739. {
  1740. char *hexstr = NULL;
  1741. json_t *val, *res;
  1742. char s[345], sd[345];
  1743. bool rc = false;
  1744. int thr_id = work->thr_id;
  1745. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1746. CURL *curl = curl_easy_init();
  1747. struct pool *pool = work->pool;
  1748. bool rolltime;
  1749. uint32_t *hash32;
  1750. char hashshow[32+1] = "";
  1751. if (unlikely(!curl)) {
  1752. applog(LOG_ERR, "CURL initialisation failed");
  1753. return rc;
  1754. }
  1755. /* build hex string */
  1756. hexstr = bin2hex(work->data, sizeof(work->data));
  1757. if (unlikely(!hexstr)) {
  1758. applog(LOG_ERR, "submit_upstream_work OOM");
  1759. goto out_nofree;
  1760. }
  1761. /* build JSON-RPC request */
  1762. sprintf(s,
  1763. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  1764. hexstr);
  1765. sprintf(sd,
  1766. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  1767. hexstr);
  1768. if (opt_debug)
  1769. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  1770. /* issue JSON-RPC request */
  1771. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool);
  1772. if (unlikely(!val)) {
  1773. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  1774. if (!pool_tset(pool, &pool->submit_fail)) {
  1775. total_ro++;
  1776. pool->remotefail_occasions++;
  1777. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  1778. }
  1779. goto out;
  1780. } else if (pool_tclear(pool, &pool->submit_fail))
  1781. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  1782. res = json_object_get(val, "result");
  1783. if (!QUIET) {
  1784. regeneratehash(work);
  1785. hash32 = (uint32_t *)(work->hash);
  1786. sprintf(hashshow, "%08lx%08lx%08lx%08lx",
  1787. (unsigned long)(hash32[7]), (unsigned long)(hash32[6]),
  1788. (unsigned long)(hash32[5]), (unsigned long)(hash32[4]));
  1789. }
  1790. /* Theoretically threads could race when modifying accepted and
  1791. * rejected values but the chance of two submits completing at the
  1792. * same time is zero so there is no point adding extra locking */
  1793. if (json_is_true(res)) {
  1794. cgpu->accepted++;
  1795. total_accepted++;
  1796. pool->accepted++;
  1797. if (opt_debug)
  1798. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  1799. if (!QUIET) {
  1800. if (total_pools > 1)
  1801. applog(LOG_NOTICE, "Accepted %.32s %sPU %d thread %d pool %d",
  1802. hashshow, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  1803. else
  1804. applog(LOG_NOTICE, "Accepted %.32s %sPU %d thread %d",
  1805. hashshow, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  1806. }
  1807. if (opt_shares && total_accepted >= opt_shares) {
  1808. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  1809. kill_work();
  1810. goto out;
  1811. }
  1812. } else {
  1813. cgpu->rejected++;
  1814. total_rejected++;
  1815. pool->rejected++;
  1816. if (opt_debug)
  1817. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  1818. if (!QUIET) {
  1819. if (total_pools > 1)
  1820. applog(LOG_NOTICE, "Rejected %.32s %sPU %d thread %d pool %d",
  1821. hashshow, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  1822. else
  1823. applog(LOG_NOTICE, "Rejected %.32s %sPU %d thread %d",
  1824. hashshow, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  1825. }
  1826. }
  1827. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1828. if (!opt_realquiet)
  1829. print_status(thr_id);
  1830. if (!want_per_device_stats) {
  1831. char logline[255];
  1832. get_statline(logline, cgpu);
  1833. applog(LOG_INFO, "%s", logline);
  1834. }
  1835. json_decref(val);
  1836. rc = true;
  1837. out:
  1838. free(hexstr);
  1839. out_nofree:
  1840. curl_easy_cleanup(curl);
  1841. return rc;
  1842. }
  1843. static const char *rpc_req =
  1844. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  1845. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  1846. static inline struct pool *select_pool(bool lagging)
  1847. {
  1848. static int rotating_pool = 0;
  1849. struct pool *pool, *cp;
  1850. cp = current_pool();
  1851. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  1852. pool = cp;
  1853. else
  1854. pool = NULL;
  1855. while (!pool) {
  1856. if (++rotating_pool >= total_pools)
  1857. rotating_pool = 0;
  1858. pool = pools[rotating_pool];
  1859. if ((!pool->idle && pool->enabled) || pool == cp)
  1860. break;
  1861. pool = NULL;
  1862. }
  1863. return pool;
  1864. }
  1865. static bool get_upstream_work(struct work *work, bool lagging)
  1866. {
  1867. struct pool *pool;
  1868. json_t *val = NULL;
  1869. bool rc = false;
  1870. int retries = 0;
  1871. CURL *curl;
  1872. curl = curl_easy_init();
  1873. if (unlikely(!curl)) {
  1874. applog(LOG_ERR, "CURL initialisation failed");
  1875. return rc;
  1876. }
  1877. pool = select_pool(lagging);
  1878. if (opt_debug)
  1879. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  1880. retry:
  1881. /* A single failure response here might be reported as a dead pool and
  1882. * there may be temporary denied messages etc. falsely reporting
  1883. * failure so retry a few times before giving up */
  1884. while (!val && retries++ < 3)
  1885. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1886. false, false, &work->rolltime, pool);
  1887. if (unlikely(!val)) {
  1888. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  1889. goto out;
  1890. }
  1891. rc = work_decode(json_object_get(val, "result"), work);
  1892. if (!rc && retries < 3)
  1893. goto retry;
  1894. work->pool = pool;
  1895. total_getworks++;
  1896. pool->getwork_requested++;
  1897. json_decref(val);
  1898. out:
  1899. curl_easy_cleanup(curl);
  1900. return rc;
  1901. }
  1902. static struct work *make_work(void)
  1903. {
  1904. struct work *work = calloc(1, sizeof(struct work));
  1905. if (unlikely(!work))
  1906. quit(1, "Failed to calloc work in make_work");
  1907. work->id = total_work++;
  1908. return work;
  1909. }
  1910. static void free_work(struct work *work)
  1911. {
  1912. free(work);
  1913. }
  1914. static void workio_cmd_free(struct workio_cmd *wc)
  1915. {
  1916. if (!wc)
  1917. return;
  1918. switch (wc->cmd) {
  1919. case WC_SUBMIT_WORK:
  1920. free_work(wc->u.work);
  1921. break;
  1922. default: /* do nothing */
  1923. break;
  1924. }
  1925. memset(wc, 0, sizeof(*wc)); /* poison */
  1926. free(wc);
  1927. }
  1928. static void disable_curses(void)
  1929. {
  1930. if (curses_active_locked()) {
  1931. curses_active = false;
  1932. leaveok(logwin, false);
  1933. leaveok(statuswin, false);
  1934. leaveok(mainwin, false);
  1935. nocbreak();
  1936. echo();
  1937. delwin(logwin);
  1938. delwin(statuswin);
  1939. delwin(mainwin);
  1940. endwin();
  1941. refresh();
  1942. #ifdef WIN32
  1943. // Move the cursor to after curses output.
  1944. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  1945. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1946. COORD coord;
  1947. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  1948. coord.X = 0;
  1949. coord.Y = csbi.dwSize.Y - 1;
  1950. SetConsoleCursorPosition(hout, coord);
  1951. }
  1952. #endif
  1953. unlock_curses();
  1954. }
  1955. }
  1956. static void print_summary(void);
  1957. void kill_work(void)
  1958. {
  1959. struct thr_info *thr;
  1960. unsigned int i;
  1961. disable_curses();
  1962. applog(LOG_INFO, "Received kill message");
  1963. if (opt_debug)
  1964. applog(LOG_DEBUG, "Killing off watchdog thread");
  1965. /* Kill the watchdog thread */
  1966. thr = &thr_info[watchdog_thr_id];
  1967. thr_info_cancel(thr);
  1968. if (opt_debug)
  1969. applog(LOG_DEBUG, "Killing off mining threads");
  1970. /* Stop the mining threads*/
  1971. for (i = 0; i < mining_threads; i++) {
  1972. thr = &thr_info[i];
  1973. thr_info_cancel(thr);
  1974. }
  1975. if (opt_debug)
  1976. applog(LOG_DEBUG, "Killing off stage thread");
  1977. /* Stop the others */
  1978. thr = &thr_info[stage_thr_id];
  1979. thr_info_cancel(thr);
  1980. if (opt_debug)
  1981. applog(LOG_DEBUG, "Killing off longpoll thread");
  1982. thr = &thr_info[longpoll_thr_id];
  1983. thr_info_cancel(thr);
  1984. if (opt_debug)
  1985. applog(LOG_DEBUG, "Killing off work thread");
  1986. thr = &thr_info[work_thr_id];
  1987. thr_info_cancel(thr);
  1988. }
  1989. void quit(int status, const char *format, ...);
  1990. static void sighandler(int sig)
  1991. {
  1992. /* Restore signal handlers so we can still quit if kill_work fails */
  1993. sigaction(SIGTERM, &termhandler, NULL);
  1994. sigaction(SIGINT, &inthandler, NULL);
  1995. kill_work();
  1996. quit(sig, "Received interrupt signal.");
  1997. }
  1998. static void *get_work_thread(void *userdata)
  1999. {
  2000. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2001. struct work *ret_work;
  2002. int failures = 0;
  2003. pthread_detach(pthread_self());
  2004. ret_work = make_work();
  2005. if (wc->thr)
  2006. ret_work->thr = wc->thr;
  2007. else
  2008. ret_work->thr = NULL;
  2009. /* obtain new work from bitcoin via JSON-RPC */
  2010. while (!get_upstream_work(ret_work, wc->lagging)) {
  2011. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  2012. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  2013. free_work(ret_work);
  2014. kill_work();
  2015. goto out;
  2016. }
  2017. /* pause, then restart work-request loop */
  2018. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  2019. fail_pause);
  2020. sleep(fail_pause);
  2021. fail_pause += opt_fail_pause;
  2022. }
  2023. fail_pause = opt_fail_pause;
  2024. if (opt_debug)
  2025. applog(LOG_DEBUG, "Pushing work to requesting thread");
  2026. /* send work to requesting thread */
  2027. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  2028. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  2029. kill_work();
  2030. free_work(ret_work);
  2031. }
  2032. out:
  2033. workio_cmd_free(wc);
  2034. return NULL;
  2035. }
  2036. static bool workio_get_work(struct workio_cmd *wc)
  2037. {
  2038. pthread_t get_thread;
  2039. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  2040. applog(LOG_ERR, "Failed to create get_work_thread");
  2041. return false;
  2042. }
  2043. return true;
  2044. }
  2045. static bool stale_work(struct work *work)
  2046. {
  2047. struct timeval now;
  2048. bool ret = false;
  2049. char *hexstr;
  2050. gettimeofday(&now, NULL);
  2051. if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_scantime)
  2052. return true;
  2053. hexstr = bin2hex(work->data, 18);
  2054. if (unlikely(!hexstr)) {
  2055. applog(LOG_ERR, "submit_work_thread OOM");
  2056. return ret;
  2057. }
  2058. if (strcmp(hexstr, current_block))
  2059. ret = true;
  2060. free(hexstr);
  2061. return ret;
  2062. }
  2063. static void *submit_work_thread(void *userdata)
  2064. {
  2065. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2066. struct work *work = wc->u.work;
  2067. struct pool *pool = work->pool;
  2068. int failures = 0;
  2069. pthread_detach(pthread_self());
  2070. if (!opt_submit_stale && stale_work(work)) {
  2071. applog(LOG_NOTICE, "Stale share detected, discarding");
  2072. total_stale++;
  2073. pool->stale_shares++;
  2074. goto out;
  2075. }
  2076. /* submit solution to bitcoin via JSON-RPC */
  2077. while (!submit_upstream_work(work)) {
  2078. if (!opt_submit_stale && stale_work(work)) {
  2079. applog(LOG_NOTICE, "Stale share detected, discarding");
  2080. total_stale++;
  2081. pool->stale_shares++;
  2082. break;
  2083. }
  2084. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  2085. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  2086. kill_work();
  2087. break;
  2088. }
  2089. /* pause, then restart work-request loop */
  2090. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  2091. fail_pause);
  2092. sleep(fail_pause);
  2093. fail_pause += opt_fail_pause;
  2094. }
  2095. fail_pause = opt_fail_pause;
  2096. out:
  2097. workio_cmd_free(wc);
  2098. return NULL;
  2099. }
  2100. static bool workio_submit_work(struct workio_cmd *wc)
  2101. {
  2102. pthread_t submit_thread;
  2103. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  2104. applog(LOG_ERR, "Failed to create submit_work_thread");
  2105. return false;
  2106. }
  2107. return true;
  2108. }
  2109. /* Find the pool that currently has the highest priority */
  2110. static struct pool *priority_pool(int choice)
  2111. {
  2112. struct pool *ret = NULL;
  2113. int i;
  2114. for (i = 0; i < total_pools; i++) {
  2115. struct pool *pool = pools[i];
  2116. if (pool->prio == choice) {
  2117. ret = pool;
  2118. break;
  2119. }
  2120. }
  2121. if (unlikely(!ret)) {
  2122. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2123. return pools[choice];
  2124. }
  2125. return ret;
  2126. }
  2127. static void restart_longpoll(void);
  2128. static void switch_pools(struct pool *selected)
  2129. {
  2130. struct pool *pool, *last_pool;
  2131. int i, pool_no;
  2132. mutex_lock(&control_lock);
  2133. last_pool = currentpool;
  2134. pool_no = currentpool->pool_no;
  2135. /* Switch selected to pool number 0 and move the rest down */
  2136. if (selected) {
  2137. if (selected->prio != 0) {
  2138. for (i = 0; i < total_pools; i++) {
  2139. pool = pools[i];
  2140. if (pool->prio < selected->prio)
  2141. pool->prio++;
  2142. }
  2143. selected->prio = 0;
  2144. }
  2145. }
  2146. switch (pool_strategy) {
  2147. /* Both of these set to the master pool */
  2148. case POOL_FAILOVER:
  2149. case POOL_LOADBALANCE:
  2150. for (i = 0; i < total_pools; i++) {
  2151. pool = priority_pool(i);
  2152. if (!pool->idle && pool->enabled) {
  2153. pool_no = pool->pool_no;
  2154. break;
  2155. }
  2156. }
  2157. break;
  2158. /* Both of these simply increment and cycle */
  2159. case POOL_ROUNDROBIN:
  2160. case POOL_ROTATE:
  2161. if (selected) {
  2162. pool_no = selected->pool_no;
  2163. break;
  2164. }
  2165. pool_no++;
  2166. if (pool_no >= total_pools)
  2167. pool_no = 0;
  2168. break;
  2169. default:
  2170. break;
  2171. }
  2172. currentpool = pools[pool_no];
  2173. pool = currentpool;
  2174. mutex_unlock(&control_lock);
  2175. if (pool != last_pool) {
  2176. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  2177. /* Only switch longpoll if the new pool also supports LP */
  2178. if (pool->hdr_path)
  2179. restart_longpoll();
  2180. }
  2181. /* Reset the queued amount to allow more to be queued for the new pool */
  2182. mutex_lock(&qd_lock);
  2183. total_queued = 0;
  2184. mutex_unlock(&qd_lock);
  2185. }
  2186. static void discard_work(struct work *work)
  2187. {
  2188. if (!work->clone && !work->rolls && !work->mined) {
  2189. if (work->pool)
  2190. work->pool->discarded_work++;
  2191. total_discarded++;
  2192. if (opt_debug)
  2193. applog(LOG_DEBUG, "Discarded work");
  2194. } else if (opt_debug)
  2195. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2196. free_work(work);
  2197. }
  2198. /* This is overkill, but at least we'll know accurately how much work is
  2199. * queued to prevent ever being left without work */
  2200. static void inc_queued(void)
  2201. {
  2202. mutex_lock(&qd_lock);
  2203. total_queued++;
  2204. mutex_unlock(&qd_lock);
  2205. }
  2206. static void dec_queued(void)
  2207. {
  2208. mutex_lock(&qd_lock);
  2209. if (total_queued > 0)
  2210. total_queued--;
  2211. mutex_unlock(&qd_lock);
  2212. }
  2213. static int requests_queued(void)
  2214. {
  2215. int ret;
  2216. mutex_lock(&qd_lock);
  2217. ret = total_queued;
  2218. mutex_unlock(&qd_lock);
  2219. return ret;
  2220. }
  2221. static int discard_stale(void)
  2222. {
  2223. struct work *work, *tmp;
  2224. int i, stale = 0;
  2225. mutex_lock(stgd_lock);
  2226. HASH_ITER(hh, staged_work, work, tmp) {
  2227. if (stale_work(work)) {
  2228. HASH_DEL(staged_work, work);
  2229. if (work->clone)
  2230. --staged_clones;
  2231. discard_work(work);
  2232. stale++;
  2233. }
  2234. }
  2235. mutex_unlock(stgd_lock);
  2236. if (opt_debug)
  2237. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  2238. /* Dec queued outside the loop to not have recursive locks */
  2239. for (i = 0; i < stale; i++)
  2240. dec_queued();
  2241. return stale;
  2242. }
  2243. static bool queue_request(struct thr_info *thr, bool needed);
  2244. static void restart_threads(void)
  2245. {
  2246. int i, stale;
  2247. /* Discard staged work that is now stale */
  2248. stale = discard_stale();
  2249. for (i = 0; i < stale; i++)
  2250. queue_request(NULL, true);
  2251. for (i = 0; i < mining_threads; i++)
  2252. work_restart[i].restart = 1;
  2253. }
  2254. static void set_curblock(char *hexstr, unsigned char *hash)
  2255. {
  2256. unsigned char hash_swap[32];
  2257. char *old_hash = NULL;
  2258. struct timeval tv_now;
  2259. /* Don't free current_hash directly to avoid dereferencing it when
  2260. * we might be accessing its data elsewhere */
  2261. if (current_hash)
  2262. old_hash = current_hash;
  2263. strcpy(current_block, hexstr);
  2264. gettimeofday(&tv_now, NULL);
  2265. get_timestamp(blocktime, &tv_now);
  2266. swap256(hash_swap, hash);
  2267. current_hash = bin2hex(hash_swap, 16);
  2268. if (unlikely(!current_hash))
  2269. quit (1, "set_curblock OOM");
  2270. if (old_hash)
  2271. free(old_hash);
  2272. }
  2273. static void test_work_current(struct work *work)
  2274. {
  2275. struct block *s;
  2276. char *hexstr;
  2277. hexstr = bin2hex(work->data, 18);
  2278. if (unlikely(!hexstr)) {
  2279. applog(LOG_ERR, "stage_thread OOM");
  2280. return;
  2281. }
  2282. /* Search to see if this block exists yet and if not, consider it a
  2283. * new block and set the current block details to this one */
  2284. rd_lock(&blk_lock);
  2285. HASH_FIND_STR(blocks, hexstr, s);
  2286. rd_unlock(&blk_lock);
  2287. if (!s) {
  2288. s = calloc(sizeof(struct block), 1);
  2289. if (unlikely(!s))
  2290. quit (1, "test_work_current OOM");
  2291. strcpy(s->hash, hexstr);
  2292. wr_lock(&blk_lock);
  2293. HASH_ADD_STR(blocks, hash, s);
  2294. wr_unlock(&blk_lock);
  2295. set_curblock(hexstr, work->data);
  2296. new_blocks++;
  2297. if (block_changed != BLOCK_LP && block_changed != BLOCK_FIRST) {
  2298. block_changed = BLOCK_DETECT;
  2299. if (have_longpoll)
  2300. applog(LOG_NOTICE, "New block detected on network before longpoll, waiting on fresh work");
  2301. else
  2302. applog(LOG_NOTICE, "New block detected on network, waiting on fresh work");
  2303. } else
  2304. block_changed = BLOCK_NONE;
  2305. restart_threads();
  2306. }
  2307. free(hexstr);
  2308. }
  2309. static int tv_sort(struct work *worka, struct work *workb)
  2310. {
  2311. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  2312. }
  2313. static bool hash_push(struct work *work)
  2314. {
  2315. bool rc = true;
  2316. mutex_lock(stgd_lock);
  2317. if (likely(!getq->frozen)) {
  2318. HASH_ADD_INT(staged_work, id, work);
  2319. HASH_SORT(staged_work, tv_sort);
  2320. if (work->clone)
  2321. ++staged_clones;
  2322. } else
  2323. rc = false;
  2324. pthread_cond_signal(&getq->cond);
  2325. mutex_unlock(stgd_lock);
  2326. return rc;
  2327. }
  2328. static void *stage_thread(void *userdata)
  2329. {
  2330. struct thr_info *mythr = userdata;
  2331. bool ok = true;
  2332. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2333. while (ok) {
  2334. struct work *work = NULL;
  2335. if (opt_debug)
  2336. applog(LOG_DEBUG, "Popping work to stage thread");
  2337. work = tq_pop(mythr->q, NULL);
  2338. if (unlikely(!work)) {
  2339. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  2340. ok = false;
  2341. break;
  2342. }
  2343. test_work_current(work);
  2344. if (opt_debug)
  2345. applog(LOG_DEBUG, "Pushing work to getwork queue");
  2346. if (unlikely(!hash_push(work))) {
  2347. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  2348. continue;
  2349. }
  2350. }
  2351. tq_freeze(mythr->q);
  2352. return NULL;
  2353. }
  2354. int curses_int(const char *query)
  2355. {
  2356. int ret;
  2357. char *cvar;
  2358. cvar = curses_input(query);
  2359. ret = atoi(cvar);
  2360. free(cvar);
  2361. return ret;
  2362. }
  2363. static bool input_pool(bool live);
  2364. static int active_pools(void)
  2365. {
  2366. int ret = 0;
  2367. int i;
  2368. for (i = 0; i < total_pools; i++) {
  2369. if ((pools[i])->enabled)
  2370. ret++;
  2371. }
  2372. return ret;
  2373. }
  2374. static void display_pool_summary(struct pool *pool)
  2375. {
  2376. double efficiency = 0.0;
  2377. if (curses_active_locked()) {
  2378. wlog("Pool: %s\n", pool->rpc_url);
  2379. wlog("%s long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  2380. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  2381. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  2382. wlog(" Accepted shares: %d\n", pool->accepted);
  2383. wlog(" Rejected shares: %d\n", pool->rejected);
  2384. if (pool->accepted || pool->rejected)
  2385. wlog(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  2386. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  2387. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2388. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  2389. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  2390. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  2391. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2392. wrefresh(logwin);
  2393. unlock_curses();
  2394. }
  2395. }
  2396. /* We can't remove the memory used for this struct pool because there may
  2397. * still be work referencing it. We just remove it from the pools list */
  2398. static void remove_pool(struct pool *pool)
  2399. {
  2400. int i, last_pool = total_pools - 1;
  2401. struct pool *other;
  2402. /* Boost priority of any lower prio than this one */
  2403. for (i = 0; i < total_pools; i++) {
  2404. other = pools[i];
  2405. if (other->prio > pool->prio)
  2406. other->prio--;
  2407. }
  2408. if (pool->pool_no < last_pool) {
  2409. /* Swap the last pool for this one */
  2410. (pools[last_pool])->pool_no = pool->pool_no;
  2411. pools[pool->pool_no] = pools[last_pool];
  2412. }
  2413. /* Give it an invalid number */
  2414. pool->pool_no = total_pools;
  2415. total_pools--;
  2416. }
  2417. static void display_pools(void)
  2418. {
  2419. struct pool *pool;
  2420. int selected, i;
  2421. char input;
  2422. opt_loginput = true;
  2423. immedok(logwin, true);
  2424. clear_logwin();
  2425. updated:
  2426. for (i = 0; i < total_pools; i++) {
  2427. pool = pools[i];
  2428. if (pool == current_pool())
  2429. wattron(logwin, A_BOLD);
  2430. if (!pool->enabled)
  2431. wattron(logwin, A_DIM);
  2432. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  2433. pool->pool_no,
  2434. pool->enabled? "Enabled" : "Disabled",
  2435. pool->idle? "Dead" : "Alive",
  2436. pool->prio,
  2437. pool->rpc_url, pool->rpc_user);
  2438. wattroff(logwin, A_BOLD | A_DIM);
  2439. }
  2440. retry:
  2441. wlogprint("\nCurrent pool management strategy: %s\n",
  2442. strategies[pool_strategy]);
  2443. if (pool_strategy == POOL_ROTATE)
  2444. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  2445. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  2446. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  2447. wlogprint("Or press any other key to continue\n");
  2448. input = getch();
  2449. if (!strncasecmp(&input, "a", 1)) {
  2450. input_pool(true);
  2451. goto updated;
  2452. } else if (!strncasecmp(&input, "r", 1)) {
  2453. if (total_pools <= 1) {
  2454. wlogprint("Cannot remove last pool");
  2455. goto retry;
  2456. }
  2457. selected = curses_int("Select pool number");
  2458. if (selected < 0 || selected >= total_pools) {
  2459. wlogprint("Invalid selection\n");
  2460. goto retry;
  2461. }
  2462. pool = pools[selected];
  2463. if (pool == current_pool())
  2464. switch_pools(NULL);
  2465. if (pool == current_pool()) {
  2466. wlogprint("Unable to remove pool due to activity\n");
  2467. goto retry;
  2468. }
  2469. pool->enabled = false;
  2470. remove_pool(pool);
  2471. goto updated;
  2472. } else if (!strncasecmp(&input, "s", 1)) {
  2473. selected = curses_int("Select pool number");
  2474. if (selected < 0 || selected >= total_pools) {
  2475. wlogprint("Invalid selection\n");
  2476. goto retry;
  2477. }
  2478. pool = pools[selected];
  2479. pool->enabled = true;
  2480. switch_pools(pool);
  2481. goto updated;
  2482. } else if (!strncasecmp(&input, "d", 1)) {
  2483. if (active_pools() <= 1) {
  2484. wlogprint("Cannot disable last pool");
  2485. goto retry;
  2486. }
  2487. selected = curses_int("Select pool number");
  2488. if (selected < 0 || selected >= total_pools) {
  2489. wlogprint("Invalid selection\n");
  2490. goto retry;
  2491. }
  2492. pool = pools[selected];
  2493. pool->enabled = false;
  2494. if (pool == current_pool())
  2495. switch_pools(NULL);
  2496. goto updated;
  2497. } else if (!strncasecmp(&input, "e", 1)) {
  2498. selected = curses_int("Select pool number");
  2499. if (selected < 0 || selected >= total_pools) {
  2500. wlogprint("Invalid selection\n");
  2501. goto retry;
  2502. }
  2503. pool = pools[selected];
  2504. pool->enabled = true;
  2505. if (pool->prio < current_pool()->prio)
  2506. switch_pools(pool);
  2507. goto updated;
  2508. } else if (!strncasecmp(&input, "c", 1)) {
  2509. for (i = 0; i <= TOP_STRATEGY; i++)
  2510. wlogprint("%d: %s\n", i, strategies[i]);
  2511. selected = curses_int("Select strategy number type");
  2512. if (selected < 0 || selected > TOP_STRATEGY) {
  2513. wlogprint("Invalid selection\n");
  2514. goto retry;
  2515. }
  2516. if (selected == POOL_ROTATE) {
  2517. opt_rotate_period = curses_int("Select interval in minutes");
  2518. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  2519. opt_rotate_period = 0;
  2520. wlogprint("Invalid selection\n");
  2521. goto retry;
  2522. }
  2523. }
  2524. pool_strategy = selected;
  2525. switch_pools(NULL);
  2526. goto updated;
  2527. } else if (!strncasecmp(&input, "i", 1)) {
  2528. selected = curses_int("Select pool number");
  2529. if (selected < 0 || selected >= total_pools) {
  2530. wlogprint("Invalid selection\n");
  2531. goto retry;
  2532. }
  2533. pool = pools[selected];
  2534. display_pool_summary(pool);
  2535. goto retry;
  2536. } else
  2537. clear_logwin();
  2538. immedok(logwin, false);
  2539. opt_loginput = false;
  2540. }
  2541. static void display_options(void)
  2542. {
  2543. int selected;
  2544. char input;
  2545. opt_loginput = true;
  2546. immedok(logwin, true);
  2547. clear_logwin();
  2548. retry:
  2549. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  2550. 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",
  2551. opt_debug ? "on" : "off",
  2552. want_per_device_stats? "on" : "off",
  2553. opt_quiet ? "on" : "off",
  2554. opt_log_output ? "on" : "off",
  2555. opt_protocol ? "on" : "off",
  2556. opt_log_interval);
  2557. wlogprint("Select an option or any other key to return\n");
  2558. input = getch();
  2559. if (!strncasecmp(&input, "q", 1)) {
  2560. opt_quiet ^= true;
  2561. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  2562. goto retry;
  2563. } else if (!strncasecmp(&input, "v", 1)) {
  2564. opt_log_output ^= true;
  2565. if (opt_log_output)
  2566. opt_quiet = false;
  2567. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2568. goto retry;
  2569. } else if (!strncasecmp(&input, "n", 1)) {
  2570. opt_log_output = false;
  2571. opt_debug = false;
  2572. opt_quiet = false;
  2573. opt_protocol = false;
  2574. want_per_device_stats = false;
  2575. wlogprint("Output mode reset to normal\n");
  2576. goto retry;
  2577. } else if (!strncasecmp(&input, "d", 1)) {
  2578. opt_debug ^= true;
  2579. opt_log_output = opt_debug;
  2580. if (opt_debug)
  2581. opt_quiet = false;
  2582. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2583. goto retry;
  2584. } else if (!strncasecmp(&input, "p", 1)) {
  2585. want_per_device_stats ^= true;
  2586. opt_log_output = want_per_device_stats;
  2587. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  2588. goto retry;
  2589. } else if (!strncasecmp(&input, "r", 1)) {
  2590. opt_protocol ^= true;
  2591. if (opt_protocol)
  2592. opt_quiet = false;
  2593. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2594. goto retry;
  2595. } else if (!strncasecmp(&input, "c", 1))
  2596. clear_logwin();
  2597. else if (!strncasecmp(&input, "l", 1)) {
  2598. selected = curses_int("Interval in seconds");
  2599. if (selected < 0 || selected > 9999) {
  2600. wlogprint("Invalid selection\n");
  2601. goto retry;
  2602. }
  2603. opt_log_interval = selected;
  2604. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2605. goto retry;
  2606. } else if (!strncasecmp(&input, "s", 1)) {
  2607. opt_realquiet = true;
  2608. } else
  2609. clear_logwin();
  2610. immedok(logwin, false);
  2611. opt_loginput = false;
  2612. }
  2613. static void set_options(void)
  2614. {
  2615. int selected;
  2616. char input;
  2617. opt_loginput = true;
  2618. immedok(logwin, true);
  2619. clear_logwin();
  2620. retry:
  2621. wlogprint("\n[D]ynamic mode: %s\n[L]ongpoll: %s\n",
  2622. opt_dynamic ? "On" : "Off", want_longpoll ? "On" : "Off");
  2623. if (opt_dynamic)
  2624. wlogprint("[I]ntensity: Dynamic\n");
  2625. else
  2626. wlogprint("[I]ntensity: %d\n", scan_intensity);
  2627. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[R]etries: %d\n[P]ause: %d\n",
  2628. opt_queue, opt_scantime, opt_retries, opt_fail_pause);
  2629. wlogprint("Select an option or any other key to return\n");
  2630. input = getch();
  2631. if (!strncasecmp(&input, "q", 1)) {
  2632. selected = curses_int("Extra work items to queue");
  2633. if (selected < 0 || selected > 9999) {
  2634. wlogprint("Invalid selection\n");
  2635. goto retry;
  2636. }
  2637. opt_queue = selected;
  2638. goto retry;
  2639. } else if (!strncasecmp(&input, "d", 1)) {
  2640. opt_dynamic ^= true;
  2641. goto retry;
  2642. } else if (!strncasecmp(&input, "l", 1)) {
  2643. want_longpoll ^= true;
  2644. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2645. restart_longpoll();
  2646. goto retry;
  2647. } else if (!strncasecmp(&input, "i", 1)) {
  2648. selected = curses_int("Set GPU scan intensity (-10 -> 10)");
  2649. if (selected < -10 || selected > 10) {
  2650. wlogprint("Invalid selection\n");
  2651. goto retry;
  2652. }
  2653. opt_dynamic = false;
  2654. scan_intensity = selected;
  2655. goto retry;
  2656. } else if (!strncasecmp(&input, "s", 1)) {
  2657. selected = curses_int("Set scantime in seconds");
  2658. if (selected < 0 || selected > 9999) {
  2659. wlogprint("Invalid selection\n");
  2660. goto retry;
  2661. }
  2662. opt_scantime = selected;
  2663. goto retry;
  2664. } else if (!strncasecmp(&input, "r", 1)) {
  2665. selected = curses_int("Retries before failing (-1 infinite)");
  2666. if (selected < -1 || selected > 9999) {
  2667. wlogprint("Invalid selection\n");
  2668. goto retry;
  2669. }
  2670. opt_retries = selected;
  2671. goto retry;
  2672. } else if (!strncasecmp(&input, "p", 1)) {
  2673. selected = curses_int("Seconds to pause before network retries");
  2674. if (selected < 1 || selected > 9999) {
  2675. wlogprint("Invalid selection\n");
  2676. goto retry;
  2677. }
  2678. opt_fail_pause = selected;
  2679. goto retry;
  2680. } else
  2681. clear_logwin();
  2682. immedok(logwin, false);
  2683. opt_loginput = false;
  2684. }
  2685. #ifdef HAVE_OPENCL
  2686. static void reinit_device(struct cgpu_info *cgpu);
  2687. static void manage_gpu(void)
  2688. {
  2689. struct thr_info *thr;
  2690. int selected, gpu, i;
  2691. char checkin[40];
  2692. char input;
  2693. if (!opt_g_threads)
  2694. return;
  2695. opt_loginput = true;
  2696. immedok(logwin, true);
  2697. clear_logwin();
  2698. retry:
  2699. for (gpu = 0; gpu < nDevs; gpu++) {
  2700. struct cgpu_info *cgpu = &gpus[gpu];
  2701. wlog("GPU %d: %.1f / %.1f Mh/s | A:%d R:%d HW:%d U:%.2f/m\n",
  2702. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  2703. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  2704. cgpu->utility);
  2705. #ifdef HAVE_ADL
  2706. if (gpus[gpu].has_adl) {
  2707. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  2708. float temp = 0, vddc = 0;
  2709. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune)) {
  2710. char logline[255];
  2711. strcpy(logline, ""); // In case it has no data
  2712. if (temp != -1)
  2713. sprintf(logline, "%.1f C ", temp);
  2714. if (fanspeed != -1 || fanpercent != -1) {
  2715. tailsprintf(logline, "F: ");
  2716. if (fanpercent != -1)
  2717. tailsprintf(logline, "%d%% ", fanpercent);
  2718. if (fanspeed != -1)
  2719. tailsprintf(logline, "(%d RPM) ", fanspeed);
  2720. tailsprintf(logline, " ");
  2721. }
  2722. if (engineclock != -1)
  2723. tailsprintf(logline, "E: %d MHz ", engineclock);
  2724. if (memclock != -1)
  2725. tailsprintf(logline, "M: %d Mhz ", memclock);
  2726. if (vddc != -1)
  2727. tailsprintf(logline, "V: %.3fV ", vddc);
  2728. if (activity != -1)
  2729. tailsprintf(logline, "A: %d%% ", activity);
  2730. if (powertune != -1)
  2731. tailsprintf(logline, "P: %d%%", powertune);
  2732. tailsprintf(logline, "\n");
  2733. wlog(logline);
  2734. }
  2735. }
  2736. #endif
  2737. wlog("Last initialised: %s\n", cgpu->init);
  2738. for (i = 0; i < mining_threads; i++) {
  2739. thr = &thr_info[i];
  2740. if (thr->cgpu != cgpu)
  2741. continue;
  2742. get_datestamp(checkin, &thr->last);
  2743. wlog("Thread %d: %.1f Mh/s %s ", i, thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled");
  2744. switch (cgpu->status) {
  2745. default:
  2746. case LIFE_WELL:
  2747. wlog("ALIVE");
  2748. break;
  2749. case LIFE_SICK:
  2750. wlog("SICK reported in %s", checkin);
  2751. break;
  2752. case LIFE_DEAD:
  2753. wlog("DEAD reported in %s", checkin);
  2754. break;
  2755. case LIFE_NOSTART:
  2756. wlog("Never started");
  2757. break;
  2758. }
  2759. wlog("\n");
  2760. }
  2761. wlog("\n");
  2762. }
  2763. wlogprint("[E]nable [D]isable [R]estart GPU %s\n",adl_active ? "[C]hange settings" : "");
  2764. wlogprint("Or press any other key to continue\n");
  2765. input = getch();
  2766. if (!strncasecmp(&input, "e", 1)) {
  2767. selected = curses_int("Select GPU to enable");
  2768. if (selected < 0 || selected >= nDevs) {
  2769. wlogprint("Invalid selection\n");
  2770. goto retry;
  2771. }
  2772. if (gpu_devices[selected]) {
  2773. wlogprint("Device already enabled\n");
  2774. goto retry;
  2775. }
  2776. gpu_devices[selected] = true;
  2777. for (i = 0; i < gpu_threads; i++) {
  2778. if (dev_from_id(i) != selected)
  2779. continue;
  2780. thr = &thr_info[i];
  2781. if (thr->cgpu->status != LIFE_WELL) {
  2782. wlogprint("Must restart device before enabling it");
  2783. gpu_devices[selected] = false;
  2784. goto retry;
  2785. }
  2786. if (opt_debug)
  2787. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  2788. tq_push(thr->q, &ping);
  2789. }
  2790. } if (!strncasecmp(&input, "d", 1)) {
  2791. selected = curses_int("Select GPU to disable");
  2792. if (selected < 0 || selected >= nDevs) {
  2793. wlogprint("Invalid selection\n");
  2794. goto retry;
  2795. }
  2796. if (!gpu_devices[selected]) {
  2797. wlogprint("Device already disabled\n");
  2798. goto retry;
  2799. }
  2800. gpu_devices[selected] = false;
  2801. } else if (!strncasecmp(&input, "r", 1)) {
  2802. selected = curses_int("Select GPU to attempt to restart");
  2803. if (selected < 0 || selected >= nDevs) {
  2804. wlogprint("Invalid selection\n");
  2805. goto retry;
  2806. }
  2807. wlogprint("Attempting to restart threads of GPU %d\n", selected);
  2808. reinit_device(&gpus[selected]);
  2809. } else if (adl_active && (!strncasecmp(&input, "c", 1))) {
  2810. selected = curses_int("Select GPU to change settings on");
  2811. if (selected < 0 || selected >= nDevs) {
  2812. wlogprint("Invalid selection\n");
  2813. goto retry;
  2814. }
  2815. change_gpusettings(selected);
  2816. } else
  2817. clear_logwin();
  2818. immedok(logwin, false);
  2819. opt_loginput = false;
  2820. }
  2821. #else
  2822. static void manage_gpu(void)
  2823. {
  2824. }
  2825. #endif
  2826. static void *input_thread(void *userdata)
  2827. {
  2828. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2829. if (!curses_active)
  2830. return NULL;
  2831. while (1) {
  2832. char input;
  2833. input = getch();
  2834. if (!strncasecmp(&input, "q", 1)) {
  2835. kill_work();
  2836. return NULL;
  2837. } else if (!strncasecmp(&input, "d", 1))
  2838. display_options();
  2839. else if (!strncasecmp(&input, "p", 1))
  2840. display_pools();
  2841. else if (!strncasecmp(&input, "s", 1))
  2842. set_options();
  2843. else if (!strncasecmp(&input, "g", 1))
  2844. manage_gpu();
  2845. if (opt_realquiet) {
  2846. disable_curses();
  2847. break;
  2848. }
  2849. }
  2850. return NULL;
  2851. }
  2852. static void *workio_thread(void *userdata)
  2853. {
  2854. struct thr_info *mythr = userdata;
  2855. bool ok = true;
  2856. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2857. while (ok) {
  2858. struct workio_cmd *wc;
  2859. if (opt_debug)
  2860. applog(LOG_DEBUG, "Popping work to work thread");
  2861. /* wait for workio_cmd sent to us, on our queue */
  2862. wc = tq_pop(mythr->q, NULL);
  2863. if (unlikely(!wc)) {
  2864. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  2865. ok = false;
  2866. break;
  2867. }
  2868. /* process workio_cmd */
  2869. switch (wc->cmd) {
  2870. case WC_GET_WORK:
  2871. ok = workio_get_work(wc);
  2872. break;
  2873. case WC_SUBMIT_WORK:
  2874. ok = workio_submit_work(wc);
  2875. break;
  2876. default:
  2877. ok = false;
  2878. break;
  2879. }
  2880. }
  2881. tq_freeze(mythr->q);
  2882. return NULL;
  2883. }
  2884. static void thread_reportin(struct thr_info *thr)
  2885. {
  2886. gettimeofday(&thr->last, NULL);
  2887. thr->cgpu->status = LIFE_WELL;
  2888. thr->getwork = false;
  2889. }
  2890. static inline void thread_reportout(struct thr_info *thr)
  2891. {
  2892. thr->getwork = true;
  2893. }
  2894. static void hashmeter(int thr_id, struct timeval *diff,
  2895. unsigned long hashes_done)
  2896. {
  2897. struct timeval temp_tv_end, total_diff;
  2898. double secs;
  2899. double local_secs;
  2900. double utility, efficiency = 0.0;
  2901. static double local_mhashes_done = 0;
  2902. static double rolling = 0;
  2903. double local_mhashes = (double)hashes_done / 1000000.0;
  2904. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2905. bool showlog = false;
  2906. /* Update the last time this thread reported in */
  2907. if (thr_id >= 0)
  2908. gettimeofday(&thr_info[thr_id].last, NULL);
  2909. /* Don't bother calculating anything if we're not displaying it */
  2910. if (opt_realquiet || !opt_log_interval)
  2911. return;
  2912. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  2913. /* So we can call hashmeter from a non worker thread */
  2914. if (thr_id >= 0) {
  2915. struct thr_info *thr = &thr_info[thr_id];
  2916. double thread_rolling = 0.0;
  2917. int i;
  2918. if (opt_debug)
  2919. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  2920. thr_id, hashes_done, hashes_done / secs);
  2921. /* Rolling average for each thread and each device */
  2922. decay_time(&thr->rolling, local_mhashes / secs);
  2923. for (i = 0; i < mining_threads; i++) {
  2924. struct thr_info *th = &thr_info[i];
  2925. if (th->cgpu == cgpu)
  2926. thread_rolling += th->rolling;
  2927. }
  2928. decay_time(&cgpu->rolling, thread_rolling);
  2929. cgpu->total_mhashes += local_mhashes;
  2930. // If needed, output detailed, per-device stats
  2931. if (want_per_device_stats) {
  2932. struct timeval now;
  2933. struct timeval elapsed;
  2934. gettimeofday(&now, NULL);
  2935. timeval_subtract(&elapsed, &now, &thr->cgpu->last_message_tv);
  2936. if (opt_log_interval <= elapsed.tv_sec) {
  2937. struct cgpu_info *cgpu = thr->cgpu;
  2938. char logline[255];
  2939. cgpu->last_message_tv = now;
  2940. get_statline(logline, cgpu);
  2941. if (!curses_active) {
  2942. printf("%s \r", logline);
  2943. fflush(stdout);
  2944. } else
  2945. applog(LOG_INFO, "%s", logline);
  2946. }
  2947. }
  2948. }
  2949. /* Totals are updated by all threads so can race without locking */
  2950. mutex_lock(&hash_lock);
  2951. gettimeofday(&temp_tv_end, NULL);
  2952. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  2953. total_mhashes_done += local_mhashes;
  2954. local_mhashes_done += local_mhashes;
  2955. if (total_diff.tv_sec < opt_log_interval)
  2956. /* Only update the total every opt_log_interval seconds */
  2957. goto out_unlock;
  2958. showlog = true;
  2959. gettimeofday(&total_tv_end, NULL);
  2960. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  2961. decay_time(&rolling, local_mhashes_done / local_secs);
  2962. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  2963. total_secs = (double)total_diff.tv_sec +
  2964. ((double)total_diff.tv_usec / 1000000.0);
  2965. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2966. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2967. sprintf(statusline, "%s(%ds):%.1f (avg):%.1f Mh/s | Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  2968. want_per_device_stats ? "ALL " : "",
  2969. opt_log_interval, rolling, total_mhashes_done / total_secs,
  2970. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  2971. local_mhashes_done = 0;
  2972. out_unlock:
  2973. mutex_unlock(&hash_lock);
  2974. if (showlog) {
  2975. if (!curses_active) {
  2976. printf("%s \r", statusline);
  2977. fflush(stdout);
  2978. } else
  2979. applog(LOG_INFO, "%s", statusline);
  2980. }
  2981. }
  2982. static bool pool_active(struct pool *pool, bool pinging)
  2983. {
  2984. bool ret = false;
  2985. json_t *val;
  2986. CURL *curl;
  2987. bool rolltime;
  2988. curl = curl_easy_init();
  2989. if (unlikely(!curl)) {
  2990. applog(LOG_ERR, "CURL initialisation failed");
  2991. return false;
  2992. }
  2993. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  2994. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2995. true, false, &rolltime, pool);
  2996. if (val) {
  2997. struct work *work = make_work();
  2998. bool rc;
  2999. rc = work_decode(json_object_get(val, "result"), work);
  3000. if (rc) {
  3001. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  3002. pool->pool_no, pool->rpc_url);
  3003. work->pool = pool;
  3004. work->rolltime = rolltime;
  3005. if (opt_debug)
  3006. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  3007. tq_push(thr_info[stage_thr_id].q, work);
  3008. total_getworks++;
  3009. pool->getwork_requested++;
  3010. inc_queued();
  3011. ret = true;
  3012. gettimeofday(&pool->tv_idle, NULL);
  3013. } else {
  3014. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  3015. pool->pool_no, pool->rpc_url);
  3016. free_work(work);
  3017. }
  3018. json_decref(val);
  3019. } else {
  3020. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  3021. pool->pool_no, pool->rpc_url);
  3022. if (!pinging)
  3023. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  3024. }
  3025. curl_easy_cleanup(curl);
  3026. return ret;
  3027. }
  3028. static void pool_died(struct pool *pool)
  3029. {
  3030. if (!pool_tset(pool, &pool->idle)) {
  3031. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  3032. gettimeofday(&pool->tv_idle, NULL);
  3033. switch_pools(NULL);
  3034. }
  3035. }
  3036. static inline int cp_prio(void)
  3037. {
  3038. int prio;
  3039. mutex_lock(&control_lock);
  3040. prio = currentpool->prio;
  3041. mutex_unlock(&control_lock);
  3042. return prio;
  3043. }
  3044. static void pool_resus(struct pool *pool)
  3045. {
  3046. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  3047. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  3048. switch_pools(NULL);
  3049. }
  3050. static bool queue_request(struct thr_info *thr, bool needed)
  3051. {
  3052. struct workio_cmd *wc;
  3053. int rq = requests_queued();
  3054. if (rq >= mining_threads + staged_clones)
  3055. return true;
  3056. /* fill out work request message */
  3057. wc = calloc(1, sizeof(*wc));
  3058. if (unlikely(!wc)) {
  3059. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  3060. return false;
  3061. }
  3062. wc->cmd = WC_GET_WORK;
  3063. if (thr)
  3064. wc->thr = thr;
  3065. else
  3066. wc->thr = NULL;
  3067. /* If we're queueing work faster than we can stage it, consider the
  3068. * system lagging and allow work to be gathered from another pool if
  3069. * possible */
  3070. if (rq && needed && !requests_staged() && !opt_fail_only)
  3071. wc->lagging = true;
  3072. if (opt_debug)
  3073. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  3074. /* send work request to workio thread */
  3075. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3076. applog(LOG_ERR, "Failed to tq_push in queue_request");
  3077. workio_cmd_free(wc);
  3078. return false;
  3079. }
  3080. inc_queued();
  3081. return true;
  3082. }
  3083. struct work *hash_pop(const struct timespec *abstime)
  3084. {
  3085. struct work *work = NULL;
  3086. int rc;
  3087. mutex_lock(stgd_lock);
  3088. if (HASH_COUNT(staged_work))
  3089. goto pop;
  3090. if (abstime)
  3091. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  3092. else
  3093. rc = pthread_cond_wait(&getq->cond, stgd_lock);
  3094. if (rc)
  3095. goto out;
  3096. if (!HASH_COUNT(staged_work))
  3097. goto out;
  3098. pop:
  3099. work = staged_work;
  3100. HASH_DEL(staged_work, work);
  3101. if (work->clone)
  3102. --staged_clones;
  3103. out:
  3104. mutex_unlock(stgd_lock);
  3105. return work;
  3106. }
  3107. static inline bool should_roll(struct work *work)
  3108. {
  3109. int rs;
  3110. rs = requests_staged();
  3111. if (rs >= mining_threads)
  3112. return false;
  3113. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE || !rs)
  3114. return true;
  3115. return false;
  3116. }
  3117. static inline bool can_roll(struct work *work)
  3118. {
  3119. return (work->pool && !stale_work(work) && work->rolltime &&
  3120. work->rolls < 11 && !work->clone);
  3121. }
  3122. static void roll_work(struct work *work)
  3123. {
  3124. uint32_t *work_ntime;
  3125. uint32_t ntime;
  3126. work_ntime = (uint32_t *)(work->data + 68);
  3127. ntime = be32toh(*work_ntime);
  3128. ntime++;
  3129. *work_ntime = htobe32(ntime);
  3130. local_work++;
  3131. work->rolls++;
  3132. work->blk.nonce = 0;
  3133. if (opt_debug)
  3134. applog(LOG_DEBUG, "Successfully rolled work");
  3135. }
  3136. /* Recycle the work at a higher starting res_nonce if we know the thread we're
  3137. * giving it to will not finish scanning it. We keep the master copy to be
  3138. * recycled more rapidly and discard the clone to avoid repeating work */
  3139. static bool divide_work(struct timeval *now, struct work *work, uint32_t hash_div)
  3140. {
  3141. uint64_t hash_inc;
  3142. if (work->clone)
  3143. return false;
  3144. hash_inc = MAXTHREADS / hash_div * 2;
  3145. if ((uint64_t)work->blk.nonce + hash_inc < MAXTHREADS) {
  3146. /* Okay we can divide it up */
  3147. work->blk.nonce += hash_inc;
  3148. work->cloned = true;
  3149. local_work++;
  3150. if (opt_debug)
  3151. applog(LOG_DEBUG, "Successfully divided work");
  3152. return true;
  3153. } else if (can_roll(work) && should_roll(work)) {
  3154. roll_work(work);
  3155. return true;
  3156. }
  3157. return false;
  3158. }
  3159. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  3160. const int thr_id, uint32_t hash_div)
  3161. {
  3162. struct timespec abstime = {};
  3163. struct timeval now;
  3164. struct work *work_heap;
  3165. struct pool *pool;
  3166. bool ret = false;
  3167. int failures = 0;
  3168. /* Tell the watchdog thread this thread is waiting on getwork and
  3169. * should not be restarted */
  3170. thread_reportout(thr);
  3171. retry:
  3172. pool = current_pool();
  3173. if (unlikely((!requested || requests_queued() < opt_queue) && !queue_request(thr, true))) {
  3174. applog(LOG_WARNING, "Failed to queue_request in get_work");
  3175. goto out;
  3176. }
  3177. if (!requests_staged()) {
  3178. if (can_roll(work)) {
  3179. roll_work(work);
  3180. ret = true;
  3181. goto out;
  3182. }
  3183. if (requested && requests_queued() >= mining_threads &&
  3184. !pool_tset(pool, &pool->lagging)) {
  3185. applog(LOG_WARNING, "Pool %d not providing work fast enough",
  3186. pool->pool_no);
  3187. pool->getfail_occasions++;
  3188. total_go++;
  3189. }
  3190. }
  3191. requested = false;
  3192. gettimeofday(&now, NULL);
  3193. abstime.tv_sec = now.tv_sec + 60;
  3194. if (opt_debug)
  3195. applog(LOG_DEBUG, "Popping work from get queue to get work");
  3196. /* wait for 1st response, or get cached response */
  3197. work_heap = hash_pop(&abstime);
  3198. if (unlikely(!work_heap)) {
  3199. /* Attempt to switch pools if this one times out */
  3200. pool_died(pool);
  3201. goto retry;
  3202. }
  3203. if (stale_work(work_heap)) {
  3204. dec_queued();
  3205. discard_work(work_heap);
  3206. goto retry;
  3207. }
  3208. pool = work_heap->pool;
  3209. /* If we make it here we have succeeded in getting fresh work */
  3210. if (!work_heap->mined) {
  3211. pool_tclear(pool, &pool->lagging);
  3212. if (pool_tclear(pool, &pool->idle))
  3213. pool_resus(pool);
  3214. }
  3215. memcpy(work, work_heap, sizeof(*work));
  3216. /* Copy the res nonce back so we know to start at a higher baseline
  3217. * should we divide the same work up again. Make the work we're
  3218. * handing out be clone */
  3219. if (divide_work(&now, work_heap, hash_div)) {
  3220. if (opt_debug)
  3221. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  3222. hash_push(work_heap);
  3223. work->clone = true;
  3224. } else {
  3225. dec_queued();
  3226. free_work(work_heap);
  3227. }
  3228. ret = true;
  3229. out:
  3230. if (unlikely(ret == false)) {
  3231. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  3232. applog(LOG_ERR, "Failed %d times to get_work");
  3233. return ret;
  3234. }
  3235. applog(LOG_DEBUG, "Retrying after %d seconds", fail_pause);
  3236. sleep(fail_pause);
  3237. fail_pause += opt_fail_pause;
  3238. goto retry;
  3239. }
  3240. fail_pause = opt_fail_pause;
  3241. work->thr_id = thr_id;
  3242. thread_reportin(thr);
  3243. if (ret)
  3244. work->mined = true;
  3245. return ret;
  3246. }
  3247. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  3248. {
  3249. struct workio_cmd *wc;
  3250. /* fill out work request message */
  3251. wc = calloc(1, sizeof(*wc));
  3252. if (unlikely(!wc)) {
  3253. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  3254. return false;
  3255. }
  3256. wc->u.work = make_work();
  3257. wc->cmd = WC_SUBMIT_WORK;
  3258. wc->thr = thr;
  3259. memcpy(wc->u.work, work_in, sizeof(*work_in));
  3260. if (opt_debug)
  3261. applog(LOG_DEBUG, "Pushing submit work to work thread");
  3262. /* send solution to workio thread */
  3263. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3264. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  3265. goto err_out;
  3266. }
  3267. return true;
  3268. err_out:
  3269. workio_cmd_free(wc);
  3270. return false;
  3271. }
  3272. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  3273. {
  3274. work->data[64+12+0] = (nonce>>0) & 0xff;
  3275. work->data[64+12+1] = (nonce>>8) & 0xff;
  3276. work->data[64+12+2] = (nonce>>16) & 0xff;
  3277. work->data[64+12+3] = (nonce>>24) & 0xff;
  3278. /* Do one last check before attempting to submit the work */
  3279. if (!fulltest(work->data + 64, work->target))
  3280. return true;
  3281. return submit_work_sync(thr, work);
  3282. }
  3283. static void *miner_thread(void *userdata)
  3284. {
  3285. struct work *work = make_work();
  3286. struct thr_info *mythr = userdata;
  3287. const int thr_id = mythr->id;
  3288. uint32_t max_nonce = 0xffffff, total_hashes = 0;
  3289. unsigned long hashes_done = max_nonce;
  3290. bool needs_work = true;
  3291. /* Try to cycle approximately 5 times before each log update */
  3292. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  3293. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3294. bool requested = false;
  3295. uint32_t nonce_inc = max_nonce, hash_div = 1;
  3296. double hash_divfloat = 1.0;
  3297. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3298. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  3299. * and if that fails, then SCHED_BATCH. No need for this to be an
  3300. * error if it fails */
  3301. setpriority(PRIO_PROCESS, 0, 19);
  3302. drop_policy();
  3303. /* Cpu affinity only makes sense if the number of threads is a multiple
  3304. * of the number of CPUs */
  3305. if (!(opt_n_threads % num_processors))
  3306. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  3307. /* Invalidate pool so it fails can_roll() test */
  3308. work->pool = NULL;
  3309. while (1) {
  3310. struct timeval tv_workstart, tv_start, tv_end, diff;
  3311. uint64_t max64;
  3312. bool rc;
  3313. if (needs_work) {
  3314. gettimeofday(&tv_workstart, NULL);
  3315. /* obtain new work from internal workio thread */
  3316. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3317. applog(LOG_ERR, "work retrieval failed, exiting "
  3318. "mining thread %d", thr_id);
  3319. goto out;
  3320. }
  3321. needs_work = requested = false;
  3322. total_hashes = 0;
  3323. max_nonce = work->blk.nonce + hashes_done;
  3324. }
  3325. hashes_done = 0;
  3326. gettimeofday(&tv_start, NULL);
  3327. /* scan nonces for a proof-of-work hash */
  3328. switch (opt_algo) {
  3329. case ALGO_C:
  3330. rc = scanhash_c(thr_id, work->midstate, work->data + 64,
  3331. work->hash1, work->hash, work->target,
  3332. max_nonce, &hashes_done,
  3333. work->blk.nonce);
  3334. break;
  3335. #ifdef WANT_X8632_SSE2
  3336. case ALGO_SSE2_32: {
  3337. unsigned int rc5 =
  3338. scanhash_sse2_32(thr_id, work->midstate, work->data + 64,
  3339. work->hash1, work->hash,
  3340. work->target,
  3341. max_nonce, &hashes_done,
  3342. work->blk.nonce);
  3343. rc = (rc5 == -1) ? false : true;
  3344. }
  3345. break;
  3346. #endif
  3347. #ifdef WANT_X8664_SSE2
  3348. case ALGO_SSE2_64: {
  3349. unsigned int rc5 =
  3350. scanhash_sse2_64(thr_id, work->midstate, work->data + 64,
  3351. work->hash1, work->hash,
  3352. work->target,
  3353. max_nonce, &hashes_done,
  3354. work->blk.nonce);
  3355. rc = (rc5 == -1) ? false : true;
  3356. }
  3357. break;
  3358. #endif
  3359. #ifdef WANT_X8664_SSE4
  3360. case ALGO_SSE4_64: {
  3361. unsigned int rc5 =
  3362. scanhash_sse4_64(thr_id, work->midstate, work->data + 64,
  3363. work->hash1, work->hash,
  3364. work->target,
  3365. max_nonce, &hashes_done,
  3366. work->blk.nonce);
  3367. rc = (rc5 == -1) ? false : true;
  3368. }
  3369. break;
  3370. #endif
  3371. #ifdef WANT_SSE2_4WAY
  3372. case ALGO_4WAY: {
  3373. unsigned int rc4 =
  3374. ScanHash_4WaySSE2(thr_id, work->midstate, work->data + 64,
  3375. work->hash1, work->hash,
  3376. work->target,
  3377. max_nonce, &hashes_done,
  3378. work->blk.nonce);
  3379. rc = (rc4 == -1) ? false : true;
  3380. }
  3381. break;
  3382. #endif
  3383. #ifdef WANT_VIA_PADLOCK
  3384. case ALGO_VIA:
  3385. rc = scanhash_via(thr_id, work->data, work->target,
  3386. max_nonce, &hashes_done,
  3387. work->blk.nonce);
  3388. break;
  3389. #endif
  3390. case ALGO_CRYPTOPP:
  3391. rc = scanhash_cryptopp(thr_id, work->midstate, work->data + 64,
  3392. work->hash1, work->hash, work->target,
  3393. max_nonce, &hashes_done,
  3394. work->blk.nonce);
  3395. break;
  3396. #ifdef WANT_CRYPTOPP_ASM32
  3397. case ALGO_CRYPTOPP_ASM32:
  3398. rc = scanhash_asm32(thr_id, work->midstate, work->data + 64,
  3399. work->hash1, work->hash, work->target,
  3400. max_nonce, &hashes_done,
  3401. work->blk.nonce);
  3402. break;
  3403. #endif
  3404. default:
  3405. /* should never happen */
  3406. goto out;
  3407. }
  3408. /* record scanhash elapsed time */
  3409. gettimeofday(&tv_end, NULL);
  3410. timeval_subtract(&diff, &tv_end, &tv_start);
  3411. hashes_done -= work->blk.nonce;
  3412. hashmeter(thr_id, &diff, hashes_done);
  3413. total_hashes += hashes_done;
  3414. work->blk.nonce += hashes_done;
  3415. /* adjust max_nonce to meet target cycle time */
  3416. if (diff.tv_usec > 500000)
  3417. diff.tv_sec++;
  3418. if (diff.tv_sec && diff.tv_sec != cycle) {
  3419. uint64_t next_inc = ((uint64_t)hashes_done * (uint64_t)cycle) / (uint64_t)diff.tv_sec;
  3420. if (next_inc > (uint64_t)nonce_inc / 2 * 3)
  3421. next_inc = nonce_inc / 2 * 3;
  3422. nonce_inc = next_inc;
  3423. } else if (!diff.tv_sec)
  3424. nonce_inc = hashes_done * 2;
  3425. if (nonce_inc < 4)
  3426. nonce_inc = 0xffffff;
  3427. max64 = work->blk.nonce + nonce_inc;
  3428. if (max64 > 0xfffffffaULL)
  3429. max64 = 0xfffffffaULL;
  3430. max_nonce = max64;
  3431. /* if nonce found, submit work */
  3432. if (unlikely(rc)) {
  3433. if (opt_debug)
  3434. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  3435. if (unlikely(!submit_work_sync(mythr, work))) {
  3436. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  3437. break;
  3438. }
  3439. work->blk.nonce += 4;
  3440. }
  3441. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3442. if (!requested && (diff.tv_sec >= request_interval)) {
  3443. thread_reportout(mythr);
  3444. if (unlikely(!queue_request(mythr, false))) {
  3445. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  3446. goto out;
  3447. }
  3448. thread_reportin(mythr);
  3449. requested = true;
  3450. }
  3451. if (diff.tv_sec > opt_scantime) {
  3452. decay_time(&hash_divfloat , (double)((MAXTHREADS / total_hashes) ? : 1));
  3453. hash_div = hash_divfloat;
  3454. needs_work = true;
  3455. } else if (work_restart[thr_id].restart || stale_work(work) ||
  3456. work->blk.nonce >= MAXTHREADS - hashes_done)
  3457. needs_work = true;
  3458. if (unlikely(mythr->pause)) {
  3459. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3460. mythr->rolling = mythr->cgpu->rolling = 0;
  3461. if (opt_debug)
  3462. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  3463. thread_reportout(mythr);
  3464. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3465. thread_reportin(mythr);
  3466. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3467. }
  3468. }
  3469. out:
  3470. thread_reportin(mythr);
  3471. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3472. tq_freeze(mythr->q);
  3473. return NULL;
  3474. }
  3475. enum {
  3476. STAT_SLEEP_INTERVAL = 1,
  3477. STAT_CTR_INTERVAL = 10000000,
  3478. FAILURE_INTERVAL = 30,
  3479. };
  3480. #ifdef HAVE_OPENCL
  3481. static _clState *clStates[MAX_GPUDEVICES];
  3482. static cl_int queue_poclbm_kernel(_clState *clState, dev_blk_ctx *blk)
  3483. {
  3484. cl_kernel *kernel = &clState->kernel;
  3485. cl_int status = 0;
  3486. int num = 0;
  3487. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  3488. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  3489. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  3490. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  3491. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  3492. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  3493. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  3494. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  3495. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  3496. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3497. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3498. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3499. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3500. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3501. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  3502. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  3503. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  3504. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  3505. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  3506. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  3507. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  3508. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  3509. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  3510. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  3511. (void *)&clState->outputBuffer);
  3512. return status;
  3513. }
  3514. static cl_int queue_phatk_kernel(_clState *clState, dev_blk_ctx *blk)
  3515. {
  3516. cl_uint vwidth = clState->preferred_vwidth;
  3517. cl_kernel *kernel = &clState->kernel;
  3518. cl_int status = 0;
  3519. int i, num = 0;
  3520. uint *nonces;
  3521. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  3522. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  3523. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  3524. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  3525. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  3526. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  3527. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  3528. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  3529. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  3530. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3531. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3532. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3533. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3534. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3535. nonces = alloca(sizeof(uint) * vwidth);
  3536. for (i = 0; i < vwidth; i++)
  3537. nonces[i] = blk->nonce + i;
  3538. status |= clSetKernelArg(*kernel, num++, vwidth * sizeof(uint), (void *)nonces);
  3539. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  3540. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  3541. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4_2);
  3542. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal0);
  3543. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW18);
  3544. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW19);
  3545. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW31);
  3546. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW32);
  3547. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  3548. (void *)&clState->outputBuffer);
  3549. return status;
  3550. }
  3551. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  3552. unsigned int *hashes, size_t *globalThreads,
  3553. unsigned int minthreads)
  3554. {
  3555. *threads = 1 << (15 + scan_intensity);
  3556. if (*threads < minthreads)
  3557. *threads = minthreads;
  3558. *globalThreads = *threads;
  3559. *hashes = *threads * vectors;
  3560. }
  3561. static void *gpuminer_thread(void *userdata)
  3562. {
  3563. cl_int (*queue_kernel_parameters)(_clState *, dev_blk_ctx *);
  3564. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  3565. struct timeval tv_start, tv_end, diff, tv_workstart;
  3566. struct thr_info *mythr = userdata;
  3567. const int thr_id = mythr->id;
  3568. uint32_t *res, *blank_res;
  3569. double gpu_ms_average = 7;
  3570. int gpu = dev_from_id(thr_id);
  3571. size_t globalThreads[1];
  3572. size_t localThreads[1];
  3573. cl_int status;
  3574. _clState *clState = clStates[thr_id];
  3575. const cl_kernel *kernel = &clState->kernel;
  3576. struct work *work = make_work();
  3577. unsigned int threads;
  3578. unsigned const int vectors = clState->preferred_vwidth;
  3579. unsigned int hashes;
  3580. unsigned int hashes_done = 0;
  3581. /* Request the next work item at 2/3 of the scantime */
  3582. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3583. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  3584. bool requested = false;
  3585. uint32_t total_hashes = 0, hash_div = 1;
  3586. switch (chosen_kernel) {
  3587. case KL_POCLBM:
  3588. queue_kernel_parameters = &queue_poclbm_kernel;
  3589. break;
  3590. case KL_PHATK:
  3591. default:
  3592. queue_kernel_parameters = &queue_phatk_kernel;
  3593. break;
  3594. }
  3595. if (opt_dynamic) {
  3596. /* Minimise impact on desktop if we want dynamic mode */
  3597. setpriority(PRIO_PROCESS, 0, 19);
  3598. drop_policy();
  3599. }
  3600. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3601. res = calloc(BUFFERSIZE, 1);
  3602. blank_res = calloc(BUFFERSIZE, 1);
  3603. if (!res || !blank_res) {
  3604. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  3605. goto out;
  3606. }
  3607. gettimeofday(&tv_start, NULL);
  3608. localThreads[0] = clState->work_size;
  3609. set_threads_hashes(vectors, &threads, &hashes, &globalThreads[0],
  3610. localThreads[0]);
  3611. diff.tv_sec = 0;
  3612. gettimeofday(&tv_end, NULL);
  3613. work->pool = NULL;
  3614. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  3615. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3616. if (unlikely(status != CL_SUCCESS))
  3617. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3618. mythr->cgpu->status = LIFE_WELL;
  3619. if (opt_debug)
  3620. applog(LOG_DEBUG, "Popping ping in gpuminer thread");
  3621. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  3622. gettimeofday(&tv_workstart, NULL);
  3623. /* obtain new work from internal workio thread */
  3624. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3625. applog(LOG_ERR, "work retrieval failed, exiting "
  3626. "gpu mining thread %d", thr_id);
  3627. goto out;
  3628. }
  3629. requested = false;
  3630. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3631. work->blk.nonce = 0;
  3632. while (1) {
  3633. struct timeval tv_gpustart, tv_gpuend;
  3634. suseconds_t gpu_us;
  3635. gettimeofday(&tv_gpustart, NULL);
  3636. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  3637. /* This finish flushes the readbuffer set with CL_FALSE later */
  3638. clFinish(clState->commandQueue);
  3639. gettimeofday(&tv_gpuend, NULL);
  3640. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  3641. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  3642. decay_time(&gpu_ms_average, gpu_us / 1000);
  3643. if (opt_dynamic) {
  3644. /* Try to not let the GPU be out for longer than 6ms, but
  3645. * increase intensity when the system is idle, unless
  3646. * dynamic is disabled. */
  3647. if (gpu_ms_average > 7) {
  3648. if (scan_intensity > -10)
  3649. scan_intensity--;
  3650. } else if (gpu_ms_average < 3) {
  3651. if (scan_intensity < 10)
  3652. scan_intensity++;
  3653. }
  3654. }
  3655. set_threads_hashes(vectors, &threads, &hashes, globalThreads, localThreads[0]);
  3656. if (diff.tv_sec > opt_scantime ||
  3657. work->blk.nonce >= MAXTHREADS - hashes ||
  3658. work_restart[thr_id].restart ||
  3659. stale_work(work)) {
  3660. /* Ignore any reads since we're getting new work and queue a clean buffer */
  3661. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3662. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3663. if (unlikely(status != CL_SUCCESS))
  3664. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3665. memset(res, 0, BUFFERSIZE);
  3666. gettimeofday(&tv_workstart, NULL);
  3667. if (opt_debug)
  3668. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  3669. /* obtain new work from internal workio thread */
  3670. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3671. applog(LOG_ERR, "work retrieval failed, exiting "
  3672. "gpu mining thread %d", thr_id);
  3673. goto out;
  3674. }
  3675. requested = false;
  3676. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3677. work_restart[thr_id].restart = 0;
  3678. /* Flushes the writebuffer set with CL_FALSE above */
  3679. clFinish(clState->commandQueue);
  3680. }
  3681. status = queue_kernel_parameters(clState, &work->blk);
  3682. if (unlikely(status != CL_SUCCESS))
  3683. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  3684. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  3685. if (res[FOUND]) {
  3686. /* Clear the buffer again */
  3687. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3688. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3689. if (unlikely(status != CL_SUCCESS))
  3690. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3691. if (opt_debug)
  3692. applog(LOG_DEBUG, "GPU %d found something?", gpu);
  3693. postcalc_hash_async(mythr, work, res);
  3694. memset(res, 0, BUFFERSIZE);
  3695. clFinish(clState->commandQueue);
  3696. }
  3697. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  3698. globalThreads, localThreads, 0, NULL, NULL);
  3699. if (unlikely(status != CL_SUCCESS))
  3700. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  3701. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3702. BUFFERSIZE, res, 0, NULL, NULL);
  3703. if (unlikely(status != CL_SUCCESS))
  3704. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  3705. gettimeofday(&tv_end, NULL);
  3706. timeval_subtract(&diff, &tv_end, &tv_start);
  3707. hashes_done += hashes;
  3708. total_hashes += hashes;
  3709. work->blk.nonce += hashes;
  3710. if (diff.tv_sec >= cycle) {
  3711. hashmeter(thr_id, &diff, hashes_done);
  3712. gettimeofday(&tv_start, NULL);
  3713. hashes_done = 0;
  3714. }
  3715. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3716. if (!requested) {
  3717. #if 0
  3718. if (diff.tv_sec > request_interval)
  3719. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  3720. #endif
  3721. if (diff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  3722. thread_reportout(mythr);
  3723. if (unlikely(!queue_request(mythr, false))) {
  3724. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  3725. goto out;
  3726. }
  3727. thread_reportin(mythr);
  3728. requested = true;
  3729. }
  3730. }
  3731. if (unlikely(!gpu_devices[gpu] || mythr->pause)) {
  3732. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3733. mythr->rolling = mythr->cgpu->rolling = 0;
  3734. if (opt_debug)
  3735. applog(LOG_DEBUG, "Popping wakeup ping in gpuminer thread");
  3736. thread_reportout(mythr);
  3737. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3738. thread_reportin(mythr);
  3739. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3740. }
  3741. }
  3742. out:
  3743. clReleaseCommandQueue(clState->commandQueue);
  3744. clReleaseKernel(clState->kernel);
  3745. clReleaseProgram(clState->program);
  3746. clReleaseContext(clState->context);
  3747. thread_reportin(mythr);
  3748. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3749. tq_freeze(mythr->q);
  3750. return NULL;
  3751. }
  3752. #endif /* HAVE_OPENCL */
  3753. /* Stage another work item from the work returned in a longpoll */
  3754. static void convert_to_work(json_t *val, bool rolltime)
  3755. {
  3756. struct work *work;
  3757. bool rc;
  3758. work = make_work();
  3759. rc= work_decode(json_object_get(val, "result"), work);
  3760. if (unlikely(!rc)) {
  3761. applog(LOG_ERR, "Could not convert longpoll data to work");
  3762. return;
  3763. }
  3764. work->pool = current_pool();
  3765. work->rolltime = rolltime;
  3766. /* We'll be checking this work item twice, but we already know it's
  3767. * from a new block so explicitly force the new block detection now
  3768. * rather than waiting for it to hit the stage thread */
  3769. test_work_current(work);
  3770. if (opt_debug)
  3771. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  3772. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  3773. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  3774. else if (opt_debug)
  3775. applog(LOG_DEBUG, "Converted longpoll data to work");
  3776. }
  3777. static void *longpoll_thread(void *userdata)
  3778. {
  3779. struct thr_info *mythr = userdata;
  3780. CURL *curl = NULL;
  3781. char *copy_start, *hdr_path, *lp_url = NULL;
  3782. bool need_slash = false;
  3783. int failures = 0;
  3784. struct pool *pool = current_pool();
  3785. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3786. pthread_detach(pthread_self());
  3787. curl = curl_easy_init();
  3788. if (unlikely(!curl)) {
  3789. applog(LOG_ERR, "CURL initialisation failed");
  3790. goto out;
  3791. }
  3792. tq_pop(mythr->q, NULL);
  3793. if (!pool->hdr_path) {
  3794. applog(LOG_NOTICE, "No long-poll found on this server");
  3795. goto out;
  3796. }
  3797. hdr_path = pool->hdr_path;
  3798. /* full URL */
  3799. if (strstr(hdr_path, "://")) {
  3800. lp_url = hdr_path;
  3801. hdr_path = NULL;
  3802. }
  3803. /* absolute path, on current server */
  3804. else {
  3805. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3806. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3807. need_slash = true;
  3808. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3809. if (!lp_url)
  3810. goto out;
  3811. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3812. }
  3813. have_longpoll = true;
  3814. applog(LOG_NOTICE, "Long-polling activated for %s", lp_url);
  3815. while (1) {
  3816. struct timeval start, end;
  3817. bool rolltime;
  3818. json_t *val;
  3819. gettimeofday(&start, NULL);
  3820. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  3821. false, true, &rolltime, pool);
  3822. if (likely(val)) {
  3823. /* Keep track of who ordered a restart_threads to make
  3824. * sure it's only done once per new block */
  3825. if (block_changed != BLOCK_DETECT) {
  3826. block_changed = BLOCK_LP;
  3827. applog(LOG_NOTICE, "LONGPOLL detected new block on network, waiting on fresh work");
  3828. } else {
  3829. applog(LOG_INFO, "LONGPOLL received after new block already detected");
  3830. block_changed = BLOCK_NONE;
  3831. }
  3832. convert_to_work(val, rolltime);
  3833. failures = 0;
  3834. json_decref(val);
  3835. } else {
  3836. /* Some pools regularly drop the longpoll request so
  3837. * only see this as longpoll failure if it happens
  3838. * immediately and just restart it the rest of the
  3839. * time. */
  3840. gettimeofday(&end, NULL);
  3841. if (end.tv_sec - start.tv_sec > 30)
  3842. continue;
  3843. if (failures++ < 10) {
  3844. sleep(30);
  3845. applog(LOG_WARNING,
  3846. "longpoll failed for %s, sleeping for 30s", lp_url);
  3847. } else {
  3848. applog(LOG_ERR,
  3849. "longpoll failed for %s, ending thread", lp_url);
  3850. goto out;
  3851. }
  3852. }
  3853. }
  3854. out:
  3855. have_longpoll = false;
  3856. tq_freeze(mythr->q);
  3857. if (curl)
  3858. curl_easy_cleanup(curl);
  3859. return NULL;
  3860. }
  3861. static void stop_longpoll(void)
  3862. {
  3863. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3864. thr_info_cancel(thr);
  3865. have_longpoll = false;
  3866. }
  3867. static void start_longpoll(void)
  3868. {
  3869. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3870. tq_thaw(thr->q);
  3871. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  3872. quit(1, "longpoll thread create failed");
  3873. if (opt_debug)
  3874. applog(LOG_DEBUG, "Pushing ping to longpoll thread");
  3875. tq_push(thr_info[longpoll_thr_id].q, &ping);
  3876. }
  3877. static void restart_longpoll(void)
  3878. {
  3879. if (want_longpoll && have_longpoll)
  3880. return;
  3881. stop_longpoll();
  3882. if (want_longpoll)
  3883. start_longpoll();
  3884. }
  3885. static void *reinit_cpu(void *userdata)
  3886. {
  3887. pthread_detach(pthread_self());
  3888. #if 0
  3889. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  3890. int cpu = cgpu->cpu_gpu;
  3891. long thr_id = ....(long)userdata;
  3892. struct thr_info *thr = &thr_info[thr_id];
  3893. int cpu = dev_from_id(thr_id);
  3894. cpus[cpu].alive = false;
  3895. thr->rolling = thr->cgpu->rolling = 0;
  3896. tq_freeze(thr->q);
  3897. if (!pthread_cancel(*thr->pth))
  3898. pthread_join(*thr->pth, NULL);
  3899. free(thr->q);
  3900. thr->q = tq_new();
  3901. if (!thr->q)
  3902. quit(1, "Failed to tq_new in reinit_cputhread");
  3903. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  3904. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  3905. applog(LOG_ERR, "thread %d create failed", thr_id);
  3906. return NULL;
  3907. }
  3908. tq_push(thr->q, &ping);
  3909. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3910. #endif
  3911. return NULL;
  3912. }
  3913. #ifdef HAVE_OPENCL
  3914. /* We have only one thread that ever re-initialises GPUs, thus if any GPU
  3915. * init command fails due to a completely wedged GPU, the thread will never
  3916. * return, unable to harm other GPUs. If it does return, it means we only had
  3917. * a soft failure and then the reinit_gpu thread is ready to tackle another
  3918. * GPU */
  3919. static void *reinit_gpu(void *userdata)
  3920. {
  3921. struct thr_info *mythr = userdata;
  3922. struct cgpu_info *cgpu;
  3923. struct thr_info *thr;
  3924. struct timeval now;
  3925. char name[256];
  3926. int thr_id;
  3927. int gpu;
  3928. pthread_detach(pthread_self());
  3929. select_cgpu:
  3930. cgpu = tq_pop(mythr->q, NULL);
  3931. if (!cgpu)
  3932. goto out;
  3933. if (clDevicesNum() != nDevs) {
  3934. applog(LOG_WARNING, "Hardware not reporting same number of active devices, will not attempt to restart GPU");
  3935. goto out;
  3936. }
  3937. gpu = cgpu->cpu_gpu;
  3938. gpu_devices[gpu] = false;
  3939. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3940. if (dev_from_id(thr_id) != gpu)
  3941. continue;
  3942. thr = &thr_info[thr_id];
  3943. if (!thr) {
  3944. applog(LOG_WARNING, "No reference to thread %d exists", thr_id);
  3945. continue;
  3946. }
  3947. thr->rolling = thr->cgpu->rolling = 0;
  3948. /* Reports the last time we tried to revive a sick GPU */
  3949. gettimeofday(&thr->sick, NULL);
  3950. if (!pthread_cancel(thr->pth)) {
  3951. applog(LOG_WARNING, "Thread %d still exists, killing it off", thr_id);
  3952. } else
  3953. applog(LOG_WARNING, "Thread %d no longer exists", thr_id);
  3954. }
  3955. gpu_devices[gpu] = true;
  3956. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3957. if (dev_from_id(thr_id) != gpu)
  3958. continue;
  3959. thr = &thr_info[thr_id];
  3960. /* Lose this ram cause we may get stuck here! */
  3961. //tq_freeze(thr->q);
  3962. thr->q = tq_new();
  3963. if (!thr->q)
  3964. quit(1, "Failed to tq_new in reinit_gpu");
  3965. /* Lose this ram cause we may dereference in the dying thread! */
  3966. //free(clState);
  3967. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  3968. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  3969. if (!clStates[thr_id]) {
  3970. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  3971. goto select_cgpu;
  3972. }
  3973. applog(LOG_INFO, "initCl() finished. Found %s", name);
  3974. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  3975. applog(LOG_ERR, "thread %d create failed", thr_id);
  3976. return NULL;
  3977. }
  3978. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3979. }
  3980. gettimeofday(&now, NULL);
  3981. get_datestamp(cgpu->init, &now);
  3982. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3983. if (dev_from_id(thr_id) != gpu)
  3984. continue;
  3985. thr = &thr_info[thr_id];
  3986. tq_push(thr->q, &ping);
  3987. }
  3988. goto select_cgpu;
  3989. out:
  3990. return NULL;
  3991. }
  3992. #else
  3993. static void *reinit_gpu(void *userdata)
  3994. {
  3995. }
  3996. #endif
  3997. static void reinit_device(struct cgpu_info *cgpu)
  3998. {
  3999. if (cgpu->is_gpu)
  4000. tq_push(thr_info[gpur_thr_id].q, cgpu);
  4001. else
  4002. tq_push(thr_info[cpur_thr_id].q, cgpu);
  4003. }
  4004. /* Determine which are the first threads belonging to a device and if they're
  4005. * active */
  4006. static bool active_device(int thr_id)
  4007. {
  4008. if (thr_id < gpu_threads) {
  4009. if (thr_id >= total_devices)
  4010. return false;
  4011. if (!gpu_devices[dev_from_id(thr_id)])
  4012. return false;
  4013. } else if (thr_id > gpu_threads + num_processors)
  4014. return false;
  4015. return true;
  4016. }
  4017. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  4018. * the screen at regular intervals, and restarts threads if they appear to have
  4019. * died. */
  4020. static void *watchdog_thread(void *userdata)
  4021. {
  4022. const unsigned int interval = opt_log_interval / 2 ? : 1;
  4023. static struct timeval rotate_tv;
  4024. struct timeval zero_tv;
  4025. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4026. memset(&zero_tv, 0, sizeof(struct timeval));
  4027. gettimeofday(&rotate_tv, NULL);
  4028. while (1) {
  4029. int i;
  4030. struct timeval now;
  4031. sleep(interval);
  4032. if (requests_queued() < opt_queue)
  4033. queue_request(NULL, false);
  4034. hashmeter(-1, &zero_tv, 0);
  4035. if (curses_active_locked()) {
  4036. change_logwinsize();
  4037. curses_print_status();
  4038. for (i = 0; i < mining_threads; i++)
  4039. curses_print_devstatus(i);
  4040. clearok(statuswin, true);
  4041. doupdate();
  4042. unlock_curses();
  4043. }
  4044. gettimeofday(&now, NULL);
  4045. for (i = 0; i < total_pools; i++) {
  4046. struct pool *pool = pools[i];
  4047. if (!pool->enabled)
  4048. continue;
  4049. /* Test pool is idle once every minute */
  4050. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  4051. gettimeofday(&pool->tv_idle, NULL);
  4052. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  4053. pool_resus(pool);
  4054. }
  4055. }
  4056. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  4057. gettimeofday(&rotate_tv, NULL);
  4058. switch_pools(NULL);
  4059. }
  4060. if (!sched_paused && !should_run()) {
  4061. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  4062. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4063. if (!schedstart.enable) {
  4064. quit(0, "Terminating execution as planned");
  4065. break;
  4066. }
  4067. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  4068. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4069. sched_paused = true;
  4070. for (i = 0; i < mining_threads; i++) {
  4071. struct thr_info *thr;
  4072. thr = &thr_info[i];
  4073. thr->pause = true;
  4074. }
  4075. } else if (sched_paused && should_run()) {
  4076. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  4077. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4078. if (schedstop.enable)
  4079. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  4080. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4081. sched_paused = false;
  4082. for (i = 0; i < mining_threads; i++) {
  4083. struct thr_info *thr;
  4084. thr = &thr_info[i];
  4085. /* Don't touch disabled GPUs */
  4086. if (thr->cgpu->is_gpu && !gpu_devices[thr->cgpu->cpu_gpu])
  4087. continue;
  4088. thr->pause = false;
  4089. tq_push(thr->q, &ping);
  4090. }
  4091. }
  4092. for (i = 0; i < gpu_threads; i++) {
  4093. struct thr_info *thr;
  4094. bool *enable;
  4095. int gpu;
  4096. /* Use only one thread per device to determine if the GPU is healthy */
  4097. if (i >= nDevs)
  4098. break;
  4099. thr = &thr_info[i];
  4100. gpu = thr->cgpu->cpu_gpu;
  4101. enable = &gpu_devices[gpu];
  4102. #ifdef HAVE_ADL
  4103. if (adl_active && gpus[gpu].has_adl && *enable)
  4104. gpu_autotune(gpu, enable);
  4105. if (opt_debug && gpus[gpu].has_adl) {
  4106. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  4107. float temp = 0, vddc = 0;
  4108. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  4109. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  4110. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  4111. }
  4112. #endif
  4113. /* Thread is waiting on getwork or disabled */
  4114. if (thr->getwork || !*enable)
  4115. continue;
  4116. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  4117. applog(LOG_ERR, "Thread %d recovered, GPU %d declared WELL!", i, gpu);
  4118. gpus[gpu].status = LIFE_WELL;
  4119. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  4120. thr->rolling = thr->cgpu->rolling = 0;
  4121. gpus[gpu].status = LIFE_SICK;
  4122. applog(LOG_ERR, "Thread %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  4123. gettimeofday(&thr->sick, NULL);
  4124. if (opt_restart) {
  4125. applog(LOG_ERR, "Attempting to restart GPU");
  4126. reinit_device(thr->cgpu);
  4127. }
  4128. } else if (now.tv_sec - thr->last.tv_sec > 600 && gpus[i].status == LIFE_SICK) {
  4129. gpus[gpu].status = LIFE_DEAD;
  4130. applog(LOG_ERR, "Thread %d not responding for more than 10 minutes, GPU %d declared DEAD!", i, gpu);
  4131. } else if (now.tv_sec - thr->sick.tv_sec > 60 && gpus[i].status == LIFE_SICK) {
  4132. /* Attempt to restart a GPU once every minute */
  4133. gettimeofday(&thr->sick, NULL);
  4134. if (opt_restart)
  4135. reinit_device(thr->cgpu);
  4136. }
  4137. }
  4138. }
  4139. return NULL;
  4140. }
  4141. static void log_print_status(int thr_id)
  4142. {
  4143. struct cgpu_info *cgpu;
  4144. char logline[255];
  4145. cgpu = thr_info[thr_id].cgpu;
  4146. get_statline(logline, cgpu);
  4147. applog(LOG_WARNING, "%s", logline);
  4148. }
  4149. static void print_summary(void)
  4150. {
  4151. struct timeval diff;
  4152. int hours, mins, secs, i;
  4153. double utility, efficiency = 0.0;
  4154. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  4155. hours = diff.tv_sec / 3600;
  4156. mins = (diff.tv_sec % 3600) / 60;
  4157. secs = diff.tv_sec % 60;
  4158. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  4159. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4160. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  4161. applog(LOG_WARNING, "Started at %s", datestamp);
  4162. if (opt_n_threads)
  4163. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  4164. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  4165. if (total_secs)
  4166. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  4167. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  4168. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  4169. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  4170. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  4171. if (total_accepted || total_rejected)
  4172. applog(LOG_WARNING, "Reject ratio: %.1f", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  4173. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  4174. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  4175. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  4176. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  4177. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  4178. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  4179. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  4180. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  4181. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  4182. if (total_pools > 1) {
  4183. for (i = 0; i < total_pools; i++) {
  4184. struct pool *pool = pools[i];
  4185. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  4186. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  4187. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  4188. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  4189. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  4190. if (pool->accepted || pool->rejected)
  4191. applog(LOG_WARNING, " Reject ratio: %.1f", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4192. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  4193. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  4194. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  4195. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  4196. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  4197. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  4198. }
  4199. }
  4200. applog(LOG_WARNING, "Summary of per device statistics:\n");
  4201. for (i = 0; i < mining_threads; i++) {
  4202. if (active_device(i))
  4203. log_print_status(i);
  4204. }
  4205. if (opt_shares)
  4206. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  4207. fflush(stdout);
  4208. fflush(stderr);
  4209. if (opt_shares > total_accepted)
  4210. quit(1, "Did not successfully mine as many shares as were requested.");
  4211. }
  4212. void quit(int status, const char *format, ...)
  4213. {
  4214. va_list ap;
  4215. disable_curses();
  4216. if (!opt_realquiet && successful_connect)
  4217. print_summary();
  4218. if (format) {
  4219. va_start(ap, format);
  4220. vfprintf(stderr, format, ap);
  4221. va_end(ap);
  4222. }
  4223. fprintf(stderr, "\n");
  4224. fflush(stderr);
  4225. exit(status);
  4226. }
  4227. char *curses_input(const char *query)
  4228. {
  4229. char *input;
  4230. echo();
  4231. input = malloc(255);
  4232. if (!input)
  4233. quit(1, "Failed to malloc input");
  4234. leaveok(logwin, false);
  4235. wlogprint("%s:\n", query);
  4236. wgetnstr(logwin, input, 255);
  4237. if (!strlen(input))
  4238. strcpy(input, "-1");
  4239. leaveok(logwin, true);
  4240. noecho();
  4241. return input;
  4242. }
  4243. static bool input_pool(bool live)
  4244. {
  4245. char *url = NULL, *user = NULL, *pass = NULL;
  4246. struct pool *pool = NULL;
  4247. bool ret = false;
  4248. immedok(logwin, true);
  4249. if (total_pools == MAX_POOLS) {
  4250. wlogprint("Reached maximum number of pools.\n");
  4251. goto out;
  4252. }
  4253. wlogprint("Input server details.\n");
  4254. url = curses_input("URL");
  4255. if (!url)
  4256. goto out;
  4257. if (strncmp(url, "http://", 7) &&
  4258. strncmp(url, "https://", 8)) {
  4259. char *httpinput;
  4260. httpinput = malloc(255);
  4261. if (!httpinput)
  4262. quit(1, "Failed to malloc httpinput");
  4263. strcpy(httpinput, "http://");
  4264. strncat(httpinput, url, 248);
  4265. free(url);
  4266. url = httpinput;
  4267. }
  4268. user = curses_input("Username");
  4269. if (!user)
  4270. goto out;
  4271. pass = curses_input("Password");
  4272. if (!pass)
  4273. goto out;
  4274. pool = calloc(sizeof(struct pool), 1);
  4275. if (!pool)
  4276. quit(1, "Failed to realloc pools in input_pool");
  4277. pool->pool_no = total_pools;
  4278. pool->prio = total_pools;
  4279. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  4280. quit (1, "Failed to pthread_mutex_init in input_pool");
  4281. pool->rpc_url = url;
  4282. pool->rpc_user = user;
  4283. pool->rpc_pass = pass;
  4284. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4285. if (!pool->rpc_userpass)
  4286. quit(1, "Failed to malloc userpass");
  4287. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4288. pool->tv_idle.tv_sec = ~0UL;
  4289. /* Test the pool is not idle if we're live running, otherwise
  4290. * it will be tested separately */
  4291. ret = true;
  4292. pool->enabled = true;
  4293. if (live && !pool_active(pool, false))
  4294. pool->idle = true;
  4295. pools[total_pools++] = pool;
  4296. out:
  4297. immedok(logwin, false);
  4298. if (!ret) {
  4299. if (url)
  4300. free(url);
  4301. if (user)
  4302. free(user);
  4303. if (pass)
  4304. free(pass);
  4305. if (pool)
  4306. free(pool);
  4307. }
  4308. return ret;
  4309. }
  4310. #if defined(unix)
  4311. static void fork_monitor()
  4312. {
  4313. // Make a pipe: [readFD, writeFD]
  4314. int pfd[2];
  4315. int r = pipe(pfd);
  4316. if (r<0) {
  4317. perror("pipe - failed to create pipe for --monitor");
  4318. exit(1);
  4319. }
  4320. // Make stderr write end of pipe
  4321. fflush(stderr);
  4322. r = dup2(pfd[1], 2);
  4323. if (r<0) {
  4324. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  4325. exit(1);
  4326. }
  4327. r = close(pfd[1]);
  4328. if (r<0) {
  4329. perror("close - failed to close write end of pipe for --monitor");
  4330. exit(1);
  4331. }
  4332. // Don't allow a dying monitor to kill the main process
  4333. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  4334. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  4335. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  4336. perror("signal - failed to edit signal mask for --monitor");
  4337. exit(1);
  4338. }
  4339. // Fork a child process
  4340. r = fork();
  4341. if (r<0) {
  4342. perror("fork - failed to fork child process for --monitor");
  4343. exit(1);
  4344. }
  4345. // Child: launch monitor command
  4346. if (0==r) {
  4347. // Make stdin read end of pipe
  4348. r = dup2(pfd[0], 0);
  4349. if (r<0) {
  4350. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  4351. exit(1);
  4352. }
  4353. close(pfd[0]);
  4354. if (r<0) {
  4355. perror("close - in child, failed to close read end of pipe for --monitor");
  4356. exit(1);
  4357. }
  4358. // Launch user specified command
  4359. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  4360. perror("execl - in child failed to exec user specified command for --monitor");
  4361. exit(1);
  4362. }
  4363. // Parent: clean up unused fds and bail
  4364. r = close(pfd[0]);
  4365. if (r<0) {
  4366. perror("close - failed to close read end of pipe for --monitor");
  4367. exit(1);
  4368. }
  4369. }
  4370. #endif // defined(unix)
  4371. static void enable_curses(void) {
  4372. int x,y;
  4373. lock_curses();
  4374. if (curses_active) {
  4375. unlock_curses();
  4376. return;
  4377. }
  4378. mainwin = initscr();
  4379. getmaxyx(mainwin, y, x);
  4380. statuswin = newwin(logstart, x, 0, 0);
  4381. leaveok(statuswin, true);
  4382. logwin = newwin(y - logcursor, 0, logcursor, 0);
  4383. idlok(logwin, true);
  4384. scrollok(logwin, true);
  4385. leaveok(logwin, true);
  4386. cbreak();
  4387. noecho();
  4388. curses_active = true;
  4389. unlock_curses();
  4390. }
  4391. int main (int argc, char *argv[])
  4392. {
  4393. unsigned int i, pools_active = 0;
  4394. struct block *block, *tmpblock;
  4395. struct work *work, *tmpwork;
  4396. struct sigaction handler;
  4397. struct thr_info *thr;
  4398. char name[256];
  4399. /* This dangerous functions tramples random dynamically allocated
  4400. * variables so do it before anything at all */
  4401. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  4402. quit(1, "Failed to curl_global_init");
  4403. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  4404. quit(1, "Failed to pthread_mutex_init");
  4405. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  4406. quit(1, "Failed to pthread_mutex_init");
  4407. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  4408. quit(1, "Failed to pthread_mutex_init");
  4409. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  4410. quit(1, "Failed to pthread_mutex_init");
  4411. if (unlikely(pthread_rwlock_init(&blk_lock, NULL)))
  4412. quit(1, "Failed to pthread_rwlock_init");
  4413. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  4414. init_max_name_len();
  4415. handler.sa_handler = &sighandler;
  4416. sigaction(SIGTERM, &handler, &termhandler);
  4417. sigaction(SIGINT, &handler, &inthandler);
  4418. opt_kernel_path = alloca(PATH_MAX);
  4419. strcpy(opt_kernel_path, CGMINER_PREFIX);
  4420. cgminer_path = alloca(PATH_MAX);
  4421. strcpy(cgminer_path, dirname(argv[0]));
  4422. strcat(cgminer_path, "/");
  4423. // Hack to make cgminer silent when called recursively on WIN32
  4424. int skip_to_bench = 0;
  4425. #if defined(WIN32)
  4426. char buf[32];
  4427. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  4428. skip_to_bench = 1;
  4429. #endif // defined(WIN32)
  4430. block = calloc(sizeof(struct block), 1);
  4431. if (unlikely(!block))
  4432. quit (1, "main OOM");
  4433. for (i = 0; i < 36; i++)
  4434. strcat(block->hash, "0");
  4435. HASH_ADD_STR(blocks, hash, block);
  4436. strcpy(current_block, block->hash);
  4437. // Reckon number of cores in the box
  4438. #if defined(WIN32)
  4439. DWORD system_am;
  4440. DWORD process_am;
  4441. BOOL ok = GetProcessAffinityMask(
  4442. GetCurrentProcess(),
  4443. &system_am,
  4444. &process_am
  4445. );
  4446. if (!ok) {
  4447. applog(LOG_ERR, "couldn't figure out number of processors :(");
  4448. num_processors = 1;
  4449. } else {
  4450. size_t n = 32;
  4451. num_processors = 0;
  4452. while (n--)
  4453. if (process_am & (1<<n))
  4454. ++num_processors;
  4455. }
  4456. #else
  4457. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  4458. #endif /* !WIN32 */
  4459. opt_n_threads = num_processors;
  4460. #ifdef HAVE_OPENCL
  4461. if (!skip_to_bench) {
  4462. for (i = 0; i < MAX_GPUDEVICES; i++)
  4463. gpu_devices[i] = false;
  4464. nDevs = clDevicesNum();
  4465. if (nDevs < 0) {
  4466. applog(LOG_ERR, "clDevicesNum returned error, none usable");
  4467. nDevs = 0;
  4468. }
  4469. }
  4470. #endif
  4471. /* parse command line */
  4472. opt_register_table(opt_config_table,
  4473. "Options for both config file and command line");
  4474. opt_register_table(opt_cmdline_table,
  4475. "Options for command line only");
  4476. opt_parse(&argc, argv, applog_and_exit);
  4477. if (argc != 1)
  4478. quit(1, "Unexpected extra commandline arguments");
  4479. applog(LOG_WARNING, "Started %s", packagename);
  4480. if (opt_nogpu)
  4481. nDevs = 0;
  4482. if (nDevs && !opt_usecpu)
  4483. opt_n_threads = 0;
  4484. strcat(opt_kernel_path, "/");
  4485. if (want_per_device_stats)
  4486. opt_log_output = true;
  4487. if (0<=opt_bench_algo) {
  4488. double rate = bench_algo_stage3(opt_bench_algo);
  4489. if (!skip_to_bench) {
  4490. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  4491. } else {
  4492. // Write result to shared memory for parent
  4493. #if defined(WIN32)
  4494. char unique_name[64];
  4495. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  4496. HANDLE map_handle = CreateFileMapping(
  4497. INVALID_HANDLE_VALUE, // use paging file
  4498. NULL, // default security attributes
  4499. PAGE_READWRITE, // read/write access
  4500. 0, // size: high 32-bits
  4501. 4096, // size: low 32-bits
  4502. unique_name // name of map object
  4503. );
  4504. if (NULL!=map_handle) {
  4505. void *shared_mem = MapViewOfFile(
  4506. map_handle, // object to map view of
  4507. FILE_MAP_WRITE, // read/write access
  4508. 0, // high offset: map from
  4509. 0, // low offset: beginning
  4510. 0 // default: map entire file
  4511. );
  4512. if (NULL!=shared_mem)
  4513. CopyMemory(shared_mem, &rate, sizeof(rate));
  4514. (void)UnmapViewOfFile(shared_mem);
  4515. }
  4516. (void)CloseHandle(map_handle);
  4517. }
  4518. #endif
  4519. }
  4520. exit(0);
  4521. }
  4522. if (opt_kernel) {
  4523. if (strcmp(opt_kernel, "poclbm") && strcmp(opt_kernel, "phatk"))
  4524. quit(1, "Invalid kernel name specified - must be poclbm or phatk");
  4525. if (!strcmp(opt_kernel, "poclbm"))
  4526. chosen_kernel = KL_POCLBM;
  4527. else
  4528. chosen_kernel = KL_PHATK;
  4529. } else
  4530. chosen_kernel = KL_NONE;
  4531. gpu_threads = nDevs * opt_g_threads;
  4532. if (total_devices) {
  4533. if (total_devices > nDevs)
  4534. quit(1, "More devices specified than exist");
  4535. for (i = 0; i < MAX_GPUDEVICES; i++)
  4536. if (gpu_devices[i] && i + 1 > nDevs)
  4537. quit (1, "Command line options set a device that doesn't exist");
  4538. } else {
  4539. for (i = 0; i < nDevs; i++)
  4540. gpu_devices[i] = true;
  4541. total_devices = nDevs;
  4542. }
  4543. if (!gpu_threads && !forced_n_threads) {
  4544. /* Maybe they turned GPU off; restore default CPU threads. */
  4545. opt_n_threads = num_processors;
  4546. }
  4547. if (!opt_n_threads && ! gpu_threads)
  4548. quit(1, "All devices disabled, cannot mine!");
  4549. logcursor = 8;
  4550. gpucursor = logcursor;
  4551. cpucursor = gpucursor + nDevs;
  4552. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  4553. logcursor = logstart + 1;
  4554. if (opt_realquiet)
  4555. use_curses = false;
  4556. if (!total_pools) {
  4557. enable_curses();
  4558. applog(LOG_WARNING, "Need to specify at least one pool server.");
  4559. if (!input_pool(false))
  4560. quit(1, "Pool setup failed");
  4561. if (!use_curses)
  4562. disable_curses();
  4563. }
  4564. for (i = 0; i < total_pools; i++) {
  4565. struct pool *pool = pools[i];
  4566. if (!pool->rpc_userpass) {
  4567. if (!pool->rpc_user || !pool->rpc_pass)
  4568. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  4569. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4570. if (!pool->rpc_userpass)
  4571. quit(1, "Failed to malloc userpass");
  4572. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4573. } else {
  4574. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  4575. if (!pool->rpc_user)
  4576. quit(1, "Failed to malloc user");
  4577. strcpy(pool->rpc_user, pool->rpc_userpass);
  4578. pool->rpc_user = strtok(pool->rpc_user, ":");
  4579. if (!pool->rpc_user)
  4580. quit(1, "Failed to find colon delimiter in userpass");
  4581. }
  4582. }
  4583. /* Set the currentpool to pool 0 */
  4584. currentpool = pools[0];
  4585. #ifdef HAVE_SYSLOG_H
  4586. if (use_syslog)
  4587. openlog(PACKAGE, LOG_PID, LOG_USER);
  4588. #endif
  4589. #if defined(unix)
  4590. if (opt_stderr_cmd)
  4591. fork_monitor();
  4592. #endif // defined(unix)
  4593. mining_threads = opt_n_threads + gpu_threads;
  4594. total_threads = mining_threads + 7;
  4595. work_restart = calloc(total_threads, sizeof(*work_restart));
  4596. if (!work_restart)
  4597. quit(1, "Failed to calloc work_restart");
  4598. thr_info = calloc(total_threads, sizeof(*thr));
  4599. if (!thr_info)
  4600. quit(1, "Failed to calloc thr_info");
  4601. /* init workio thread info */
  4602. work_thr_id = mining_threads;
  4603. thr = &thr_info[work_thr_id];
  4604. thr->id = work_thr_id;
  4605. thr->q = tq_new();
  4606. if (!thr->q)
  4607. quit(1, "Failed to tq_new");
  4608. /* start work I/O thread */
  4609. if (thr_info_create(thr, NULL, workio_thread, thr))
  4610. quit(1, "workio thread create failed");
  4611. /* init longpoll thread info */
  4612. longpoll_thr_id = mining_threads + 1;
  4613. thr = &thr_info[longpoll_thr_id];
  4614. thr->id = longpoll_thr_id;
  4615. thr->q = tq_new();
  4616. if (!thr->q)
  4617. quit(1, "Failed to tq_new");
  4618. if (opt_n_threads ) {
  4619. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  4620. if (unlikely(!cpus))
  4621. quit(1, "Failed to calloc cpus");
  4622. }
  4623. stage_thr_id = mining_threads + 3;
  4624. thr = &thr_info[stage_thr_id];
  4625. thr->q = tq_new();
  4626. if (!thr->q)
  4627. quit(1, "Failed to tq_new");
  4628. /* start stage thread */
  4629. if (thr_info_create(thr, NULL, stage_thread, thr))
  4630. quit(1, "stage thread create failed");
  4631. pthread_detach(thr->pth);
  4632. /* Create a unique get work queue */
  4633. getq = tq_new();
  4634. if (!getq)
  4635. quit(1, "Failed to create getq");
  4636. /* We use the getq mutex as the staged lock */
  4637. stgd_lock = &getq->mutex;
  4638. /* Test each pool to see if we can retrieve and use work and for what
  4639. * it supports */
  4640. for (i = 0; i < total_pools; i++) {
  4641. struct pool *pool;
  4642. pool = pools[i];
  4643. pool->enabled = true;
  4644. if (pool_active(pool, false)) {
  4645. if (!currentpool)
  4646. currentpool = pool;
  4647. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  4648. pools_active++;
  4649. } else {
  4650. if (pool == currentpool)
  4651. currentpool = NULL;
  4652. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  4653. pool->idle = true;
  4654. }
  4655. }
  4656. if (!pools_active) {
  4657. enable_curses();
  4658. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  4659. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  4660. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  4661. for (i = 0; i < total_pools; i++) {
  4662. struct pool *pool;
  4663. pool = pools[i];
  4664. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  4665. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  4666. }
  4667. curses_input("Press enter to exit");
  4668. quit(0, "No servers could be used! Exiting.");
  4669. }
  4670. /* If we want longpoll, enable it for the chosen default pool, or, if
  4671. * the pool does not support longpoll, find the first one that does
  4672. * and use its longpoll support */
  4673. if (want_longpoll) {
  4674. if (currentpool->hdr_path)
  4675. start_longpoll();
  4676. else {
  4677. for (i = 0; i < total_pools; i++) {
  4678. struct pool *pool;
  4679. pool = pools[i];
  4680. if (pool->hdr_path) {
  4681. struct pool *temp = currentpool;
  4682. currentpool = pool;
  4683. start_longpoll();
  4684. /* Not real blocking, but good enough */
  4685. sleep(1);
  4686. currentpool = temp;
  4687. break;
  4688. }
  4689. }
  4690. }
  4691. }
  4692. gettimeofday(&total_tv_start, NULL);
  4693. gettimeofday(&total_tv_end, NULL);
  4694. get_datestamp(datestamp, &total_tv_start);
  4695. #ifdef HAVE_OPENCL
  4696. if (!opt_noadl)
  4697. init_adl(nDevs);
  4698. bool failmessage = false;
  4699. /* start GPU mining threads */
  4700. for (i = 0; i < nDevs * opt_g_threads; i++) {
  4701. int gpu = i % nDevs;
  4702. struct cgpu_info *cgpu;
  4703. struct timeval now;
  4704. gpus[gpu].is_gpu = 1;
  4705. gpus[gpu].cpu_gpu = gpu;
  4706. thr = &thr_info[i];
  4707. thr->id = i;
  4708. cgpu = thr->cgpu = &gpus[gpu];
  4709. thr->q = tq_new();
  4710. if (!thr->q)
  4711. quit(1, "tq_new failed in starting gpu mining threads");
  4712. /* Enable threads for devices set not to mine but disable
  4713. * their queue in case we wish to enable them later*/
  4714. if (gpu_devices[gpu]) {
  4715. if (opt_debug)
  4716. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  4717. tq_push(thr->q, &ping);
  4718. }
  4719. applog(LOG_INFO, "Init GPU thread %i", i);
  4720. clStates[i] = initCl(gpu, name, sizeof(name));
  4721. if (!clStates[i]) {
  4722. enable_curses();
  4723. applog(LOG_ERR, "Failed to init GPU thread %d, disabling device %d", i, gpu);
  4724. if (!failmessage) {
  4725. char *buf;
  4726. applog(LOG_ERR, "The most common reason for this failure is cgminer being unable to read the kernel .cl files");
  4727. applog(LOG_ERR, "Alternatively if it has failed on different GPUs, restarting might help.");
  4728. failmessage = true;
  4729. buf = curses_input("Press enter to continue");
  4730. if (buf)
  4731. free(buf);
  4732. }
  4733. gpu_devices[gpu] = false;
  4734. cgpu->status = LIFE_NOSTART;
  4735. continue;
  4736. }
  4737. applog(LOG_INFO, "initCl() finished. Found %s", name);
  4738. gettimeofday(&now, NULL);
  4739. get_datestamp(cgpu->init, &now);
  4740. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  4741. quit(1, "thread %d create failed", i);
  4742. }
  4743. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  4744. #else
  4745. opt_g_threads = 0;
  4746. #endif
  4747. /* start CPU mining threads */
  4748. for (i = gpu_threads; i < mining_threads; i++) {
  4749. int cpu = (i - gpu_threads) % num_processors;
  4750. thr = &thr_info[i];
  4751. thr->id = i;
  4752. cpus[cpu].cpu_gpu = cpu;
  4753. thr->cgpu = &cpus[cpu];
  4754. thr->q = tq_new();
  4755. if (!thr->q)
  4756. quit(1, "tq_new failed in starting cpu mining threads");
  4757. thread_reportin(thr);
  4758. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  4759. quit(1, "thread %d create failed", i);
  4760. }
  4761. applog(LOG_INFO, "%d cpu miner threads started, "
  4762. "using SHA256 '%s' algorithm.",
  4763. opt_n_threads,
  4764. algo_names[opt_algo]);
  4765. if (use_curses)
  4766. enable_curses();
  4767. watchdog_thr_id = mining_threads + 2;
  4768. thr = &thr_info[watchdog_thr_id];
  4769. /* start wakeup thread */
  4770. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  4771. quit(1, "wakeup thread create failed");
  4772. /* Create curses input thread for keyboard input */
  4773. input_thr_id = mining_threads + 4;
  4774. thr = &thr_info[input_thr_id];
  4775. if (thr_info_create(thr, NULL, input_thread, thr))
  4776. quit(1, "input thread create failed");
  4777. pthread_detach(thr->pth);
  4778. /* Create reinit cpu thread */
  4779. cpur_thr_id = mining_threads + 5;
  4780. thr = &thr_info[cpur_thr_id];
  4781. thr->q = tq_new();
  4782. if (!thr->q)
  4783. quit(1, "tq_new failed for cpur_thr_id");
  4784. if (thr_info_create(thr, NULL, reinit_cpu, thr))
  4785. quit(1, "reinit_cpu thread create failed");
  4786. /* Create reinit gpu thread */
  4787. gpur_thr_id = mining_threads + 6;
  4788. thr = &thr_info[gpur_thr_id];
  4789. thr->q = tq_new();
  4790. if (!thr->q)
  4791. quit(1, "tq_new failed for gpur_thr_id");
  4792. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  4793. quit(1, "reinit_gpu thread create failed");
  4794. /* main loop - simply wait for workio thread to exit */
  4795. pthread_join(thr_info[work_thr_id].pth, NULL);
  4796. applog(LOG_INFO, "workio thread dead, exiting.");
  4797. gettimeofday(&total_tv_end, NULL);
  4798. disable_curses();
  4799. if (!opt_realquiet && successful_connect)
  4800. print_summary();
  4801. #ifdef HAVE_OPENCL
  4802. clear_adl(nDevs);
  4803. #endif
  4804. if (opt_n_threads)
  4805. free(cpus);
  4806. HASH_ITER(hh, staged_work, work, tmpwork) {
  4807. HASH_DEL(staged_work, work);
  4808. free_work(work);
  4809. }
  4810. HASH_ITER(hh, blocks, block, tmpblock) {
  4811. HASH_DEL(blocks, block);
  4812. free(block);
  4813. }
  4814. curl_global_cleanup();
  4815. return 0;
  4816. }