cgminer.c 143 KB

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