main.c 152 KB

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