main.c 149 KB

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