cgminer.c 146 KB

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