cgminer.c 143 KB

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