cgminer.c 146 KB

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