cgminer.c 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730
  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. 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. int opt_log_interval = 5;
  83. static int opt_queue = 1;
  84. int opt_scantime = 60;
  85. int opt_expiry = 120;
  86. int opt_bench_algo = -1;
  87. static const bool opt_time = true;
  88. unsigned long long global_hashrate;
  89. #ifdef HAVE_OPENCL
  90. int opt_dynamic_interval = 7;
  91. int nDevs;
  92. int opt_g_threads = 2;
  93. int gpu_threads;
  94. #ifdef USE_SCRYPT
  95. bool opt_scrypt;
  96. #endif
  97. #endif
  98. bool opt_restart = true;
  99. static bool opt_nogpu;
  100. struct list_head scan_devices;
  101. static signed int devices_enabled;
  102. static bool opt_removedisabled;
  103. int total_devices;
  104. struct cgpu_info **devices;
  105. bool have_opencl;
  106. int opt_n_threads = -1;
  107. int mining_threads;
  108. int num_processors;
  109. #ifdef HAVE_CURSES
  110. bool use_curses = true;
  111. #else
  112. bool use_curses;
  113. #endif
  114. static bool opt_submit_stale = true;
  115. static int opt_shares;
  116. bool opt_fail_only;
  117. bool opt_autofan;
  118. bool opt_autoengine;
  119. bool opt_noadl;
  120. char *opt_api_allow = NULL;
  121. char *opt_api_groups;
  122. char *opt_api_description = PACKAGE_STRING;
  123. int opt_api_port = 4028;
  124. bool opt_api_listen;
  125. bool opt_api_network;
  126. bool opt_delaynet;
  127. bool opt_disable_pool = true;
  128. char *opt_icarus_options = NULL;
  129. char *opt_icarus_timing = NULL;
  130. char *opt_kernel_path;
  131. char *cgminer_path;
  132. #if defined(USE_BITFORCE)
  133. bool opt_bfl_noncerange;
  134. #endif
  135. #define QUIET (opt_quiet || opt_realquiet)
  136. struct thr_info *thr_info;
  137. static int work_thr_id;
  138. static int stage_thr_id;
  139. static int watchpool_thr_id;
  140. static int watchdog_thr_id;
  141. #ifdef HAVE_CURSES
  142. static int input_thr_id;
  143. #endif
  144. int gpur_thr_id;
  145. static int api_thr_id;
  146. static int total_threads;
  147. static pthread_mutex_t hash_lock;
  148. static pthread_mutex_t qd_lock;
  149. static pthread_mutex_t *stgd_lock;
  150. pthread_mutex_t console_lock;
  151. pthread_mutex_t ch_lock;
  152. static pthread_rwlock_t blk_lock;
  153. pthread_rwlock_t netacc_lock;
  154. static pthread_mutex_t lp_lock;
  155. static pthread_cond_t lp_cond;
  156. pthread_mutex_t restart_lock;
  157. pthread_cond_t restart_cond;
  158. double total_mhashes_done;
  159. static struct timeval total_tv_start, total_tv_end;
  160. pthread_mutex_t control_lock;
  161. int hw_errors;
  162. int total_accepted, total_rejected, total_diff1;
  163. int total_getworks, total_stale, total_discarded;
  164. static int total_queued, staged_rollable;
  165. unsigned int new_blocks;
  166. static unsigned int work_block;
  167. unsigned int found_blocks;
  168. unsigned int local_work;
  169. unsigned int total_go, total_ro;
  170. struct pool **pools;
  171. static struct pool *currentpool = NULL;
  172. int total_pools, enabled_pools;
  173. enum pool_strategy pool_strategy = POOL_FAILOVER;
  174. int opt_rotate_period;
  175. static int total_urls, total_users, total_passes, total_userpasses;
  176. static
  177. #ifndef HAVE_CURSES
  178. const
  179. #endif
  180. bool curses_active;
  181. static char current_block[37];
  182. static char *current_hash;
  183. char *current_fullhash;
  184. static char datestamp[40];
  185. static char blocktime[30];
  186. struct timeval block_timeval;
  187. struct block {
  188. char hash[37];
  189. UT_hash_handle hh;
  190. };
  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",
  835. set_null, NULL, NULL,
  836. opt_hidden),
  837. OPT_WITH_ARG("--retry-pause",
  838. set_null, NULL, NULL,
  839. opt_hidden),
  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, bool resubmit)
  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 %s",
  1587. hashshow, cgpu->api->name, cgpu->device_id, work->pool->pool_no, resubmit ? "(resubmit)" : "");
  1588. else
  1589. applog(LOG_NOTICE, "Accepted %s %s %d %s",
  1590. hashshow, cgpu->api->name, cgpu->device_id, resubmit ? "(resubmit)" : "");
  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 %s",
  1635. hashshow, cgpu->api->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "");
  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. char *url;
  1736. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  1737. url = pool->rpc_url;
  1738. gettimeofday(&tv_start, NULL);
  1739. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  1740. false, &work->rolltime, pool, false);
  1741. pool_stats->getwork_attempts++;
  1742. if (likely(val)) {
  1743. rc = work_decode(json_object_get(val, "result"), work);
  1744. if (unlikely(!rc))
  1745. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  1746. } else
  1747. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  1748. gettimeofday(&tv_end, NULL);
  1749. timersub(&tv_end, &tv_start, &tv_elapsed);
  1750. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  1751. pool_stats->getwork_wait_rolling /= 1.63;
  1752. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  1753. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  1754. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  1755. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  1756. }
  1757. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  1758. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  1759. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  1760. }
  1761. pool_stats->getwork_calls++;
  1762. work->pool = pool;
  1763. work->longpoll = false;
  1764. total_getworks++;
  1765. pool->getwork_requested++;
  1766. if (likely(val))
  1767. json_decref(val);
  1768. return rc;
  1769. }
  1770. static struct work *make_work(void)
  1771. {
  1772. struct work *work = calloc(1, sizeof(struct work));
  1773. if (unlikely(!work))
  1774. quit(1, "Failed to calloc work in make_work");
  1775. mutex_lock(&control_lock);
  1776. work->id = total_work++;
  1777. mutex_unlock(&control_lock);
  1778. return work;
  1779. }
  1780. static void free_work(struct work *work)
  1781. {
  1782. free(work);
  1783. }
  1784. static void workio_cmd_free(struct workio_cmd *wc)
  1785. {
  1786. if (!wc)
  1787. return;
  1788. switch (wc->cmd) {
  1789. case WC_SUBMIT_WORK:
  1790. free_work(wc->work);
  1791. break;
  1792. default: /* do nothing */
  1793. break;
  1794. }
  1795. memset(wc, 0, sizeof(*wc)); /* poison */
  1796. free(wc);
  1797. }
  1798. #ifdef HAVE_CURSES
  1799. static void disable_curses(void)
  1800. {
  1801. if (curses_active_locked()) {
  1802. curses_active = false;
  1803. leaveok(logwin, false);
  1804. leaveok(statuswin, false);
  1805. leaveok(mainwin, false);
  1806. nocbreak();
  1807. echo();
  1808. delwin(logwin);
  1809. delwin(statuswin);
  1810. delwin(mainwin);
  1811. endwin();
  1812. #ifdef WIN32
  1813. // Move the cursor to after curses output.
  1814. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  1815. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1816. COORD coord;
  1817. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  1818. coord.X = 0;
  1819. coord.Y = csbi.dwSize.Y - 1;
  1820. SetConsoleCursorPosition(hout, coord);
  1821. }
  1822. #endif
  1823. unlock_curses();
  1824. }
  1825. }
  1826. #endif
  1827. static void print_summary(void);
  1828. static void __kill_work(void)
  1829. {
  1830. struct thr_info *thr;
  1831. int i;
  1832. if (!successful_connect)
  1833. return;
  1834. applog(LOG_INFO, "Received kill message");
  1835. applog(LOG_DEBUG, "Killing off watchpool thread");
  1836. /* Kill the watchpool thread */
  1837. thr = &thr_info[watchpool_thr_id];
  1838. thr_info_cancel(thr);
  1839. applog(LOG_DEBUG, "Killing off watchdog thread");
  1840. /* Kill the watchdog thread */
  1841. thr = &thr_info[watchdog_thr_id];
  1842. thr_info_cancel(thr);
  1843. applog(LOG_DEBUG, "Stopping mining threads");
  1844. /* Stop the mining threads*/
  1845. for (i = 0; i < mining_threads; i++) {
  1846. thr = &thr_info[i];
  1847. thr_info_freeze(thr);
  1848. thr->pause = true;
  1849. }
  1850. sleep(1);
  1851. applog(LOG_DEBUG, "Killing off mining threads");
  1852. /* Kill the mining threads*/
  1853. for (i = 0; i < mining_threads; i++) {
  1854. thr = &thr_info[i];
  1855. thr_info_cancel(thr);
  1856. }
  1857. applog(LOG_DEBUG, "Killing off stage thread");
  1858. /* Stop the others */
  1859. thr = &thr_info[stage_thr_id];
  1860. thr_info_cancel(thr);
  1861. applog(LOG_DEBUG, "Killing off API thread");
  1862. thr = &thr_info[api_thr_id];
  1863. thr_info_cancel(thr);
  1864. }
  1865. /* This should be the common exit path */
  1866. void kill_work(void)
  1867. {
  1868. __kill_work();
  1869. quit(0, "Shutdown signal received.");
  1870. }
  1871. static
  1872. #ifdef WIN32
  1873. const
  1874. #endif
  1875. char **initial_args;
  1876. static void clean_up(void);
  1877. void app_restart(void)
  1878. {
  1879. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  1880. __kill_work();
  1881. clean_up();
  1882. #if defined(unix)
  1883. if (forkpid > 0) {
  1884. kill(forkpid, SIGTERM);
  1885. forkpid = 0;
  1886. }
  1887. #endif
  1888. execv(initial_args[0], initial_args);
  1889. applog(LOG_WARNING, "Failed to restart application");
  1890. }
  1891. static void sighandler(int __maybe_unused sig)
  1892. {
  1893. /* Restore signal handlers so we can still quit if kill_work fails */
  1894. sigaction(SIGTERM, &termhandler, NULL);
  1895. sigaction(SIGINT, &inthandler, NULL);
  1896. kill_work();
  1897. }
  1898. /* Called with pool_lock held. Recruit an extra curl if none are available for
  1899. * this pool. */
  1900. static void recruit_curl(struct pool *pool)
  1901. {
  1902. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  1903. ce->curl = curl_easy_init();
  1904. if (unlikely(!ce->curl || !ce))
  1905. quit(1, "Failed to init in recruit_curl");
  1906. list_add(&ce->node, &pool->curlring);
  1907. pool->curls++;
  1908. applog(LOG_DEBUG, "Recruited curl %d for pool %d", pool->curls, pool->pool_no);
  1909. }
  1910. /* Grab an available curl if there is one. If not, then recruit extra curls
  1911. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  1912. * and there are already 5 curls in circulation. Limit total number to the
  1913. * number of mining threads per pool as well to prevent blasting a pool during
  1914. * network delays/outages. */
  1915. static struct curl_ent *pop_curl_entry(struct pool *pool)
  1916. {
  1917. int curl_limit = opt_delaynet ? 5 : mining_threads * 4 / 3;
  1918. struct curl_ent *ce;
  1919. mutex_lock(&pool->pool_lock);
  1920. retry:
  1921. if (!pool->curls)
  1922. recruit_curl(pool);
  1923. else if (list_empty(&pool->curlring)) {
  1924. if (pool->submit_fail || pool->curls >= curl_limit) {
  1925. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  1926. goto retry;
  1927. } else
  1928. recruit_curl(pool);
  1929. }
  1930. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  1931. list_del(&ce->node);
  1932. mutex_unlock(&pool->pool_lock);
  1933. return ce;
  1934. }
  1935. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  1936. {
  1937. mutex_lock(&pool->pool_lock);
  1938. list_add_tail(&ce->node, &pool->curlring);
  1939. gettimeofday(&ce->tv, NULL);
  1940. pthread_cond_signal(&pool->cr_cond);
  1941. mutex_unlock(&pool->pool_lock);
  1942. }
  1943. /* This is overkill, but at least we'll know accurately how much work is
  1944. * queued to prevent ever being left without work */
  1945. static void inc_queued(void)
  1946. {
  1947. mutex_lock(&qd_lock);
  1948. total_queued++;
  1949. mutex_unlock(&qd_lock);
  1950. }
  1951. static void dec_queued(void)
  1952. {
  1953. mutex_lock(&qd_lock);
  1954. total_queued--;
  1955. mutex_unlock(&qd_lock);
  1956. }
  1957. static int __global_queued(void)
  1958. {
  1959. return total_queued;
  1960. }
  1961. static int global_queued(void)
  1962. {
  1963. int ret;
  1964. mutex_lock(&qd_lock);
  1965. ret = __global_queued();
  1966. mutex_unlock(&qd_lock);
  1967. return ret;
  1968. }
  1969. static bool stale_work(struct work *work, bool share);
  1970. static inline bool should_roll(struct work *work)
  1971. {
  1972. struct timeval now;
  1973. time_t expiry;
  1974. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  1975. return false;
  1976. if (work->rolltime > opt_scantime)
  1977. expiry = work->rolltime;
  1978. else
  1979. expiry = opt_scantime;
  1980. expiry = expiry * 2 / 3;
  1981. /* We shouldn't roll if we're unlikely to get one shares' duration
  1982. * work out of doing so */
  1983. gettimeofday(&now, NULL);
  1984. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  1985. return false;
  1986. return true;
  1987. }
  1988. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  1989. * reject blocks as invalid. */
  1990. static inline bool can_roll(struct work *work)
  1991. {
  1992. return (work->pool && work->rolltime && !work->clone &&
  1993. work->rolls < 7000 && !stale_work(work, false));
  1994. }
  1995. static void roll_work(struct work *work)
  1996. {
  1997. uint32_t *work_ntime;
  1998. uint32_t ntime;
  1999. work_ntime = (uint32_t *)(work->data + 68);
  2000. ntime = be32toh(*work_ntime);
  2001. ntime++;
  2002. *work_ntime = htobe32(ntime);
  2003. local_work++;
  2004. work->rolls++;
  2005. work->blk.nonce = 0;
  2006. applog(LOG_DEBUG, "Successfully rolled work");
  2007. /* This is now a different work item so it needs a different ID for the
  2008. * hashtable */
  2009. work->id = total_work++;
  2010. }
  2011. static struct work *make_clone(struct work *work)
  2012. {
  2013. struct work *work_clone = make_work();
  2014. memcpy(work_clone, work, sizeof(struct work));
  2015. work_clone->clone = true;
  2016. work_clone->longpoll = false;
  2017. work_clone->mandatory = false;
  2018. /* Make cloned work appear slightly older to bias towards keeping the
  2019. * master work item which can be further rolled */
  2020. work_clone->tv_staged.tv_sec -= 1;
  2021. return work_clone;
  2022. }
  2023. static bool stage_work(struct work *work);
  2024. static bool clone_available(void)
  2025. {
  2026. struct work *work, *tmp;
  2027. bool cloned = false;
  2028. if (!staged_rollable)
  2029. goto out;
  2030. mutex_lock(stgd_lock);
  2031. HASH_ITER(hh, staged_work, work, tmp) {
  2032. if (can_roll(work) && should_roll(work)) {
  2033. struct work *work_clone;
  2034. roll_work(work);
  2035. work_clone = make_clone(work);
  2036. roll_work(work);
  2037. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  2038. if (unlikely(!stage_work(work_clone))) {
  2039. free(work_clone);
  2040. break;
  2041. }
  2042. cloned = true;
  2043. break;
  2044. }
  2045. }
  2046. mutex_unlock(stgd_lock);
  2047. out:
  2048. return cloned;
  2049. }
  2050. static void *get_work_thread(void *userdata)
  2051. {
  2052. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2053. int ts, tq, maxq = opt_queue + mining_threads;
  2054. struct pool *pool = current_pool();
  2055. struct work *ret_work= NULL;
  2056. struct curl_ent *ce = NULL;
  2057. bool lagging = false;
  2058. pthread_detach(pthread_self());
  2059. applog(LOG_DEBUG, "Creating extra get work thread");
  2060. retry:
  2061. tq = global_queued();
  2062. ts = total_staged();
  2063. if (ts >= maxq)
  2064. goto out;
  2065. if (ts >= opt_queue && tq >= maxq - 1)
  2066. goto out;
  2067. if (clone_available())
  2068. goto out;
  2069. ret_work = make_work();
  2070. if (wc->thr)
  2071. ret_work->thr = wc->thr;
  2072. else
  2073. ret_work->thr = NULL;
  2074. if (opt_benchmark) {
  2075. get_benchmark_work(ret_work);
  2076. ret_work->queued = true;
  2077. } else {
  2078. if (ts <= opt_queue)
  2079. lagging = true;
  2080. pool = ret_work->pool = select_pool(lagging);
  2081. if (!ce)
  2082. ce = pop_curl_entry(pool);
  2083. /* Inc queued count after ce is popped in case there're none
  2084. * left and we think we've queued work when we're just waiting
  2085. * for curls */
  2086. inc_queued();
  2087. /* obtain new work from bitcoin via JSON-RPC */
  2088. if (!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, retrying");
  2091. lagging = true;
  2092. dec_queued();
  2093. free_work(ret_work);
  2094. goto retry;
  2095. }
  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. bool resubmit = false;
  2178. struct curl_ent *ce;
  2179. pthread_detach(pthread_self());
  2180. applog(LOG_DEBUG, "Creating extra submit work thread");
  2181. check_solve(work);
  2182. if (stale_work(work, true)) {
  2183. if (opt_submit_stale)
  2184. applog(LOG_NOTICE, "Stale share detected, submitting as user requested");
  2185. else if (pool->submit_old)
  2186. applog(LOG_NOTICE, "Stale share detected, submitting as pool requested");
  2187. else {
  2188. applog(LOG_NOTICE, "Stale share detected, discarding");
  2189. sharelog("discard", work);
  2190. total_stale++;
  2191. pool->stale_shares++;
  2192. goto out;
  2193. }
  2194. work->stale = true;
  2195. }
  2196. ce = pop_curl_entry(pool);
  2197. /* submit solution to bitcoin via JSON-RPC */
  2198. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  2199. resubmit = true;
  2200. if (stale_work(work, true)) {
  2201. applog(LOG_NOTICE, "Share became stale while retrying submit, discarding");
  2202. total_stale++;
  2203. pool->stale_shares++;
  2204. break;
  2205. }
  2206. /* pause, then restart work-request loop */
  2207. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  2208. }
  2209. push_curl_entry(ce, pool);
  2210. out:
  2211. workio_cmd_free(wc);
  2212. return NULL;
  2213. }
  2214. /* We try to reuse curl handles as much as possible, but if there is already
  2215. * work queued to be submitted, we start generating extra handles to submit
  2216. * the shares to avoid ever increasing backlogs. This allows us to scale to
  2217. * any size hardware */
  2218. static bool workio_submit_work(struct workio_cmd *wc)
  2219. {
  2220. pthread_t submit_thread;
  2221. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  2222. applog(LOG_ERR, "Failed to create submit_work_thread");
  2223. return false;
  2224. }
  2225. return true;
  2226. }
  2227. /* Find the pool that currently has the highest priority */
  2228. static struct pool *priority_pool(int choice)
  2229. {
  2230. struct pool *ret = NULL;
  2231. int i;
  2232. for (i = 0; i < total_pools; i++) {
  2233. struct pool *pool = pools[i];
  2234. if (pool->prio == choice) {
  2235. ret = pool;
  2236. break;
  2237. }
  2238. }
  2239. if (unlikely(!ret)) {
  2240. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2241. return pools[choice];
  2242. }
  2243. return ret;
  2244. }
  2245. static bool queue_request(struct thr_info *thr, bool needed);
  2246. void switch_pools(struct pool *selected)
  2247. {
  2248. struct pool *pool, *last_pool;
  2249. int i, pool_no, next_pool;
  2250. mutex_lock(&control_lock);
  2251. last_pool = currentpool;
  2252. pool_no = currentpool->pool_no;
  2253. /* Switch selected to pool number 0 and move the rest down */
  2254. if (selected) {
  2255. if (selected->prio != 0) {
  2256. for (i = 0; i < total_pools; i++) {
  2257. pool = pools[i];
  2258. if (pool->prio < selected->prio)
  2259. pool->prio++;
  2260. }
  2261. selected->prio = 0;
  2262. }
  2263. }
  2264. switch (pool_strategy) {
  2265. /* Both of these set to the master pool */
  2266. case POOL_BALANCE:
  2267. case POOL_FAILOVER:
  2268. case POOL_LOADBALANCE:
  2269. for (i = 0; i < total_pools; i++) {
  2270. pool = priority_pool(i);
  2271. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  2272. pool_no = pool->pool_no;
  2273. break;
  2274. }
  2275. }
  2276. break;
  2277. /* Both of these simply increment and cycle */
  2278. case POOL_ROUNDROBIN:
  2279. case POOL_ROTATE:
  2280. if (selected && !selected->idle) {
  2281. pool_no = selected->pool_no;
  2282. break;
  2283. }
  2284. next_pool = pool_no;
  2285. /* Select the next alive pool */
  2286. for (i = 1; i < total_pools; i++) {
  2287. next_pool++;
  2288. if (next_pool >= total_pools)
  2289. next_pool = 0;
  2290. pool = pools[next_pool];
  2291. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  2292. pool_no = next_pool;
  2293. break;
  2294. }
  2295. }
  2296. break;
  2297. default:
  2298. break;
  2299. }
  2300. currentpool = pools[pool_no];
  2301. pool = currentpool;
  2302. mutex_unlock(&control_lock);
  2303. /* Set the lagging flag to avoid pool not providing work fast enough
  2304. * messages in failover only mode since we have to get all fresh work
  2305. * as in restart_threads */
  2306. if (opt_fail_only)
  2307. pool_tset(pool, &pool->lagging);
  2308. if (pool != last_pool)
  2309. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  2310. mutex_lock(&lp_lock);
  2311. pthread_cond_broadcast(&lp_cond);
  2312. mutex_unlock(&lp_lock);
  2313. queue_request(NULL, false);
  2314. }
  2315. static void discard_work(struct work *work)
  2316. {
  2317. if (!work->clone && !work->rolls && !work->mined) {
  2318. if (work->pool)
  2319. work->pool->discarded_work++;
  2320. total_discarded++;
  2321. applog(LOG_DEBUG, "Discarded work");
  2322. } else
  2323. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2324. free_work(work);
  2325. }
  2326. static void discard_stale(void)
  2327. {
  2328. struct work *work, *tmp;
  2329. int stale = 0;
  2330. mutex_lock(stgd_lock);
  2331. HASH_ITER(hh, staged_work, work, tmp) {
  2332. if (stale_work(work, false)) {
  2333. HASH_DEL(staged_work, work);
  2334. discard_work(work);
  2335. stale++;
  2336. }
  2337. }
  2338. mutex_unlock(stgd_lock);
  2339. if (stale) {
  2340. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  2341. while (stale-- > 0)
  2342. queue_request(NULL, false);
  2343. }
  2344. }
  2345. /* A generic wait function for threads that poll that will wait a specified
  2346. * time tdiff waiting on the pthread conditional that is broadcast when a
  2347. * work restart is required. Returns the value of pthread_cond_timedwait
  2348. * which is zero if the condition was met or ETIMEDOUT if not.
  2349. */
  2350. int restart_wait(unsigned int mstime)
  2351. {
  2352. struct timeval now, then, tdiff;
  2353. struct timespec abstime;
  2354. int rc;
  2355. tdiff.tv_sec = mstime / 1000;
  2356. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  2357. gettimeofday(&now, NULL);
  2358. timeradd(&now, &tdiff, &then);
  2359. abstime.tv_sec = then.tv_sec;
  2360. abstime.tv_nsec = then.tv_usec * 1000;
  2361. mutex_lock(&restart_lock);
  2362. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  2363. mutex_unlock(&restart_lock);
  2364. return rc;
  2365. }
  2366. static void restart_threads(void)
  2367. {
  2368. struct pool *cp = current_pool();
  2369. int i;
  2370. /* Artificially set the lagging flag to avoid pool not providing work
  2371. * fast enough messages after every long poll */
  2372. pool_tset(cp, &cp->lagging);
  2373. /* Discard staged work that is now stale */
  2374. discard_stale();
  2375. for (i = 0; i < mining_threads; i++)
  2376. thr_info[i].work_restart = true;
  2377. mutex_lock(&restart_lock);
  2378. pthread_cond_broadcast(&restart_cond);
  2379. mutex_unlock(&restart_lock);
  2380. }
  2381. static void set_curblock(char *hexstr, unsigned char *hash)
  2382. {
  2383. unsigned char hash_swap[32];
  2384. unsigned char block_hash_swap[32];
  2385. char *old_hash;
  2386. strcpy(current_block, hexstr);
  2387. swap256(hash_swap, hash);
  2388. swap256(block_hash_swap, hash+4);
  2389. /* Don't free current_hash directly to avoid dereferencing when read
  2390. * elsewhere - and update block_timeval inside the same lock */
  2391. mutex_lock(&ch_lock);
  2392. gettimeofday(&block_timeval, NULL);
  2393. old_hash = current_hash;
  2394. current_hash = bin2hex(hash_swap, 16);
  2395. free(old_hash);
  2396. old_hash = current_fullhash;
  2397. current_fullhash = bin2hex(block_hash_swap, 32);
  2398. free(old_hash);
  2399. mutex_unlock(&ch_lock);
  2400. get_timestamp(blocktime, &block_timeval);
  2401. if (unlikely(!current_hash))
  2402. quit (1, "set_curblock OOM");
  2403. applog(LOG_INFO, "New block: %s...", current_hash);
  2404. }
  2405. /* Search to see if this string is from a block that has been seen before */
  2406. static bool block_exists(char *hexstr)
  2407. {
  2408. struct block *s;
  2409. rd_lock(&blk_lock);
  2410. HASH_FIND_STR(blocks, hexstr, s);
  2411. rd_unlock(&blk_lock);
  2412. if (s)
  2413. return true;
  2414. return false;
  2415. }
  2416. /* Tests if this work is from a block that has been seen before */
  2417. static inline bool from_existing_block(struct work *work)
  2418. {
  2419. char *hexstr = bin2hex(work->data, 18);
  2420. bool ret;
  2421. if (unlikely(!hexstr)) {
  2422. applog(LOG_ERR, "from_existing_block OOM");
  2423. return true;
  2424. }
  2425. ret = block_exists(hexstr);
  2426. free(hexstr);
  2427. return ret;
  2428. }
  2429. static void test_work_current(struct work *work)
  2430. {
  2431. char *hexstr;
  2432. if (work->mandatory)
  2433. return;
  2434. hexstr = bin2hex(work->data, 18);
  2435. if (unlikely(!hexstr)) {
  2436. applog(LOG_ERR, "stage_thread OOM");
  2437. return;
  2438. }
  2439. /* Search to see if this block exists yet and if not, consider it a
  2440. * new block and set the current block details to this one */
  2441. if (!block_exists(hexstr)) {
  2442. struct block *s = calloc(sizeof(struct block), 1);
  2443. if (unlikely(!s))
  2444. quit (1, "test_work_current OOM");
  2445. strcpy(s->hash, hexstr);
  2446. wr_lock(&blk_lock);
  2447. HASH_ADD_STR(blocks, hash, s);
  2448. wr_unlock(&blk_lock);
  2449. set_curblock(hexstr, work->data);
  2450. if (unlikely(++new_blocks == 1))
  2451. goto out_free;
  2452. work_block++;
  2453. if (work->longpoll) {
  2454. applog(LOG_NOTICE, "LONGPOLL from pool %d detected new block",
  2455. work->pool->pool_no);
  2456. work->longpoll = false;
  2457. } else if (have_longpoll)
  2458. applog(LOG_NOTICE, "New block detected on network before longpoll");
  2459. else
  2460. applog(LOG_NOTICE, "New block detected on network");
  2461. restart_threads();
  2462. } else if (work->longpoll) {
  2463. work->longpoll = false;
  2464. if (work->pool == current_pool()) {
  2465. applog(LOG_NOTICE, "LONGPOLL from pool %d requested work restart",
  2466. work->pool->pool_no);
  2467. work_block++;
  2468. restart_threads();
  2469. }
  2470. }
  2471. out_free:
  2472. free(hexstr);
  2473. }
  2474. static int tv_sort(struct work *worka, struct work *workb)
  2475. {
  2476. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  2477. }
  2478. static bool work_rollable(struct work *work)
  2479. {
  2480. return (!work->clone && work->rolltime);
  2481. }
  2482. static bool hash_push(struct work *work)
  2483. {
  2484. bool rc = true;
  2485. mutex_lock(stgd_lock);
  2486. if (work_rollable(work))
  2487. staged_rollable++;
  2488. if (likely(!getq->frozen)) {
  2489. HASH_ADD_INT(staged_work, id, work);
  2490. HASH_SORT(staged_work, tv_sort);
  2491. } else
  2492. rc = false;
  2493. pthread_cond_signal(&getq->cond);
  2494. mutex_unlock(stgd_lock);
  2495. if (work->queued) {
  2496. work->queued = false;
  2497. dec_queued();
  2498. }
  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. "[W]rite config file\n[C]gminer restart\n",
  3038. opt_queue, opt_scantime, opt_expiry);
  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, "w", 1)) {
  3066. FILE *fcfg;
  3067. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  3068. default_save_file(filename);
  3069. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  3070. str = curses_input(prompt);
  3071. if (strcmp(str, "-1")) {
  3072. struct stat statbuf;
  3073. strcpy(filename, str);
  3074. if (!stat(filename, &statbuf)) {
  3075. wlogprint("File exists, overwrite?\n");
  3076. input = getch();
  3077. if (strncasecmp(&input, "y", 1))
  3078. goto retry;
  3079. }
  3080. }
  3081. fcfg = fopen(filename, "w");
  3082. if (!fcfg) {
  3083. wlogprint("Cannot open or create file\n");
  3084. goto retry;
  3085. }
  3086. write_config(fcfg);
  3087. fclose(fcfg);
  3088. goto retry;
  3089. } else if (!strncasecmp(&input, "c", 1)) {
  3090. wlogprint("Are you sure?\n");
  3091. input = getch();
  3092. if (!strncasecmp(&input, "y", 1))
  3093. app_restart();
  3094. else
  3095. clear_logwin();
  3096. } else
  3097. clear_logwin();
  3098. immedok(logwin, false);
  3099. opt_loginput = false;
  3100. }
  3101. static void *input_thread(void __maybe_unused *userdata)
  3102. {
  3103. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3104. if (!curses_active)
  3105. return NULL;
  3106. while (1) {
  3107. char input;
  3108. input = getch();
  3109. if (!strncasecmp(&input, "q", 1)) {
  3110. kill_work();
  3111. return NULL;
  3112. } else if (!strncasecmp(&input, "d", 1))
  3113. display_options();
  3114. else if (!strncasecmp(&input, "p", 1))
  3115. display_pools();
  3116. else if (!strncasecmp(&input, "s", 1))
  3117. set_options();
  3118. else if (have_opencl && !strncasecmp(&input, "g", 1))
  3119. manage_gpu();
  3120. if (opt_realquiet) {
  3121. disable_curses();
  3122. break;
  3123. }
  3124. }
  3125. return NULL;
  3126. }
  3127. #endif
  3128. /* This thread should not be shut down unless a problem occurs */
  3129. static void *workio_thread(void *userdata)
  3130. {
  3131. struct thr_info *mythr = userdata;
  3132. bool ok = true;
  3133. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3134. while (ok) {
  3135. struct workio_cmd *wc;
  3136. applog(LOG_DEBUG, "Popping work to work thread");
  3137. /* wait for workio_cmd sent to us, on our queue */
  3138. wc = tq_pop(mythr->q, NULL);
  3139. if (unlikely(!wc)) {
  3140. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  3141. ok = false;
  3142. break;
  3143. }
  3144. /* process workio_cmd */
  3145. switch (wc->cmd) {
  3146. case WC_GET_WORK:
  3147. ok = workio_get_work(wc);
  3148. break;
  3149. case WC_SUBMIT_WORK:
  3150. ok = workio_submit_work(wc);
  3151. break;
  3152. default:
  3153. ok = false;
  3154. break;
  3155. }
  3156. }
  3157. tq_freeze(mythr->q);
  3158. return NULL;
  3159. }
  3160. static void *api_thread(void *userdata)
  3161. {
  3162. struct thr_info *mythr = userdata;
  3163. pthread_detach(pthread_self());
  3164. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3165. api(api_thr_id);
  3166. PTH(mythr) = 0L;
  3167. return NULL;
  3168. }
  3169. void thread_reportin(struct thr_info *thr)
  3170. {
  3171. gettimeofday(&thr->last, NULL);
  3172. thr->cgpu->status = LIFE_WELL;
  3173. thr->getwork = false;
  3174. thr->cgpu->device_last_well = time(NULL);
  3175. }
  3176. static inline void thread_reportout(struct thr_info *thr)
  3177. {
  3178. thr->getwork = true;
  3179. }
  3180. static void hashmeter(int thr_id, struct timeval *diff,
  3181. unsigned long long hashes_done)
  3182. {
  3183. struct timeval temp_tv_end, total_diff;
  3184. double secs;
  3185. double local_secs;
  3186. double utility, efficiency = 0.0;
  3187. static double local_mhashes_done = 0;
  3188. static double rolling = 0;
  3189. double local_mhashes, displayed_hashes, displayed_rolling;
  3190. bool mhash_base = true;
  3191. bool showlog = false;
  3192. local_mhashes = (double)hashes_done / 1000000.0;
  3193. /* Update the last time this thread reported in */
  3194. if (thr_id >= 0) {
  3195. gettimeofday(&thr_info[thr_id].last, NULL);
  3196. thr_info[thr_id].cgpu->device_last_well = time(NULL);
  3197. }
  3198. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  3199. /* So we can call hashmeter from a non worker thread */
  3200. if (thr_id >= 0) {
  3201. struct thr_info *thr = &thr_info[thr_id];
  3202. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  3203. double thread_rolling = 0.0;
  3204. int i;
  3205. applog(LOG_DEBUG, "[thread %d: %llu hashes, %.1f khash/sec]",
  3206. thr_id, hashes_done, hashes_done / 1000 / secs);
  3207. /* Rolling average for each thread and each device */
  3208. decay_time(&thr->rolling, local_mhashes / secs);
  3209. for (i = 0; i < cgpu->threads; i++)
  3210. thread_rolling += cgpu->thr[i]->rolling;
  3211. mutex_lock(&hash_lock);
  3212. decay_time(&cgpu->rolling, thread_rolling);
  3213. cgpu->total_mhashes += local_mhashes;
  3214. mutex_unlock(&hash_lock);
  3215. // If needed, output detailed, per-device stats
  3216. if (want_per_device_stats) {
  3217. struct timeval now;
  3218. struct timeval elapsed;
  3219. gettimeofday(&now, NULL);
  3220. timersub(&now, &thr->cgpu->last_message_tv, &elapsed);
  3221. if (opt_log_interval <= elapsed.tv_sec) {
  3222. struct cgpu_info *cgpu = thr->cgpu;
  3223. char logline[255];
  3224. cgpu->last_message_tv = now;
  3225. get_statline(logline, cgpu);
  3226. if (!curses_active) {
  3227. printf("%s \r", logline);
  3228. fflush(stdout);
  3229. } else
  3230. applog(LOG_INFO, "%s", logline);
  3231. }
  3232. }
  3233. }
  3234. /* Totals are updated by all threads so can race without locking */
  3235. mutex_lock(&hash_lock);
  3236. gettimeofday(&temp_tv_end, NULL);
  3237. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  3238. total_mhashes_done += local_mhashes;
  3239. local_mhashes_done += local_mhashes;
  3240. if (total_diff.tv_sec < opt_log_interval)
  3241. /* Only update the total every opt_log_interval seconds */
  3242. goto out_unlock;
  3243. showlog = true;
  3244. gettimeofday(&total_tv_end, NULL);
  3245. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  3246. decay_time(&rolling, local_mhashes_done / local_secs);
  3247. global_hashrate = roundl(rolling) * 1000000;
  3248. timersub(&total_tv_end, &total_tv_start, &total_diff);
  3249. total_secs = (double)total_diff.tv_sec +
  3250. ((double)total_diff.tv_usec / 1000000.0);
  3251. utility = total_accepted / total_secs * 60;
  3252. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3253. displayed_hashes = total_mhashes_done / total_secs;
  3254. displayed_rolling = rolling;
  3255. if (displayed_hashes < 1) {
  3256. displayed_hashes *= 1000;
  3257. displayed_rolling *= 1000;
  3258. mhash_base = false;
  3259. }
  3260. sprintf(statusline, "%s(%ds):%.1f (avg):%.1f %sh/s | Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.1f/m",
  3261. want_per_device_stats ? "ALL " : "",
  3262. opt_log_interval, displayed_rolling, displayed_hashes, mhash_base ? "M" : "K",
  3263. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  3264. local_mhashes_done = 0;
  3265. out_unlock:
  3266. mutex_unlock(&hash_lock);
  3267. if (showlog) {
  3268. if (!curses_active) {
  3269. printf("%s \r", statusline);
  3270. fflush(stdout);
  3271. } else
  3272. applog(LOG_INFO, "%s", statusline);
  3273. }
  3274. }
  3275. static void *longpoll_thread(void *userdata);
  3276. static bool pool_active(struct pool *pool, bool pinging)
  3277. {
  3278. bool ret = false;
  3279. json_t *val;
  3280. CURL *curl;
  3281. int rolltime;
  3282. curl = curl_easy_init();
  3283. if (unlikely(!curl)) {
  3284. applog(LOG_ERR, "CURL initialisation failed");
  3285. return false;
  3286. }
  3287. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  3288. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  3289. true, false, &rolltime, pool, false);
  3290. if (val) {
  3291. struct work *work = make_work();
  3292. bool rc;
  3293. rc = work_decode(json_object_get(val, "result"), work);
  3294. if (rc) {
  3295. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  3296. pool->pool_no, pool->rpc_url);
  3297. work->pool = pool;
  3298. work->rolltime = rolltime;
  3299. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  3300. tq_push(thr_info[stage_thr_id].q, work);
  3301. total_getworks++;
  3302. pool->getwork_requested++;
  3303. ret = true;
  3304. gettimeofday(&pool->tv_idle, NULL);
  3305. } else {
  3306. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  3307. pool->pool_no, pool->rpc_url);
  3308. free_work(work);
  3309. }
  3310. json_decref(val);
  3311. if (pool->lp_url)
  3312. goto out;
  3313. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  3314. if (pool->hdr_path) {
  3315. char *copy_start, *hdr_path;
  3316. bool need_slash = false;
  3317. hdr_path = pool->hdr_path;
  3318. if (strstr(hdr_path, "://")) {
  3319. pool->lp_url = hdr_path;
  3320. hdr_path = NULL;
  3321. } else {
  3322. /* absolute path, on current server */
  3323. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3324. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3325. need_slash = true;
  3326. pool->lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3327. if (!pool->lp_url) {
  3328. applog(LOG_ERR, "Malloc failure in pool_active");
  3329. return false;
  3330. }
  3331. sprintf(pool->lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3332. }
  3333. } else
  3334. pool->lp_url = NULL;
  3335. if (!pool->lp_started) {
  3336. pool->lp_started = true;
  3337. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  3338. quit(1, "Failed to create pool longpoll thread");
  3339. }
  3340. } else {
  3341. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  3342. pool->pool_no, pool->rpc_url);
  3343. if (!pinging)
  3344. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  3345. }
  3346. out:
  3347. curl_easy_cleanup(curl);
  3348. return ret;
  3349. }
  3350. static void pool_died(struct pool *pool)
  3351. {
  3352. if (!pool_tset(pool, &pool->idle)) {
  3353. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  3354. gettimeofday(&pool->tv_idle, NULL);
  3355. switch_pools(NULL);
  3356. }
  3357. }
  3358. static inline int cp_prio(void)
  3359. {
  3360. int prio;
  3361. mutex_lock(&control_lock);
  3362. prio = currentpool->prio;
  3363. mutex_unlock(&control_lock);
  3364. return prio;
  3365. }
  3366. static void pool_resus(struct pool *pool)
  3367. {
  3368. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  3369. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  3370. switch_pools(NULL);
  3371. }
  3372. static bool queue_request(struct thr_info *thr, bool needed)
  3373. {
  3374. struct workio_cmd *wc;
  3375. /* fill out work request message */
  3376. wc = calloc(1, sizeof(*wc));
  3377. if (unlikely(!wc)) {
  3378. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  3379. return false;
  3380. }
  3381. wc->cmd = WC_GET_WORK;
  3382. wc->thr = thr;
  3383. wc->needed = needed;
  3384. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  3385. /* send work request to workio thread */
  3386. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3387. applog(LOG_ERR, "Failed to tq_push in queue_request");
  3388. workio_cmd_free(wc);
  3389. return false;
  3390. }
  3391. return true;
  3392. }
  3393. static struct work *hash_pop(const struct timespec *abstime)
  3394. {
  3395. struct work *work = NULL, *tmp;
  3396. int rc = 0, hc;
  3397. mutex_lock(stgd_lock);
  3398. while (!getq->frozen && !HASH_COUNT(staged_work) && !rc)
  3399. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  3400. hc = HASH_COUNT(staged_work);
  3401. if (likely(hc)) {
  3402. /* Find clone work if possible, to allow masters to be reused */
  3403. if (hc > staged_rollable) {
  3404. HASH_ITER(hh, staged_work, work, tmp) {
  3405. if (!work_rollable(work))
  3406. break;
  3407. }
  3408. } else
  3409. work = staged_work;
  3410. HASH_DEL(staged_work, work);
  3411. if (work_rollable(work))
  3412. staged_rollable--;
  3413. }
  3414. mutex_unlock(stgd_lock);
  3415. queue_request(NULL, false);
  3416. return work;
  3417. }
  3418. static bool reuse_work(struct work *work)
  3419. {
  3420. if (can_roll(work) && should_roll(work)) {
  3421. roll_work(work);
  3422. return true;
  3423. }
  3424. return false;
  3425. }
  3426. /* Clones work by rolling it if possible, and returning a clone instead of the
  3427. * original work item which gets staged again to possibly be rolled again in
  3428. * the future */
  3429. static struct work *clone_work(struct work *work)
  3430. {
  3431. int mrs = mining_threads + opt_queue - total_staged();
  3432. struct work *work_clone;
  3433. bool cloned;
  3434. if (mrs < 1)
  3435. return work;
  3436. cloned = false;
  3437. work_clone = make_clone(work);
  3438. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  3439. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  3440. if (unlikely(!stage_work(work_clone))) {
  3441. cloned = false;
  3442. break;
  3443. }
  3444. roll_work(work);
  3445. work_clone = make_clone(work);
  3446. /* Roll it again to prevent duplicates should this be used
  3447. * directly later on */
  3448. roll_work(work);
  3449. cloned = true;
  3450. }
  3451. if (cloned) {
  3452. stage_work(work);
  3453. return work_clone;
  3454. }
  3455. free_work(work_clone);
  3456. return work;
  3457. }
  3458. static void get_work(struct work *work, struct thr_info *thr, const int thr_id)
  3459. {
  3460. struct timespec abstime = {0, 0};
  3461. struct work *work_heap;
  3462. struct timeval now;
  3463. struct pool *pool;
  3464. /* Tell the watchdog thread this thread is waiting on getwork and
  3465. * should not be restarted */
  3466. thread_reportout(thr);
  3467. if (opt_benchmark) {
  3468. get_benchmark_work(work);
  3469. goto out;
  3470. }
  3471. retry:
  3472. pool = current_pool();
  3473. if (reuse_work(work))
  3474. goto out;
  3475. if (!pool->lagging && !total_staged() && global_queued() >= mining_threads + opt_queue) {
  3476. struct cgpu_info *cgpu = thr->cgpu;
  3477. bool stalled = true;
  3478. int i;
  3479. /* Check to see if all the threads on the device that called
  3480. * get_work are waiting on work and only consider the pool
  3481. * lagging if true */
  3482. for (i = 0; i < cgpu->threads; i++) {
  3483. if (!cgpu->thr[i]->getwork) {
  3484. stalled = false;
  3485. break;
  3486. }
  3487. }
  3488. if (stalled && !pool_tset(pool, &pool->lagging)) {
  3489. applog(LOG_WARNING, "Pool %d not providing work fast enough", pool->pool_no);
  3490. pool->getfail_occasions++;
  3491. total_go++;
  3492. }
  3493. }
  3494. gettimeofday(&now, NULL);
  3495. abstime.tv_sec = now.tv_sec + 60;
  3496. applog(LOG_DEBUG, "Popping work from get queue to get work");
  3497. /* wait for 1st response, or get cached response */
  3498. work_heap = hash_pop(&abstime);
  3499. if (unlikely(!work_heap)) {
  3500. /* Attempt to switch pools if this one times out */
  3501. pool_died(pool);
  3502. goto retry;
  3503. }
  3504. if (stale_work(work_heap, false)) {
  3505. discard_work(work_heap);
  3506. goto retry;
  3507. }
  3508. pool = work_heap->pool;
  3509. /* If we make it here we have succeeded in getting fresh work */
  3510. if (!work_heap->mined) {
  3511. pool_tclear(pool, &pool->lagging);
  3512. if (pool_tclear(pool, &pool->idle))
  3513. pool_resus(pool);
  3514. }
  3515. work_heap = clone_work(work_heap);
  3516. memcpy(work, work_heap, sizeof(struct work));
  3517. free_work(work_heap);
  3518. out:
  3519. work->thr_id = thr_id;
  3520. thread_reportin(thr);
  3521. work->mined = true;
  3522. }
  3523. bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  3524. {
  3525. struct workio_cmd *wc;
  3526. /* fill out work request message */
  3527. wc = calloc(1, sizeof(*wc));
  3528. if (unlikely(!wc)) {
  3529. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  3530. return false;
  3531. }
  3532. wc->work = make_work();
  3533. wc->cmd = WC_SUBMIT_WORK;
  3534. wc->thr = thr;
  3535. memcpy(wc->work, work_in, sizeof(*work_in));
  3536. wc->work->share_found_time = time(NULL);
  3537. applog(LOG_DEBUG, "Pushing submit work to work thread");
  3538. /* send solution to workio thread */
  3539. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3540. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  3541. goto err_out;
  3542. }
  3543. return true;
  3544. err_out:
  3545. workio_cmd_free(wc);
  3546. return false;
  3547. }
  3548. bool hashtest(const struct work *work)
  3549. {
  3550. uint32_t *data32 = (uint32_t *)(work->data);
  3551. unsigned char swap[128];
  3552. uint32_t *swap32 = (uint32_t *)swap;
  3553. unsigned char hash1[32];
  3554. unsigned char hash2[32];
  3555. uint32_t *hash2_32 = (uint32_t *)hash2;
  3556. int i;
  3557. for (i = 0; i < 80 / 4; i++)
  3558. swap32[i] = swab32(data32[i]);
  3559. sha2(swap, 80, hash1, false);
  3560. sha2(hash1, 32, hash2, false);
  3561. for (i = 0; i < 32 / 4; i++)
  3562. hash2_32[i] = swab32(hash2_32[i]);
  3563. memcpy((void*)work->hash, hash2, 32);
  3564. return fulltest(work->hash, work->target);
  3565. }
  3566. bool test_nonce(struct work *work, uint32_t nonce)
  3567. {
  3568. if (opt_scrypt) {
  3569. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  3570. *work_nonce = nonce;
  3571. return true;
  3572. }
  3573. work->data[64 + 12 + 0] = (nonce >> 0) & 0xff;
  3574. work->data[64 + 12 + 1] = (nonce >> 8) & 0xff;
  3575. work->data[64 + 12 + 2] = (nonce >> 16) & 0xff;
  3576. work->data[64 + 12 + 3] = (nonce >> 24) & 0xff;
  3577. return hashtest(work);
  3578. }
  3579. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  3580. {
  3581. total_diff1++;
  3582. work->pool->diff1++;
  3583. /* Do one last check before attempting to submit the work */
  3584. /* Side effect: sets work->data for us */
  3585. if (!test_nonce(work, nonce)) {
  3586. applog(LOG_INFO, "Share below target");
  3587. return true;
  3588. }
  3589. return submit_work_sync(thr, work);
  3590. }
  3591. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  3592. {
  3593. if (wdiff->tv_sec > opt_scantime ||
  3594. work->blk.nonce >= MAXTHREADS - hashes ||
  3595. hashes >= 0xfffffffe ||
  3596. stale_work(work, false))
  3597. return true;
  3598. return false;
  3599. }
  3600. static void mt_disable(struct thr_info *mythr, const int thr_id,
  3601. struct device_api *api)
  3602. {
  3603. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3604. mythr->rolling = mythr->cgpu->rolling = 0;
  3605. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  3606. thread_reportout(mythr);
  3607. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3608. thread_reportin(mythr);
  3609. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3610. if (api->thread_enable)
  3611. api->thread_enable(mythr);
  3612. }
  3613. void *miner_thread(void *userdata)
  3614. {
  3615. struct thr_info *mythr = userdata;
  3616. const int thr_id = mythr->id;
  3617. struct cgpu_info *cgpu = mythr->cgpu;
  3618. struct device_api *api = cgpu->api;
  3619. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  3620. struct cgminer_stats *pool_stats;
  3621. struct timeval getwork_start;
  3622. /* Try to cycle approximately 5 times before each log update */
  3623. const long cycle = opt_log_interval / 5 ? : 1;
  3624. struct timeval tv_start, tv_end, tv_workstart, tv_lastupdate;
  3625. struct timeval diff, sdiff, wdiff = {0, 0};
  3626. uint32_t max_nonce = api->can_limit_work ? api->can_limit_work(mythr) : 0xffffffff;
  3627. int64_t hashes_done = 0;
  3628. int64_t hashes;
  3629. struct work *work = make_work();
  3630. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  3631. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3632. gettimeofday(&getwork_start, NULL);
  3633. if (api->thread_init && !api->thread_init(mythr)) {
  3634. cgpu->device_last_not_well = time(NULL);
  3635. cgpu->device_not_well_reason = REASON_THREAD_FAIL_INIT;
  3636. cgpu->thread_fail_init_count++;
  3637. goto out;
  3638. }
  3639. thread_reportout(mythr);
  3640. applog(LOG_DEBUG, "Popping ping in miner thread");
  3641. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  3642. sdiff.tv_sec = sdiff.tv_usec = 0;
  3643. gettimeofday(&tv_lastupdate, NULL);
  3644. while (1) {
  3645. mythr->work_restart = false;
  3646. if (api->free_work && likely(work->pool))
  3647. api->free_work(mythr, work);
  3648. get_work(work, mythr, thr_id);
  3649. gettimeofday(&tv_workstart, NULL);
  3650. work->blk.nonce = 0;
  3651. cgpu->max_hashes = 0;
  3652. if (api->prepare_work && !api->prepare_work(mythr, work)) {
  3653. applog(LOG_ERR, "work prepare failed, exiting "
  3654. "mining thread %d", thr_id);
  3655. break;
  3656. }
  3657. do {
  3658. gettimeofday(&tv_start, NULL);
  3659. timersub(&tv_start, &getwork_start, &getwork_start);
  3660. timeradd(&getwork_start,
  3661. &(dev_stats->getwork_wait),
  3662. &(dev_stats->getwork_wait));
  3663. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_max), >)) {
  3664. dev_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  3665. dev_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  3666. }
  3667. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_min), <)) {
  3668. dev_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  3669. dev_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  3670. }
  3671. dev_stats->getwork_calls++;
  3672. pool_stats = &(work->pool->cgminer_stats);
  3673. timeradd(&getwork_start,
  3674. &(pool_stats->getwork_wait),
  3675. &(pool_stats->getwork_wait));
  3676. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_max), >)) {
  3677. pool_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  3678. pool_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  3679. }
  3680. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_min), <)) {
  3681. pool_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  3682. pool_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  3683. }
  3684. pool_stats->getwork_calls++;
  3685. thread_reportin(mythr);
  3686. hashes = api->scanhash(mythr, work, work->blk.nonce + max_nonce);
  3687. thread_reportin(mythr);
  3688. gettimeofday(&getwork_start, NULL);
  3689. if (unlikely(hashes == -1)) {
  3690. applog(LOG_ERR, "%s %d failure, disabling!", api->name, cgpu->device_id);
  3691. cgpu->deven = DEV_DISABLED;
  3692. cgpu->device_last_not_well = time(NULL);
  3693. cgpu->device_not_well_reason = REASON_THREAD_ZERO_HASH;
  3694. cgpu->thread_zero_hash_count++;
  3695. mt_disable(mythr, thr_id, api);
  3696. }
  3697. hashes_done += hashes;
  3698. if (hashes > cgpu->max_hashes)
  3699. cgpu->max_hashes = hashes;
  3700. gettimeofday(&tv_end, NULL);
  3701. timersub(&tv_end, &tv_start, &diff);
  3702. sdiff.tv_sec += diff.tv_sec;
  3703. sdiff.tv_usec += diff.tv_usec;
  3704. if (sdiff.tv_usec > 1000000) {
  3705. ++sdiff.tv_sec;
  3706. sdiff.tv_usec -= 1000000;
  3707. }
  3708. timersub(&tv_end, &tv_workstart, &wdiff);
  3709. if (unlikely((long)sdiff.tv_sec < cycle)) {
  3710. int mult;
  3711. if (likely(!api->can_limit_work || max_nonce == 0xffffffff))
  3712. continue;
  3713. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  3714. mult *= cycle;
  3715. if (max_nonce > (0xffffffff * 0x400) / mult)
  3716. max_nonce = 0xffffffff;
  3717. else
  3718. max_nonce = (max_nonce * mult) / 0x400;
  3719. } else if (unlikely(sdiff.tv_sec > cycle) && api->can_limit_work)
  3720. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  3721. else if (unlikely(sdiff.tv_usec > 100000) && api->can_limit_work)
  3722. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  3723. timersub(&tv_end, &tv_lastupdate, &diff);
  3724. if (diff.tv_sec >= opt_log_interval) {
  3725. hashmeter(thr_id, &diff, hashes_done);
  3726. hashes_done = 0;
  3727. tv_lastupdate = tv_end;
  3728. }
  3729. if (unlikely(mythr->work_restart)) {
  3730. /* Apart from device_thread 0, we stagger the
  3731. * starting of every next thread to try and get
  3732. * all devices busy before worrying about
  3733. * getting work for their extra threads */
  3734. if (!primary) {
  3735. struct timespec rgtp;
  3736. rgtp.tv_sec = 0;
  3737. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  3738. nanosleep(&rgtp, NULL);
  3739. }
  3740. break;
  3741. }
  3742. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  3743. mt_disable(mythr, thr_id, api);
  3744. sdiff.tv_sec = sdiff.tv_usec = 0;
  3745. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  3746. }
  3747. out:
  3748. if (api->thread_shutdown)
  3749. api->thread_shutdown(mythr);
  3750. thread_reportin(mythr);
  3751. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3752. tq_freeze(mythr->q);
  3753. return NULL;
  3754. }
  3755. enum {
  3756. STAT_SLEEP_INTERVAL = 1,
  3757. STAT_CTR_INTERVAL = 10000000,
  3758. FAILURE_INTERVAL = 30,
  3759. };
  3760. /* Stage another work item from the work returned in a longpoll */
  3761. static void convert_to_work(json_t *val, int rolltime, struct pool *pool)
  3762. {
  3763. struct work *work;
  3764. bool rc;
  3765. work = make_work();
  3766. rc = work_decode(json_object_get(val, "result"), work);
  3767. if (unlikely(!rc)) {
  3768. applog(LOG_ERR, "Could not convert longpoll data to work");
  3769. free_work(work);
  3770. return;
  3771. }
  3772. work->pool = pool;
  3773. work->rolltime = rolltime;
  3774. work->longpoll = true;
  3775. if (pool->enabled == POOL_REJECTING)
  3776. work->mandatory = true;
  3777. /* We'll be checking this work item twice, but we already know it's
  3778. * from a new block so explicitly force the new block detection now
  3779. * rather than waiting for it to hit the stage thread. This also
  3780. * allows testwork to know whether LP discovered the block or not. */
  3781. test_work_current(work);
  3782. /* Don't use backup LPs as work if we have failover-only enabled. Use
  3783. * the longpoll work from a pool that has been rejecting shares as a
  3784. * way to detect when the pool has recovered.
  3785. */
  3786. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  3787. free_work(work);
  3788. return;
  3789. }
  3790. work = clone_work(work);
  3791. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  3792. if (unlikely(!stage_work(work)))
  3793. free_work(work);
  3794. else
  3795. applog(LOG_DEBUG, "Converted longpoll data to work");
  3796. }
  3797. /* If we want longpoll, enable it for the chosen default pool, or, if
  3798. * the pool does not support longpoll, find the first one that does
  3799. * and use its longpoll support */
  3800. static struct pool *select_longpoll_pool(struct pool *cp)
  3801. {
  3802. int i;
  3803. if (cp->hdr_path)
  3804. return cp;
  3805. for (i = 0; i < total_pools; i++) {
  3806. struct pool *pool = pools[i];
  3807. if (pool->hdr_path)
  3808. return pool;
  3809. }
  3810. return NULL;
  3811. }
  3812. /* This will make the longpoll thread wait till it's the current pool, or it
  3813. * has been flagged as rejecting, before attempting to open any connections.
  3814. */
  3815. static void wait_lpcurrent(struct pool *pool)
  3816. {
  3817. if (pool->enabled == POOL_REJECTING || pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  3818. return;
  3819. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3820. mutex_lock(&lp_lock);
  3821. pthread_cond_wait(&lp_cond, &lp_lock);
  3822. mutex_unlock(&lp_lock);
  3823. }
  3824. }
  3825. static void *longpoll_thread(void *userdata)
  3826. {
  3827. struct pool *cp = (struct pool *)userdata;
  3828. /* This *pool is the source of the actual longpoll, not the pool we've
  3829. * tied it to */
  3830. struct pool *pool = NULL;
  3831. struct timeval start, end;
  3832. CURL *curl = NULL;
  3833. int failures = 0;
  3834. int rolltime;
  3835. curl = curl_easy_init();
  3836. if (unlikely(!curl)) {
  3837. applog(LOG_ERR, "CURL initialisation failed");
  3838. goto out;
  3839. }
  3840. retry_pool:
  3841. pool = select_longpoll_pool(cp);
  3842. if (!pool) {
  3843. applog(LOG_WARNING, "No suitable long-poll found for pool %s", cp->rpc_url);
  3844. while (!pool) {
  3845. sleep(60);
  3846. pool = select_longpoll_pool(cp);
  3847. }
  3848. }
  3849. /* Any longpoll from any pool is enough for this to be true */
  3850. have_longpoll = true;
  3851. wait_lpcurrent(cp);
  3852. if (cp == pool)
  3853. applog(LOG_WARNING, "Long-polling activated for %s", pool->lp_url);
  3854. else
  3855. applog(LOG_WARNING, "Long-polling activated for pool %s via %s", cp->rpc_url, pool->lp_url);
  3856. while (42) {
  3857. json_t *val, *soval;
  3858. wait_lpcurrent(cp);
  3859. gettimeofday(&start, NULL);
  3860. /* Longpoll connections can be persistent for a very long time
  3861. * and any number of issues could have come up in the meantime
  3862. * so always establish a fresh connection instead of relying on
  3863. * a persistent one. */
  3864. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  3865. val = json_rpc_call(curl, pool->lp_url, pool->rpc_userpass, rpc_req,
  3866. false, true, &rolltime, pool, false);
  3867. if (likely(val)) {
  3868. soval = json_object_get(json_object_get(val, "result"), "submitold");
  3869. if (soval)
  3870. pool->submit_old = json_is_true(soval);
  3871. else
  3872. pool->submit_old = false;
  3873. convert_to_work(val, rolltime, pool);
  3874. failures = 0;
  3875. json_decref(val);
  3876. } else {
  3877. /* Some pools regularly drop the longpoll request so
  3878. * only see this as longpoll failure if it happens
  3879. * immediately and just restart it the rest of the
  3880. * time. */
  3881. gettimeofday(&end, NULL);
  3882. if (end.tv_sec - start.tv_sec > 30)
  3883. continue;
  3884. if (failures == 1)
  3885. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", pool->lp_url);
  3886. sleep(30);
  3887. }
  3888. if (pool != cp) {
  3889. pool = select_longpoll_pool(cp);
  3890. if (unlikely(!pool))
  3891. goto retry_pool;
  3892. }
  3893. if (unlikely(pool->removed))
  3894. break;
  3895. }
  3896. out:
  3897. if (curl)
  3898. curl_easy_cleanup(curl);
  3899. return NULL;
  3900. }
  3901. void reinit_device(struct cgpu_info *cgpu)
  3902. {
  3903. if (cgpu->api->reinit_device)
  3904. cgpu->api->reinit_device(cgpu);
  3905. }
  3906. static struct timeval rotate_tv;
  3907. /* We reap curls if they are unused for over a minute */
  3908. static void reap_curl(struct pool *pool)
  3909. {
  3910. struct curl_ent *ent, *iter;
  3911. struct timeval now;
  3912. int reaped = 0;
  3913. gettimeofday(&now, NULL);
  3914. mutex_lock(&pool->pool_lock);
  3915. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  3916. if (pool->curls < 2)
  3917. break;
  3918. if (now.tv_sec - ent->tv.tv_sec > 300) {
  3919. reaped++;
  3920. pool->curls--;
  3921. list_del(&ent->node);
  3922. curl_easy_cleanup(ent->curl);
  3923. free(ent);
  3924. }
  3925. }
  3926. mutex_unlock(&pool->pool_lock);
  3927. if (reaped)
  3928. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  3929. }
  3930. static void *watchpool_thread(void __maybe_unused *userdata)
  3931. {
  3932. int intervals = 0;
  3933. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3934. while (42) {
  3935. struct timeval now;
  3936. int i;
  3937. if (++intervals > 20)
  3938. intervals = 0;
  3939. gettimeofday(&now, NULL);
  3940. for (i = 0; i < total_pools; i++) {
  3941. struct pool *pool = pools[i];
  3942. if (!opt_benchmark)
  3943. reap_curl(pool);
  3944. if (pool->enabled == POOL_DISABLED)
  3945. continue;
  3946. /* Test pool is idle once every minute */
  3947. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  3948. gettimeofday(&pool->tv_idle, NULL);
  3949. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  3950. pool_resus(pool);
  3951. }
  3952. /* Get a rolling utility per pool over 10 mins */
  3953. if (intervals > 19) {
  3954. int shares = pool->diff1 - pool->last_shares;
  3955. pool->last_shares = pool->diff1;
  3956. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  3957. pool->shares = pool->utility;
  3958. }
  3959. }
  3960. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  3961. gettimeofday(&rotate_tv, NULL);
  3962. switch_pools(NULL);
  3963. }
  3964. sleep(30);
  3965. }
  3966. return NULL;
  3967. }
  3968. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  3969. * the screen at regular intervals, and restarts threads if they appear to have
  3970. * died. */
  3971. #define WATCHDOG_INTERVAL 3
  3972. #define WATCHDOG_SICK_TIME 60
  3973. #define WATCHDOG_DEAD_TIME 600
  3974. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  3975. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  3976. static void *watchdog_thread(void __maybe_unused *userdata)
  3977. {
  3978. const unsigned int interval = WATCHDOG_INTERVAL;
  3979. struct timeval zero_tv;
  3980. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3981. memset(&zero_tv, 0, sizeof(struct timeval));
  3982. gettimeofday(&rotate_tv, NULL);
  3983. while (1) {
  3984. int i;
  3985. struct timeval now;
  3986. sleep(interval);
  3987. discard_stale();
  3988. hashmeter(-1, &zero_tv, 0);
  3989. #ifdef HAVE_CURSES
  3990. if (curses_active_locked()) {
  3991. change_logwinsize();
  3992. curses_print_status();
  3993. for (i = 0; i < mining_threads; i++)
  3994. curses_print_devstatus(i);
  3995. touchwin(statuswin);
  3996. wrefresh(statuswin);
  3997. touchwin(logwin);
  3998. wrefresh(logwin);
  3999. unlock_curses();
  4000. }
  4001. #endif
  4002. gettimeofday(&now, NULL);
  4003. if (!sched_paused && !should_run()) {
  4004. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  4005. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4006. if (!schedstart.enable) {
  4007. quit(0, "Terminating execution as planned");
  4008. break;
  4009. }
  4010. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  4011. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4012. sched_paused = true;
  4013. for (i = 0; i < mining_threads; i++) {
  4014. struct thr_info *thr;
  4015. thr = &thr_info[i];
  4016. thr->pause = true;
  4017. }
  4018. } else if (sched_paused && should_run()) {
  4019. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  4020. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4021. if (schedstop.enable)
  4022. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  4023. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4024. sched_paused = false;
  4025. for (i = 0; i < mining_threads; i++) {
  4026. struct thr_info *thr;
  4027. thr = &thr_info[i];
  4028. /* Don't touch disabled devices */
  4029. if (thr->cgpu->deven == DEV_DISABLED)
  4030. continue;
  4031. thr->pause = false;
  4032. tq_push(thr->q, &ping);
  4033. }
  4034. }
  4035. for (i = 0; i < total_devices; ++i) {
  4036. struct cgpu_info *cgpu = devices[i];
  4037. struct thr_info *thr = cgpu->thr[0];
  4038. enum dev_enable *denable;
  4039. char dev_str[8];
  4040. int gpu;
  4041. if (cgpu->api->get_stats)
  4042. cgpu->api->get_stats(cgpu);
  4043. gpu = cgpu->device_id;
  4044. denable = &cgpu->deven;
  4045. sprintf(dev_str, "%s%d", cgpu->api->name, gpu);
  4046. #ifdef HAVE_ADL
  4047. if (adl_active && cgpu->has_adl)
  4048. gpu_autotune(gpu, denable);
  4049. if (opt_debug && cgpu->has_adl) {
  4050. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  4051. float temp = 0, vddc = 0;
  4052. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  4053. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  4054. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  4055. }
  4056. #endif
  4057. /* Thread is waiting on getwork or disabled */
  4058. if (thr->getwork || *denable == DEV_DISABLED)
  4059. continue;
  4060. #ifdef WANT_CPUMINE
  4061. if (!strcmp(cgpu->api->dname, "cpu"))
  4062. continue;
  4063. #endif
  4064. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  4065. if (cgpu->status != LIFE_INIT)
  4066. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  4067. cgpu->status = LIFE_WELL;
  4068. cgpu->device_last_well = time(NULL);
  4069. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  4070. thr->rolling = cgpu->rolling = 0;
  4071. cgpu->status = LIFE_SICK;
  4072. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  4073. gettimeofday(&thr->sick, NULL);
  4074. cgpu->device_last_not_well = time(NULL);
  4075. cgpu->device_not_well_reason = REASON_DEV_SICK_IDLE_60;
  4076. cgpu->dev_sick_idle_60_count++;
  4077. #ifdef HAVE_ADL
  4078. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  4079. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  4080. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  4081. } else
  4082. #endif
  4083. if (opt_restart) {
  4084. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  4085. reinit_device(cgpu);
  4086. }
  4087. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  4088. cgpu->status = LIFE_DEAD;
  4089. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  4090. gettimeofday(&thr->sick, NULL);
  4091. cgpu->device_last_not_well = time(NULL);
  4092. cgpu->device_not_well_reason = REASON_DEV_DEAD_IDLE_600;
  4093. cgpu->dev_dead_idle_600_count++;
  4094. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  4095. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  4096. /* Attempt to restart a GPU that's sick or dead once every minute */
  4097. gettimeofday(&thr->sick, NULL);
  4098. #ifdef HAVE_ADL
  4099. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  4100. /* Again do not attempt to restart a device that may have hard hung */
  4101. } else
  4102. #endif
  4103. if (opt_restart)
  4104. reinit_device(cgpu);
  4105. }
  4106. }
  4107. }
  4108. return NULL;
  4109. }
  4110. static void log_print_status(struct cgpu_info *cgpu)
  4111. {
  4112. char logline[255];
  4113. get_statline(logline, cgpu);
  4114. applog(LOG_WARNING, "%s", logline);
  4115. }
  4116. static void print_summary(void)
  4117. {
  4118. struct timeval diff;
  4119. int hours, mins, secs, i;
  4120. double utility, efficiency = 0.0, displayed_hashes, work_util;
  4121. bool mhash_base = true;
  4122. timersub(&total_tv_end, &total_tv_start, &diff);
  4123. hours = diff.tv_sec / 3600;
  4124. mins = (diff.tv_sec % 3600) / 60;
  4125. secs = diff.tv_sec % 60;
  4126. utility = total_accepted / total_secs * 60;
  4127. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4128. work_util = total_diff1 / total_secs * 60;
  4129. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  4130. applog(LOG_WARNING, "Started at %s", datestamp);
  4131. if (total_pools == 1)
  4132. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  4133. #ifdef WANT_CPUMINE
  4134. if (opt_n_threads)
  4135. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  4136. #endif
  4137. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  4138. displayed_hashes = total_mhashes_done / total_secs;
  4139. if (displayed_hashes < 1) {
  4140. displayed_hashes *= 1000;
  4141. mhash_base = false;
  4142. }
  4143. applog(LOG_WARNING, "Average hashrate: %.1f %shash/s", displayed_hashes, mhash_base? "Mega" : "Kilo");
  4144. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  4145. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  4146. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  4147. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  4148. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  4149. if (total_accepted || total_rejected)
  4150. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  4151. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  4152. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  4153. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min", utility);
  4154. applog(LOG_WARNING, "Work Utility (diff1 shares solved / min): %.2f/min\n", work_util);
  4155. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  4156. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  4157. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  4158. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  4159. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  4160. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  4161. if (total_pools > 1) {
  4162. for (i = 0; i < total_pools; i++) {
  4163. struct pool *pool = pools[i];
  4164. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  4165. if (pool->solved)
  4166. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  4167. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  4168. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  4169. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  4170. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  4171. if (pool->accepted || pool->rejected)
  4172. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4173. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  4174. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  4175. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  4176. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  4177. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  4178. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  4179. }
  4180. }
  4181. applog(LOG_WARNING, "Summary of per device statistics:\n");
  4182. for (i = 0; i < total_devices; ++i)
  4183. log_print_status(devices[i]);
  4184. if (opt_shares)
  4185. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  4186. fflush(stdout);
  4187. fflush(stderr);
  4188. if (opt_shares > total_accepted)
  4189. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  4190. }
  4191. static void clean_up(void)
  4192. {
  4193. #ifdef HAVE_OPENCL
  4194. clear_adl(nDevs);
  4195. #endif
  4196. #ifdef HAVE_LIBUSB
  4197. libusb_exit(NULL);
  4198. #endif
  4199. gettimeofday(&total_tv_end, NULL);
  4200. #ifdef HAVE_CURSES
  4201. disable_curses();
  4202. #endif
  4203. if (!opt_realquiet && successful_connect)
  4204. print_summary();
  4205. if (opt_n_threads)
  4206. free(cpus);
  4207. curl_global_cleanup();
  4208. }
  4209. void quit(int status, const char *format, ...)
  4210. {
  4211. va_list ap;
  4212. clean_up();
  4213. if (format) {
  4214. va_start(ap, format);
  4215. vfprintf(stderr, format, ap);
  4216. va_end(ap);
  4217. }
  4218. fprintf(stderr, "\n");
  4219. fflush(stderr);
  4220. #if defined(unix)
  4221. if (forkpid > 0) {
  4222. kill(forkpid, SIGTERM);
  4223. forkpid = 0;
  4224. }
  4225. #endif
  4226. exit(status);
  4227. }
  4228. #ifdef HAVE_CURSES
  4229. char *curses_input(const char *query)
  4230. {
  4231. char *input;
  4232. echo();
  4233. input = malloc(255);
  4234. if (!input)
  4235. quit(1, "Failed to malloc input");
  4236. leaveok(logwin, false);
  4237. wlogprint("%s:\n", query);
  4238. wgetnstr(logwin, input, 255);
  4239. if (!strlen(input))
  4240. strcpy(input, "-1");
  4241. leaveok(logwin, true);
  4242. noecho();
  4243. return input;
  4244. }
  4245. #endif
  4246. void add_pool_details(bool live, char *url, char *user, char *pass)
  4247. {
  4248. struct pool *pool;
  4249. pool = add_pool();
  4250. pool->rpc_url = url;
  4251. pool->rpc_user = user;
  4252. pool->rpc_pass = pass;
  4253. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4254. if (!pool->rpc_userpass)
  4255. quit(1, "Failed to malloc userpass");
  4256. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4257. /* Test the pool is not idle if we're live running, otherwise
  4258. * it will be tested separately */
  4259. enable_pool(pool);
  4260. if (live && !pool_active(pool, false))
  4261. pool->idle = true;
  4262. }
  4263. #ifdef HAVE_CURSES
  4264. static bool input_pool(bool live)
  4265. {
  4266. char *url = NULL, *user = NULL, *pass = NULL;
  4267. bool ret = false;
  4268. immedok(logwin, true);
  4269. wlogprint("Input server details.\n");
  4270. url = curses_input("URL");
  4271. if (!url)
  4272. goto out;
  4273. if (strncmp(url, "http://", 7) &&
  4274. strncmp(url, "https://", 8)) {
  4275. char *httpinput;
  4276. httpinput = malloc(255);
  4277. if (!httpinput)
  4278. quit(1, "Failed to malloc httpinput");
  4279. strcpy(httpinput, "http://");
  4280. strncat(httpinput, url, 248);
  4281. free(url);
  4282. url = httpinput;
  4283. }
  4284. user = curses_input("Username");
  4285. if (!user)
  4286. goto out;
  4287. pass = curses_input("Password");
  4288. if (!pass)
  4289. goto out;
  4290. add_pool_details(live, url, user, pass);
  4291. ret = true;
  4292. out:
  4293. immedok(logwin, false);
  4294. if (!ret) {
  4295. if (url)
  4296. free(url);
  4297. if (user)
  4298. free(user);
  4299. if (pass)
  4300. free(pass);
  4301. }
  4302. return ret;
  4303. }
  4304. #endif
  4305. #if defined(unix)
  4306. static void fork_monitor()
  4307. {
  4308. // Make a pipe: [readFD, writeFD]
  4309. int pfd[2];
  4310. int r = pipe(pfd);
  4311. if (r < 0) {
  4312. perror("pipe - failed to create pipe for --monitor");
  4313. exit(1);
  4314. }
  4315. // Make stderr write end of pipe
  4316. fflush(stderr);
  4317. r = dup2(pfd[1], 2);
  4318. if (r < 0) {
  4319. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  4320. exit(1);
  4321. }
  4322. r = close(pfd[1]);
  4323. if (r < 0) {
  4324. perror("close - failed to close write end of pipe for --monitor");
  4325. exit(1);
  4326. }
  4327. // Don't allow a dying monitor to kill the main process
  4328. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  4329. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  4330. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  4331. perror("signal - failed to edit signal mask for --monitor");
  4332. exit(1);
  4333. }
  4334. // Fork a child process
  4335. forkpid = fork();
  4336. if (forkpid < 0) {
  4337. perror("fork - failed to fork child process for --monitor");
  4338. exit(1);
  4339. }
  4340. // Child: launch monitor command
  4341. if (0 == forkpid) {
  4342. // Make stdin read end of pipe
  4343. r = dup2(pfd[0], 0);
  4344. if (r < 0) {
  4345. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  4346. exit(1);
  4347. }
  4348. close(pfd[0]);
  4349. if (r < 0) {
  4350. perror("close - in child, failed to close read end of pipe for --monitor");
  4351. exit(1);
  4352. }
  4353. // Launch user specified command
  4354. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  4355. perror("execl - in child failed to exec user specified command for --monitor");
  4356. exit(1);
  4357. }
  4358. // Parent: clean up unused fds and bail
  4359. r = close(pfd[0]);
  4360. if (r < 0) {
  4361. perror("close - failed to close read end of pipe for --monitor");
  4362. exit(1);
  4363. }
  4364. }
  4365. #endif // defined(unix)
  4366. #ifdef HAVE_CURSES
  4367. void enable_curses(void) {
  4368. int x,y;
  4369. lock_curses();
  4370. if (curses_active) {
  4371. unlock_curses();
  4372. return;
  4373. }
  4374. mainwin = initscr();
  4375. getmaxyx(mainwin, y, x);
  4376. statuswin = newwin(logstart, x, 0, 0);
  4377. leaveok(statuswin, true);
  4378. logwin = newwin(y - logcursor, 0, logcursor, 0);
  4379. idlok(logwin, true);
  4380. scrollok(logwin, true);
  4381. leaveok(logwin, true);
  4382. cbreak();
  4383. noecho();
  4384. curses_active = true;
  4385. statusy = logstart;
  4386. unlock_curses();
  4387. }
  4388. #endif
  4389. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  4390. #ifndef WANT_CPUMINE
  4391. struct device_api cpu_api;
  4392. struct device_api cpu_api = {
  4393. .name = "CPU",
  4394. };
  4395. #endif
  4396. #ifdef USE_BITFORCE
  4397. extern struct device_api bitforce_api;
  4398. #endif
  4399. #ifdef USE_ICARUS
  4400. extern struct device_api icarus_api;
  4401. #endif
  4402. #ifdef USE_MODMINER
  4403. extern struct device_api modminer_api;
  4404. #endif
  4405. #ifdef USE_ZTEX
  4406. extern struct device_api ztex_api;
  4407. #endif
  4408. static int cgminer_id_count = 0;
  4409. void enable_device(struct cgpu_info *cgpu)
  4410. {
  4411. cgpu->deven = DEV_ENABLED;
  4412. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  4413. mining_threads += cgpu->threads;
  4414. #ifdef HAVE_CURSES
  4415. adj_width(mining_threads, &dev_width);
  4416. #endif
  4417. #ifdef HAVE_OPENCL
  4418. if (cgpu->api == &opencl_api) {
  4419. gpu_threads += cgpu->threads;
  4420. }
  4421. #endif
  4422. }
  4423. struct _cgpu_devid_counter {
  4424. char name[4];
  4425. int lastid;
  4426. UT_hash_handle hh;
  4427. };
  4428. bool add_cgpu(struct cgpu_info*cgpu)
  4429. {
  4430. static struct _cgpu_devid_counter *devids = NULL;
  4431. struct _cgpu_devid_counter *d;
  4432. HASH_FIND_STR(devids, cgpu->api->name, d);
  4433. if (d)
  4434. cgpu->device_id = ++d->lastid;
  4435. else {
  4436. d = malloc(sizeof(*d));
  4437. memcpy(d->name, cgpu->api->name, sizeof(d->name));
  4438. cgpu->device_id = d->lastid = 0;
  4439. HASH_ADD_STR(devids, name, d);
  4440. }
  4441. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + 2));
  4442. devices[total_devices++] = cgpu;
  4443. return true;
  4444. }
  4445. int main(int argc, char *argv[])
  4446. {
  4447. struct block *block, *tmpblock;
  4448. struct work *work, *tmpwork;
  4449. bool pools_active = false;
  4450. struct sigaction handler;
  4451. struct thr_info *thr;
  4452. char *s;
  4453. unsigned int k;
  4454. int i, j;
  4455. /* This dangerous functions tramples random dynamically allocated
  4456. * variables so do it before anything at all */
  4457. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  4458. quit(1, "Failed to curl_global_init");
  4459. initial_args = malloc(sizeof(char *) * (argc + 1));
  4460. for (i = 0; i < argc; i++)
  4461. initial_args[i] = strdup(argv[i]);
  4462. initial_args[argc] = NULL;
  4463. #ifdef HAVE_LIBUSB
  4464. libusb_init(NULL);
  4465. #endif
  4466. mutex_init(&hash_lock);
  4467. mutex_init(&qd_lock);
  4468. mutex_init(&console_lock);
  4469. mutex_init(&control_lock);
  4470. mutex_init(&sharelog_lock);
  4471. mutex_init(&ch_lock);
  4472. rwlock_init(&blk_lock);
  4473. rwlock_init(&netacc_lock);
  4474. mutex_init(&lp_lock);
  4475. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  4476. quit(1, "Failed to pthread_cond_init lp_cond");
  4477. mutex_init(&restart_lock);
  4478. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  4479. quit(1, "Failed to pthread_cond_init restart_cond");
  4480. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  4481. #ifdef WANT_CPUMINE
  4482. init_max_name_len();
  4483. #endif
  4484. handler.sa_handler = &sighandler;
  4485. handler.sa_flags = 0;
  4486. sigemptyset(&handler.sa_mask);
  4487. sigaction(SIGTERM, &handler, &termhandler);
  4488. sigaction(SIGINT, &handler, &inthandler);
  4489. opt_kernel_path = alloca(PATH_MAX);
  4490. strcpy(opt_kernel_path, CGMINER_PREFIX);
  4491. cgminer_path = alloca(PATH_MAX);
  4492. s = strdup(argv[0]);
  4493. strcpy(cgminer_path, dirname(s));
  4494. free(s);
  4495. strcat(cgminer_path, "/");
  4496. #ifdef WANT_CPUMINE
  4497. // Hack to make cgminer silent when called recursively on WIN32
  4498. int skip_to_bench = 0;
  4499. #if defined(WIN32)
  4500. char buf[32];
  4501. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  4502. skip_to_bench = 1;
  4503. #endif // defined(WIN32)
  4504. #endif
  4505. devcursor = 8;
  4506. logstart = devcursor + 1;
  4507. logcursor = logstart + 1;
  4508. block = calloc(sizeof(struct block), 1);
  4509. if (unlikely(!block))
  4510. quit (1, "main OOM");
  4511. for (i = 0; i < 36; i++)
  4512. strcat(block->hash, "0");
  4513. HASH_ADD_STR(blocks, hash, block);
  4514. strcpy(current_block, block->hash);
  4515. INIT_LIST_HEAD(&scan_devices);
  4516. #ifdef HAVE_OPENCL
  4517. memset(gpus, 0, sizeof(gpus));
  4518. for (i = 0; i < MAX_GPUDEVICES; i++)
  4519. gpus[i].dynamic = true;
  4520. #endif
  4521. /* parse command line */
  4522. opt_register_table(opt_config_table,
  4523. "Options for both config file and command line");
  4524. opt_register_table(opt_cmdline_table,
  4525. "Options for command line only");
  4526. opt_parse(&argc, argv, applog_and_exit);
  4527. if (argc != 1)
  4528. quit(1, "Unexpected extra commandline arguments");
  4529. if (!config_loaded)
  4530. load_default_config();
  4531. if (opt_benchmark) {
  4532. struct pool *pool;
  4533. pool = add_pool();
  4534. pool->rpc_url = malloc(255);
  4535. strcpy(pool->rpc_url, "Benchmark");
  4536. pool->rpc_user = pool->rpc_url;
  4537. pool->rpc_pass = pool->rpc_url;
  4538. enable_pool(pool);
  4539. pool->idle = false;
  4540. successful_connect = true;
  4541. }
  4542. #ifdef HAVE_CURSES
  4543. if (opt_realquiet || devices_enabled == -1)
  4544. use_curses = false;
  4545. if (use_curses)
  4546. enable_curses();
  4547. #endif
  4548. applog(LOG_WARNING, "Started %s", packagename);
  4549. if (cnfbuf) {
  4550. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  4551. switch (fileconf_load) {
  4552. case 0:
  4553. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  4554. applog(LOG_WARNING, "Configuration file could not be used.");
  4555. break;
  4556. case -1:
  4557. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  4558. if (use_curses)
  4559. applog(LOG_WARNING, "Start cgminer with -T to see what failed to load.");
  4560. break;
  4561. default:
  4562. break;
  4563. }
  4564. free(cnfbuf);
  4565. cnfbuf = NULL;
  4566. }
  4567. strcat(opt_kernel_path, "/");
  4568. if (want_per_device_stats)
  4569. opt_log_output = true;
  4570. #ifdef WANT_CPUMINE
  4571. #ifdef USE_SCRYPT
  4572. if (opt_scrypt)
  4573. set_scrypt_algo(&opt_algo);
  4574. else
  4575. #endif
  4576. if (0 <= opt_bench_algo) {
  4577. double rate = bench_algo_stage3(opt_bench_algo);
  4578. if (!skip_to_bench)
  4579. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  4580. else {
  4581. // Write result to shared memory for parent
  4582. #if defined(WIN32)
  4583. char unique_name[64];
  4584. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  4585. HANDLE map_handle = CreateFileMapping(
  4586. INVALID_HANDLE_VALUE, // use paging file
  4587. NULL, // default security attributes
  4588. PAGE_READWRITE, // read/write access
  4589. 0, // size: high 32-bits
  4590. 4096, // size: low 32-bits
  4591. unique_name // name of map object
  4592. );
  4593. if (NULL != map_handle) {
  4594. void *shared_mem = MapViewOfFile(
  4595. map_handle, // object to map view of
  4596. FILE_MAP_WRITE, // read/write access
  4597. 0, // high offset: map from
  4598. 0, // low offset: beginning
  4599. 0 // default: map entire file
  4600. );
  4601. if (NULL != shared_mem)
  4602. CopyMemory(shared_mem, &rate, sizeof(rate));
  4603. (void)UnmapViewOfFile(shared_mem);
  4604. }
  4605. (void)CloseHandle(map_handle);
  4606. }
  4607. #endif
  4608. }
  4609. exit(0);
  4610. }
  4611. #endif
  4612. #ifdef HAVE_OPENCL
  4613. if (!opt_nogpu)
  4614. opencl_api.api_detect();
  4615. gpu_threads = 0;
  4616. #endif
  4617. #ifdef USE_ICARUS
  4618. if (!opt_scrypt)
  4619. icarus_api.api_detect();
  4620. #endif
  4621. #ifdef USE_BITFORCE
  4622. if (!opt_scrypt)
  4623. bitforce_api.api_detect();
  4624. #endif
  4625. #ifdef USE_MODMINER
  4626. if (!opt_scrypt)
  4627. modminer_api.api_detect();
  4628. #endif
  4629. #ifdef USE_ZTEX
  4630. if (!opt_scrypt)
  4631. ztex_api.api_detect();
  4632. #endif
  4633. #ifdef WANT_CPUMINE
  4634. cpu_api.api_detect();
  4635. #endif
  4636. if (devices_enabled == -1) {
  4637. applog(LOG_ERR, "Devices detected:");
  4638. for (i = 0; i < total_devices; ++i) {
  4639. struct cgpu_info *cgpu = devices[i];
  4640. if (cgpu->name)
  4641. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->name, cgpu->api->dname);
  4642. else
  4643. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->api->dname);
  4644. }
  4645. quit(0, "%d devices listed", total_devices);
  4646. }
  4647. mining_threads = 0;
  4648. if (devices_enabled) {
  4649. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  4650. if (devices_enabled & (1 << i)) {
  4651. if (i >= total_devices)
  4652. quit (1, "Command line options set a device that doesn't exist");
  4653. enable_device(devices[i]);
  4654. } else if (i < total_devices) {
  4655. if (opt_removedisabled) {
  4656. if (devices[i]->api == &cpu_api)
  4657. --opt_n_threads;
  4658. } else {
  4659. enable_device(devices[i]);
  4660. }
  4661. devices[i]->deven = DEV_DISABLED;
  4662. }
  4663. }
  4664. total_devices = cgminer_id_count;
  4665. } else {
  4666. for (i = 0; i < total_devices; ++i)
  4667. enable_device(devices[i]);
  4668. }
  4669. if (!total_devices)
  4670. quit(1, "All devices disabled, cannot mine!");
  4671. load_temp_cutoffs();
  4672. for (i = 0; i < total_devices; ++i)
  4673. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  4674. logstart += total_devices;
  4675. logcursor = logstart + 1;
  4676. #ifdef HAVE_CURSES
  4677. check_winsizes();
  4678. #endif
  4679. if (!total_pools) {
  4680. applog(LOG_WARNING, "Need to specify at least one pool server.");
  4681. #ifdef HAVE_CURSES
  4682. if (!use_curses || !input_pool(false))
  4683. #endif
  4684. quit(1, "Pool setup failed");
  4685. }
  4686. for (i = 0; i < total_pools; i++) {
  4687. struct pool *pool = pools[i];
  4688. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  4689. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  4690. if (!pool->rpc_userpass) {
  4691. if (!pool->rpc_user || !pool->rpc_pass)
  4692. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  4693. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4694. if (!pool->rpc_userpass)
  4695. quit(1, "Failed to malloc userpass");
  4696. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4697. } else {
  4698. pool->rpc_user = malloc(strlen(pool->rpc_userpass) + 1);
  4699. if (!pool->rpc_user)
  4700. quit(1, "Failed to malloc user");
  4701. strcpy(pool->rpc_user, pool->rpc_userpass);
  4702. pool->rpc_user = strtok(pool->rpc_user, ":");
  4703. if (!pool->rpc_user)
  4704. quit(1, "Failed to find colon delimiter in userpass");
  4705. }
  4706. }
  4707. /* Set the currentpool to pool 0 */
  4708. currentpool = pools[0];
  4709. #ifdef HAVE_SYSLOG_H
  4710. if (use_syslog)
  4711. openlog(PACKAGE, LOG_PID, LOG_USER);
  4712. #endif
  4713. #if defined(unix)
  4714. if (opt_stderr_cmd)
  4715. fork_monitor();
  4716. #endif // defined(unix)
  4717. total_threads = mining_threads + 7;
  4718. thr_info = calloc(total_threads, sizeof(*thr));
  4719. if (!thr_info)
  4720. quit(1, "Failed to calloc thr_info");
  4721. /* init workio thread info */
  4722. work_thr_id = mining_threads;
  4723. thr = &thr_info[work_thr_id];
  4724. thr->id = work_thr_id;
  4725. thr->q = tq_new();
  4726. if (!thr->q)
  4727. quit(1, "Failed to tq_new");
  4728. /* start work I/O thread */
  4729. if (thr_info_create(thr, NULL, workio_thread, thr))
  4730. quit(1, "workio thread create failed");
  4731. stage_thr_id = mining_threads + 1;
  4732. thr = &thr_info[stage_thr_id];
  4733. thr->q = tq_new();
  4734. if (!thr->q)
  4735. quit(1, "Failed to tq_new");
  4736. /* start stage thread */
  4737. if (thr_info_create(thr, NULL, stage_thread, thr))
  4738. quit(1, "stage thread create failed");
  4739. pthread_detach(thr->pth);
  4740. /* Create a unique get work queue */
  4741. getq = tq_new();
  4742. if (!getq)
  4743. quit(1, "Failed to create getq");
  4744. /* We use the getq mutex as the staged lock */
  4745. stgd_lock = &getq->mutex;
  4746. if (opt_benchmark)
  4747. goto begin_bench;
  4748. for (i = 0; i < total_pools; i++) {
  4749. struct pool *pool = pools[i];
  4750. enable_pool(pool);
  4751. pool->idle = true;
  4752. }
  4753. applog(LOG_NOTICE, "Probing for an alive pool");
  4754. do {
  4755. /* Look for at least one active pool before starting */
  4756. for (i = 0; i < total_pools; i++) {
  4757. struct pool *pool = pools[i];
  4758. if (pool_active(pool, false)) {
  4759. if (!currentpool)
  4760. currentpool = pool;
  4761. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  4762. pools_active = true;
  4763. break;
  4764. } else {
  4765. if (pool == currentpool)
  4766. currentpool = NULL;
  4767. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  4768. }
  4769. }
  4770. if (!pools_active) {
  4771. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  4772. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  4773. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  4774. for (i = 0; i < total_pools; i++) {
  4775. struct pool *pool;
  4776. pool = pools[i];
  4777. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  4778. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  4779. }
  4780. #ifdef HAVE_CURSES
  4781. if (use_curses) {
  4782. halfdelay(150);
  4783. applog(LOG_ERR, "Press any key to exit, or cgminer will try again in 15s.");
  4784. if (getch() != ERR)
  4785. quit(0, "No servers could be used! Exiting.");
  4786. nocbreak();
  4787. } else
  4788. #endif
  4789. quit(0, "No servers could be used! Exiting.");
  4790. }
  4791. } while (!pools_active);
  4792. begin_bench:
  4793. total_mhashes_done = 0;
  4794. for (i = 0; i < total_devices; i++) {
  4795. struct cgpu_info *cgpu = devices[i];
  4796. cgpu->rolling = cgpu->total_mhashes = 0;
  4797. }
  4798. gettimeofday(&total_tv_start, NULL);
  4799. gettimeofday(&total_tv_end, NULL);
  4800. get_datestamp(datestamp, &total_tv_start);
  4801. // Start threads
  4802. k = 0;
  4803. for (i = 0; i < total_devices; ++i) {
  4804. struct cgpu_info *cgpu = devices[i];
  4805. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  4806. cgpu->thr[cgpu->threads] = NULL;
  4807. cgpu->status = LIFE_INIT;
  4808. for (j = 0; j < cgpu->threads; ++j, ++k) {
  4809. thr = &thr_info[k];
  4810. thr->id = k;
  4811. thr->cgpu = cgpu;
  4812. thr->device_thread = j;
  4813. thr->q = tq_new();
  4814. if (!thr->q)
  4815. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->api->name, cgpu->device_id, i);
  4816. /* Enable threads for devices set not to mine but disable
  4817. * their queue in case we wish to enable them later */
  4818. if (cgpu->deven != DEV_DISABLED) {
  4819. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  4820. tq_push(thr->q, &ping);
  4821. }
  4822. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  4823. continue;
  4824. thread_reportout(thr);
  4825. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  4826. quit(1, "thread %d create failed", thr->id);
  4827. cgpu->thr[j] = thr;
  4828. }
  4829. }
  4830. #ifdef HAVE_OPENCL
  4831. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  4832. for (i = 0; i < nDevs; i++)
  4833. pause_dynamic_threads(i);
  4834. #endif
  4835. #ifdef WANT_CPUMINE
  4836. applog(LOG_INFO, "%d cpu miner threads started, "
  4837. "using SHA256 '%s' algorithm.",
  4838. opt_n_threads,
  4839. algo_names[opt_algo]);
  4840. #endif
  4841. gettimeofday(&total_tv_start, NULL);
  4842. gettimeofday(&total_tv_end, NULL);
  4843. watchpool_thr_id = mining_threads + 2;
  4844. thr = &thr_info[watchpool_thr_id];
  4845. /* start watchpool thread */
  4846. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  4847. quit(1, "watchpool thread create failed");
  4848. pthread_detach(thr->pth);
  4849. watchdog_thr_id = mining_threads + 3;
  4850. thr = &thr_info[watchdog_thr_id];
  4851. /* start watchdog thread */
  4852. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  4853. quit(1, "watchdog thread create failed");
  4854. pthread_detach(thr->pth);
  4855. #ifdef HAVE_OPENCL
  4856. /* Create reinit gpu thread */
  4857. gpur_thr_id = mining_threads + 4;
  4858. thr = &thr_info[gpur_thr_id];
  4859. thr->q = tq_new();
  4860. if (!thr->q)
  4861. quit(1, "tq_new failed for gpur_thr_id");
  4862. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  4863. quit(1, "reinit_gpu thread create failed");
  4864. #endif
  4865. /* Create API socket thread */
  4866. api_thr_id = mining_threads + 5;
  4867. thr = &thr_info[api_thr_id];
  4868. if (thr_info_create(thr, NULL, api_thread, thr))
  4869. quit(1, "API thread create failed");
  4870. #ifdef HAVE_CURSES
  4871. /* Create curses input thread for keyboard input. Create this last so
  4872. * that we know all threads are created since this can call kill_work
  4873. * to try and shut down ll previous threads. */
  4874. input_thr_id = mining_threads + 6;
  4875. thr = &thr_info[input_thr_id];
  4876. if (thr_info_create(thr, NULL, input_thread, thr))
  4877. quit(1, "input thread create failed");
  4878. pthread_detach(thr->pth);
  4879. #endif
  4880. /* main loop - simply wait for workio thread to exit. This is not the
  4881. * normal exit path and only occurs should the workio_thread die
  4882. * unexpectedly */
  4883. pthread_join(thr_info[work_thr_id].pth, NULL);
  4884. applog(LOG_INFO, "workio thread dead, exiting.");
  4885. clean_up();
  4886. /* Not really necessary, but let's clean this up too anyway */
  4887. HASH_ITER(hh, staged_work, work, tmpwork) {
  4888. HASH_DEL(staged_work, work);
  4889. free_work(work);
  4890. }
  4891. HASH_ITER(hh, blocks, block, tmpblock) {
  4892. HASH_DEL(blocks, block);
  4893. free(block);
  4894. }
  4895. #if defined(unix)
  4896. if (forkpid > 0) {
  4897. kill(forkpid, SIGTERM);
  4898. forkpid = 0;
  4899. }
  4900. #endif
  4901. return 0;
  4902. }