main.c 146 KB

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