main.c 162 KB

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