cgminer.c 146 KB

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