cgminer.c 130 KB

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