main.c 160 KB

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