main.c 143 KB

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