miner.c 154 KB

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