cgminer.c 134 KB

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