miner.c 135 KB

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