cgminer.c 147 KB

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