cgminer.c 147 KB

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