miner.c 155 KB

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