main.c 150 KB

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