main.c 148 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778
  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. hexstr = bin2hex(work->data, 18);
  2146. if (unlikely(!hexstr)) {
  2147. applog(LOG_ERR, "submit_work_thread OOM");
  2148. return ret;
  2149. }
  2150. if (strcmp(hexstr, current_block))
  2151. ret = true;
  2152. free(hexstr);
  2153. return ret;
  2154. }
  2155. static void *submit_work_thread(void *userdata)
  2156. {
  2157. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2158. struct work *work = wc->u.work;
  2159. struct pool *pool = work->pool;
  2160. int failures = 0;
  2161. pthread_detach(pthread_self());
  2162. if (!opt_submit_stale && stale_work(work)) {
  2163. applog(LOG_NOTICE, "Stale share detected, discarding");
  2164. total_stale++;
  2165. pool->stale_shares++;
  2166. goto out;
  2167. }
  2168. /* submit solution to bitcoin via JSON-RPC */
  2169. while (!submit_upstream_work(work)) {
  2170. if (!opt_submit_stale && stale_work(work)) {
  2171. applog(LOG_NOTICE, "Stale share detected, discarding");
  2172. total_stale++;
  2173. pool->stale_shares++;
  2174. break;
  2175. }
  2176. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  2177. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  2178. kill_work();
  2179. break;
  2180. }
  2181. /* pause, then restart work-request loop */
  2182. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  2183. fail_pause);
  2184. sleep(fail_pause);
  2185. fail_pause += opt_fail_pause;
  2186. }
  2187. fail_pause = opt_fail_pause;
  2188. out:
  2189. workio_cmd_free(wc);
  2190. return NULL;
  2191. }
  2192. static bool workio_submit_work(struct workio_cmd *wc)
  2193. {
  2194. pthread_t submit_thread;
  2195. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  2196. applog(LOG_ERR, "Failed to create submit_work_thread");
  2197. return false;
  2198. }
  2199. return true;
  2200. }
  2201. /* Find the pool that currently has the highest priority */
  2202. static struct pool *priority_pool(int choice)
  2203. {
  2204. struct pool *ret = NULL;
  2205. int i;
  2206. for (i = 0; i < total_pools; i++) {
  2207. struct pool *pool = pools[i];
  2208. if (pool->prio == choice) {
  2209. ret = pool;
  2210. break;
  2211. }
  2212. }
  2213. if (unlikely(!ret)) {
  2214. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2215. return pools[choice];
  2216. }
  2217. return ret;
  2218. }
  2219. static void restart_longpoll(void);
  2220. static void switch_pools(struct pool *selected)
  2221. {
  2222. struct pool *pool, *last_pool;
  2223. int i, pool_no;
  2224. mutex_lock(&control_lock);
  2225. last_pool = currentpool;
  2226. pool_no = currentpool->pool_no;
  2227. /* Switch selected to pool number 0 and move the rest down */
  2228. if (selected) {
  2229. if (selected->prio != 0) {
  2230. for (i = 0; i < total_pools; i++) {
  2231. pool = pools[i];
  2232. if (pool->prio < selected->prio)
  2233. pool->prio++;
  2234. }
  2235. selected->prio = 0;
  2236. }
  2237. }
  2238. switch (pool_strategy) {
  2239. /* Both of these set to the master pool */
  2240. case POOL_FAILOVER:
  2241. case POOL_LOADBALANCE:
  2242. for (i = 0; i < total_pools; i++) {
  2243. pool = priority_pool(i);
  2244. if (!pool->idle && pool->enabled) {
  2245. pool_no = pool->pool_no;
  2246. break;
  2247. }
  2248. }
  2249. break;
  2250. /* Both of these simply increment and cycle */
  2251. case POOL_ROUNDROBIN:
  2252. case POOL_ROTATE:
  2253. if (selected) {
  2254. pool_no = selected->pool_no;
  2255. break;
  2256. }
  2257. pool_no++;
  2258. if (pool_no >= total_pools)
  2259. pool_no = 0;
  2260. break;
  2261. default:
  2262. break;
  2263. }
  2264. currentpool = pools[pool_no];
  2265. pool = currentpool;
  2266. mutex_unlock(&control_lock);
  2267. if (pool != last_pool) {
  2268. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  2269. /* Only switch longpoll if the new pool also supports LP */
  2270. if (pool->hdr_path)
  2271. restart_longpoll();
  2272. }
  2273. /* Reset the queued amount to allow more to be queued for the new pool */
  2274. mutex_lock(&qd_lock);
  2275. total_queued = 0;
  2276. mutex_unlock(&qd_lock);
  2277. }
  2278. static void discard_work(struct work *work)
  2279. {
  2280. if (!work->clone && !work->rolls && !work->mined) {
  2281. if (work->pool)
  2282. work->pool->discarded_work++;
  2283. total_discarded++;
  2284. if (opt_debug)
  2285. applog(LOG_DEBUG, "Discarded work");
  2286. } else if (opt_debug)
  2287. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2288. free_work(work);
  2289. }
  2290. /* This is overkill, but at least we'll know accurately how much work is
  2291. * queued to prevent ever being left without work */
  2292. static void inc_queued(void)
  2293. {
  2294. mutex_lock(&qd_lock);
  2295. total_queued++;
  2296. mutex_unlock(&qd_lock);
  2297. }
  2298. static void dec_queued(void)
  2299. {
  2300. mutex_lock(&qd_lock);
  2301. if (total_queued > 0)
  2302. total_queued--;
  2303. mutex_unlock(&qd_lock);
  2304. }
  2305. static int requests_queued(void)
  2306. {
  2307. int ret;
  2308. mutex_lock(&qd_lock);
  2309. ret = total_queued;
  2310. mutex_unlock(&qd_lock);
  2311. return ret;
  2312. }
  2313. static int discard_stale(void)
  2314. {
  2315. struct work *work, *tmp;
  2316. int i, stale = 0;
  2317. mutex_lock(stgd_lock);
  2318. HASH_ITER(hh, staged_work, work, tmp) {
  2319. if (stale_work(work)) {
  2320. HASH_DEL(staged_work, work);
  2321. if (work->clone)
  2322. --staged_clones;
  2323. discard_work(work);
  2324. stale++;
  2325. }
  2326. }
  2327. mutex_unlock(stgd_lock);
  2328. if (opt_debug)
  2329. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  2330. /* Dec queued outside the loop to not have recursive locks */
  2331. for (i = 0; i < stale; i++)
  2332. dec_queued();
  2333. return stale;
  2334. }
  2335. static bool queue_request(struct thr_info *thr, bool needed);
  2336. static void restart_threads(void)
  2337. {
  2338. int i, stale;
  2339. /* Discard staged work that is now stale */
  2340. stale = discard_stale();
  2341. for (i = 0; i < stale; i++)
  2342. queue_request(NULL, true);
  2343. for (i = 0; i < mining_threads; i++)
  2344. work_restart[i].restart = 1;
  2345. }
  2346. static void set_curblock(char *hexstr, unsigned char *hash)
  2347. {
  2348. unsigned char hash_swap[32];
  2349. char *old_hash = NULL;
  2350. struct timeval tv_now;
  2351. /* Don't free current_hash directly to avoid dereferencing it when
  2352. * we might be accessing its data elsewhere */
  2353. if (current_hash)
  2354. old_hash = current_hash;
  2355. strcpy(current_block, hexstr);
  2356. gettimeofday(&tv_now, NULL);
  2357. get_timestamp(blocktime, &tv_now);
  2358. swap256(hash_swap, hash);
  2359. current_hash = bin2hex(hash_swap, 16);
  2360. if (unlikely(!current_hash))
  2361. quit (1, "set_curblock OOM");
  2362. if (old_hash)
  2363. free(old_hash);
  2364. }
  2365. static void test_work_current(struct work *work, bool longpoll)
  2366. {
  2367. struct block *s;
  2368. char *hexstr;
  2369. hexstr = bin2hex(work->data, 18);
  2370. if (unlikely(!hexstr)) {
  2371. applog(LOG_ERR, "stage_thread OOM");
  2372. return;
  2373. }
  2374. /* Search to see if this block exists yet and if not, consider it a
  2375. * new block and set the current block details to this one */
  2376. rd_lock(&blk_lock);
  2377. HASH_FIND_STR(blocks, hexstr, s);
  2378. rd_unlock(&blk_lock);
  2379. if (!s) {
  2380. s = calloc(sizeof(struct block), 1);
  2381. if (unlikely(!s))
  2382. quit (1, "test_work_current OOM");
  2383. strcpy(s->hash, hexstr);
  2384. wr_lock(&blk_lock);
  2385. HASH_ADD_STR(blocks, hash, s);
  2386. wr_unlock(&blk_lock);
  2387. set_curblock(hexstr, work->data);
  2388. if (++new_blocks == 1)
  2389. goto out_free;
  2390. if (longpoll)
  2391. applog(LOG_NOTICE, "LONGPOLL detected new block on network, waiting on fresh work");
  2392. else if (have_longpoll)
  2393. applog(LOG_NOTICE, "New block detected on network before longpoll, waiting on fresh work");
  2394. else
  2395. applog(LOG_NOTICE, "New block detected on network, waiting on fresh work");
  2396. restart_threads();
  2397. }
  2398. out_free:
  2399. free(hexstr);
  2400. }
  2401. static int tv_sort(struct work *worka, struct work *workb)
  2402. {
  2403. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  2404. }
  2405. static bool hash_push(struct work *work)
  2406. {
  2407. bool rc = true;
  2408. mutex_lock(stgd_lock);
  2409. if (likely(!getq->frozen)) {
  2410. HASH_ADD_INT(staged_work, id, work);
  2411. HASH_SORT(staged_work, tv_sort);
  2412. if (work->clone)
  2413. ++staged_clones;
  2414. } else
  2415. rc = false;
  2416. pthread_cond_signal(&getq->cond);
  2417. mutex_unlock(stgd_lock);
  2418. return rc;
  2419. }
  2420. static void *stage_thread(void *userdata)
  2421. {
  2422. struct thr_info *mythr = userdata;
  2423. bool ok = true;
  2424. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2425. while (ok) {
  2426. struct work *work = NULL;
  2427. if (opt_debug)
  2428. applog(LOG_DEBUG, "Popping work to stage thread");
  2429. work = tq_pop(mythr->q, NULL);
  2430. if (unlikely(!work)) {
  2431. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  2432. ok = false;
  2433. break;
  2434. }
  2435. test_work_current(work, false);
  2436. if (opt_debug)
  2437. applog(LOG_DEBUG, "Pushing work to getwork queue");
  2438. if (unlikely(!hash_push(work))) {
  2439. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  2440. continue;
  2441. }
  2442. }
  2443. tq_freeze(mythr->q);
  2444. return NULL;
  2445. }
  2446. int curses_int(const char *query)
  2447. {
  2448. int ret;
  2449. char *cvar;
  2450. cvar = curses_input(query);
  2451. ret = atoi(cvar);
  2452. free(cvar);
  2453. return ret;
  2454. }
  2455. static bool input_pool(bool live);
  2456. static int active_pools(void)
  2457. {
  2458. int ret = 0;
  2459. int i;
  2460. for (i = 0; i < total_pools; i++) {
  2461. if ((pools[i])->enabled)
  2462. ret++;
  2463. }
  2464. return ret;
  2465. }
  2466. static void display_pool_summary(struct pool *pool)
  2467. {
  2468. double efficiency = 0.0;
  2469. if (curses_active_locked()) {
  2470. wlog("Pool: %s\n", pool->rpc_url);
  2471. wlog("%s long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  2472. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  2473. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  2474. wlog(" Accepted shares: %d\n", pool->accepted);
  2475. wlog(" Rejected shares: %d\n", pool->rejected);
  2476. if (pool->accepted || pool->rejected)
  2477. wlog(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  2478. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  2479. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2480. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  2481. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  2482. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  2483. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2484. wrefresh(logwin);
  2485. unlock_curses();
  2486. }
  2487. }
  2488. /* We can't remove the memory used for this struct pool because there may
  2489. * still be work referencing it. We just remove it from the pools list */
  2490. static void remove_pool(struct pool *pool)
  2491. {
  2492. int i, last_pool = total_pools - 1;
  2493. struct pool *other;
  2494. /* Boost priority of any lower prio than this one */
  2495. for (i = 0; i < total_pools; i++) {
  2496. other = pools[i];
  2497. if (other->prio > pool->prio)
  2498. other->prio--;
  2499. }
  2500. if (pool->pool_no < last_pool) {
  2501. /* Swap the last pool for this one */
  2502. (pools[last_pool])->pool_no = pool->pool_no;
  2503. pools[pool->pool_no] = pools[last_pool];
  2504. }
  2505. /* Give it an invalid number */
  2506. pool->pool_no = total_pools;
  2507. total_pools--;
  2508. }
  2509. static void display_pools(void)
  2510. {
  2511. struct pool *pool;
  2512. int selected, i;
  2513. char input;
  2514. opt_loginput = true;
  2515. immedok(logwin, true);
  2516. clear_logwin();
  2517. updated:
  2518. for (i = 0; i < total_pools; i++) {
  2519. pool = pools[i];
  2520. if (pool == current_pool())
  2521. wattron(logwin, A_BOLD);
  2522. if (!pool->enabled)
  2523. wattron(logwin, A_DIM);
  2524. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  2525. pool->pool_no,
  2526. pool->enabled? "Enabled" : "Disabled",
  2527. pool->idle? "Dead" : "Alive",
  2528. pool->prio,
  2529. pool->rpc_url, pool->rpc_user);
  2530. wattroff(logwin, A_BOLD | A_DIM);
  2531. }
  2532. retry:
  2533. wlogprint("\nCurrent pool management strategy: %s\n",
  2534. strategies[pool_strategy]);
  2535. if (pool_strategy == POOL_ROTATE)
  2536. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  2537. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  2538. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  2539. wlogprint("Or press any other key to continue\n");
  2540. input = getch();
  2541. if (!strncasecmp(&input, "a", 1)) {
  2542. input_pool(true);
  2543. goto updated;
  2544. } else if (!strncasecmp(&input, "r", 1)) {
  2545. if (total_pools <= 1) {
  2546. wlogprint("Cannot remove last pool");
  2547. goto retry;
  2548. }
  2549. selected = curses_int("Select pool number");
  2550. if (selected < 0 || selected >= total_pools) {
  2551. wlogprint("Invalid selection\n");
  2552. goto retry;
  2553. }
  2554. pool = pools[selected];
  2555. if (pool == current_pool())
  2556. switch_pools(NULL);
  2557. if (pool == current_pool()) {
  2558. wlogprint("Unable to remove pool due to activity\n");
  2559. goto retry;
  2560. }
  2561. pool->enabled = false;
  2562. remove_pool(pool);
  2563. goto updated;
  2564. } else if (!strncasecmp(&input, "s", 1)) {
  2565. selected = curses_int("Select pool number");
  2566. if (selected < 0 || selected >= total_pools) {
  2567. wlogprint("Invalid selection\n");
  2568. goto retry;
  2569. }
  2570. pool = pools[selected];
  2571. pool->enabled = true;
  2572. switch_pools(pool);
  2573. goto updated;
  2574. } else if (!strncasecmp(&input, "d", 1)) {
  2575. if (active_pools() <= 1) {
  2576. wlogprint("Cannot disable last pool");
  2577. goto retry;
  2578. }
  2579. selected = curses_int("Select pool number");
  2580. if (selected < 0 || selected >= total_pools) {
  2581. wlogprint("Invalid selection\n");
  2582. goto retry;
  2583. }
  2584. pool = pools[selected];
  2585. pool->enabled = false;
  2586. if (pool == current_pool())
  2587. switch_pools(NULL);
  2588. goto updated;
  2589. } else if (!strncasecmp(&input, "e", 1)) {
  2590. selected = curses_int("Select pool number");
  2591. if (selected < 0 || selected >= total_pools) {
  2592. wlogprint("Invalid selection\n");
  2593. goto retry;
  2594. }
  2595. pool = pools[selected];
  2596. pool->enabled = true;
  2597. if (pool->prio < current_pool()->prio)
  2598. switch_pools(pool);
  2599. goto updated;
  2600. } else if (!strncasecmp(&input, "c", 1)) {
  2601. for (i = 0; i <= TOP_STRATEGY; i++)
  2602. wlogprint("%d: %s\n", i, strategies[i]);
  2603. selected = curses_int("Select strategy number type");
  2604. if (selected < 0 || selected > TOP_STRATEGY) {
  2605. wlogprint("Invalid selection\n");
  2606. goto retry;
  2607. }
  2608. if (selected == POOL_ROTATE) {
  2609. opt_rotate_period = curses_int("Select interval in minutes");
  2610. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  2611. opt_rotate_period = 0;
  2612. wlogprint("Invalid selection\n");
  2613. goto retry;
  2614. }
  2615. }
  2616. pool_strategy = selected;
  2617. switch_pools(NULL);
  2618. goto updated;
  2619. } else if (!strncasecmp(&input, "i", 1)) {
  2620. selected = curses_int("Select pool number");
  2621. if (selected < 0 || selected >= total_pools) {
  2622. wlogprint("Invalid selection\n");
  2623. goto retry;
  2624. }
  2625. pool = pools[selected];
  2626. display_pool_summary(pool);
  2627. goto retry;
  2628. } else
  2629. clear_logwin();
  2630. immedok(logwin, false);
  2631. opt_loginput = false;
  2632. }
  2633. static void display_options(void)
  2634. {
  2635. int selected;
  2636. char input;
  2637. opt_loginput = true;
  2638. immedok(logwin, true);
  2639. clear_logwin();
  2640. retry:
  2641. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  2642. 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",
  2643. opt_debug ? "on" : "off",
  2644. want_per_device_stats? "on" : "off",
  2645. opt_quiet ? "on" : "off",
  2646. opt_log_output ? "on" : "off",
  2647. opt_protocol ? "on" : "off",
  2648. opt_log_interval);
  2649. wlogprint("Select an option or any other key to return\n");
  2650. input = getch();
  2651. if (!strncasecmp(&input, "q", 1)) {
  2652. opt_quiet ^= true;
  2653. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  2654. goto retry;
  2655. } else if (!strncasecmp(&input, "v", 1)) {
  2656. opt_log_output ^= true;
  2657. if (opt_log_output)
  2658. opt_quiet = false;
  2659. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2660. goto retry;
  2661. } else if (!strncasecmp(&input, "n", 1)) {
  2662. opt_log_output = false;
  2663. opt_debug = false;
  2664. opt_quiet = false;
  2665. opt_protocol = false;
  2666. want_per_device_stats = false;
  2667. wlogprint("Output mode reset to normal\n");
  2668. goto retry;
  2669. } else if (!strncasecmp(&input, "d", 1)) {
  2670. opt_debug ^= true;
  2671. opt_log_output = opt_debug;
  2672. if (opt_debug)
  2673. opt_quiet = false;
  2674. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2675. goto retry;
  2676. } else if (!strncasecmp(&input, "p", 1)) {
  2677. want_per_device_stats ^= true;
  2678. opt_log_output = want_per_device_stats;
  2679. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  2680. goto retry;
  2681. } else if (!strncasecmp(&input, "r", 1)) {
  2682. opt_protocol ^= true;
  2683. if (opt_protocol)
  2684. opt_quiet = false;
  2685. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2686. goto retry;
  2687. } else if (!strncasecmp(&input, "c", 1))
  2688. clear_logwin();
  2689. else if (!strncasecmp(&input, "l", 1)) {
  2690. selected = curses_int("Interval in seconds");
  2691. if (selected < 0 || selected > 9999) {
  2692. wlogprint("Invalid selection\n");
  2693. goto retry;
  2694. }
  2695. opt_log_interval = selected;
  2696. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2697. goto retry;
  2698. } else if (!strncasecmp(&input, "s", 1)) {
  2699. opt_realquiet = true;
  2700. } else
  2701. clear_logwin();
  2702. immedok(logwin, false);
  2703. opt_loginput = false;
  2704. }
  2705. static void set_options(void)
  2706. {
  2707. int selected;
  2708. char input;
  2709. opt_loginput = true;
  2710. immedok(logwin, true);
  2711. clear_logwin();
  2712. retry:
  2713. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  2714. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[R]etries: %d\n[P]ause: %d\n",
  2715. opt_queue, opt_scantime, opt_retries, opt_fail_pause);
  2716. wlogprint("Select an option or any other key to return\n");
  2717. input = getch();
  2718. if (!strncasecmp(&input, "q", 1)) {
  2719. selected = curses_int("Extra work items to queue");
  2720. if (selected < 0 || selected > 9999) {
  2721. wlogprint("Invalid selection\n");
  2722. goto retry;
  2723. }
  2724. opt_queue = selected;
  2725. goto retry;
  2726. } else if (!strncasecmp(&input, "l", 1)) {
  2727. want_longpoll ^= true;
  2728. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2729. restart_longpoll();
  2730. goto retry;
  2731. } else if (!strncasecmp(&input, "s", 1)) {
  2732. selected = curses_int("Set scantime in seconds");
  2733. if (selected < 0 || selected > 9999) {
  2734. wlogprint("Invalid selection\n");
  2735. goto retry;
  2736. }
  2737. opt_scantime = selected;
  2738. goto retry;
  2739. } else if (!strncasecmp(&input, "r", 1)) {
  2740. selected = curses_int("Retries before failing (-1 infinite)");
  2741. if (selected < -1 || selected > 9999) {
  2742. wlogprint("Invalid selection\n");
  2743. goto retry;
  2744. }
  2745. opt_retries = selected;
  2746. goto retry;
  2747. } else if (!strncasecmp(&input, "p", 1)) {
  2748. selected = curses_int("Seconds to pause before network retries");
  2749. if (selected < 1 || selected > 9999) {
  2750. wlogprint("Invalid selection\n");
  2751. goto retry;
  2752. }
  2753. opt_fail_pause = selected;
  2754. goto retry;
  2755. } else
  2756. clear_logwin();
  2757. immedok(logwin, false);
  2758. opt_loginput = false;
  2759. }
  2760. #ifdef HAVE_OPENCL
  2761. static void reinit_device(struct cgpu_info *cgpu);
  2762. static void manage_gpu(void)
  2763. {
  2764. struct thr_info *thr;
  2765. int selected, gpu, i;
  2766. char checkin[40];
  2767. char input;
  2768. if (!opt_g_threads)
  2769. return;
  2770. opt_loginput = true;
  2771. immedok(logwin, true);
  2772. clear_logwin();
  2773. retry:
  2774. for (gpu = 0; gpu < nDevs; gpu++) {
  2775. struct cgpu_info *cgpu = &gpus[gpu];
  2776. wlog("GPU %d: %.1f / %.1f Mh/s | A:%d R:%d HW:%d U:%.2f/m I:%d\n",
  2777. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  2778. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  2779. cgpu->utility, cgpu->intensity);
  2780. #ifdef HAVE_ADL
  2781. if (gpus[gpu].has_adl) {
  2782. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  2783. float temp = 0, vddc = 0;
  2784. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune)) {
  2785. char logline[255];
  2786. strcpy(logline, ""); // In case it has no data
  2787. if (temp != -1)
  2788. sprintf(logline, "%.1f C ", temp);
  2789. if (fanspeed != -1 || fanpercent != -1) {
  2790. tailsprintf(logline, "F: ");
  2791. if (fanpercent != -1)
  2792. tailsprintf(logline, "%d%% ", fanpercent);
  2793. if (fanspeed != -1)
  2794. tailsprintf(logline, "(%d RPM) ", fanspeed);
  2795. tailsprintf(logline, " ");
  2796. }
  2797. if (engineclock != -1)
  2798. tailsprintf(logline, "E: %d MHz ", engineclock);
  2799. if (memclock != -1)
  2800. tailsprintf(logline, "M: %d Mhz ", memclock);
  2801. if (vddc != -1)
  2802. tailsprintf(logline, "V: %.3fV ", vddc);
  2803. if (activity != -1)
  2804. tailsprintf(logline, "A: %d%% ", activity);
  2805. if (powertune != -1)
  2806. tailsprintf(logline, "P: %d%%", powertune);
  2807. tailsprintf(logline, "\n");
  2808. wlog(logline);
  2809. }
  2810. }
  2811. #endif
  2812. wlog("Last initialised: %s\n", cgpu->init);
  2813. wlog("Intensity: ");
  2814. if (gpus[gpu].dynamic)
  2815. wlog("Dynamic\n");
  2816. else
  2817. wlog("%d\n", gpus[gpu].intensity);
  2818. for (i = 0; i < mining_threads; i++) {
  2819. thr = &thr_info[i];
  2820. if (thr->cgpu != cgpu)
  2821. continue;
  2822. get_datestamp(checkin, &thr->last);
  2823. wlog("Thread %d: %.1f Mh/s %s ", i, thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled");
  2824. switch (cgpu->status) {
  2825. default:
  2826. case LIFE_WELL:
  2827. wlog("ALIVE");
  2828. break;
  2829. case LIFE_SICK:
  2830. wlog("SICK reported in %s", checkin);
  2831. break;
  2832. case LIFE_DEAD:
  2833. wlog("DEAD reported in %s", checkin);
  2834. break;
  2835. case LIFE_NOSTART:
  2836. wlog("Never started");
  2837. break;
  2838. }
  2839. wlog("\n");
  2840. }
  2841. wlog("\n");
  2842. }
  2843. wlogprint("[E]nable [D]isable [I]ntensity [R]estart GPU %s\n",adl_active ? "[C]hange settings" : "");
  2844. wlogprint("Or press any other key to continue\n");
  2845. input = getch();
  2846. if (nDevs == 1)
  2847. selected = 0;
  2848. else
  2849. selected = -1;
  2850. if (!strncasecmp(&input, "e", 1)) {
  2851. if (selected)
  2852. selected = curses_int("Select GPU to enable");
  2853. if (selected < 0 || selected >= nDevs) {
  2854. wlogprint("Invalid selection\n");
  2855. goto retry;
  2856. }
  2857. if (gpu_devices[selected]) {
  2858. wlogprint("Device already enabled\n");
  2859. goto retry;
  2860. }
  2861. gpu_devices[selected] = true;
  2862. for (i = 0; i < gpu_threads; i++) {
  2863. if (dev_from_id(i) != selected)
  2864. continue;
  2865. thr = &thr_info[i];
  2866. if (thr->cgpu->status != LIFE_WELL) {
  2867. wlogprint("Must restart device before enabling it");
  2868. gpu_devices[selected] = false;
  2869. goto retry;
  2870. }
  2871. if (opt_debug)
  2872. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  2873. tq_push(thr->q, &ping);
  2874. }
  2875. goto retry;
  2876. } if (!strncasecmp(&input, "d", 1)) {
  2877. if (selected)
  2878. selected = curses_int("Select GPU to disable");
  2879. if (selected < 0 || selected >= nDevs) {
  2880. wlogprint("Invalid selection\n");
  2881. goto retry;
  2882. }
  2883. if (!gpu_devices[selected]) {
  2884. wlogprint("Device already disabled\n");
  2885. goto retry;
  2886. }
  2887. gpu_devices[selected] = false;
  2888. goto retry;
  2889. } else if (!strncasecmp(&input, "i", 1)) {
  2890. int intensity;
  2891. char *intvar;
  2892. if (selected)
  2893. selected = curses_int("Select GPU to change intensity on");
  2894. if (selected < 0 || selected >= nDevs) {
  2895. wlogprint("Invalid selection\n");
  2896. goto retry;
  2897. }
  2898. intvar = curses_input("Set GPU scan intensity (d or -10 -> 10)");
  2899. if (!intvar) {
  2900. wlogprint("Invalid input\n");
  2901. goto retry;
  2902. }
  2903. if (!strncasecmp(intvar, "d", 1)) {
  2904. wlogprint("Dynamic mode enabled on gpu %d\n", selected);
  2905. gpus[selected].dynamic = true;
  2906. free(intvar);
  2907. goto retry;
  2908. }
  2909. intensity = atoi(intvar);
  2910. free(intvar);
  2911. if (intensity < -10 || intensity > 10) {
  2912. wlogprint("Invalid selection\n");
  2913. goto retry;
  2914. }
  2915. gpus[selected].dynamic = false;
  2916. gpus[selected].intensity = intensity;
  2917. wlogprint("Intensity on gpu %d set to %d\n", selected, intensity);
  2918. goto retry;
  2919. } else if (!strncasecmp(&input, "r", 1)) {
  2920. if (selected)
  2921. selected = curses_int("Select GPU to attempt to restart");
  2922. if (selected < 0 || selected >= nDevs) {
  2923. wlogprint("Invalid selection\n");
  2924. goto retry;
  2925. }
  2926. wlogprint("Attempting to restart threads of GPU %d\n", selected);
  2927. reinit_device(&gpus[selected]);
  2928. goto retry;
  2929. } else if (adl_active && (!strncasecmp(&input, "c", 1))) {
  2930. if (selected)
  2931. selected = curses_int("Select GPU to change settings on");
  2932. if (selected < 0 || selected >= nDevs) {
  2933. wlogprint("Invalid selection\n");
  2934. goto retry;
  2935. }
  2936. change_gpusettings(selected);
  2937. goto retry;
  2938. } else
  2939. clear_logwin();
  2940. immedok(logwin, false);
  2941. opt_loginput = false;
  2942. }
  2943. #else
  2944. static void manage_gpu(void)
  2945. {
  2946. }
  2947. #endif
  2948. static void *input_thread(void *userdata)
  2949. {
  2950. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2951. if (!curses_active)
  2952. return NULL;
  2953. while (1) {
  2954. char input;
  2955. input = getch();
  2956. if (!strncasecmp(&input, "q", 1)) {
  2957. kill_work();
  2958. return NULL;
  2959. } else if (!strncasecmp(&input, "d", 1))
  2960. display_options();
  2961. else if (!strncasecmp(&input, "p", 1))
  2962. display_pools();
  2963. else if (!strncasecmp(&input, "s", 1))
  2964. set_options();
  2965. else if (!strncasecmp(&input, "g", 1))
  2966. manage_gpu();
  2967. if (opt_realquiet) {
  2968. disable_curses();
  2969. break;
  2970. }
  2971. }
  2972. return NULL;
  2973. }
  2974. static void *workio_thread(void *userdata)
  2975. {
  2976. struct thr_info *mythr = userdata;
  2977. bool ok = true;
  2978. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2979. while (ok) {
  2980. struct workio_cmd *wc;
  2981. if (opt_debug)
  2982. applog(LOG_DEBUG, "Popping work to work thread");
  2983. /* wait for workio_cmd sent to us, on our queue */
  2984. wc = tq_pop(mythr->q, NULL);
  2985. if (unlikely(!wc)) {
  2986. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  2987. ok = false;
  2988. break;
  2989. }
  2990. /* process workio_cmd */
  2991. switch (wc->cmd) {
  2992. case WC_GET_WORK:
  2993. ok = workio_get_work(wc);
  2994. break;
  2995. case WC_SUBMIT_WORK:
  2996. ok = workio_submit_work(wc);
  2997. break;
  2998. default:
  2999. ok = false;
  3000. break;
  3001. }
  3002. }
  3003. tq_freeze(mythr->q);
  3004. return NULL;
  3005. }
  3006. static void thread_reportin(struct thr_info *thr)
  3007. {
  3008. gettimeofday(&thr->last, NULL);
  3009. thr->cgpu->status = LIFE_WELL;
  3010. thr->getwork = false;
  3011. }
  3012. static inline void thread_reportout(struct thr_info *thr)
  3013. {
  3014. thr->getwork = true;
  3015. }
  3016. static void hashmeter(int thr_id, struct timeval *diff,
  3017. unsigned long hashes_done)
  3018. {
  3019. struct timeval temp_tv_end, total_diff;
  3020. double secs;
  3021. double local_secs;
  3022. double utility, efficiency = 0.0;
  3023. static double local_mhashes_done = 0;
  3024. static double rolling = 0;
  3025. double local_mhashes = (double)hashes_done / 1000000.0;
  3026. bool showlog = false;
  3027. /* Update the last time this thread reported in */
  3028. if (thr_id >= 0)
  3029. gettimeofday(&thr_info[thr_id].last, NULL);
  3030. /* Don't bother calculating anything if we're not displaying it */
  3031. if (opt_realquiet || !opt_log_interval)
  3032. return;
  3033. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  3034. /* So we can call hashmeter from a non worker thread */
  3035. if (thr_id >= 0) {
  3036. struct thr_info *thr = &thr_info[thr_id];
  3037. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  3038. double thread_rolling = 0.0;
  3039. int i;
  3040. if (opt_debug)
  3041. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  3042. thr_id, hashes_done, hashes_done / secs);
  3043. /* Rolling average for each thread and each device */
  3044. decay_time(&thr->rolling, local_mhashes / secs);
  3045. for (i = 0; i < mining_threads; i++) {
  3046. struct thr_info *th = &thr_info[i];
  3047. if (th->cgpu == cgpu)
  3048. thread_rolling += th->rolling;
  3049. }
  3050. decay_time(&cgpu->rolling, thread_rolling);
  3051. cgpu->total_mhashes += local_mhashes;
  3052. // If needed, output detailed, per-device stats
  3053. if (want_per_device_stats) {
  3054. struct timeval now;
  3055. struct timeval elapsed;
  3056. gettimeofday(&now, NULL);
  3057. timeval_subtract(&elapsed, &now, &thr->cgpu->last_message_tv);
  3058. if (opt_log_interval <= elapsed.tv_sec) {
  3059. struct cgpu_info *cgpu = thr->cgpu;
  3060. char logline[255];
  3061. cgpu->last_message_tv = now;
  3062. get_statline(logline, cgpu);
  3063. if (!curses_active) {
  3064. printf("%s \r", logline);
  3065. fflush(stdout);
  3066. } else
  3067. applog(LOG_INFO, "%s", logline);
  3068. }
  3069. }
  3070. }
  3071. /* Totals are updated by all threads so can race without locking */
  3072. mutex_lock(&hash_lock);
  3073. gettimeofday(&temp_tv_end, NULL);
  3074. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  3075. total_mhashes_done += local_mhashes;
  3076. local_mhashes_done += local_mhashes;
  3077. if (total_diff.tv_sec < opt_log_interval)
  3078. /* Only update the total every opt_log_interval seconds */
  3079. goto out_unlock;
  3080. showlog = true;
  3081. gettimeofday(&total_tv_end, NULL);
  3082. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  3083. decay_time(&rolling, local_mhashes_done / local_secs);
  3084. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  3085. total_secs = (double)total_diff.tv_sec +
  3086. ((double)total_diff.tv_usec / 1000000.0);
  3087. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3088. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3089. sprintf(statusline, "%s(%ds):%.1f (avg):%.1f Mh/s | Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  3090. want_per_device_stats ? "ALL " : "",
  3091. opt_log_interval, rolling, total_mhashes_done / total_secs,
  3092. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  3093. local_mhashes_done = 0;
  3094. out_unlock:
  3095. mutex_unlock(&hash_lock);
  3096. if (showlog) {
  3097. if (!curses_active) {
  3098. printf("%s \r", statusline);
  3099. fflush(stdout);
  3100. } else
  3101. applog(LOG_INFO, "%s", statusline);
  3102. }
  3103. }
  3104. static bool pool_active(struct pool *pool, bool pinging)
  3105. {
  3106. bool ret = false;
  3107. json_t *val;
  3108. CURL *curl;
  3109. bool rolltime;
  3110. curl = curl_easy_init();
  3111. if (unlikely(!curl)) {
  3112. applog(LOG_ERR, "CURL initialisation failed");
  3113. return false;
  3114. }
  3115. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  3116. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  3117. true, false, &rolltime, pool);
  3118. if (val) {
  3119. struct work *work = make_work();
  3120. bool rc;
  3121. rc = work_decode(json_object_get(val, "result"), work);
  3122. if (rc) {
  3123. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  3124. pool->pool_no, pool->rpc_url);
  3125. work->pool = pool;
  3126. work->rolltime = rolltime;
  3127. if (opt_debug)
  3128. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  3129. tq_push(thr_info[stage_thr_id].q, work);
  3130. total_getworks++;
  3131. pool->getwork_requested++;
  3132. inc_queued();
  3133. ret = true;
  3134. gettimeofday(&pool->tv_idle, NULL);
  3135. } else {
  3136. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  3137. pool->pool_no, pool->rpc_url);
  3138. free_work(work);
  3139. }
  3140. json_decref(val);
  3141. } else {
  3142. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  3143. pool->pool_no, pool->rpc_url);
  3144. if (!pinging)
  3145. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  3146. }
  3147. curl_easy_cleanup(curl);
  3148. return ret;
  3149. }
  3150. static void pool_died(struct pool *pool)
  3151. {
  3152. if (!pool_tset(pool, &pool->idle)) {
  3153. if (!donor(pool))
  3154. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  3155. gettimeofday(&pool->tv_idle, NULL);
  3156. switch_pools(NULL);
  3157. }
  3158. }
  3159. static inline int cp_prio(void)
  3160. {
  3161. int prio;
  3162. mutex_lock(&control_lock);
  3163. prio = currentpool->prio;
  3164. mutex_unlock(&control_lock);
  3165. return prio;
  3166. }
  3167. static void pool_resus(struct pool *pool)
  3168. {
  3169. if (!donor(pool))
  3170. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  3171. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  3172. switch_pools(NULL);
  3173. }
  3174. static bool queue_request(struct thr_info *thr, bool needed)
  3175. {
  3176. struct workio_cmd *wc;
  3177. int rq = requests_queued();
  3178. if (rq >= mining_threads + staged_clones)
  3179. return true;
  3180. /* fill out work request message */
  3181. wc = calloc(1, sizeof(*wc));
  3182. if (unlikely(!wc)) {
  3183. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  3184. return false;
  3185. }
  3186. wc->cmd = WC_GET_WORK;
  3187. if (thr)
  3188. wc->thr = thr;
  3189. else
  3190. wc->thr = NULL;
  3191. /* If we're queueing work faster than we can stage it, consider the
  3192. * system lagging and allow work to be gathered from another pool if
  3193. * possible */
  3194. if (rq && needed && !requests_staged() && !opt_fail_only)
  3195. wc->lagging = true;
  3196. if (opt_debug)
  3197. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  3198. /* send work request to workio thread */
  3199. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3200. applog(LOG_ERR, "Failed to tq_push in queue_request");
  3201. workio_cmd_free(wc);
  3202. return false;
  3203. }
  3204. inc_queued();
  3205. return true;
  3206. }
  3207. struct work *hash_pop(const struct timespec *abstime)
  3208. {
  3209. struct work *work = NULL;
  3210. int rc;
  3211. mutex_lock(stgd_lock);
  3212. if (HASH_COUNT(staged_work))
  3213. goto pop;
  3214. if (abstime)
  3215. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  3216. else
  3217. rc = pthread_cond_wait(&getq->cond, stgd_lock);
  3218. if (rc)
  3219. goto out;
  3220. if (!HASH_COUNT(staged_work))
  3221. goto out;
  3222. pop:
  3223. work = staged_work;
  3224. HASH_DEL(staged_work, work);
  3225. if (work->clone)
  3226. --staged_clones;
  3227. out:
  3228. mutex_unlock(stgd_lock);
  3229. return work;
  3230. }
  3231. static inline bool should_roll(struct work *work)
  3232. {
  3233. int rs;
  3234. rs = requests_staged();
  3235. if (rs >= mining_threads)
  3236. return false;
  3237. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE || !rs)
  3238. return true;
  3239. return false;
  3240. }
  3241. static inline bool can_roll(struct work *work)
  3242. {
  3243. return (work->pool && !stale_work(work) && work->rolltime &&
  3244. work->rolls < 11 && !work->clone && !donor(work->pool));
  3245. }
  3246. static void roll_work(struct work *work)
  3247. {
  3248. uint32_t *work_ntime;
  3249. uint32_t ntime;
  3250. work_ntime = (uint32_t *)(work->data + 68);
  3251. ntime = be32toh(*work_ntime);
  3252. ntime++;
  3253. *work_ntime = htobe32(ntime);
  3254. local_work++;
  3255. work->rolls++;
  3256. work->blk.nonce = 0;
  3257. if (opt_debug)
  3258. applog(LOG_DEBUG, "Successfully rolled work");
  3259. }
  3260. /* Recycle the work at a higher starting res_nonce if we know the thread we're
  3261. * giving it to will not finish scanning it. We keep the master copy to be
  3262. * recycled more rapidly and discard the clone to avoid repeating work */
  3263. static bool divide_work(struct timeval *now, struct work *work, uint32_t hash_div)
  3264. {
  3265. uint64_t hash_inc;
  3266. if (work->clone)
  3267. return false;
  3268. hash_inc = MAXTHREADS / hash_div * 2;
  3269. if ((uint64_t)work->blk.nonce + hash_inc < MAXTHREADS) {
  3270. /* Okay we can divide it up */
  3271. work->blk.nonce += hash_inc;
  3272. work->cloned = true;
  3273. local_work++;
  3274. if (opt_debug)
  3275. applog(LOG_DEBUG, "Successfully divided work");
  3276. return true;
  3277. } else if (can_roll(work) && should_roll(work)) {
  3278. roll_work(work);
  3279. return true;
  3280. }
  3281. return false;
  3282. }
  3283. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  3284. const int thr_id, uint32_t hash_div)
  3285. {
  3286. struct timespec abstime = {};
  3287. struct timeval now;
  3288. struct work *work_heap;
  3289. struct pool *pool;
  3290. bool ret = false;
  3291. int failures = 0;
  3292. /* Tell the watchdog thread this thread is waiting on getwork and
  3293. * should not be restarted */
  3294. thread_reportout(thr);
  3295. retry:
  3296. pool = current_pool();
  3297. if (unlikely((!requested || requests_queued() < opt_queue) && !queue_request(thr, true))) {
  3298. applog(LOG_WARNING, "Failed to queue_request in get_work");
  3299. goto out;
  3300. }
  3301. if (!requests_staged()) {
  3302. if (can_roll(work)) {
  3303. roll_work(work);
  3304. ret = true;
  3305. goto out;
  3306. }
  3307. if (requested && requests_queued() >= mining_threads &&
  3308. !pool_tset(pool, &pool->lagging)) {
  3309. applog(LOG_WARNING, "Pool %d not providing work fast enough",
  3310. pool->pool_no);
  3311. pool->getfail_occasions++;
  3312. total_go++;
  3313. }
  3314. }
  3315. requested = false;
  3316. gettimeofday(&now, NULL);
  3317. abstime.tv_sec = now.tv_sec + 60;
  3318. if (opt_debug)
  3319. applog(LOG_DEBUG, "Popping work from get queue to get work");
  3320. /* wait for 1st response, or get cached response */
  3321. work_heap = hash_pop(&abstime);
  3322. if (unlikely(!work_heap)) {
  3323. /* Attempt to switch pools if this one times out */
  3324. pool_died(pool);
  3325. goto retry;
  3326. }
  3327. if (stale_work(work_heap)) {
  3328. dec_queued();
  3329. discard_work(work_heap);
  3330. goto retry;
  3331. }
  3332. pool = work_heap->pool;
  3333. /* If we make it here we have succeeded in getting fresh work */
  3334. if (!work_heap->mined) {
  3335. pool_tclear(pool, &pool->lagging);
  3336. if (pool_tclear(pool, &pool->idle))
  3337. pool_resus(pool);
  3338. }
  3339. memcpy(work, work_heap, sizeof(*work));
  3340. /* Copy the res nonce back so we know to start at a higher baseline
  3341. * should we divide the same work up again. Make the work we're
  3342. * handing out be clone */
  3343. if (divide_work(&now, work_heap, hash_div)) {
  3344. if (opt_debug)
  3345. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  3346. hash_push(work_heap);
  3347. work->clone = true;
  3348. } else {
  3349. dec_queued();
  3350. free_work(work_heap);
  3351. }
  3352. ret = true;
  3353. out:
  3354. if (unlikely(ret == false)) {
  3355. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  3356. applog(LOG_ERR, "Failed %d times to get_work");
  3357. return ret;
  3358. }
  3359. applog(LOG_DEBUG, "Retrying after %d seconds", fail_pause);
  3360. sleep(fail_pause);
  3361. fail_pause += opt_fail_pause;
  3362. goto retry;
  3363. }
  3364. fail_pause = opt_fail_pause;
  3365. work->thr_id = thr_id;
  3366. thread_reportin(thr);
  3367. if (ret)
  3368. work->mined = true;
  3369. return ret;
  3370. }
  3371. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  3372. {
  3373. struct workio_cmd *wc;
  3374. /* fill out work request message */
  3375. wc = calloc(1, sizeof(*wc));
  3376. if (unlikely(!wc)) {
  3377. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  3378. return false;
  3379. }
  3380. wc->u.work = make_work();
  3381. wc->cmd = WC_SUBMIT_WORK;
  3382. wc->thr = thr;
  3383. memcpy(wc->u.work, work_in, sizeof(*work_in));
  3384. if (opt_debug)
  3385. applog(LOG_DEBUG, "Pushing submit work to work thread");
  3386. /* send solution to workio thread */
  3387. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3388. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  3389. goto err_out;
  3390. }
  3391. return true;
  3392. err_out:
  3393. workio_cmd_free(wc);
  3394. return false;
  3395. }
  3396. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  3397. {
  3398. work->data[64+12+0] = (nonce>>0) & 0xff;
  3399. work->data[64+12+1] = (nonce>>8) & 0xff;
  3400. work->data[64+12+2] = (nonce>>16) & 0xff;
  3401. work->data[64+12+3] = (nonce>>24) & 0xff;
  3402. /* Do one last check before attempting to submit the work */
  3403. if (!fulltest(work->data + 64, work->target))
  3404. return true;
  3405. return submit_work_sync(thr, work);
  3406. }
  3407. static void *miner_thread(void *userdata)
  3408. {
  3409. struct work *work = make_work();
  3410. struct thr_info *mythr = userdata;
  3411. const int thr_id = mythr->id;
  3412. uint32_t max_nonce = 0xffffff, total_hashes = 0;
  3413. unsigned long hashes_done = max_nonce;
  3414. bool needs_work = true;
  3415. /* Try to cycle approximately 5 times before each log update */
  3416. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  3417. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3418. bool requested = false;
  3419. uint32_t nonce_inc = max_nonce, hash_div = 1;
  3420. double hash_divfloat = 1.0;
  3421. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3422. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  3423. * and if that fails, then SCHED_BATCH. No need for this to be an
  3424. * error if it fails */
  3425. setpriority(PRIO_PROCESS, 0, 19);
  3426. drop_policy();
  3427. /* Cpu affinity only makes sense if the number of threads is a multiple
  3428. * of the number of CPUs */
  3429. if (!(opt_n_threads % num_processors))
  3430. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  3431. /* Invalidate pool so it fails can_roll() test */
  3432. work->pool = NULL;
  3433. while (1) {
  3434. struct timeval tv_workstart, tv_start, tv_end, diff;
  3435. uint64_t max64;
  3436. bool rc;
  3437. if (needs_work) {
  3438. gettimeofday(&tv_workstart, NULL);
  3439. /* obtain new work from internal workio thread */
  3440. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3441. applog(LOG_ERR, "work retrieval failed, exiting "
  3442. "mining thread %d", thr_id);
  3443. goto out;
  3444. }
  3445. needs_work = requested = false;
  3446. total_hashes = 0;
  3447. max_nonce = work->blk.nonce + hashes_done;
  3448. }
  3449. hashes_done = 0;
  3450. gettimeofday(&tv_start, NULL);
  3451. /* scan nonces for a proof-of-work hash */
  3452. switch (opt_algo) {
  3453. case ALGO_C:
  3454. rc = scanhash_c(thr_id, work->midstate, work->data + 64,
  3455. work->hash1, work->hash, work->target,
  3456. max_nonce, &hashes_done,
  3457. work->blk.nonce);
  3458. break;
  3459. #ifdef WANT_X8632_SSE2
  3460. case ALGO_SSE2_32: {
  3461. unsigned int rc5 =
  3462. scanhash_sse2_32(thr_id, work->midstate, work->data + 64,
  3463. work->hash1, work->hash,
  3464. work->target,
  3465. max_nonce, &hashes_done,
  3466. work->blk.nonce);
  3467. rc = (rc5 == -1) ? false : true;
  3468. }
  3469. break;
  3470. #endif
  3471. #ifdef WANT_X8664_SSE2
  3472. case ALGO_SSE2_64: {
  3473. unsigned int rc5 =
  3474. scanhash_sse2_64(thr_id, work->midstate, work->data + 64,
  3475. work->hash1, work->hash,
  3476. work->target,
  3477. max_nonce, &hashes_done,
  3478. work->blk.nonce);
  3479. rc = (rc5 == -1) ? false : true;
  3480. }
  3481. break;
  3482. #endif
  3483. #ifdef WANT_X8664_SSE4
  3484. case ALGO_SSE4_64: {
  3485. unsigned int rc5 =
  3486. scanhash_sse4_64(thr_id, work->midstate, work->data + 64,
  3487. work->hash1, work->hash,
  3488. work->target,
  3489. max_nonce, &hashes_done,
  3490. work->blk.nonce);
  3491. rc = (rc5 == -1) ? false : true;
  3492. }
  3493. break;
  3494. #endif
  3495. #ifdef WANT_SSE2_4WAY
  3496. case ALGO_4WAY: {
  3497. unsigned int rc4 =
  3498. ScanHash_4WaySSE2(thr_id, work->midstate, work->data + 64,
  3499. work->hash1, work->hash,
  3500. work->target,
  3501. max_nonce, &hashes_done,
  3502. work->blk.nonce);
  3503. rc = (rc4 == -1) ? false : true;
  3504. }
  3505. break;
  3506. #endif
  3507. #ifdef WANT_VIA_PADLOCK
  3508. case ALGO_VIA:
  3509. rc = scanhash_via(thr_id, work->data, work->target,
  3510. max_nonce, &hashes_done,
  3511. work->blk.nonce);
  3512. break;
  3513. #endif
  3514. case ALGO_CRYPTOPP:
  3515. rc = scanhash_cryptopp(thr_id, work->midstate, work->data + 64,
  3516. work->hash1, work->hash, work->target,
  3517. max_nonce, &hashes_done,
  3518. work->blk.nonce);
  3519. break;
  3520. #ifdef WANT_CRYPTOPP_ASM32
  3521. case ALGO_CRYPTOPP_ASM32:
  3522. rc = scanhash_asm32(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. #endif
  3528. default:
  3529. /* should never happen */
  3530. goto out;
  3531. }
  3532. /* record scanhash elapsed time */
  3533. gettimeofday(&tv_end, NULL);
  3534. timeval_subtract(&diff, &tv_end, &tv_start);
  3535. hashes_done -= work->blk.nonce;
  3536. hashmeter(thr_id, &diff, hashes_done);
  3537. total_hashes += hashes_done;
  3538. work->blk.nonce += hashes_done;
  3539. /* adjust max_nonce to meet target cycle time */
  3540. if (diff.tv_usec > 500000)
  3541. diff.tv_sec++;
  3542. if (diff.tv_sec && diff.tv_sec != cycle) {
  3543. uint64_t next_inc = ((uint64_t)hashes_done * (uint64_t)cycle) / (uint64_t)diff.tv_sec;
  3544. if (next_inc > (uint64_t)nonce_inc / 2 * 3)
  3545. next_inc = nonce_inc / 2 * 3;
  3546. nonce_inc = next_inc;
  3547. } else if (!diff.tv_sec)
  3548. nonce_inc = hashes_done * 2;
  3549. if (nonce_inc < 4)
  3550. nonce_inc = 0xffffff;
  3551. max64 = work->blk.nonce + nonce_inc;
  3552. if (max64 > 0xfffffffaULL)
  3553. max64 = 0xfffffffaULL;
  3554. max_nonce = max64;
  3555. /* if nonce found, submit work */
  3556. if (unlikely(rc)) {
  3557. if (opt_debug)
  3558. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  3559. if (unlikely(!submit_work_sync(mythr, work))) {
  3560. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  3561. break;
  3562. }
  3563. work->blk.nonce += 4;
  3564. }
  3565. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3566. if (!requested && (diff.tv_sec >= request_interval)) {
  3567. thread_reportout(mythr);
  3568. if (unlikely(!queue_request(mythr, false))) {
  3569. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  3570. goto out;
  3571. }
  3572. thread_reportin(mythr);
  3573. requested = true;
  3574. }
  3575. if (diff.tv_sec > opt_scantime) {
  3576. decay_time(&hash_divfloat , (double)((MAXTHREADS / total_hashes) ? : 1));
  3577. hash_div = hash_divfloat;
  3578. needs_work = true;
  3579. } else if (work_restart[thr_id].restart || stale_work(work) ||
  3580. work->blk.nonce >= MAXTHREADS - hashes_done)
  3581. needs_work = true;
  3582. if (unlikely(mythr->pause)) {
  3583. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3584. mythr->rolling = mythr->cgpu->rolling = 0;
  3585. if (opt_debug)
  3586. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  3587. thread_reportout(mythr);
  3588. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3589. thread_reportin(mythr);
  3590. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3591. }
  3592. }
  3593. out:
  3594. thread_reportin(mythr);
  3595. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3596. tq_freeze(mythr->q);
  3597. return NULL;
  3598. }
  3599. enum {
  3600. STAT_SLEEP_INTERVAL = 1,
  3601. STAT_CTR_INTERVAL = 10000000,
  3602. FAILURE_INTERVAL = 30,
  3603. };
  3604. #ifdef HAVE_OPENCL
  3605. static _clState *clStates[MAX_GPUDEVICES];
  3606. static cl_int queue_poclbm_kernel(_clState *clState, dev_blk_ctx *blk)
  3607. {
  3608. cl_kernel *kernel = &clState->kernel;
  3609. cl_int status = 0;
  3610. int num = 0;
  3611. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  3612. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  3613. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  3614. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  3615. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  3616. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  3617. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  3618. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  3619. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  3620. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3621. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3622. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3623. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3624. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3625. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  3626. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  3627. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  3628. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  3629. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  3630. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  3631. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  3632. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  3633. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  3634. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  3635. (void *)&clState->outputBuffer);
  3636. return status;
  3637. }
  3638. static cl_int queue_phatk_kernel(_clState *clState, dev_blk_ctx *blk)
  3639. {
  3640. cl_uint vwidth = clState->preferred_vwidth;
  3641. cl_kernel *kernel = &clState->kernel;
  3642. cl_int status = 0;
  3643. int i, num = 0;
  3644. uint *nonces;
  3645. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  3646. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  3647. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  3648. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  3649. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  3650. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  3651. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  3652. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  3653. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  3654. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3655. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3656. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3657. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3658. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3659. nonces = alloca(sizeof(uint) * vwidth);
  3660. for (i = 0; i < vwidth; i++)
  3661. nonces[i] = blk->nonce + i;
  3662. status |= clSetKernelArg(*kernel, num++, vwidth * sizeof(uint), (void *)nonces);
  3663. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  3664. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  3665. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4_2);
  3666. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal0);
  3667. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW18);
  3668. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW19);
  3669. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW31);
  3670. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW32);
  3671. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  3672. (void *)&clState->outputBuffer);
  3673. return status;
  3674. }
  3675. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  3676. unsigned int *hashes, size_t *globalThreads,
  3677. unsigned int minthreads, int intensity)
  3678. {
  3679. *threads = 1 << (15 + intensity);
  3680. if (*threads < minthreads)
  3681. *threads = minthreads;
  3682. *globalThreads = *threads;
  3683. *hashes = *threads * vectors;
  3684. }
  3685. static void *gpuminer_thread(void *userdata)
  3686. {
  3687. cl_int (*queue_kernel_parameters)(_clState *, dev_blk_ctx *);
  3688. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  3689. struct timeval tv_start, tv_end, diff, tv_workstart;
  3690. struct thr_info *mythr = userdata;
  3691. const int thr_id = mythr->id;
  3692. uint32_t *res, *blank_res;
  3693. double gpu_ms_average = 7;
  3694. int gpu = dev_from_id(thr_id);
  3695. size_t globalThreads[1];
  3696. size_t localThreads[1];
  3697. cl_int status;
  3698. _clState *clState = clStates[thr_id];
  3699. const cl_kernel *kernel = &clState->kernel;
  3700. struct work *work = make_work();
  3701. unsigned int threads;
  3702. unsigned const int vectors = clState->preferred_vwidth;
  3703. unsigned int hashes;
  3704. unsigned int hashes_done = 0;
  3705. /* Request the next work item at 2/3 of the scantime */
  3706. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3707. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  3708. bool requested = false;
  3709. uint32_t total_hashes = 0, hash_div = 1;
  3710. switch (chosen_kernel) {
  3711. case KL_POCLBM:
  3712. queue_kernel_parameters = &queue_poclbm_kernel;
  3713. break;
  3714. case KL_PHATK:
  3715. default:
  3716. queue_kernel_parameters = &queue_phatk_kernel;
  3717. break;
  3718. }
  3719. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3720. res = calloc(BUFFERSIZE, 1);
  3721. blank_res = calloc(BUFFERSIZE, 1);
  3722. if (!res || !blank_res) {
  3723. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  3724. goto out;
  3725. }
  3726. gettimeofday(&tv_start, NULL);
  3727. localThreads[0] = clState->work_size;
  3728. set_threads_hashes(vectors, &threads, &hashes, &globalThreads[0],
  3729. localThreads[0], gpus[gpu].intensity);
  3730. diff.tv_sec = 0;
  3731. gettimeofday(&tv_end, NULL);
  3732. work->pool = NULL;
  3733. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  3734. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3735. if (unlikely(status != CL_SUCCESS))
  3736. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3737. mythr->cgpu->status = LIFE_WELL;
  3738. if (opt_debug)
  3739. applog(LOG_DEBUG, "Popping ping in gpuminer thread");
  3740. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  3741. gettimeofday(&tv_workstart, NULL);
  3742. /* obtain new work from internal workio thread */
  3743. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3744. applog(LOG_ERR, "work retrieval failed, exiting "
  3745. "gpu mining thread %d", thr_id);
  3746. goto out;
  3747. }
  3748. requested = false;
  3749. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3750. work->blk.nonce = 0;
  3751. while (1) {
  3752. struct timeval tv_gpustart, tv_gpuend;
  3753. suseconds_t gpu_us;
  3754. gettimeofday(&tv_gpustart, NULL);
  3755. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  3756. /* This finish flushes the readbuffer set with CL_FALSE later */
  3757. clFinish(clState->commandQueue);
  3758. gettimeofday(&tv_gpuend, NULL);
  3759. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  3760. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  3761. decay_time(&gpu_ms_average, gpu_us / 1000);
  3762. if (gpus[gpu].dynamic) {
  3763. /* Try to not let the GPU be out for longer than 6ms, but
  3764. * increase intensity when the system is idle, unless
  3765. * dynamic is disabled. */
  3766. if (gpu_ms_average > 7) {
  3767. if (gpus[gpu].intensity > -10)
  3768. gpus[gpu].intensity--;
  3769. } else if (gpu_ms_average < 3) {
  3770. if (gpus[gpu].intensity < 10)
  3771. gpus[gpu].intensity++;
  3772. }
  3773. }
  3774. set_threads_hashes(vectors, &threads, &hashes, globalThreads,
  3775. localThreads[0], gpus[gpu].intensity);
  3776. if (diff.tv_sec > opt_scantime ||
  3777. work->blk.nonce >= MAXTHREADS - hashes ||
  3778. work_restart[thr_id].restart ||
  3779. stale_work(work)) {
  3780. /* Ignore any reads since we're getting new work and queue a clean buffer */
  3781. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3782. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3783. if (unlikely(status != CL_SUCCESS))
  3784. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3785. memset(res, 0, BUFFERSIZE);
  3786. gettimeofday(&tv_workstart, NULL);
  3787. if (opt_debug)
  3788. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  3789. /* obtain new work from internal workio thread */
  3790. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3791. applog(LOG_ERR, "work retrieval failed, exiting "
  3792. "gpu mining thread %d", thr_id);
  3793. goto out;
  3794. }
  3795. requested = false;
  3796. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3797. work_restart[thr_id].restart = 0;
  3798. /* Flushes the writebuffer set with CL_FALSE above */
  3799. clFinish(clState->commandQueue);
  3800. }
  3801. status = queue_kernel_parameters(clState, &work->blk);
  3802. if (unlikely(status != CL_SUCCESS))
  3803. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  3804. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  3805. if (res[FOUND]) {
  3806. /* Clear the buffer again */
  3807. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3808. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3809. if (unlikely(status != CL_SUCCESS))
  3810. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3811. if (opt_debug)
  3812. applog(LOG_DEBUG, "GPU %d found something?", gpu);
  3813. postcalc_hash_async(mythr, work, res);
  3814. memset(res, 0, BUFFERSIZE);
  3815. clFinish(clState->commandQueue);
  3816. }
  3817. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  3818. globalThreads, localThreads, 0, NULL, NULL);
  3819. if (unlikely(status != CL_SUCCESS))
  3820. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  3821. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3822. BUFFERSIZE, res, 0, NULL, NULL);
  3823. if (unlikely(status != CL_SUCCESS))
  3824. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  3825. gettimeofday(&tv_end, NULL);
  3826. timeval_subtract(&diff, &tv_end, &tv_start);
  3827. hashes_done += hashes;
  3828. total_hashes += hashes;
  3829. work->blk.nonce += hashes;
  3830. if (diff.tv_sec >= cycle) {
  3831. hashmeter(thr_id, &diff, hashes_done);
  3832. gettimeofday(&tv_start, NULL);
  3833. hashes_done = 0;
  3834. }
  3835. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3836. if (!requested) {
  3837. #if 0
  3838. if (diff.tv_sec > request_interval)
  3839. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  3840. #endif
  3841. if (diff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  3842. thread_reportout(mythr);
  3843. if (unlikely(!queue_request(mythr, false))) {
  3844. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  3845. goto out;
  3846. }
  3847. thread_reportin(mythr);
  3848. requested = true;
  3849. }
  3850. }
  3851. if (unlikely(!gpu_devices[gpu] || mythr->pause)) {
  3852. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3853. mythr->rolling = mythr->cgpu->rolling = 0;
  3854. if (opt_debug)
  3855. applog(LOG_DEBUG, "Popping wakeup ping in gpuminer thread");
  3856. thread_reportout(mythr);
  3857. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3858. thread_reportin(mythr);
  3859. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3860. }
  3861. }
  3862. out:
  3863. clReleaseCommandQueue(clState->commandQueue);
  3864. clReleaseKernel(clState->kernel);
  3865. clReleaseProgram(clState->program);
  3866. clReleaseContext(clState->context);
  3867. thread_reportin(mythr);
  3868. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3869. tq_freeze(mythr->q);
  3870. return NULL;
  3871. }
  3872. #endif /* HAVE_OPENCL */
  3873. /* Stage another work item from the work returned in a longpoll */
  3874. static void convert_to_work(json_t *val, bool rolltime)
  3875. {
  3876. struct work *work;
  3877. bool rc;
  3878. work = make_work();
  3879. rc= work_decode(json_object_get(val, "result"), work);
  3880. if (unlikely(!rc)) {
  3881. applog(LOG_ERR, "Could not convert longpoll data to work");
  3882. return;
  3883. }
  3884. work->pool = current_pool();
  3885. work->rolltime = rolltime;
  3886. /* We'll be checking this work item twice, but we already know it's
  3887. * from a new block so explicitly force the new block detection now
  3888. * rather than waiting for it to hit the stage thread. This also
  3889. * allows testwork to know whether LP discovered the block or not. */
  3890. test_work_current(work, true);
  3891. if (opt_debug)
  3892. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  3893. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  3894. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  3895. else if (opt_debug)
  3896. applog(LOG_DEBUG, "Converted longpoll data to work");
  3897. }
  3898. static void *longpoll_thread(void *userdata)
  3899. {
  3900. struct thr_info *mythr = userdata;
  3901. CURL *curl = NULL;
  3902. char *copy_start, *hdr_path, *lp_url = NULL;
  3903. bool need_slash = false;
  3904. int failures = 0;
  3905. struct pool *pool = current_pool();
  3906. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3907. pthread_detach(pthread_self());
  3908. curl = curl_easy_init();
  3909. if (unlikely(!curl)) {
  3910. applog(LOG_ERR, "CURL initialisation failed");
  3911. goto out;
  3912. }
  3913. tq_pop(mythr->q, NULL);
  3914. if (!pool->hdr_path) {
  3915. applog(LOG_NOTICE, "No long-poll found on this server");
  3916. goto out;
  3917. }
  3918. hdr_path = pool->hdr_path;
  3919. /* full URL */
  3920. if (strstr(hdr_path, "://")) {
  3921. lp_url = hdr_path;
  3922. hdr_path = NULL;
  3923. }
  3924. /* absolute path, on current server */
  3925. else {
  3926. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3927. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3928. need_slash = true;
  3929. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3930. if (!lp_url)
  3931. goto out;
  3932. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3933. }
  3934. have_longpoll = true;
  3935. applog(LOG_NOTICE, "Long-polling activated for %s", lp_url);
  3936. while (1) {
  3937. struct timeval start, end;
  3938. bool rolltime;
  3939. json_t *val;
  3940. gettimeofday(&start, NULL);
  3941. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  3942. false, true, &rolltime, pool);
  3943. if (likely(val)) {
  3944. convert_to_work(val, rolltime);
  3945. failures = 0;
  3946. json_decref(val);
  3947. } else {
  3948. /* Some pools regularly drop the longpoll request so
  3949. * only see this as longpoll failure if it happens
  3950. * immediately and just restart it the rest of the
  3951. * time. */
  3952. gettimeofday(&end, NULL);
  3953. if (end.tv_sec - start.tv_sec > 30)
  3954. continue;
  3955. if (opt_retries == -1 || failures++ < opt_retries) {
  3956. sleep(30);
  3957. applog(LOG_WARNING,
  3958. "longpoll failed for %s, sleeping for 30s", lp_url);
  3959. } else {
  3960. applog(LOG_ERR,
  3961. "longpoll failed for %s, ending thread", lp_url);
  3962. goto out;
  3963. }
  3964. }
  3965. }
  3966. out:
  3967. have_longpoll = false;
  3968. tq_freeze(mythr->q);
  3969. if (curl)
  3970. curl_easy_cleanup(curl);
  3971. return NULL;
  3972. }
  3973. static void stop_longpoll(void)
  3974. {
  3975. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3976. thr_info_cancel(thr);
  3977. have_longpoll = false;
  3978. }
  3979. static void start_longpoll(void)
  3980. {
  3981. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3982. tq_thaw(thr->q);
  3983. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  3984. quit(1, "longpoll thread create failed");
  3985. if (opt_debug)
  3986. applog(LOG_DEBUG, "Pushing ping to longpoll thread");
  3987. tq_push(thr_info[longpoll_thr_id].q, &ping);
  3988. }
  3989. static void restart_longpoll(void)
  3990. {
  3991. if (want_longpoll && have_longpoll)
  3992. return;
  3993. stop_longpoll();
  3994. if (want_longpoll)
  3995. start_longpoll();
  3996. }
  3997. static void *reinit_cpu(void *userdata)
  3998. {
  3999. pthread_detach(pthread_self());
  4000. #if 0
  4001. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  4002. int cpu = cgpu->cpu_gpu;
  4003. long thr_id = ....(long)userdata;
  4004. struct thr_info *thr = &thr_info[thr_id];
  4005. int cpu = dev_from_id(thr_id);
  4006. cpus[cpu].alive = false;
  4007. thr->rolling = thr->cgpu->rolling = 0;
  4008. tq_freeze(thr->q);
  4009. if (!pthread_cancel(*thr->pth))
  4010. pthread_join(*thr->pth, NULL);
  4011. free(thr->q);
  4012. thr->q = tq_new();
  4013. if (!thr->q)
  4014. quit(1, "Failed to tq_new in reinit_cputhread");
  4015. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  4016. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  4017. applog(LOG_ERR, "thread %d create failed", thr_id);
  4018. return NULL;
  4019. }
  4020. tq_push(thr->q, &ping);
  4021. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  4022. #endif
  4023. return NULL;
  4024. }
  4025. #ifdef HAVE_OPENCL
  4026. /* We have only one thread that ever re-initialises GPUs, thus if any GPU
  4027. * init command fails due to a completely wedged GPU, the thread will never
  4028. * return, unable to harm other GPUs. If it does return, it means we only had
  4029. * a soft failure and then the reinit_gpu thread is ready to tackle another
  4030. * GPU */
  4031. static void *reinit_gpu(void *userdata)
  4032. {
  4033. struct thr_info *mythr = userdata;
  4034. struct cgpu_info *cgpu;
  4035. struct thr_info *thr;
  4036. struct timeval now;
  4037. char name[256];
  4038. int thr_id;
  4039. int gpu;
  4040. pthread_detach(pthread_self());
  4041. select_cgpu:
  4042. cgpu = tq_pop(mythr->q, NULL);
  4043. if (!cgpu)
  4044. goto out;
  4045. if (clDevicesNum() != nDevs) {
  4046. applog(LOG_WARNING, "Hardware not reporting same number of active devices, will not attempt to restart GPU");
  4047. goto out;
  4048. }
  4049. gpu = cgpu->cpu_gpu;
  4050. gpu_devices[gpu] = false;
  4051. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  4052. if (dev_from_id(thr_id) != gpu)
  4053. continue;
  4054. thr = &thr_info[thr_id];
  4055. if (!thr) {
  4056. applog(LOG_WARNING, "No reference to thread %d exists", thr_id);
  4057. continue;
  4058. }
  4059. thr->rolling = thr->cgpu->rolling = 0;
  4060. /* Reports the last time we tried to revive a sick GPU */
  4061. gettimeofday(&thr->sick, NULL);
  4062. if (!pthread_cancel(thr->pth)) {
  4063. applog(LOG_WARNING, "Thread %d still exists, killing it off", thr_id);
  4064. } else
  4065. applog(LOG_WARNING, "Thread %d no longer exists", thr_id);
  4066. }
  4067. gpu_devices[gpu] = true;
  4068. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  4069. if (dev_from_id(thr_id) != gpu)
  4070. continue;
  4071. thr = &thr_info[thr_id];
  4072. /* Lose this ram cause we may get stuck here! */
  4073. //tq_freeze(thr->q);
  4074. thr->q = tq_new();
  4075. if (!thr->q)
  4076. quit(1, "Failed to tq_new in reinit_gpu");
  4077. /* Lose this ram cause we may dereference in the dying thread! */
  4078. //free(clState);
  4079. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  4080. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  4081. if (!clStates[thr_id]) {
  4082. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  4083. goto select_cgpu;
  4084. }
  4085. applog(LOG_INFO, "initCl() finished. Found %s", name);
  4086. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  4087. applog(LOG_ERR, "thread %d create failed", thr_id);
  4088. return NULL;
  4089. }
  4090. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  4091. }
  4092. gettimeofday(&now, NULL);
  4093. get_datestamp(cgpu->init, &now);
  4094. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  4095. if (dev_from_id(thr_id) != gpu)
  4096. continue;
  4097. thr = &thr_info[thr_id];
  4098. tq_push(thr->q, &ping);
  4099. }
  4100. goto select_cgpu;
  4101. out:
  4102. return NULL;
  4103. }
  4104. #else
  4105. static void *reinit_gpu(void *userdata)
  4106. {
  4107. }
  4108. #endif
  4109. static void reinit_device(struct cgpu_info *cgpu)
  4110. {
  4111. if (cgpu->is_gpu)
  4112. tq_push(thr_info[gpur_thr_id].q, cgpu);
  4113. else
  4114. tq_push(thr_info[cpur_thr_id].q, cgpu);
  4115. }
  4116. /* Determine which are the first threads belonging to a device and if they're
  4117. * active */
  4118. static bool active_device(int thr_id)
  4119. {
  4120. if (thr_id < gpu_threads) {
  4121. if (thr_id >= total_devices)
  4122. return false;
  4123. if (!gpu_devices[dev_from_id(thr_id)])
  4124. return false;
  4125. } else if (thr_id > gpu_threads + num_processors)
  4126. return false;
  4127. return true;
  4128. }
  4129. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  4130. * the screen at regular intervals, and restarts threads if they appear to have
  4131. * died. */
  4132. static void *watchdog_thread(void *userdata)
  4133. {
  4134. const unsigned int interval = 3;
  4135. static struct timeval rotate_tv;
  4136. struct timeval zero_tv;
  4137. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4138. memset(&zero_tv, 0, sizeof(struct timeval));
  4139. gettimeofday(&rotate_tv, NULL);
  4140. while (1) {
  4141. int i;
  4142. struct timeval now;
  4143. sleep(interval);
  4144. if (requests_queued() < opt_queue)
  4145. queue_request(NULL, false);
  4146. hashmeter(-1, &zero_tv, 0);
  4147. if (curses_active_locked()) {
  4148. change_logwinsize();
  4149. curses_print_status();
  4150. for (i = 0; i < mining_threads; i++)
  4151. curses_print_devstatus(i);
  4152. clearok(statuswin, true);
  4153. doupdate();
  4154. unlock_curses();
  4155. }
  4156. gettimeofday(&now, NULL);
  4157. for (i = 0; i < total_pools; i++) {
  4158. struct pool *pool = pools[i];
  4159. if (!pool->enabled)
  4160. continue;
  4161. /* Test pool is idle once every minute */
  4162. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  4163. gettimeofday(&pool->tv_idle, NULL);
  4164. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  4165. pool_resus(pool);
  4166. }
  4167. }
  4168. if (opt_donation > 0.0) {
  4169. if (donationpool.idle && now.tv_sec - donationpool.tv_idle.tv_sec > 60) {
  4170. gettimeofday(&donationpool.tv_idle, NULL);
  4171. if (pool_active(&donationpool, true) && pool_tclear(&donationpool, &donationpool.idle))
  4172. pool_resus(&donationpool);
  4173. }
  4174. }
  4175. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  4176. gettimeofday(&rotate_tv, NULL);
  4177. switch_pools(NULL);
  4178. }
  4179. if (!sched_paused && !should_run()) {
  4180. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  4181. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4182. if (!schedstart.enable) {
  4183. quit(0, "Terminating execution as planned");
  4184. break;
  4185. }
  4186. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  4187. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4188. sched_paused = true;
  4189. for (i = 0; i < mining_threads; i++) {
  4190. struct thr_info *thr;
  4191. thr = &thr_info[i];
  4192. thr->pause = true;
  4193. }
  4194. } else if (sched_paused && should_run()) {
  4195. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  4196. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4197. if (schedstop.enable)
  4198. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  4199. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4200. sched_paused = false;
  4201. for (i = 0; i < mining_threads; i++) {
  4202. struct thr_info *thr;
  4203. thr = &thr_info[i];
  4204. /* Don't touch disabled GPUs */
  4205. if (thr->cgpu->is_gpu && !gpu_devices[thr->cgpu->cpu_gpu])
  4206. continue;
  4207. thr->pause = false;
  4208. tq_push(thr->q, &ping);
  4209. }
  4210. }
  4211. for (i = 0; i < gpu_threads; i++) {
  4212. struct thr_info *thr;
  4213. bool *enable;
  4214. int gpu;
  4215. /* Use only one thread per device to determine if the GPU is healthy */
  4216. if (i >= nDevs)
  4217. break;
  4218. thr = &thr_info[i];
  4219. gpu = thr->cgpu->cpu_gpu;
  4220. enable = &gpu_devices[gpu];
  4221. #ifdef HAVE_ADL
  4222. if (adl_active && gpus[gpu].has_adl && *enable)
  4223. gpu_autotune(gpu, enable);
  4224. if (opt_debug && gpus[gpu].has_adl) {
  4225. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  4226. float temp = 0, vddc = 0;
  4227. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  4228. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  4229. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  4230. }
  4231. #endif
  4232. /* Thread is waiting on getwork or disabled */
  4233. if (thr->getwork || !*enable)
  4234. continue;
  4235. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  4236. applog(LOG_ERR, "Thread %d recovered, GPU %d declared WELL!", i, gpu);
  4237. gpus[gpu].status = LIFE_WELL;
  4238. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  4239. thr->rolling = thr->cgpu->rolling = 0;
  4240. gpus[gpu].status = LIFE_SICK;
  4241. applog(LOG_ERR, "Thread %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  4242. gettimeofday(&thr->sick, NULL);
  4243. if (opt_restart) {
  4244. applog(LOG_ERR, "Attempting to restart GPU");
  4245. reinit_device(thr->cgpu);
  4246. }
  4247. } else if (now.tv_sec - thr->last.tv_sec > 600 && gpus[i].status == LIFE_SICK) {
  4248. gpus[gpu].status = LIFE_DEAD;
  4249. applog(LOG_ERR, "Thread %d not responding for more than 10 minutes, GPU %d declared DEAD!", i, gpu);
  4250. } else if (now.tv_sec - thr->sick.tv_sec > 60 && gpus[i].status == LIFE_SICK) {
  4251. /* Attempt to restart a GPU once every minute */
  4252. gettimeofday(&thr->sick, NULL);
  4253. if (opt_restart)
  4254. reinit_device(thr->cgpu);
  4255. }
  4256. }
  4257. }
  4258. return NULL;
  4259. }
  4260. static void log_print_status(int thr_id)
  4261. {
  4262. struct cgpu_info *cgpu;
  4263. char logline[255];
  4264. cgpu = thr_info[thr_id].cgpu;
  4265. get_statline(logline, cgpu);
  4266. applog(LOG_WARNING, "%s", logline);
  4267. }
  4268. static void print_summary(void)
  4269. {
  4270. struct timeval diff;
  4271. int hours, mins, secs, i;
  4272. double utility, efficiency = 0.0;
  4273. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  4274. hours = diff.tv_sec / 3600;
  4275. mins = (diff.tv_sec % 3600) / 60;
  4276. secs = diff.tv_sec % 60;
  4277. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  4278. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4279. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  4280. applog(LOG_WARNING, "Started at %s", datestamp);
  4281. if (opt_n_threads)
  4282. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  4283. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  4284. if (total_secs)
  4285. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  4286. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  4287. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  4288. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  4289. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  4290. if (total_accepted || total_rejected)
  4291. applog(LOG_WARNING, "Reject ratio: %.1f", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  4292. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  4293. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  4294. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  4295. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  4296. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  4297. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  4298. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  4299. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  4300. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  4301. if (total_pools > 1) {
  4302. for (i = 0; i < total_pools; i++) {
  4303. struct pool *pool = pools[i];
  4304. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  4305. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  4306. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  4307. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  4308. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  4309. if (pool->accepted || pool->rejected)
  4310. applog(LOG_WARNING, " Reject ratio: %.1f", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4311. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  4312. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  4313. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  4314. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  4315. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  4316. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  4317. }
  4318. }
  4319. if (opt_donation > 0.0)
  4320. applog(LOG_WARNING, "Donated share submissions: %d\n", donationpool.accepted + donationpool.rejected);
  4321. applog(LOG_WARNING, "Summary of per device statistics:\n");
  4322. for (i = 0; i < mining_threads; i++) {
  4323. if (active_device(i))
  4324. log_print_status(i);
  4325. }
  4326. if (opt_shares)
  4327. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  4328. fflush(stdout);
  4329. fflush(stderr);
  4330. if (opt_shares > total_accepted)
  4331. quit(1, "Did not successfully mine as many shares as were requested.");
  4332. }
  4333. void quit(int status, const char *format, ...)
  4334. {
  4335. va_list ap;
  4336. disable_curses();
  4337. if (!opt_realquiet && successful_connect)
  4338. print_summary();
  4339. if (format) {
  4340. va_start(ap, format);
  4341. vfprintf(stderr, format, ap);
  4342. va_end(ap);
  4343. }
  4344. fprintf(stderr, "\n");
  4345. fflush(stderr);
  4346. exit(status);
  4347. }
  4348. char *curses_input(const char *query)
  4349. {
  4350. char *input;
  4351. echo();
  4352. input = malloc(255);
  4353. if (!input)
  4354. quit(1, "Failed to malloc input");
  4355. leaveok(logwin, false);
  4356. wlogprint("%s:\n", query);
  4357. wgetnstr(logwin, input, 255);
  4358. if (!strlen(input))
  4359. strcpy(input, "-1");
  4360. leaveok(logwin, true);
  4361. noecho();
  4362. return input;
  4363. }
  4364. static bool input_pool(bool live)
  4365. {
  4366. char *url = NULL, *user = NULL, *pass = NULL;
  4367. struct pool *pool = NULL;
  4368. bool ret = false;
  4369. immedok(logwin, true);
  4370. if (total_pools == MAX_POOLS) {
  4371. wlogprint("Reached maximum number of pools.\n");
  4372. goto out;
  4373. }
  4374. wlogprint("Input server details.\n");
  4375. url = curses_input("URL");
  4376. if (!url)
  4377. goto out;
  4378. if (strncmp(url, "http://", 7) &&
  4379. strncmp(url, "https://", 8)) {
  4380. char *httpinput;
  4381. httpinput = malloc(255);
  4382. if (!httpinput)
  4383. quit(1, "Failed to malloc httpinput");
  4384. strcpy(httpinput, "http://");
  4385. strncat(httpinput, url, 248);
  4386. free(url);
  4387. url = httpinput;
  4388. }
  4389. user = curses_input("Username");
  4390. if (!user)
  4391. goto out;
  4392. pass = curses_input("Password");
  4393. if (!pass)
  4394. goto out;
  4395. pool = calloc(sizeof(struct pool), 1);
  4396. if (!pool)
  4397. quit(1, "Failed to realloc pools in input_pool");
  4398. pool->pool_no = total_pools;
  4399. pool->prio = total_pools;
  4400. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  4401. quit (1, "Failed to pthread_mutex_init in input_pool");
  4402. pool->rpc_url = url;
  4403. pool->rpc_user = user;
  4404. pool->rpc_pass = pass;
  4405. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4406. if (!pool->rpc_userpass)
  4407. quit(1, "Failed to malloc userpass");
  4408. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4409. pool->tv_idle.tv_sec = ~0UL;
  4410. /* Test the pool is not idle if we're live running, otherwise
  4411. * it will be tested separately */
  4412. ret = true;
  4413. pool->enabled = true;
  4414. if (live && !pool_active(pool, false))
  4415. pool->idle = true;
  4416. pools[total_pools++] = pool;
  4417. out:
  4418. immedok(logwin, false);
  4419. if (!ret) {
  4420. if (url)
  4421. free(url);
  4422. if (user)
  4423. free(user);
  4424. if (pass)
  4425. free(pass);
  4426. if (pool)
  4427. free(pool);
  4428. }
  4429. return ret;
  4430. }
  4431. #if defined(unix)
  4432. static void fork_monitor()
  4433. {
  4434. // Make a pipe: [readFD, writeFD]
  4435. int pfd[2];
  4436. int r = pipe(pfd);
  4437. if (r<0) {
  4438. perror("pipe - failed to create pipe for --monitor");
  4439. exit(1);
  4440. }
  4441. // Make stderr write end of pipe
  4442. fflush(stderr);
  4443. r = dup2(pfd[1], 2);
  4444. if (r<0) {
  4445. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  4446. exit(1);
  4447. }
  4448. r = close(pfd[1]);
  4449. if (r<0) {
  4450. perror("close - failed to close write end of pipe for --monitor");
  4451. exit(1);
  4452. }
  4453. // Don't allow a dying monitor to kill the main process
  4454. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  4455. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  4456. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  4457. perror("signal - failed to edit signal mask for --monitor");
  4458. exit(1);
  4459. }
  4460. // Fork a child process
  4461. r = fork();
  4462. if (r<0) {
  4463. perror("fork - failed to fork child process for --monitor");
  4464. exit(1);
  4465. }
  4466. // Child: launch monitor command
  4467. if (0==r) {
  4468. // Make stdin read end of pipe
  4469. r = dup2(pfd[0], 0);
  4470. if (r<0) {
  4471. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  4472. exit(1);
  4473. }
  4474. close(pfd[0]);
  4475. if (r<0) {
  4476. perror("close - in child, failed to close read end of pipe for --monitor");
  4477. exit(1);
  4478. }
  4479. // Launch user specified command
  4480. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  4481. perror("execl - in child failed to exec user specified command for --monitor");
  4482. exit(1);
  4483. }
  4484. // Parent: clean up unused fds and bail
  4485. r = close(pfd[0]);
  4486. if (r<0) {
  4487. perror("close - failed to close read end of pipe for --monitor");
  4488. exit(1);
  4489. }
  4490. }
  4491. #endif // defined(unix)
  4492. static void enable_curses(void) {
  4493. int x,y;
  4494. lock_curses();
  4495. if (curses_active) {
  4496. unlock_curses();
  4497. return;
  4498. }
  4499. mainwin = initscr();
  4500. getmaxyx(mainwin, y, x);
  4501. statuswin = newwin(logstart, x, 0, 0);
  4502. leaveok(statuswin, true);
  4503. logwin = newwin(y - logcursor, 0, logcursor, 0);
  4504. idlok(logwin, true);
  4505. scrollok(logwin, true);
  4506. leaveok(logwin, true);
  4507. cbreak();
  4508. noecho();
  4509. curses_active = true;
  4510. unlock_curses();
  4511. }
  4512. int main (int argc, char *argv[])
  4513. {
  4514. unsigned int i, pools_active = 0;
  4515. struct block *block, *tmpblock;
  4516. struct work *work, *tmpwork;
  4517. struct sigaction handler;
  4518. struct thr_info *thr;
  4519. char name[256];
  4520. /* This dangerous functions tramples random dynamically allocated
  4521. * variables so do it before anything at all */
  4522. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  4523. quit(1, "Failed to curl_global_init");
  4524. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  4525. quit(1, "Failed to pthread_mutex_init");
  4526. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  4527. quit(1, "Failed to pthread_mutex_init");
  4528. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  4529. quit(1, "Failed to pthread_mutex_init");
  4530. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  4531. quit(1, "Failed to pthread_mutex_init");
  4532. if (unlikely(pthread_rwlock_init(&blk_lock, NULL)))
  4533. quit(1, "Failed to pthread_rwlock_init");
  4534. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  4535. init_max_name_len();
  4536. handler.sa_handler = &sighandler;
  4537. handler.sa_flags = 0;
  4538. sigemptyset(&handler.sa_mask);
  4539. sigaction(SIGTERM, &handler, &termhandler);
  4540. sigaction(SIGINT, &handler, &inthandler);
  4541. opt_kernel_path = alloca(PATH_MAX);
  4542. strcpy(opt_kernel_path, CGMINER_PREFIX);
  4543. cgminer_path = alloca(PATH_MAX);
  4544. strcpy(cgminer_path, dirname(argv[0]));
  4545. strcat(cgminer_path, "/");
  4546. // Hack to make cgminer silent when called recursively on WIN32
  4547. int skip_to_bench = 0;
  4548. #if defined(WIN32)
  4549. char buf[32];
  4550. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  4551. skip_to_bench = 1;
  4552. #endif // defined(WIN32)
  4553. block = calloc(sizeof(struct block), 1);
  4554. if (unlikely(!block))
  4555. quit (1, "main OOM");
  4556. for (i = 0; i < 36; i++)
  4557. strcat(block->hash, "0");
  4558. HASH_ADD_STR(blocks, hash, block);
  4559. strcpy(current_block, block->hash);
  4560. // Reckon number of cores in the box
  4561. #if defined(WIN32)
  4562. DWORD system_am;
  4563. DWORD process_am;
  4564. BOOL ok = GetProcessAffinityMask(
  4565. GetCurrentProcess(),
  4566. &system_am,
  4567. &process_am
  4568. );
  4569. if (!ok) {
  4570. applog(LOG_ERR, "couldn't figure out number of processors :(");
  4571. num_processors = 1;
  4572. } else {
  4573. size_t n = 32;
  4574. num_processors = 0;
  4575. while (n--)
  4576. if (process_am & (1<<n))
  4577. ++num_processors;
  4578. }
  4579. #else
  4580. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  4581. #endif /* !WIN32 */
  4582. opt_n_threads = num_processors;
  4583. #ifdef HAVE_OPENCL
  4584. if (!skip_to_bench) {
  4585. for (i = 0; i < MAX_GPUDEVICES; i++) {
  4586. gpu_devices[i] = false;
  4587. gpus[i].dynamic = true;
  4588. }
  4589. nDevs = clDevicesNum();
  4590. if (nDevs < 0) {
  4591. applog(LOG_ERR, "clDevicesNum returned error, none usable");
  4592. nDevs = 0;
  4593. }
  4594. }
  4595. #endif
  4596. /* parse command line */
  4597. opt_register_table(opt_config_table,
  4598. "Options for both config file and command line");
  4599. opt_register_table(opt_cmdline_table,
  4600. "Options for command line only");
  4601. opt_parse(&argc, argv, applog_and_exit);
  4602. if (argc != 1)
  4603. quit(1, "Unexpected extra commandline arguments");
  4604. applog(LOG_WARNING, "Started %s", packagename);
  4605. if (opt_nogpu)
  4606. nDevs = 0;
  4607. if (nDevs && !opt_usecpu)
  4608. opt_n_threads = 0;
  4609. strcat(opt_kernel_path, "/");
  4610. if (want_per_device_stats)
  4611. opt_log_output = true;
  4612. if (0<=opt_bench_algo) {
  4613. double rate = bench_algo_stage3(opt_bench_algo);
  4614. if (!skip_to_bench) {
  4615. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  4616. } else {
  4617. // Write result to shared memory for parent
  4618. #if defined(WIN32)
  4619. char unique_name[64];
  4620. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  4621. HANDLE map_handle = CreateFileMapping(
  4622. INVALID_HANDLE_VALUE, // use paging file
  4623. NULL, // default security attributes
  4624. PAGE_READWRITE, // read/write access
  4625. 0, // size: high 32-bits
  4626. 4096, // size: low 32-bits
  4627. unique_name // name of map object
  4628. );
  4629. if (NULL!=map_handle) {
  4630. void *shared_mem = MapViewOfFile(
  4631. map_handle, // object to map view of
  4632. FILE_MAP_WRITE, // read/write access
  4633. 0, // high offset: map from
  4634. 0, // low offset: beginning
  4635. 0 // default: map entire file
  4636. );
  4637. if (NULL!=shared_mem)
  4638. CopyMemory(shared_mem, &rate, sizeof(rate));
  4639. (void)UnmapViewOfFile(shared_mem);
  4640. }
  4641. (void)CloseHandle(map_handle);
  4642. }
  4643. #endif
  4644. }
  4645. exit(0);
  4646. }
  4647. if (opt_kernel) {
  4648. if (strcmp(opt_kernel, "poclbm") && strcmp(opt_kernel, "phatk"))
  4649. quit(1, "Invalid kernel name specified - must be poclbm or phatk");
  4650. if (!strcmp(opt_kernel, "poclbm"))
  4651. chosen_kernel = KL_POCLBM;
  4652. else
  4653. chosen_kernel = KL_PHATK;
  4654. } else
  4655. chosen_kernel = KL_NONE;
  4656. #ifdef HAVE_OPENCL
  4657. gpu_threads = nDevs * opt_g_threads;
  4658. if (total_devices) {
  4659. if (total_devices > nDevs)
  4660. quit(1, "More devices specified than exist");
  4661. for (i = 0; i < MAX_GPUDEVICES; i++)
  4662. if (gpu_devices[i] && i + 1 > nDevs)
  4663. quit (1, "Command line options set a device that doesn't exist");
  4664. for (i = 0; i < nDevs; i++) {
  4665. /* Make sure we do not attempt to adl manage devices
  4666. * that we disable */
  4667. if (!gpu_devices[i])
  4668. gpus[i].gpu_engine =
  4669. gpus[i].gpu_memclock =
  4670. gpus[i].gpu_vddc =
  4671. gpus[i].gpu_fan =
  4672. gpus[i].gpu_powertune = 0;
  4673. }
  4674. } else {
  4675. for (i = 0; i < nDevs; i++)
  4676. gpu_devices[i] = true;
  4677. total_devices = nDevs;
  4678. }
  4679. #else
  4680. gpu_threads = 0;
  4681. #endif
  4682. if (!gpu_threads && !forced_n_threads) {
  4683. /* Maybe they turned GPU off; restore default CPU threads. */
  4684. opt_n_threads = num_processors;
  4685. }
  4686. if (!opt_n_threads && ! gpu_threads)
  4687. quit(1, "All devices disabled, cannot mine!");
  4688. logcursor = 8;
  4689. gpucursor = logcursor;
  4690. cpucursor = gpucursor + nDevs;
  4691. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  4692. logcursor = logstart + 1;
  4693. if (opt_realquiet)
  4694. use_curses = false;
  4695. if (!total_pools) {
  4696. enable_curses();
  4697. applog(LOG_WARNING, "Need to specify at least one pool server.");
  4698. if (!input_pool(false))
  4699. quit(1, "Pool setup failed");
  4700. if (!use_curses)
  4701. disable_curses();
  4702. }
  4703. for (i = 0; i < total_pools; i++) {
  4704. struct pool *pool = pools[i];
  4705. if (!pool->rpc_userpass) {
  4706. if (!pool->rpc_user || !pool->rpc_pass)
  4707. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  4708. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4709. if (!pool->rpc_userpass)
  4710. quit(1, "Failed to malloc userpass");
  4711. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4712. } else {
  4713. pool->rpc_user = malloc(strlen(pool->rpc_userpass) + 1);
  4714. if (!pool->rpc_user)
  4715. quit(1, "Failed to malloc user");
  4716. strcpy(pool->rpc_user, pool->rpc_userpass);
  4717. pool->rpc_user = strtok(pool->rpc_user, ":");
  4718. if (!pool->rpc_user)
  4719. quit(1, "Failed to find colon delimiter in userpass");
  4720. }
  4721. }
  4722. /* Set the currentpool to pool 0 */
  4723. currentpool = pools[0];
  4724. #ifdef HAVE_SYSLOG_H
  4725. if (use_syslog)
  4726. openlog(PACKAGE, LOG_PID, LOG_USER);
  4727. #endif
  4728. #if defined(unix)
  4729. if (opt_stderr_cmd)
  4730. fork_monitor();
  4731. #endif // defined(unix)
  4732. mining_threads = opt_n_threads + gpu_threads;
  4733. total_threads = mining_threads + 7;
  4734. work_restart = calloc(total_threads, sizeof(*work_restart));
  4735. if (!work_restart)
  4736. quit(1, "Failed to calloc work_restart");
  4737. thr_info = calloc(total_threads, sizeof(*thr));
  4738. if (!thr_info)
  4739. quit(1, "Failed to calloc thr_info");
  4740. /* init workio thread info */
  4741. work_thr_id = mining_threads;
  4742. thr = &thr_info[work_thr_id];
  4743. thr->id = work_thr_id;
  4744. thr->q = tq_new();
  4745. if (!thr->q)
  4746. quit(1, "Failed to tq_new");
  4747. /* start work I/O thread */
  4748. if (thr_info_create(thr, NULL, workio_thread, thr))
  4749. quit(1, "workio thread create failed");
  4750. /* init longpoll thread info */
  4751. longpoll_thr_id = mining_threads + 1;
  4752. thr = &thr_info[longpoll_thr_id];
  4753. thr->id = longpoll_thr_id;
  4754. thr->q = tq_new();
  4755. if (!thr->q)
  4756. quit(1, "Failed to tq_new");
  4757. if (opt_n_threads ) {
  4758. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  4759. if (unlikely(!cpus))
  4760. quit(1, "Failed to calloc cpus");
  4761. }
  4762. stage_thr_id = mining_threads + 3;
  4763. thr = &thr_info[stage_thr_id];
  4764. thr->q = tq_new();
  4765. if (!thr->q)
  4766. quit(1, "Failed to tq_new");
  4767. /* start stage thread */
  4768. if (thr_info_create(thr, NULL, stage_thread, thr))
  4769. quit(1, "stage thread create failed");
  4770. pthread_detach(thr->pth);
  4771. /* Create a unique get work queue */
  4772. getq = tq_new();
  4773. if (!getq)
  4774. quit(1, "Failed to create getq");
  4775. /* We use the getq mutex as the staged lock */
  4776. stgd_lock = &getq->mutex;
  4777. /* Test each pool to see if we can retrieve and use work and for what
  4778. * it supports */
  4779. for (i = 0; i < total_pools; i++) {
  4780. struct pool *pool;
  4781. pool = pools[i];
  4782. pool->enabled = true;
  4783. if (pool_active(pool, false)) {
  4784. if (!currentpool)
  4785. currentpool = pool;
  4786. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  4787. pools_active++;
  4788. } else {
  4789. if (pool == currentpool)
  4790. currentpool = NULL;
  4791. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  4792. pool->idle = true;
  4793. }
  4794. }
  4795. if (!pools_active) {
  4796. enable_curses();
  4797. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  4798. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  4799. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  4800. for (i = 0; i < total_pools; i++) {
  4801. struct pool *pool;
  4802. pool = pools[i];
  4803. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  4804. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  4805. }
  4806. curses_input("Press enter to exit");
  4807. quit(0, "No servers could be used! Exiting.");
  4808. }
  4809. if (opt_donation > 0.0) {
  4810. if (!get_dondata(&donationpool.rpc_url, &donationpool.rpc_userpass))
  4811. opt_donation = 0.0;
  4812. else {
  4813. donationpool.enabled = true;
  4814. donationpool.pool_no = MAX_POOLS;
  4815. if (!pool_active(&donationpool, false))
  4816. donationpool.idle = true;
  4817. }
  4818. }
  4819. /* If we want longpoll, enable it for the chosen default pool, or, if
  4820. * the pool does not support longpoll, find the first one that does
  4821. * and use its longpoll support */
  4822. if (want_longpoll) {
  4823. if (currentpool->hdr_path)
  4824. start_longpoll();
  4825. else {
  4826. for (i = 0; i < total_pools; i++) {
  4827. struct pool *pool;
  4828. pool = pools[i];
  4829. if (pool->hdr_path) {
  4830. struct pool *temp = currentpool;
  4831. currentpool = pool;
  4832. start_longpoll();
  4833. /* Not real blocking, but good enough */
  4834. sleep(1);
  4835. currentpool = temp;
  4836. break;
  4837. }
  4838. }
  4839. }
  4840. }
  4841. gettimeofday(&total_tv_start, NULL);
  4842. gettimeofday(&total_tv_end, NULL);
  4843. get_datestamp(datestamp, &total_tv_start);
  4844. #ifdef HAVE_OPENCL
  4845. if (!opt_noadl)
  4846. init_adl(nDevs);
  4847. bool failmessage = false;
  4848. /* start GPU mining threads */
  4849. for (i = 0; i < nDevs * opt_g_threads; i++) {
  4850. int gpu = i % nDevs;
  4851. struct cgpu_info *cgpu;
  4852. struct timeval now;
  4853. gpus[gpu].is_gpu = 1;
  4854. gpus[gpu].cpu_gpu = gpu;
  4855. thr = &thr_info[i];
  4856. thr->id = i;
  4857. cgpu = thr->cgpu = &gpus[gpu];
  4858. thr->q = tq_new();
  4859. if (!thr->q)
  4860. quit(1, "tq_new failed in starting gpu mining threads");
  4861. /* Enable threads for devices set not to mine but disable
  4862. * their queue in case we wish to enable them later*/
  4863. if (gpu_devices[gpu]) {
  4864. if (opt_debug)
  4865. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  4866. tq_push(thr->q, &ping);
  4867. }
  4868. applog(LOG_INFO, "Init GPU thread %i", i);
  4869. clStates[i] = initCl(gpu, name, sizeof(name));
  4870. if (!clStates[i]) {
  4871. enable_curses();
  4872. applog(LOG_ERR, "Failed to init GPU thread %d, disabling device %d", i, gpu);
  4873. if (!failmessage) {
  4874. char *buf;
  4875. applog(LOG_ERR, "The most common reason for this failure is cgminer being unable to read the kernel .cl files");
  4876. applog(LOG_ERR, "Alternatively if it has failed on different GPUs, restarting might help.");
  4877. failmessage = true;
  4878. buf = curses_input("Press enter to continue");
  4879. if (buf)
  4880. free(buf);
  4881. }
  4882. gpu_devices[gpu] = false;
  4883. cgpu->status = LIFE_NOSTART;
  4884. continue;
  4885. }
  4886. applog(LOG_INFO, "initCl() finished. Found %s", name);
  4887. gettimeofday(&now, NULL);
  4888. get_datestamp(cgpu->init, &now);
  4889. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  4890. quit(1, "thread %d create failed", i);
  4891. }
  4892. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  4893. #else
  4894. opt_g_threads = 0;
  4895. #endif
  4896. /* start CPU mining threads */
  4897. for (i = gpu_threads; i < mining_threads; i++) {
  4898. int cpu = (i - gpu_threads) % num_processors;
  4899. thr = &thr_info[i];
  4900. thr->id = i;
  4901. cpus[cpu].cpu_gpu = cpu;
  4902. thr->cgpu = &cpus[cpu];
  4903. thr->q = tq_new();
  4904. if (!thr->q)
  4905. quit(1, "tq_new failed in starting cpu mining threads");
  4906. thread_reportin(thr);
  4907. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  4908. quit(1, "thread %d create failed", i);
  4909. }
  4910. applog(LOG_INFO, "%d cpu miner threads started, "
  4911. "using SHA256 '%s' algorithm.",
  4912. opt_n_threads,
  4913. algo_names[opt_algo]);
  4914. if (use_curses)
  4915. enable_curses();
  4916. watchdog_thr_id = mining_threads + 2;
  4917. thr = &thr_info[watchdog_thr_id];
  4918. /* start wakeup thread */
  4919. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  4920. quit(1, "wakeup thread create failed");
  4921. /* Create curses input thread for keyboard input */
  4922. input_thr_id = mining_threads + 4;
  4923. thr = &thr_info[input_thr_id];
  4924. if (thr_info_create(thr, NULL, input_thread, thr))
  4925. quit(1, "input thread create failed");
  4926. pthread_detach(thr->pth);
  4927. /* Create reinit cpu thread */
  4928. cpur_thr_id = mining_threads + 5;
  4929. thr = &thr_info[cpur_thr_id];
  4930. thr->q = tq_new();
  4931. if (!thr->q)
  4932. quit(1, "tq_new failed for cpur_thr_id");
  4933. if (thr_info_create(thr, NULL, reinit_cpu, thr))
  4934. quit(1, "reinit_cpu thread create failed");
  4935. /* Create reinit gpu thread */
  4936. gpur_thr_id = mining_threads + 6;
  4937. thr = &thr_info[gpur_thr_id];
  4938. thr->q = tq_new();
  4939. if (!thr->q)
  4940. quit(1, "tq_new failed for gpur_thr_id");
  4941. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  4942. quit(1, "reinit_gpu thread create failed");
  4943. sleep(opt_log_interval);
  4944. if (opt_donation > 0.0)
  4945. applog(LOG_WARNING, "Donation is enabled at %.1f%% thank you :-)", opt_donation);
  4946. else
  4947. applog(LOG_WARNING, "Donation is disabled, please consider just 0.5%% :-(");
  4948. /* main loop - simply wait for workio thread to exit */
  4949. pthread_join(thr_info[work_thr_id].pth, NULL);
  4950. applog(LOG_INFO, "workio thread dead, exiting.");
  4951. gettimeofday(&total_tv_end, NULL);
  4952. disable_curses();
  4953. if (!opt_realquiet && successful_connect)
  4954. print_summary();
  4955. #ifdef HAVE_OPENCL
  4956. clear_adl(nDevs);
  4957. #endif
  4958. if (opt_n_threads)
  4959. free(cpus);
  4960. HASH_ITER(hh, staged_work, work, tmpwork) {
  4961. HASH_DEL(staged_work, work);
  4962. free_work(work);
  4963. }
  4964. HASH_ITER(hh, blocks, block, tmpblock) {
  4965. HASH_DEL(blocks, block);
  4966. free(block);
  4967. }
  4968. curl_global_cleanup();
  4969. return 0;
  4970. }