miner.c 149 KB

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