miner.c 149 KB

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