main.c 148 KB

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