main.c 148 KB

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