cgminer.c 144 KB

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