cgminer.c 146 KB

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