miner.c 145 KB

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