cgminer.c 145 KB

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