cgminer.c 143 KB

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