main.c 148 KB

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