cgminer.c 146 KB

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