miner.c 149 KB

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