main.c 146 KB

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