miner.c 132 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182
  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_mutex_t ch_lock;
  146. static pthread_rwlock_t blk_lock;
  147. pthread_rwlock_t netacc_lock;
  148. double total_mhashes_done;
  149. static struct timeval total_tv_start, total_tv_end;
  150. pthread_mutex_t control_lock;
  151. int hw_errors;
  152. int total_accepted, total_rejected;
  153. int total_getworks, total_stale, total_discarded;
  154. static int total_queued;
  155. unsigned int new_blocks;
  156. static unsigned int work_block;
  157. unsigned int found_blocks;
  158. unsigned int local_work;
  159. unsigned int total_go, total_ro;
  160. struct pool *pools[MAX_POOLS];
  161. static struct pool *currentpool = NULL;
  162. int total_pools;
  163. enum pool_strategy pool_strategy = POOL_FAILOVER;
  164. int opt_rotate_period;
  165. static int total_urls, total_users, total_passes, total_userpasses;
  166. #ifndef HAVE_CURSES
  167. const
  168. #endif
  169. static bool curses_active = false;
  170. static char current_block[37];
  171. static char *current_hash;
  172. static char datestamp[40];
  173. static char blocktime[30];
  174. struct block {
  175. char hash[37];
  176. UT_hash_handle hh;
  177. };
  178. static struct block *blocks = NULL;
  179. char *opt_socks_proxy = NULL;
  180. static const char def_conf[] = "bfgminer.conf";
  181. static bool config_loaded = false;
  182. static int include_count = 0;
  183. #define JSON_INCLUDE_CONF "include"
  184. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed"
  185. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  186. #define JSON_MAX_DEPTH 10
  187. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  188. #if defined(unix)
  189. static char *opt_stderr_cmd = NULL;
  190. static int forkpid = 0;
  191. #endif // defined(unix)
  192. bool ping = true;
  193. struct sigaction termhandler, inthandler;
  194. struct thread_q *getq;
  195. static int total_work;
  196. struct work *staged_work = NULL;
  197. static int staged_extras;
  198. struct schedtime {
  199. bool enable;
  200. struct tm tm;
  201. };
  202. struct schedtime schedstart;
  203. struct schedtime schedstop;
  204. bool sched_paused;
  205. static bool time_before(struct tm *tm1, struct tm *tm2)
  206. {
  207. if (tm1->tm_hour < tm2->tm_hour)
  208. return true;
  209. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  210. return true;
  211. return false;
  212. }
  213. static bool should_run(void)
  214. {
  215. struct timeval tv;
  216. struct tm *tm;
  217. if (!schedstart.enable && !schedstop.enable)
  218. return true;
  219. gettimeofday(&tv, NULL);
  220. tm = localtime(&tv.tv_sec);
  221. if (schedstart.enable) {
  222. if (!schedstop.enable) {
  223. if (time_before(tm, &schedstart.tm))
  224. return false;
  225. /* This is a once off event with no stop time set */
  226. schedstart.enable = false;
  227. return true;
  228. }
  229. if (time_before(&schedstart.tm, &schedstop.tm)) {
  230. if (time_before(tm, &schedstop.tm) && !time_before(tm, &schedstart.tm))
  231. return true;
  232. return false;
  233. } /* Times are reversed */
  234. if (time_before(tm, &schedstart.tm)) {
  235. if (time_before(tm, &schedstop.tm))
  236. return true;
  237. return false;
  238. }
  239. return true;
  240. }
  241. /* only schedstop.enable == true */
  242. if (!time_before(tm, &schedstop.tm))
  243. return false;
  244. return true;
  245. }
  246. void get_datestamp(char *f, struct timeval *tv)
  247. {
  248. struct tm *tm;
  249. tm = localtime(&tv->tv_sec);
  250. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  251. tm->tm_year + 1900,
  252. tm->tm_mon + 1,
  253. tm->tm_mday,
  254. tm->tm_hour,
  255. tm->tm_min,
  256. tm->tm_sec);
  257. }
  258. void get_timestamp(char *f, struct timeval *tv)
  259. {
  260. struct tm *tm;
  261. tm = localtime(&tv->tv_sec);
  262. sprintf(f, "[%02d:%02d:%02d]",
  263. tm->tm_hour,
  264. tm->tm_min,
  265. tm->tm_sec);
  266. }
  267. static void applog_and_exit(const char *fmt, ...)
  268. {
  269. va_list ap;
  270. va_start(ap, fmt);
  271. vapplog(LOG_ERR, fmt, ap);
  272. va_end(ap);
  273. exit(1);
  274. }
  275. static pthread_mutex_t sharelog_lock;
  276. static FILE *sharelog_file = NULL;
  277. static void sharelog(const char*disposition, const struct work*work)
  278. {
  279. if (!sharelog_file)
  280. return;
  281. int thr_id = work->thr_id;
  282. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  283. struct pool *pool = work->pool;
  284. unsigned long int t = (unsigned long int)work->share_found_time;
  285. char *target = bin2hex(work->target, sizeof(work->target));
  286. if (unlikely(!target)) {
  287. applog(LOG_ERR, "sharelog target OOM");
  288. return;
  289. }
  290. char *hash = bin2hex(work->hash, sizeof(work->hash));
  291. if (unlikely(!hash)) {
  292. free(target);
  293. applog(LOG_ERR, "sharelog hash OOM");
  294. return;
  295. }
  296. char *data = bin2hex(work->data, sizeof(work->data));
  297. if (unlikely(!data)) {
  298. free(target);
  299. free(hash);
  300. applog(LOG_ERR, "sharelog data OOM");
  301. return;
  302. }
  303. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  304. char s[1024];
  305. int rv;
  306. 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);
  307. free(target);
  308. free(hash);
  309. free(data);
  310. if (rv >= (int)(sizeof(s)))
  311. s[sizeof(s) - 1] = '\0';
  312. else
  313. if (rv < 0) {
  314. applog(LOG_ERR, "sharelog printf error");
  315. return;
  316. }
  317. size_t ret;
  318. mutex_lock(&sharelog_lock);
  319. ret = fwrite(s, rv, 1, sharelog_file);
  320. fflush(sharelog_file);
  321. mutex_unlock(&sharelog_lock);
  322. if (1 != ret)
  323. applog(LOG_ERR, "sharelog fwrite error");
  324. }
  325. /* Return value is ignored if not called from add_pool_details */
  326. static struct pool *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. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  337. quit(1, "Failed to pthread_cond_init in add_pool");
  338. INIT_LIST_HEAD(&pool->curlring);
  339. /* Make sure the pool doesn't think we've been idle since time 0 */
  340. pool->tv_idle.tv_sec = ~0UL;
  341. return pool;
  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. /* Called with pool_lock held. Recruit an extra curl if none are available for
  1714. * this pool. */
  1715. static void recruit_curl(struct pool *pool)
  1716. {
  1717. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  1718. ce->curl = curl_easy_init();
  1719. if (unlikely(!ce->curl || !ce))
  1720. quit(1, "Failed to init in recruit_curl");
  1721. list_add(&ce->node, &pool->curlring);
  1722. pool->curls++;
  1723. applog(LOG_DEBUG, "Recruited curl %d for pool %d", pool->curls, pool->pool_no);
  1724. }
  1725. /* Grab an available curl if there is one. If not, then recruit extra curls
  1726. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  1727. * and there are already 5 curls in circulation */
  1728. static struct curl_ent *pop_curl_entry(struct pool *pool)
  1729. {
  1730. struct curl_ent *ce;
  1731. mutex_lock(&pool->pool_lock);
  1732. if (!pool->curls)
  1733. recruit_curl(pool);
  1734. else if (list_empty(&pool->curlring)) {
  1735. if ((pool->submit_fail || opt_delaynet) && pool->curls > 4)
  1736. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  1737. else
  1738. recruit_curl(pool);
  1739. }
  1740. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  1741. list_del(&ce->node);
  1742. mutex_unlock(&pool->pool_lock);
  1743. return ce;
  1744. }
  1745. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  1746. {
  1747. mutex_lock(&pool->pool_lock);
  1748. list_add_tail(&ce->node, &pool->curlring);
  1749. gettimeofday(&ce->tv, NULL);
  1750. pthread_cond_signal(&pool->cr_cond);
  1751. mutex_unlock(&pool->pool_lock);
  1752. }
  1753. static void *get_work_thread(void *userdata)
  1754. {
  1755. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1756. struct work *ret_work = make_work();
  1757. struct curl_ent *ce;
  1758. struct pool *pool;
  1759. int failures = 0;
  1760. pthread_detach(pthread_self());
  1761. applog(LOG_DEBUG, "Creating extra get work thread");
  1762. if (wc->thr)
  1763. ret_work->thr = wc->thr;
  1764. else
  1765. ret_work->thr = NULL;
  1766. pool = ret_work->pool = select_pool(wc->lagging);
  1767. ce = pop_curl_entry(pool);
  1768. /* obtain new work from bitcoin via JSON-RPC */
  1769. while (!get_upstream_work(ret_work, ce->curl)) {
  1770. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1771. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  1772. free_work(ret_work);
  1773. kill_work();
  1774. goto out;
  1775. }
  1776. /* pause, then restart work-request loop */
  1777. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  1778. fail_pause);
  1779. sleep(fail_pause);
  1780. fail_pause += opt_fail_pause;
  1781. }
  1782. fail_pause = opt_fail_pause;
  1783. applog(LOG_DEBUG, "Pushing work to requesting thread");
  1784. /* send work to requesting thread */
  1785. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  1786. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  1787. kill_work();
  1788. free_work(ret_work);
  1789. }
  1790. out:
  1791. workio_cmd_free(wc);
  1792. push_curl_entry(ce, pool);
  1793. return NULL;
  1794. }
  1795. /* As per the submit work system, we try to reuse the existing curl handles,
  1796. * but start recruiting extra connections if we start accumulating queued
  1797. * requests */
  1798. static bool workio_get_work(struct workio_cmd *wc)
  1799. {
  1800. pthread_t get_thread;
  1801. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  1802. applog(LOG_ERR, "Failed to create get_work_thread");
  1803. return false;
  1804. }
  1805. return true;
  1806. }
  1807. static bool stale_work(struct work *work, bool share)
  1808. {
  1809. struct timeval now;
  1810. if (opt_benchmark)
  1811. return false;
  1812. gettimeofday(&now, NULL);
  1813. if (share) {
  1814. if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_expiry)
  1815. return true;
  1816. } else if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_scantime)
  1817. return true;
  1818. if (work->work_block != work_block)
  1819. return true;
  1820. if (opt_fail_only && !share && work->pool != current_pool())
  1821. return true;
  1822. return false;
  1823. }
  1824. static void *submit_work_thread(void *userdata)
  1825. {
  1826. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1827. struct work *work = wc->u.work;
  1828. struct pool *pool = work->pool;
  1829. struct curl_ent *ce;
  1830. int failures = 0;
  1831. pthread_detach(pthread_self());
  1832. applog(LOG_DEBUG, "Creating extra submit work thread");
  1833. if (stale_work(work, true)) {
  1834. if (opt_submit_stale)
  1835. applog(LOG_NOTICE, "Stale share detected, submitting as user requested");
  1836. else if (pool->submit_old)
  1837. applog(LOG_NOTICE, "Stale share detected, submitting as pool requested");
  1838. else {
  1839. applog(LOG_NOTICE, "Stale share detected, discarding");
  1840. sharelog("discard", work);
  1841. total_stale++;
  1842. pool->stale_shares++;
  1843. goto out;
  1844. }
  1845. }
  1846. ce = pop_curl_entry(pool);
  1847. /* submit solution to bitcoin via JSON-RPC */
  1848. while (!submit_upstream_work(work, ce->curl)) {
  1849. if (stale_work(work, true)) {
  1850. applog(LOG_NOTICE, "Share became stale while retrying submit, discarding");
  1851. total_stale++;
  1852. pool->stale_shares++;
  1853. break;
  1854. }
  1855. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1856. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1857. kill_work();
  1858. break;
  1859. }
  1860. /* pause, then restart work-request loop */
  1861. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1862. fail_pause);
  1863. sleep(fail_pause);
  1864. fail_pause += opt_fail_pause;
  1865. }
  1866. fail_pause = opt_fail_pause;
  1867. push_curl_entry(ce, pool);
  1868. out:
  1869. workio_cmd_free(wc);
  1870. return NULL;
  1871. }
  1872. /* We try to reuse curl handles as much as possible, but if there is already
  1873. * work queued to be submitted, we start generating extra handles to submit
  1874. * the shares to avoid ever increasing backlogs. This allows us to scale to
  1875. * any size hardware */
  1876. static bool workio_submit_work(struct workio_cmd *wc)
  1877. {
  1878. pthread_t submit_thread;
  1879. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1880. applog(LOG_ERR, "Failed to create submit_work_thread");
  1881. return false;
  1882. }
  1883. return true;
  1884. }
  1885. /* Find the pool that currently has the highest priority */
  1886. static struct pool *priority_pool(int choice)
  1887. {
  1888. struct pool *ret = NULL;
  1889. int i;
  1890. for (i = 0; i < total_pools; i++) {
  1891. struct pool *pool = pools[i];
  1892. if (pool->prio == choice) {
  1893. ret = pool;
  1894. break;
  1895. }
  1896. }
  1897. if (unlikely(!ret)) {
  1898. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1899. return pools[choice];
  1900. }
  1901. return ret;
  1902. }
  1903. void switch_pools(struct pool *selected)
  1904. {
  1905. struct pool *pool, *last_pool;
  1906. int i, pool_no;
  1907. mutex_lock(&control_lock);
  1908. last_pool = currentpool;
  1909. pool_no = currentpool->pool_no;
  1910. /* Switch selected to pool number 0 and move the rest down */
  1911. if (selected) {
  1912. if (selected->prio != 0) {
  1913. for (i = 0; i < total_pools; i++) {
  1914. pool = pools[i];
  1915. if (pool->prio < selected->prio)
  1916. pool->prio++;
  1917. }
  1918. selected->prio = 0;
  1919. }
  1920. }
  1921. switch (pool_strategy) {
  1922. /* Both of these set to the master pool */
  1923. case POOL_FAILOVER:
  1924. case POOL_LOADBALANCE:
  1925. for (i = 0; i < total_pools; i++) {
  1926. pool = priority_pool(i);
  1927. if (!pool->idle && pool->enabled) {
  1928. pool_no = pool->pool_no;
  1929. break;
  1930. }
  1931. }
  1932. break;
  1933. /* Both of these simply increment and cycle */
  1934. case POOL_ROUNDROBIN:
  1935. case POOL_ROTATE:
  1936. if (selected) {
  1937. pool_no = selected->pool_no;
  1938. break;
  1939. }
  1940. pool_no++;
  1941. if (pool_no >= total_pools)
  1942. pool_no = 0;
  1943. break;
  1944. default:
  1945. break;
  1946. }
  1947. currentpool = pools[pool_no];
  1948. pool = currentpool;
  1949. mutex_unlock(&control_lock);
  1950. if (pool != last_pool)
  1951. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1952. /* Reset the queued amount to allow more to be queued for the new pool */
  1953. mutex_lock(&qd_lock);
  1954. total_queued = 0;
  1955. mutex_unlock(&qd_lock);
  1956. }
  1957. static void discard_work(struct work *work)
  1958. {
  1959. if (!work->clone && !work->rolls && !work->mined) {
  1960. if (work->pool)
  1961. work->pool->discarded_work++;
  1962. total_discarded++;
  1963. applog(LOG_DEBUG, "Discarded work");
  1964. } else
  1965. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  1966. free_work(work);
  1967. }
  1968. /* This is overkill, but at least we'll know accurately how much work is
  1969. * queued to prevent ever being left without work */
  1970. static void inc_queued(void)
  1971. {
  1972. mutex_lock(&qd_lock);
  1973. total_queued++;
  1974. mutex_unlock(&qd_lock);
  1975. }
  1976. static void dec_queued(void)
  1977. {
  1978. mutex_lock(&qd_lock);
  1979. if (total_queued > 0)
  1980. total_queued--;
  1981. mutex_unlock(&qd_lock);
  1982. }
  1983. static int requests_queued(void)
  1984. {
  1985. int ret;
  1986. mutex_lock(&qd_lock);
  1987. ret = total_queued;
  1988. mutex_unlock(&qd_lock);
  1989. return ret;
  1990. }
  1991. static int discard_stale(void)
  1992. {
  1993. struct work *work, *tmp;
  1994. int i, stale = 0;
  1995. mutex_lock(stgd_lock);
  1996. HASH_ITER(hh, staged_work, work, tmp) {
  1997. if (stale_work(work, false)) {
  1998. HASH_DEL(staged_work, work);
  1999. if (work->clone || work->longpoll)
  2000. --staged_extras;
  2001. discard_work(work);
  2002. stale++;
  2003. }
  2004. }
  2005. mutex_unlock(stgd_lock);
  2006. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  2007. /* Dec queued outside the loop to not have recursive locks */
  2008. for (i = 0; i < stale; i++)
  2009. dec_queued();
  2010. return stale;
  2011. }
  2012. static bool queue_request(struct thr_info *thr, bool needed);
  2013. static void restart_threads(void)
  2014. {
  2015. int i, stale;
  2016. /* Discard staged work that is now stale */
  2017. stale = discard_stale();
  2018. for (i = 0; i < stale; i++)
  2019. queue_request(NULL, true);
  2020. for (i = 0; i < mining_threads; i++)
  2021. work_restart[i].restart = 1;
  2022. }
  2023. static void set_curblock(char *hexstr, unsigned char *hash)
  2024. {
  2025. unsigned char hash_swap[32];
  2026. struct timeval tv_now;
  2027. char *old_hash;
  2028. strcpy(current_block, hexstr);
  2029. gettimeofday(&tv_now, NULL);
  2030. get_timestamp(blocktime, &tv_now);
  2031. swap256(hash_swap, hash);
  2032. /* Don't free current_hash directly to avoid dereferencing when read
  2033. * elsewhere */
  2034. mutex_lock(&ch_lock);
  2035. old_hash = current_hash;
  2036. current_hash = bin2hex(hash_swap, 16);
  2037. free(old_hash);
  2038. mutex_unlock(&ch_lock);
  2039. if (unlikely(!current_hash))
  2040. quit (1, "set_curblock OOM");
  2041. applog(LOG_INFO, "New block: %s...", current_hash);
  2042. }
  2043. /* Search to see if this string is from a block that has been seen before */
  2044. static bool block_exists(char *hexstr)
  2045. {
  2046. struct block *s;
  2047. rd_lock(&blk_lock);
  2048. HASH_FIND_STR(blocks, hexstr, s);
  2049. rd_unlock(&blk_lock);
  2050. if (s)
  2051. return true;
  2052. return false;
  2053. }
  2054. /* Tests if this work is from a block that has been seen before */
  2055. static inline bool from_existing_block(struct work *work)
  2056. {
  2057. char *hexstr = bin2hex(work->data, 18);
  2058. bool ret;
  2059. if (unlikely(!hexstr)) {
  2060. applog(LOG_ERR, "from_existing_block OOM");
  2061. return true;
  2062. }
  2063. ret = block_exists(hexstr);
  2064. free(hexstr);
  2065. return ret;
  2066. }
  2067. static void test_work_current(struct work *work)
  2068. {
  2069. char *hexstr;
  2070. if (opt_benchmark)
  2071. return;
  2072. hexstr = bin2hex(work->data, 18);
  2073. if (unlikely(!hexstr)) {
  2074. applog(LOG_ERR, "stage_thread OOM");
  2075. return;
  2076. }
  2077. /* Search to see if this block exists yet and if not, consider it a
  2078. * new block and set the current block details to this one */
  2079. if (!block_exists(hexstr)) {
  2080. struct block *s = calloc(sizeof(struct block), 1);
  2081. if (unlikely(!s))
  2082. quit (1, "test_work_current OOM");
  2083. strcpy(s->hash, hexstr);
  2084. wr_lock(&blk_lock);
  2085. HASH_ADD_STR(blocks, hash, s);
  2086. wr_unlock(&blk_lock);
  2087. set_curblock(hexstr, work->data);
  2088. if (unlikely(++new_blocks == 1))
  2089. goto out_free;
  2090. work_block++;
  2091. if (work->longpoll) {
  2092. applog(LOG_NOTICE, "LONGPOLL from pool %d detected new block",
  2093. work->pool->pool_no);
  2094. work->longpoll = false;
  2095. } else if (have_longpoll)
  2096. applog(LOG_NOTICE, "New block detected on network before longpoll");
  2097. else
  2098. applog(LOG_NOTICE, "New block detected on network");
  2099. restart_threads();
  2100. } else if (work->longpoll) {
  2101. work->longpoll = false;
  2102. if (work->pool == current_pool()) {
  2103. applog(LOG_NOTICE, "LONGPOLL from pool %d requested work restart",
  2104. work->pool->pool_no);
  2105. work_block++;
  2106. restart_threads();
  2107. }
  2108. }
  2109. out_free:
  2110. free(hexstr);
  2111. }
  2112. static int tv_sort(struct work *worka, struct work *workb)
  2113. {
  2114. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  2115. }
  2116. static bool hash_push(struct work *work)
  2117. {
  2118. bool rc = true;
  2119. mutex_lock(stgd_lock);
  2120. if (likely(!getq->frozen)) {
  2121. HASH_ADD_INT(staged_work, id, work);
  2122. HASH_SORT(staged_work, tv_sort);
  2123. if (work->clone || work->longpoll)
  2124. ++staged_extras;
  2125. } else
  2126. rc = false;
  2127. pthread_cond_signal(&getq->cond);
  2128. mutex_unlock(stgd_lock);
  2129. return rc;
  2130. }
  2131. static void *stage_thread(void *userdata)
  2132. {
  2133. struct thr_info *mythr = userdata;
  2134. bool ok = true;
  2135. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2136. while (ok) {
  2137. struct work *work = NULL;
  2138. applog(LOG_DEBUG, "Popping work to stage thread");
  2139. work = tq_pop(mythr->q, NULL);
  2140. if (unlikely(!work)) {
  2141. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  2142. ok = false;
  2143. break;
  2144. }
  2145. work->work_block = work_block;
  2146. test_work_current(work);
  2147. applog(LOG_DEBUG, "Pushing work to getwork queue");
  2148. if (unlikely(!hash_push(work))) {
  2149. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  2150. continue;
  2151. }
  2152. }
  2153. tq_freeze(mythr->q);
  2154. return NULL;
  2155. }
  2156. static bool stage_work(struct work *work)
  2157. {
  2158. applog(LOG_DEBUG, "Pushing work to stage thread");
  2159. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work))) {
  2160. applog(LOG_ERR, "Could not tq_push work in stage_work");
  2161. return false;
  2162. }
  2163. return true;
  2164. }
  2165. #ifdef HAVE_CURSES
  2166. int curses_int(const char *query)
  2167. {
  2168. int ret;
  2169. char *cvar;
  2170. cvar = curses_input(query);
  2171. ret = atoi(cvar);
  2172. free(cvar);
  2173. return ret;
  2174. }
  2175. #endif
  2176. #ifdef HAVE_CURSES
  2177. static bool input_pool(bool live);
  2178. #endif
  2179. int active_pools(void)
  2180. {
  2181. int ret = 0;
  2182. int i;
  2183. for (i = 0; i < total_pools; i++) {
  2184. if ((pools[i])->enabled)
  2185. ret++;
  2186. }
  2187. return ret;
  2188. }
  2189. #ifdef HAVE_CURSES
  2190. static void display_pool_summary(struct pool *pool)
  2191. {
  2192. double efficiency = 0.0;
  2193. if (curses_active_locked()) {
  2194. wlog("Pool: %s\n", pool->rpc_url);
  2195. wlog("%s long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  2196. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  2197. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  2198. wlog(" Accepted shares: %d\n", pool->accepted);
  2199. wlog(" Rejected shares: %d\n", pool->rejected);
  2200. if (pool->accepted || pool->rejected)
  2201. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  2202. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  2203. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2204. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  2205. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  2206. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  2207. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2208. unlock_curses();
  2209. }
  2210. }
  2211. #endif
  2212. /* We can't remove the memory used for this struct pool because there may
  2213. * still be work referencing it. We just remove it from the pools list */
  2214. void remove_pool(struct pool *pool)
  2215. {
  2216. int i, last_pool = total_pools - 1;
  2217. struct pool *other;
  2218. /* Boost priority of any lower prio than this one */
  2219. for (i = 0; i < total_pools; i++) {
  2220. other = pools[i];
  2221. if (other->prio > pool->prio)
  2222. other->prio--;
  2223. }
  2224. if (pool->pool_no < last_pool) {
  2225. /* Swap the last pool for this one */
  2226. (pools[last_pool])->pool_no = pool->pool_no;
  2227. pools[pool->pool_no] = pools[last_pool];
  2228. }
  2229. /* Give it an invalid number */
  2230. pool->pool_no = total_pools;
  2231. pool->removed = true;
  2232. total_pools--;
  2233. }
  2234. void write_config(FILE *fcfg)
  2235. {
  2236. int i;
  2237. /* Write pool values */
  2238. fputs("{\n\"pools\" : [", fcfg);
  2239. for(i = 0; i < total_pools; i++) {
  2240. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", pools[i]->rpc_url);
  2241. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", pools[i]->rpc_user);
  2242. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", pools[i]->rpc_pass);
  2243. }
  2244. fputs("\n],\n\n", fcfg);
  2245. if (nDevs) {
  2246. /* Write GPU device values */
  2247. fputs("\"intensity\" : \"", fcfg);
  2248. for(i = 0; i < nDevs; i++)
  2249. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  2250. #ifdef HAVE_OPENCL
  2251. fputs("\",\n\"vectors\" : \"", fcfg);
  2252. for(i = 0; i < nDevs; i++)
  2253. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2254. gpus[i].vwidth);
  2255. fputs("\",\n\"worksize\" : \"", fcfg);
  2256. for(i = 0; i < nDevs; i++)
  2257. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2258. (int)gpus[i].work_size);
  2259. fputs("\",\n\"kernel\" : \"", fcfg);
  2260. for(i = 0; i < nDevs; i++) {
  2261. fprintf(fcfg, "%s", i > 0 ? "," : "");
  2262. switch (gpus[i].kernel) {
  2263. case KL_NONE: // Shouldn't happen
  2264. break;
  2265. case KL_POCLBM:
  2266. fprintf(fcfg, "poclbm");
  2267. break;
  2268. case KL_PHATK:
  2269. fprintf(fcfg, "phatk");
  2270. break;
  2271. case KL_DIAKGCN:
  2272. fprintf(fcfg, "diakgcn");
  2273. break;
  2274. case KL_DIABLO:
  2275. fprintf(fcfg, "diablo");
  2276. break;
  2277. }
  2278. }
  2279. #ifdef HAVE_ADL
  2280. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  2281. for(i = 0; i < nDevs; i++)
  2282. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  2283. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  2284. for(i = 0; i < nDevs; i++)
  2285. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  2286. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  2287. for(i = 0; i < nDevs; i++)
  2288. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  2289. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  2290. for(i = 0; i < nDevs; i++)
  2291. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  2292. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  2293. for(i = 0; i < nDevs; i++)
  2294. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  2295. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  2296. for(i = 0; i < nDevs; i++)
  2297. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  2298. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  2299. for(i = 0; i < nDevs; i++)
  2300. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  2301. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  2302. for(i = 0; i < nDevs; i++)
  2303. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  2304. fputs("\",\n\"temp-target\" : \"", fcfg);
  2305. for(i = 0; i < nDevs; i++)
  2306. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  2307. #endif
  2308. #endif
  2309. fputs("\"", fcfg);
  2310. #ifdef WANT_CPUMINE
  2311. fputs(",\n", fcfg);
  2312. #endif
  2313. }
  2314. #ifdef HAVE_ADL
  2315. if (opt_reorder)
  2316. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  2317. #endif
  2318. #ifdef WANT_CPUMINE
  2319. fprintf(fcfg, "\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  2320. #endif
  2321. /* Simple bool and int options */
  2322. struct opt_table *opt;
  2323. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2324. char *p, *name = strdup(opt->names);
  2325. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  2326. if (p[1] != '-')
  2327. continue;
  2328. if (opt->type & OPT_NOARG &&
  2329. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  2330. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  2331. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  2332. if (opt->type & OPT_HASARG &&
  2333. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  2334. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  2335. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  2336. (void *)opt->cb_arg == (void *)set_int_1_to_10) && opt->desc != opt_hidden)
  2337. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  2338. }
  2339. }
  2340. /* Special case options */
  2341. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  2342. if (pool_strategy == POOL_LOADBALANCE)
  2343. fputs(",\n\"load-balance\" : true", fcfg);
  2344. if (pool_strategy == POOL_ROUNDROBIN)
  2345. fputs(",\n\"round-robin\" : true", fcfg);
  2346. if (pool_strategy == POOL_ROTATE)
  2347. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  2348. #if defined(unix)
  2349. if (opt_stderr_cmd && *opt_stderr_cmd)
  2350. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", opt_stderr_cmd);
  2351. #endif // defined(unix)
  2352. if (opt_kernel_path && *opt_kernel_path) {
  2353. char *kpath = strdup(opt_kernel_path);
  2354. if (kpath[strlen(kpath)-1] == '/')
  2355. kpath[strlen(kpath)-1] = 0;
  2356. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", kpath);
  2357. }
  2358. if (schedstart.enable)
  2359. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  2360. if (schedstop.enable)
  2361. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  2362. if (opt_socks_proxy && *opt_socks_proxy)
  2363. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", opt_socks_proxy);
  2364. for(i = 0; i < nDevs; i++)
  2365. if (gpus[i].deven == DEV_DISABLED)
  2366. break;
  2367. if (i < nDevs)
  2368. for (i = 0; i < nDevs; i++)
  2369. if (gpus[i].deven != DEV_DISABLED)
  2370. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  2371. if (opt_api_allow)
  2372. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", opt_api_allow);
  2373. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  2374. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", opt_api_description);
  2375. fputs("\n}", fcfg);
  2376. }
  2377. #ifdef HAVE_CURSES
  2378. static void display_pools(void)
  2379. {
  2380. struct pool *pool;
  2381. int selected, i;
  2382. char input;
  2383. opt_loginput = true;
  2384. immedok(logwin, true);
  2385. clear_logwin();
  2386. updated:
  2387. for (i = 0; i < total_pools; i++) {
  2388. pool = pools[i];
  2389. if (pool == current_pool())
  2390. wattron(logwin, A_BOLD);
  2391. if (!pool->enabled)
  2392. wattron(logwin, A_DIM);
  2393. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  2394. pool->pool_no,
  2395. pool->enabled? "Enabled" : "Disabled",
  2396. pool->idle? "Dead" : "Alive",
  2397. pool->prio,
  2398. pool->rpc_url, pool->rpc_user);
  2399. wattroff(logwin, A_BOLD | A_DIM);
  2400. }
  2401. retry:
  2402. wlogprint("\nCurrent pool management strategy: %s\n",
  2403. strategies[pool_strategy]);
  2404. if (pool_strategy == POOL_ROTATE)
  2405. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  2406. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  2407. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  2408. wlogprint("Or press any other key to continue\n");
  2409. input = getch();
  2410. if (!strncasecmp(&input, "a", 1)) {
  2411. input_pool(true);
  2412. goto updated;
  2413. } else if (!strncasecmp(&input, "r", 1)) {
  2414. if (total_pools <= 1) {
  2415. wlogprint("Cannot remove last pool");
  2416. goto retry;
  2417. }
  2418. selected = curses_int("Select pool number");
  2419. if (selected < 0 || selected >= total_pools) {
  2420. wlogprint("Invalid selection\n");
  2421. goto retry;
  2422. }
  2423. pool = pools[selected];
  2424. if (pool == current_pool())
  2425. switch_pools(NULL);
  2426. if (pool == current_pool()) {
  2427. wlogprint("Unable to remove pool due to activity\n");
  2428. goto retry;
  2429. }
  2430. pool->enabled = false;
  2431. remove_pool(pool);
  2432. goto updated;
  2433. } else if (!strncasecmp(&input, "s", 1)) {
  2434. selected = curses_int("Select pool number");
  2435. if (selected < 0 || selected >= total_pools) {
  2436. wlogprint("Invalid selection\n");
  2437. goto retry;
  2438. }
  2439. pool = pools[selected];
  2440. pool->enabled = true;
  2441. switch_pools(pool);
  2442. goto updated;
  2443. } else if (!strncasecmp(&input, "d", 1)) {
  2444. if (active_pools() <= 1) {
  2445. wlogprint("Cannot disable last pool");
  2446. goto retry;
  2447. }
  2448. selected = curses_int("Select pool number");
  2449. if (selected < 0 || selected >= total_pools) {
  2450. wlogprint("Invalid selection\n");
  2451. goto retry;
  2452. }
  2453. pool = pools[selected];
  2454. pool->enabled = false;
  2455. if (pool == current_pool())
  2456. switch_pools(NULL);
  2457. goto updated;
  2458. } else if (!strncasecmp(&input, "e", 1)) {
  2459. selected = curses_int("Select pool number");
  2460. if (selected < 0 || selected >= total_pools) {
  2461. wlogprint("Invalid selection\n");
  2462. goto retry;
  2463. }
  2464. pool = pools[selected];
  2465. pool->enabled = true;
  2466. if (pool->prio < current_pool()->prio)
  2467. switch_pools(pool);
  2468. goto updated;
  2469. } else if (!strncasecmp(&input, "c", 1)) {
  2470. for (i = 0; i <= TOP_STRATEGY; i++)
  2471. wlogprint("%d: %s\n", i, strategies[i]);
  2472. selected = curses_int("Select strategy number type");
  2473. if (selected < 0 || selected > TOP_STRATEGY) {
  2474. wlogprint("Invalid selection\n");
  2475. goto retry;
  2476. }
  2477. if (selected == POOL_ROTATE) {
  2478. opt_rotate_period = curses_int("Select interval in minutes");
  2479. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  2480. opt_rotate_period = 0;
  2481. wlogprint("Invalid selection\n");
  2482. goto retry;
  2483. }
  2484. }
  2485. pool_strategy = selected;
  2486. switch_pools(NULL);
  2487. goto updated;
  2488. } else if (!strncasecmp(&input, "i", 1)) {
  2489. selected = curses_int("Select pool number");
  2490. if (selected < 0 || selected >= total_pools) {
  2491. wlogprint("Invalid selection\n");
  2492. goto retry;
  2493. }
  2494. pool = pools[selected];
  2495. display_pool_summary(pool);
  2496. goto retry;
  2497. } else
  2498. clear_logwin();
  2499. immedok(logwin, false);
  2500. opt_loginput = false;
  2501. }
  2502. static void display_options(void)
  2503. {
  2504. int selected;
  2505. char input;
  2506. opt_loginput = true;
  2507. immedok(logwin, true);
  2508. clear_logwin();
  2509. retry:
  2510. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  2511. 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",
  2512. opt_debug ? "on" : "off",
  2513. want_per_device_stats? "on" : "off",
  2514. opt_quiet ? "on" : "off",
  2515. opt_log_output ? "on" : "off",
  2516. opt_protocol ? "on" : "off",
  2517. opt_log_interval);
  2518. wlogprint("Select an option or any other key to return\n");
  2519. input = getch();
  2520. if (!strncasecmp(&input, "q", 1)) {
  2521. opt_quiet ^= true;
  2522. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  2523. goto retry;
  2524. } else if (!strncasecmp(&input, "v", 1)) {
  2525. opt_log_output ^= true;
  2526. if (opt_log_output)
  2527. opt_quiet = false;
  2528. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2529. goto retry;
  2530. } else if (!strncasecmp(&input, "n", 1)) {
  2531. opt_log_output = false;
  2532. opt_debug = false;
  2533. opt_quiet = false;
  2534. opt_protocol = false;
  2535. want_per_device_stats = false;
  2536. wlogprint("Output mode reset to normal\n");
  2537. goto retry;
  2538. } else if (!strncasecmp(&input, "d", 1)) {
  2539. opt_debug ^= true;
  2540. opt_log_output = opt_debug;
  2541. if (opt_debug)
  2542. opt_quiet = false;
  2543. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2544. goto retry;
  2545. } else if (!strncasecmp(&input, "p", 1)) {
  2546. want_per_device_stats ^= true;
  2547. opt_log_output = want_per_device_stats;
  2548. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  2549. goto retry;
  2550. } else if (!strncasecmp(&input, "r", 1)) {
  2551. opt_protocol ^= true;
  2552. if (opt_protocol)
  2553. opt_quiet = false;
  2554. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2555. goto retry;
  2556. } else if (!strncasecmp(&input, "c", 1))
  2557. clear_logwin();
  2558. else if (!strncasecmp(&input, "l", 1)) {
  2559. selected = curses_int("Interval in seconds");
  2560. if (selected < 0 || selected > 9999) {
  2561. wlogprint("Invalid selection\n");
  2562. goto retry;
  2563. }
  2564. opt_log_interval = selected;
  2565. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2566. goto retry;
  2567. } else if (!strncasecmp(&input, "s", 1)) {
  2568. opt_realquiet = true;
  2569. } else
  2570. clear_logwin();
  2571. immedok(logwin, false);
  2572. opt_loginput = false;
  2573. }
  2574. #endif
  2575. #ifdef HAVE_CURSES
  2576. static void set_options(void)
  2577. {
  2578. int selected;
  2579. char input;
  2580. opt_loginput = true;
  2581. immedok(logwin, true);
  2582. clear_logwin();
  2583. retry:
  2584. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  2585. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  2586. "[P]ause: %d\n[W]rite config file\n[B]FGMiner restart\n",
  2587. opt_queue, opt_scantime, opt_expiry, opt_retries, opt_fail_pause);
  2588. wlogprint("Select an option or any other key to return\n");
  2589. input = getch();
  2590. if (!strncasecmp(&input, "q", 1)) {
  2591. selected = curses_int("Extra work items to queue");
  2592. if (selected < 0 || selected > 9999) {
  2593. wlogprint("Invalid selection\n");
  2594. goto retry;
  2595. }
  2596. opt_queue = selected;
  2597. goto retry;
  2598. } else if (!strncasecmp(&input, "l", 1)) {
  2599. if (want_longpoll)
  2600. stop_longpoll();
  2601. else
  2602. start_longpoll();
  2603. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2604. goto retry;
  2605. } else if (!strncasecmp(&input, "s", 1)) {
  2606. selected = curses_int("Set scantime in seconds");
  2607. if (selected < 0 || selected > 9999) {
  2608. wlogprint("Invalid selection\n");
  2609. goto retry;
  2610. }
  2611. opt_scantime = selected;
  2612. goto retry;
  2613. } else if (!strncasecmp(&input, "e", 1)) {
  2614. selected = curses_int("Set expiry time in seconds");
  2615. if (selected < 0 || selected > 9999) {
  2616. wlogprint("Invalid selection\n");
  2617. goto retry;
  2618. }
  2619. opt_expiry = selected;
  2620. goto retry;
  2621. } else if (!strncasecmp(&input, "r", 1)) {
  2622. selected = curses_int("Retries before failing (-1 infinite)");
  2623. if (selected < -1 || selected > 9999) {
  2624. wlogprint("Invalid selection\n");
  2625. goto retry;
  2626. }
  2627. opt_retries = selected;
  2628. goto retry;
  2629. } else if (!strncasecmp(&input, "p", 1)) {
  2630. selected = curses_int("Seconds to pause before network retries");
  2631. if (selected < 1 || selected > 9999) {
  2632. wlogprint("Invalid selection\n");
  2633. goto retry;
  2634. }
  2635. opt_fail_pause = selected;
  2636. goto retry;
  2637. } else if (!strncasecmp(&input, "w", 1)) {
  2638. FILE *fcfg;
  2639. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  2640. #if defined(unix)
  2641. if (getenv("HOME") && *getenv("HOME")) {
  2642. strcpy(filename, getenv("HOME"));
  2643. strcat(filename, "/");
  2644. }
  2645. else
  2646. strcpy(filename, "");
  2647. strcat(filename, ".bfgminer/");
  2648. mkdir(filename, 0777);
  2649. #else
  2650. strcpy(filename, "");
  2651. #endif
  2652. strcat(filename, def_conf);
  2653. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  2654. str = curses_input(prompt);
  2655. if (strcmp(str, "-1")) {
  2656. struct stat statbuf;
  2657. strcpy(filename, str);
  2658. if (!stat(filename, &statbuf)) {
  2659. wlogprint("File exists, overwrite?\n");
  2660. input = getch();
  2661. if (strncasecmp(&input, "y", 1))
  2662. goto retry;
  2663. }
  2664. }
  2665. fcfg = fopen(filename, "w");
  2666. if (!fcfg) {
  2667. wlogprint("Cannot open or create file\n");
  2668. goto retry;
  2669. }
  2670. write_config(fcfg);
  2671. fclose(fcfg);
  2672. goto retry;
  2673. } else if (!strncasecmp(&input, "b", 1)) {
  2674. wlogprint("Are you sure?\n");
  2675. input = getch();
  2676. if (!strncasecmp(&input, "y", 1))
  2677. app_restart();
  2678. else
  2679. clear_logwin();
  2680. } else
  2681. clear_logwin();
  2682. immedok(logwin, false);
  2683. opt_loginput = false;
  2684. }
  2685. static void *input_thread(void __maybe_unused *userdata)
  2686. {
  2687. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2688. if (!curses_active)
  2689. return NULL;
  2690. while (1) {
  2691. char input;
  2692. input = getch();
  2693. if (!strncasecmp(&input, "q", 1)) {
  2694. kill_work();
  2695. return NULL;
  2696. } else if (!strncasecmp(&input, "d", 1))
  2697. display_options();
  2698. else if (!strncasecmp(&input, "p", 1))
  2699. display_pools();
  2700. else if (!strncasecmp(&input, "s", 1))
  2701. set_options();
  2702. else if (have_opencl && !strncasecmp(&input, "g", 1))
  2703. manage_gpu();
  2704. if (opt_realquiet) {
  2705. disable_curses();
  2706. break;
  2707. }
  2708. }
  2709. return NULL;
  2710. }
  2711. #endif
  2712. /* This thread should not be shut down unless a problem occurs */
  2713. static void *workio_thread(void *userdata)
  2714. {
  2715. struct thr_info *mythr = userdata;
  2716. bool ok = true;
  2717. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2718. while (ok) {
  2719. struct workio_cmd *wc;
  2720. applog(LOG_DEBUG, "Popping work to work thread");
  2721. /* wait for workio_cmd sent to us, on our queue */
  2722. wc = tq_pop(mythr->q, NULL);
  2723. if (unlikely(!wc)) {
  2724. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  2725. ok = false;
  2726. break;
  2727. }
  2728. /* process workio_cmd */
  2729. switch (wc->cmd) {
  2730. case WC_GET_WORK:
  2731. ok = workio_get_work(wc);
  2732. break;
  2733. case WC_SUBMIT_WORK:
  2734. ok = workio_submit_work(wc);
  2735. break;
  2736. default:
  2737. ok = false;
  2738. break;
  2739. }
  2740. }
  2741. tq_freeze(mythr->q);
  2742. return NULL;
  2743. }
  2744. static void *api_thread(void *userdata)
  2745. {
  2746. struct thr_info *mythr = userdata;
  2747. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2748. api(api_thr_id);
  2749. PTH(mythr) = 0L;
  2750. return NULL;
  2751. }
  2752. void thread_reportin(struct thr_info *thr)
  2753. {
  2754. gettimeofday(&thr->last, NULL);
  2755. thr->cgpu->status = LIFE_WELL;
  2756. thr->getwork = false;
  2757. thr->cgpu->device_last_well = time(NULL);
  2758. }
  2759. static inline void thread_reportout(struct thr_info *thr)
  2760. {
  2761. thr->getwork = true;
  2762. }
  2763. static void hashmeter(int thr_id, struct timeval *diff,
  2764. unsigned long hashes_done)
  2765. {
  2766. struct timeval temp_tv_end, total_diff;
  2767. double secs;
  2768. double local_secs;
  2769. double utility, efficiency = 0.0;
  2770. static double local_mhashes_done = 0;
  2771. static double rolling = 0;
  2772. double local_mhashes = (double)hashes_done / 1000000.0;
  2773. bool showlog = false;
  2774. /* Update the last time this thread reported in */
  2775. if (thr_id >= 0) {
  2776. gettimeofday(&thr_info[thr_id].last, NULL);
  2777. thr_info[thr_id].cgpu->device_last_well = time(NULL);
  2778. }
  2779. /* Don't bother calculating anything if we're not displaying it */
  2780. if (opt_realquiet || !opt_log_interval)
  2781. return;
  2782. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  2783. /* So we can call hashmeter from a non worker thread */
  2784. if (thr_id >= 0) {
  2785. struct thr_info *thr = &thr_info[thr_id];
  2786. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2787. double thread_rolling = 0.0;
  2788. int i;
  2789. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  2790. thr_id, hashes_done, hashes_done / secs);
  2791. /* Rolling average for each thread and each device */
  2792. decay_time(&thr->rolling, local_mhashes / secs);
  2793. for (i = 0; i < mining_threads; i++) {
  2794. struct thr_info *th = &thr_info[i];
  2795. if (th->cgpu == cgpu)
  2796. thread_rolling += th->rolling;
  2797. }
  2798. mutex_lock(&hash_lock);
  2799. decay_time(&cgpu->rolling, thread_rolling);
  2800. cgpu->total_mhashes += local_mhashes;
  2801. mutex_unlock(&hash_lock);
  2802. // If needed, output detailed, per-device stats
  2803. if (want_per_device_stats) {
  2804. struct timeval now;
  2805. struct timeval elapsed;
  2806. gettimeofday(&now, NULL);
  2807. timeval_subtract(&elapsed, &now, &thr->cgpu->last_message_tv);
  2808. if (opt_log_interval <= elapsed.tv_sec) {
  2809. struct cgpu_info *cgpu = thr->cgpu;
  2810. char logline[255];
  2811. cgpu->last_message_tv = now;
  2812. get_statline(logline, cgpu);
  2813. if (!curses_active) {
  2814. printf("%s \r", logline);
  2815. fflush(stdout);
  2816. } else
  2817. applog(LOG_INFO, "%s", logline);
  2818. }
  2819. }
  2820. }
  2821. /* Totals are updated by all threads so can race without locking */
  2822. mutex_lock(&hash_lock);
  2823. gettimeofday(&temp_tv_end, NULL);
  2824. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  2825. total_mhashes_done += local_mhashes;
  2826. local_mhashes_done += local_mhashes;
  2827. if (total_diff.tv_sec < opt_log_interval)
  2828. /* Only update the total every opt_log_interval seconds */
  2829. goto out_unlock;
  2830. showlog = true;
  2831. gettimeofday(&total_tv_end, NULL);
  2832. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  2833. decay_time(&rolling, local_mhashes_done / local_secs);
  2834. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  2835. total_secs = (double)total_diff.tv_sec +
  2836. ((double)total_diff.tv_usec / 1000000.0);
  2837. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2838. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2839. sprintf(statusline, "%s(%ds):%.1f (avg):%.1f Mh/s | Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.1f/m",
  2840. want_per_device_stats ? "ALL " : "",
  2841. opt_log_interval, rolling, total_mhashes_done / total_secs,
  2842. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  2843. local_mhashes_done = 0;
  2844. out_unlock:
  2845. mutex_unlock(&hash_lock);
  2846. if (showlog) {
  2847. if (!curses_active) {
  2848. printf("%s \r", statusline);
  2849. fflush(stdout);
  2850. } else
  2851. applog(LOG_INFO, "%s", statusline);
  2852. }
  2853. }
  2854. static void *longpoll_thread(void *userdata);
  2855. static bool pool_active(struct pool *pool, bool pinging)
  2856. {
  2857. bool ret = false;
  2858. json_t *val;
  2859. CURL *curl;
  2860. bool rolltime;
  2861. curl = curl_easy_init();
  2862. if (unlikely(!curl)) {
  2863. applog(LOG_ERR, "CURL initialisation failed");
  2864. return false;
  2865. }
  2866. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  2867. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2868. true, false, &rolltime, pool, false);
  2869. if (val) {
  2870. struct work *work = make_work();
  2871. bool rc;
  2872. rc = work_decode(json_object_get(val, "result"), work);
  2873. if (rc) {
  2874. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  2875. pool->pool_no, pool->rpc_url);
  2876. work->pool = pool;
  2877. work->rolltime = rolltime;
  2878. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  2879. tq_push(thr_info[stage_thr_id].q, work);
  2880. total_getworks++;
  2881. pool->getwork_requested++;
  2882. inc_queued();
  2883. ret = true;
  2884. gettimeofday(&pool->tv_idle, NULL);
  2885. } else {
  2886. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  2887. pool->pool_no, pool->rpc_url);
  2888. free_work(work);
  2889. }
  2890. json_decref(val);
  2891. if (pool->lp_url)
  2892. goto out;
  2893. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  2894. if (pool->hdr_path) {
  2895. char *copy_start, *hdr_path;
  2896. bool need_slash = false;
  2897. hdr_path = pool->hdr_path;
  2898. if (strstr(hdr_path, "://")) {
  2899. pool->lp_url = hdr_path;
  2900. hdr_path = NULL;
  2901. } else {
  2902. /* absolute path, on current server */
  2903. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  2904. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  2905. need_slash = true;
  2906. pool->lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  2907. if (!pool->lp_url) {
  2908. applog(LOG_ERR, "Malloc failure in pool_active");
  2909. return false;
  2910. }
  2911. sprintf(pool->lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  2912. }
  2913. } else
  2914. pool->lp_url = NULL;
  2915. if (want_longpoll && !pool->lp_started) {
  2916. pool->lp_started = true;
  2917. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  2918. quit(1, "Failed to create pool longpoll thread");
  2919. }
  2920. } else {
  2921. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  2922. pool->pool_no, pool->rpc_url);
  2923. if (!pinging)
  2924. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  2925. }
  2926. out:
  2927. curl_easy_cleanup(curl);
  2928. return ret;
  2929. }
  2930. static void pool_died(struct pool *pool)
  2931. {
  2932. if (!pool_tset(pool, &pool->idle)) {
  2933. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2934. gettimeofday(&pool->tv_idle, NULL);
  2935. switch_pools(NULL);
  2936. }
  2937. }
  2938. static inline int cp_prio(void)
  2939. {
  2940. int prio;
  2941. mutex_lock(&control_lock);
  2942. prio = currentpool->prio;
  2943. mutex_unlock(&control_lock);
  2944. return prio;
  2945. }
  2946. static void pool_resus(struct pool *pool)
  2947. {
  2948. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  2949. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  2950. switch_pools(NULL);
  2951. }
  2952. static long requested_tv_sec;
  2953. static bool queue_request(struct thr_info *thr, bool needed)
  2954. {
  2955. int rq = requests_queued();
  2956. struct workio_cmd *wc;
  2957. struct timeval now;
  2958. gettimeofday(&now, NULL);
  2959. /* Space out retrieval of extra work according to the number of mining
  2960. * threads */
  2961. if (rq >= mining_threads + staged_extras &&
  2962. (now.tv_sec - requested_tv_sec) < (opt_scantime / (mining_threads + 1) ?: 1))
  2963. return true;
  2964. /* fill out work request message */
  2965. wc = calloc(1, sizeof(*wc));
  2966. if (unlikely(!wc)) {
  2967. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  2968. return false;
  2969. }
  2970. wc->cmd = WC_GET_WORK;
  2971. if (thr)
  2972. wc->thr = thr;
  2973. else
  2974. wc->thr = NULL;
  2975. /* If we're queueing work faster than we can stage it, consider the
  2976. * system lagging and allow work to be gathered from another pool if
  2977. * possible */
  2978. if (rq && needed && !requests_staged() && !opt_fail_only)
  2979. wc->lagging = true;
  2980. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  2981. /* send work request to workio thread */
  2982. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2983. applog(LOG_ERR, "Failed to tq_push in queue_request");
  2984. workio_cmd_free(wc);
  2985. return false;
  2986. }
  2987. requested_tv_sec = now.tv_sec;
  2988. inc_queued();
  2989. return true;
  2990. }
  2991. static struct work *hash_pop(const struct timespec *abstime)
  2992. {
  2993. struct work *work = NULL;
  2994. int rc = 0;
  2995. mutex_lock(stgd_lock);
  2996. while (!getq->frozen && !HASH_COUNT(staged_work) && !rc)
  2997. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  2998. if (HASH_COUNT(staged_work)) {
  2999. work = staged_work;
  3000. HASH_DEL(staged_work, work);
  3001. if (work->clone || work->longpoll)
  3002. --staged_extras;
  3003. }
  3004. mutex_unlock(stgd_lock);
  3005. return work;
  3006. }
  3007. static inline bool should_roll(struct work *work)
  3008. {
  3009. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE)
  3010. return true;
  3011. return false;
  3012. }
  3013. static inline bool can_roll(struct work *work)
  3014. {
  3015. return (work->pool && !stale_work(work, false) && work->rolltime &&
  3016. work->rolls < 11 && !work->clone);
  3017. }
  3018. static void roll_work(struct work *work)
  3019. {
  3020. uint32_t *work_ntime;
  3021. uint32_t ntime;
  3022. work_ntime = (uint32_t *)(work->data + 68);
  3023. ntime = be32toh(*work_ntime);
  3024. ntime++;
  3025. *work_ntime = htobe32(ntime);
  3026. local_work++;
  3027. work->rolls++;
  3028. work->blk.nonce = 0;
  3029. applog(LOG_DEBUG, "Successfully rolled work");
  3030. /* This is now a different work item so it needs a different ID for the
  3031. * hashtable */
  3032. work->id = total_work++;
  3033. }
  3034. static bool reuse_work(struct work *work)
  3035. {
  3036. if (can_roll(work) && should_roll(work)) {
  3037. roll_work(work);
  3038. return true;
  3039. }
  3040. return false;
  3041. }
  3042. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  3043. const int thr_id)
  3044. {
  3045. bool newreq = false, ret = false;
  3046. struct timespec abstime = {0, 0};
  3047. struct timeval now;
  3048. struct work *work_heap;
  3049. struct pool *pool;
  3050. int failures = 0;
  3051. /* Tell the watchdog thread this thread is waiting on getwork and
  3052. * should not be restarted */
  3053. thread_reportout(thr);
  3054. if (opt_benchmark) {
  3055. get_benchmark_work(work);
  3056. thread_reportin(thr);
  3057. return true;
  3058. }
  3059. retry:
  3060. pool = current_pool();
  3061. if (!requested || requests_queued() < opt_queue) {
  3062. if (unlikely(!queue_request(thr, true))) {
  3063. applog(LOG_WARNING, "Failed to queue_request in get_work");
  3064. goto out;
  3065. }
  3066. newreq = true;
  3067. }
  3068. if (reuse_work(work)) {
  3069. ret = true;
  3070. goto out;
  3071. }
  3072. if (requested && !newreq && !requests_staged() && requests_queued() >= mining_threads &&
  3073. !pool_tset(pool, &pool->lagging)) {
  3074. applog(LOG_WARNING, "Pool %d not providing work fast enough", pool->pool_no);
  3075. pool->getfail_occasions++;
  3076. total_go++;
  3077. }
  3078. newreq = requested = false;
  3079. gettimeofday(&now, NULL);
  3080. abstime.tv_sec = now.tv_sec + 60;
  3081. applog(LOG_DEBUG, "Popping work from get queue to get work");
  3082. /* wait for 1st response, or get cached response */
  3083. work_heap = hash_pop(&abstime);
  3084. if (unlikely(!work_heap)) {
  3085. /* Attempt to switch pools if this one times out */
  3086. pool_died(pool);
  3087. goto retry;
  3088. }
  3089. if (stale_work(work_heap, false)) {
  3090. dec_queued();
  3091. discard_work(work_heap);
  3092. goto retry;
  3093. }
  3094. pool = work_heap->pool;
  3095. /* If we make it here we have succeeded in getting fresh work */
  3096. if (!work_heap->mined) {
  3097. pool_tclear(pool, &pool->lagging);
  3098. if (pool_tclear(pool, &pool->idle))
  3099. pool_resus(pool);
  3100. }
  3101. memcpy(work, work_heap, sizeof(*work));
  3102. /* Hand out a clone if we can roll this work item */
  3103. if (reuse_work(work_heap)) {
  3104. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  3105. stage_work(work_heap);
  3106. work->clone = true;
  3107. } else {
  3108. dec_queued();
  3109. free_work(work_heap);
  3110. }
  3111. ret = true;
  3112. out:
  3113. if (unlikely(ret == false)) {
  3114. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  3115. applog(LOG_ERR, "Failed %d times to get_work");
  3116. return ret;
  3117. }
  3118. applog(LOG_DEBUG, "Retrying after %d seconds", fail_pause);
  3119. sleep(fail_pause);
  3120. fail_pause += opt_fail_pause;
  3121. goto retry;
  3122. }
  3123. fail_pause = opt_fail_pause;
  3124. work->thr_id = thr_id;
  3125. thread_reportin(thr);
  3126. if (ret)
  3127. work->mined = true;
  3128. return ret;
  3129. }
  3130. bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  3131. {
  3132. struct workio_cmd *wc;
  3133. /* fill out work request message */
  3134. wc = calloc(1, sizeof(*wc));
  3135. if (unlikely(!wc)) {
  3136. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  3137. return false;
  3138. }
  3139. wc->u.work = make_work();
  3140. wc->cmd = WC_SUBMIT_WORK;
  3141. wc->thr = thr;
  3142. memcpy(wc->u.work, work_in, sizeof(*work_in));
  3143. wc->u.work->share_found_time = time(NULL);
  3144. applog(LOG_DEBUG, "Pushing submit work to work thread");
  3145. /* send solution to workio thread */
  3146. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3147. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  3148. goto err_out;
  3149. }
  3150. return true;
  3151. err_out:
  3152. workio_cmd_free(wc);
  3153. return false;
  3154. }
  3155. bool hashtest(const struct work *work)
  3156. {
  3157. uint32_t *data32 = (uint32_t *)(work->data);
  3158. unsigned char swap[128];
  3159. uint32_t *swap32 = (uint32_t *)swap;
  3160. unsigned char hash1[32];
  3161. unsigned char hash2[32];
  3162. uint32_t *hash2_32 = (uint32_t *)hash2;
  3163. int i;
  3164. for (i = 0; i < 80 / 4; i++)
  3165. swap32[i] = swab32(data32[i]);
  3166. sha2(swap, 80, hash1, false);
  3167. sha2(hash1, 32, hash2, false);
  3168. for (i = 0; i < 32 / 4; i++)
  3169. hash2_32[i] = swab32(hash2_32[i]);
  3170. memcpy((void*)work->hash, hash2, 32);
  3171. return fulltest(work->hash, work->target);
  3172. }
  3173. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  3174. {
  3175. work->data[64 + 12 + 0] = (nonce >> 0) & 0xff;
  3176. work->data[64 + 12 + 1] = (nonce >> 8) & 0xff;
  3177. work->data[64 + 12 + 2] = (nonce >> 16) & 0xff;
  3178. work->data[64 + 12 + 3] = (nonce >> 24) & 0xff;
  3179. /* Do one last check before attempting to submit the work */
  3180. if (!hashtest(work)) {
  3181. applog(LOG_INFO, "Share below target");
  3182. return true;
  3183. }
  3184. return submit_work_sync(thr, work);
  3185. }
  3186. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  3187. {
  3188. if (wdiff->tv_sec > opt_scantime ||
  3189. work->blk.nonce >= MAXTHREADS - hashes ||
  3190. hashes >= 0xfffffffe ||
  3191. stale_work(work, false))
  3192. return true;
  3193. return false;
  3194. }
  3195. void *miner_thread(void *userdata)
  3196. {
  3197. struct thr_info *mythr = userdata;
  3198. const int thr_id = mythr->id;
  3199. struct cgpu_info *cgpu = mythr->cgpu;
  3200. const struct device_api *api = cgpu->api;
  3201. /* Try to cycle approximately 5 times before each log update */
  3202. const unsigned long def_cycle = opt_log_interval / 5 ? : 1;
  3203. long cycle;
  3204. struct timeval tv_start, tv_end, tv_workstart, tv_lastupdate;
  3205. struct timeval diff, sdiff, wdiff;
  3206. uint32_t max_nonce = api->can_limit_work ? api->can_limit_work(mythr) : 0xffffffff;
  3207. uint32_t hashes_done = 0;
  3208. uint32_t hashes;
  3209. struct work *work = make_work();
  3210. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3211. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  3212. bool requested = false;
  3213. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3214. if (api->thread_init && !api->thread_init(mythr)) {
  3215. cgpu->device_last_not_well = time(NULL);
  3216. cgpu->device_not_well_reason = REASON_THREAD_FAIL_INIT;
  3217. cgpu->thread_fail_init_count++;
  3218. goto out;
  3219. }
  3220. thread_reportout(mythr);
  3221. applog(LOG_DEBUG, "Popping ping in miner thread");
  3222. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  3223. sdiff.tv_sec = sdiff.tv_usec = 0;
  3224. gettimeofday(&tv_lastupdate, NULL);
  3225. while (1) {
  3226. work_restart[thr_id].restart = 0;
  3227. if (api->free_work && likely(work->pool))
  3228. api->free_work(mythr, work);
  3229. if (unlikely(!get_work(work, requested, mythr, thr_id))) {
  3230. applog(LOG_ERR, "work retrieval failed, exiting "
  3231. "mining thread %d", thr_id);
  3232. break;
  3233. }
  3234. requested = false;
  3235. cycle = (can_roll(work) && should_roll(work)) ? 1 : def_cycle;
  3236. gettimeofday(&tv_workstart, NULL);
  3237. work->blk.nonce = 0;
  3238. cgpu->max_hashes = 0;
  3239. if (api->prepare_work && !api->prepare_work(mythr, work)) {
  3240. applog(LOG_ERR, "work prepare failed, exiting "
  3241. "mining thread %d", thr_id);
  3242. break;
  3243. }
  3244. do {
  3245. gettimeofday(&tv_start, NULL);
  3246. hashes = api->scanhash(mythr, work, work->blk.nonce + max_nonce);
  3247. if (unlikely(work_restart[thr_id].restart)) {
  3248. /* Apart from device_thread 0, we stagger the
  3249. * starting of every next thread to try and get
  3250. * all devices busy before worrying about
  3251. * getting work for their extra threads */
  3252. if (mythr->device_thread) {
  3253. struct timespec rgtp;
  3254. rgtp.tv_sec = 0;
  3255. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  3256. nanosleep(&rgtp, NULL);
  3257. }
  3258. break;
  3259. }
  3260. if (unlikely(!hashes)) {
  3261. applog(LOG_ERR, "%s %d failure, disabling!", api->name, cgpu->device_id);
  3262. cgpu->deven = DEV_DISABLED;
  3263. cgpu->device_last_not_well = time(NULL);
  3264. cgpu->device_not_well_reason = REASON_THREAD_ZERO_HASH;
  3265. cgpu->thread_zero_hash_count++;
  3266. goto disabled;
  3267. }
  3268. hashes_done += hashes;
  3269. if (hashes > cgpu->max_hashes)
  3270. cgpu->max_hashes = hashes;
  3271. gettimeofday(&tv_end, NULL);
  3272. timeval_subtract(&diff, &tv_end, &tv_start);
  3273. sdiff.tv_sec += diff.tv_sec;
  3274. sdiff.tv_usec += diff.tv_usec;
  3275. if (sdiff.tv_usec > 1000000) {
  3276. ++sdiff.tv_sec;
  3277. sdiff.tv_usec -= 1000000;
  3278. }
  3279. timeval_subtract(&wdiff, &tv_end, &tv_workstart);
  3280. if (!requested) {
  3281. if (wdiff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  3282. thread_reportout(mythr);
  3283. if (unlikely(!queue_request(mythr, false))) {
  3284. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  3285. cgpu->device_last_not_well = time(NULL);
  3286. cgpu->device_not_well_reason = REASON_THREAD_FAIL_QUEUE;
  3287. cgpu->thread_fail_queue_count++;
  3288. goto out;
  3289. }
  3290. thread_reportin(mythr);
  3291. requested = true;
  3292. }
  3293. }
  3294. if (unlikely(sdiff.tv_sec < cycle)) {
  3295. if (likely(!api->can_limit_work || max_nonce == 0xffffffff))
  3296. continue;
  3297. {
  3298. int mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  3299. mult *= cycle;
  3300. if (max_nonce > (0xffffffff * 0x400) / mult)
  3301. max_nonce = 0xffffffff;
  3302. else
  3303. max_nonce = (max_nonce * mult) / 0x400;
  3304. }
  3305. } else if (unlikely(sdiff.tv_sec > cycle) && api->can_limit_work) {
  3306. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  3307. } else if (unlikely(sdiff.tv_usec > 100000) && api->can_limit_work) {
  3308. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  3309. }
  3310. timeval_subtract(&diff, &tv_end, &tv_lastupdate);
  3311. if (diff.tv_sec >= opt_log_interval) {
  3312. hashmeter(thr_id, &diff, hashes_done);
  3313. hashes_done = 0;
  3314. tv_lastupdate = tv_end;
  3315. }
  3316. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED)) {
  3317. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3318. disabled:
  3319. mythr->rolling = mythr->cgpu->rolling = 0;
  3320. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  3321. thread_reportout(mythr);
  3322. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3323. thread_reportin(mythr);
  3324. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3325. }
  3326. sdiff.tv_sec = sdiff.tv_usec = 0;
  3327. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  3328. }
  3329. out:
  3330. if (api->thread_shutdown)
  3331. api->thread_shutdown(mythr);
  3332. thread_reportin(mythr);
  3333. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3334. tq_freeze(mythr->q);
  3335. return NULL;
  3336. }
  3337. enum {
  3338. STAT_SLEEP_INTERVAL = 1,
  3339. STAT_CTR_INTERVAL = 10000000,
  3340. FAILURE_INTERVAL = 30,
  3341. };
  3342. /* Stage another work item from the work returned in a longpoll */
  3343. static void convert_to_work(json_t *val, bool rolltime, struct pool *pool)
  3344. {
  3345. struct work *work, *work_clone;
  3346. bool rc;
  3347. work = make_work();
  3348. rc = work_decode(json_object_get(val, "result"), work);
  3349. if (unlikely(!rc)) {
  3350. applog(LOG_ERR, "Could not convert longpoll data to work");
  3351. free_work(work);
  3352. return;
  3353. }
  3354. work->pool = pool;
  3355. work->rolltime = rolltime;
  3356. work->longpoll = true;
  3357. /* We'll be checking this work item twice, but we already know it's
  3358. * from a new block so explicitly force the new block detection now
  3359. * rather than waiting for it to hit the stage thread. This also
  3360. * allows testwork to know whether LP discovered the block or not. */
  3361. test_work_current(work);
  3362. /* Don't use backup LPs as work if we have failover-only enabled */
  3363. if (pool != current_pool() && opt_fail_only) {
  3364. free_work(work);
  3365. return;
  3366. }
  3367. work_clone = make_work();
  3368. memcpy(work_clone, work, sizeof(struct work));
  3369. while (reuse_work(work)) {
  3370. work_clone->clone = true;
  3371. work_clone->longpoll = false;
  3372. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  3373. if (unlikely(!stage_work(work_clone)))
  3374. break;
  3375. work_clone = make_work();
  3376. memcpy(work_clone, work, sizeof(struct work));
  3377. }
  3378. free_work(work_clone);
  3379. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  3380. if (unlikely(!stage_work(work)))
  3381. free_work(work);
  3382. else
  3383. applog(LOG_DEBUG, "Converted longpoll data to work");
  3384. }
  3385. /* If we want longpoll, enable it for the chosen default pool, or, if
  3386. * the pool does not support longpoll, find the first one that does
  3387. * and use its longpoll support */
  3388. static struct pool *select_longpoll_pool(struct pool *cp)
  3389. {
  3390. int i;
  3391. if (cp->hdr_path)
  3392. return cp;
  3393. for (i = 0; i < total_pools; i++) {
  3394. struct pool *pool = pools[i];
  3395. if (pool->hdr_path)
  3396. return pool;
  3397. }
  3398. return NULL;
  3399. }
  3400. static void *longpoll_thread(void *userdata)
  3401. {
  3402. struct pool *cp = (struct pool *)userdata;
  3403. /* This *pool is the source of the actual longpoll, not the pool we've
  3404. * tied it to */
  3405. struct pool *pool = NULL;
  3406. struct timeval start, end;
  3407. CURL *curl = NULL;
  3408. int failures = 0;
  3409. bool rolltime;
  3410. curl = curl_easy_init();
  3411. if (unlikely(!curl)) {
  3412. applog(LOG_ERR, "CURL initialisation failed");
  3413. goto out;
  3414. }
  3415. retry_pool:
  3416. pool = select_longpoll_pool(cp);
  3417. if (!pool) {
  3418. applog(LOG_WARNING, "No suitable long-poll found for pool %s", cp->rpc_url);
  3419. while (!pool) {
  3420. sleep(60);
  3421. pool = select_longpoll_pool(cp);
  3422. }
  3423. }
  3424. /* Any longpoll from any pool is enough for this to be true */
  3425. have_longpoll = true;
  3426. if (cp == pool)
  3427. applog(LOG_WARNING, "Long-polling activated for %s", pool->lp_url);
  3428. else
  3429. applog(LOG_WARNING, "Long-polling activated for pool %s via %s", cp->rpc_url, pool->lp_url);
  3430. while (42) {
  3431. json_t *val, *soval;
  3432. gettimeofday(&start, NULL);
  3433. /* Longpoll connections can be persistent for a very long time
  3434. * and any number of issues could have come up in the meantime
  3435. * so always establish a fresh connection instead of relying on
  3436. * a persistent one. */
  3437. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  3438. val = json_rpc_call(curl, pool->lp_url, pool->rpc_userpass, rpc_req,
  3439. false, true, &rolltime, pool, false);
  3440. if (likely(val)) {
  3441. soval = json_object_get(json_object_get(val, "result"), "submitold");
  3442. if (soval)
  3443. pool->submit_old = json_is_true(soval);
  3444. else
  3445. pool->submit_old = false;
  3446. convert_to_work(val, rolltime, pool);
  3447. failures = 0;
  3448. json_decref(val);
  3449. } else {
  3450. /* Some pools regularly drop the longpoll request so
  3451. * only see this as longpoll failure if it happens
  3452. * immediately and just restart it the rest of the
  3453. * time. */
  3454. gettimeofday(&end, NULL);
  3455. if (end.tv_sec - start.tv_sec > 30)
  3456. continue;
  3457. if (opt_retries == -1 || failures++ < opt_retries) {
  3458. applog(LOG_WARNING,
  3459. "longpoll failed for %s, sleeping for 30s", pool->lp_url);
  3460. sleep(30);
  3461. } else {
  3462. applog(LOG_ERR,
  3463. "longpoll failed for %s, ending thread", pool->lp_url);
  3464. goto out;
  3465. }
  3466. }
  3467. if (pool != cp) {
  3468. pool = select_longpoll_pool(cp);
  3469. if (unlikely(!pool))
  3470. goto retry_pool;
  3471. }
  3472. if (unlikely(pool->removed))
  3473. break;
  3474. }
  3475. out:
  3476. if (curl)
  3477. curl_easy_cleanup(curl);
  3478. return NULL;
  3479. }
  3480. static void stop_longpoll(void)
  3481. {
  3482. int i;
  3483. want_longpoll = false;
  3484. for (i = 0; i < total_pools; ++i)
  3485. {
  3486. struct pool *pool = pools[i];
  3487. if (unlikely(!pool->lp_started))
  3488. continue;
  3489. pool->lp_started = false;
  3490. pthread_cancel(pool->longpoll_thread);
  3491. }
  3492. have_longpoll = false;
  3493. }
  3494. static void start_longpoll(void)
  3495. {
  3496. int i;
  3497. want_longpoll = true;
  3498. for (i = 0; i < total_pools; ++i)
  3499. {
  3500. struct pool *pool = pools[i];
  3501. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  3502. continue;
  3503. pool->lp_started = true;
  3504. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  3505. quit(1, "Failed to create pool longpoll thread");
  3506. }
  3507. }
  3508. void reinit_device(struct cgpu_info *cgpu)
  3509. {
  3510. if (cgpu->api->reinit_device)
  3511. cgpu->api->reinit_device(cgpu);
  3512. }
  3513. static struct timeval rotate_tv;
  3514. /* We reap curls if they are unused for over a minute */
  3515. static void reap_curl(struct pool *pool)
  3516. {
  3517. struct curl_ent *ent, *iter;
  3518. struct timeval now;
  3519. gettimeofday(&now, NULL);
  3520. mutex_lock(&pool->pool_lock);
  3521. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  3522. if (now.tv_sec - ent->tv.tv_sec > 60) {
  3523. applog(LOG_DEBUG, "Reaped curl %d from pool %d", pool->curls, pool->pool_no);
  3524. pool->curls--;
  3525. list_del(&ent->node);
  3526. curl_easy_cleanup(ent->curl);
  3527. free(ent);
  3528. }
  3529. }
  3530. mutex_unlock(&pool->pool_lock);
  3531. }
  3532. static void *watchpool_thread(void __maybe_unused *userdata)
  3533. {
  3534. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3535. while (42) {
  3536. struct timeval now;
  3537. int i;
  3538. gettimeofday(&now, NULL);
  3539. for (i = 0; i < total_pools; i++) {
  3540. struct pool *pool = pools[i];
  3541. reap_curl(pool);
  3542. if (!pool->enabled)
  3543. continue;
  3544. /* Test pool is idle once every minute */
  3545. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  3546. gettimeofday(&pool->tv_idle, NULL);
  3547. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  3548. pool_resus(pool);
  3549. }
  3550. }
  3551. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  3552. gettimeofday(&rotate_tv, NULL);
  3553. switch_pools(NULL);
  3554. }
  3555. sleep(30);
  3556. }
  3557. return NULL;
  3558. }
  3559. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  3560. * the screen at regular intervals, and restarts threads if they appear to have
  3561. * died. */
  3562. static void *watchdog_thread(void __maybe_unused *userdata)
  3563. {
  3564. const unsigned int interval = 3;
  3565. struct timeval zero_tv;
  3566. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3567. memset(&zero_tv, 0, sizeof(struct timeval));
  3568. gettimeofday(&rotate_tv, NULL);
  3569. while (1) {
  3570. int i;
  3571. struct timeval now;
  3572. sleep(interval);
  3573. if (requests_queued() < opt_queue)
  3574. queue_request(NULL, false);
  3575. hashmeter(-1, &zero_tv, 0);
  3576. #ifdef HAVE_CURSES
  3577. if (curses_active_locked()) {
  3578. change_logwinsize();
  3579. curses_print_status();
  3580. for (i = 0; i < mining_threads; i++)
  3581. curses_print_devstatus(i);
  3582. touchwin(statuswin);
  3583. wrefresh(statuswin);
  3584. touchwin(logwin);
  3585. wrefresh(logwin);
  3586. unlock_curses();
  3587. }
  3588. #endif
  3589. gettimeofday(&now, NULL);
  3590. if (!sched_paused && !should_run()) {
  3591. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  3592. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3593. if (!schedstart.enable) {
  3594. quit(0, "Terminating execution as planned");
  3595. break;
  3596. }
  3597. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  3598. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3599. sched_paused = true;
  3600. for (i = 0; i < mining_threads; i++) {
  3601. struct thr_info *thr;
  3602. thr = &thr_info[i];
  3603. thr->pause = true;
  3604. }
  3605. } else if (sched_paused && should_run()) {
  3606. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  3607. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3608. if (schedstop.enable)
  3609. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  3610. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3611. sched_paused = false;
  3612. for (i = 0; i < mining_threads; i++) {
  3613. struct thr_info *thr;
  3614. thr = &thr_info[i];
  3615. /* Don't touch disabled devices */
  3616. if (thr->cgpu->deven == DEV_DISABLED)
  3617. continue;
  3618. thr->pause = false;
  3619. tq_push(thr->q, &ping);
  3620. }
  3621. }
  3622. #ifdef HAVE_OPENCL
  3623. for (i = 0; i < total_devices; ++i) {
  3624. struct cgpu_info *cgpu = devices[i];
  3625. struct thr_info *thr = cgpu->thread;
  3626. enum dev_enable *denable;
  3627. int gpu;
  3628. if (cgpu->api != &opencl_api)
  3629. continue;
  3630. /* Use only one thread per device to determine if the GPU is healthy */
  3631. if (i >= nDevs)
  3632. break;
  3633. gpu = thr->cgpu->device_id;
  3634. denable = &cgpu->deven;
  3635. #ifdef HAVE_ADL
  3636. if (adl_active && gpus[gpu].has_adl)
  3637. gpu_autotune(gpu, denable);
  3638. if (opt_debug && gpus[gpu].has_adl) {
  3639. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  3640. float temp = 0, vddc = 0;
  3641. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  3642. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  3643. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  3644. }
  3645. #endif
  3646. /* Thread is waiting on getwork or disabled */
  3647. if (thr->getwork || *denable == DEV_DISABLED)
  3648. continue;
  3649. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  3650. applog(LOG_ERR, "Device %d recovered, GPU %d declared WELL!", i, gpu);
  3651. gpus[gpu].status = LIFE_WELL;
  3652. gpus[gpu].device_last_well = time(NULL);
  3653. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  3654. thr->rolling = thr->cgpu->rolling = 0;
  3655. gpus[gpu].status = LIFE_SICK;
  3656. applog(LOG_ERR, "Device %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  3657. gettimeofday(&thr->sick, NULL);
  3658. gpus[gpu].device_last_not_well = time(NULL);
  3659. gpus[gpu].device_not_well_reason = REASON_DEV_SICK_IDLE_60;
  3660. gpus[gpu].dev_sick_idle_60_count++;
  3661. #ifdef HAVE_ADL
  3662. if (adl_active && gpus[gpu].has_adl && gpu_activity(gpu) > 50) {
  3663. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  3664. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  3665. } else
  3666. #endif
  3667. if (opt_restart) {
  3668. applog(LOG_ERR, "Attempting to restart GPU");
  3669. reinit_device(thr->cgpu);
  3670. }
  3671. } else if (now.tv_sec - thr->last.tv_sec > 600 && gpus[i].status == LIFE_SICK) {
  3672. gpus[gpu].status = LIFE_DEAD;
  3673. applog(LOG_ERR, "Device %d not responding for more than 10 minutes, GPU %d declared DEAD!", i, gpu);
  3674. gettimeofday(&thr->sick, NULL);
  3675. gpus[gpu].device_last_not_well = time(NULL);
  3676. gpus[gpu].device_not_well_reason = REASON_DEV_DEAD_IDLE_600;
  3677. gpus[gpu].dev_dead_idle_600_count++;
  3678. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  3679. (gpus[i].status == LIFE_SICK || gpus[i].status == LIFE_DEAD)) {
  3680. /* Attempt to restart a GPU that's sick or dead once every minute */
  3681. gettimeofday(&thr->sick, NULL);
  3682. #ifdef HAVE_ADL
  3683. if (adl_active && gpus[gpu].has_adl && gpu_activity(gpu) > 50) {
  3684. /* Again do not attempt to restart a device that may have hard hung */
  3685. } else
  3686. #endif
  3687. if (opt_restart)
  3688. reinit_device(thr->cgpu);
  3689. }
  3690. }
  3691. #endif
  3692. }
  3693. return NULL;
  3694. }
  3695. static void log_print_status(struct cgpu_info *cgpu)
  3696. {
  3697. char logline[255];
  3698. get_statline(logline, cgpu);
  3699. applog(LOG_WARNING, "%s", logline);
  3700. }
  3701. static void print_summary(void)
  3702. {
  3703. struct timeval diff;
  3704. int hours, mins, secs, i;
  3705. double utility, efficiency = 0.0;
  3706. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  3707. hours = diff.tv_sec / 3600;
  3708. mins = (diff.tv_sec % 3600) / 60;
  3709. secs = diff.tv_sec % 60;
  3710. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3711. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3712. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  3713. applog(LOG_WARNING, "Started at %s", datestamp);
  3714. if (total_pools == 1)
  3715. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  3716. #ifdef WANT_CPUMINE
  3717. if (opt_n_threads)
  3718. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  3719. #endif
  3720. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  3721. if (total_secs)
  3722. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  3723. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  3724. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  3725. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  3726. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  3727. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  3728. if (total_accepted || total_rejected)
  3729. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  3730. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  3731. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  3732. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  3733. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  3734. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  3735. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  3736. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  3737. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  3738. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  3739. if (total_pools > 1) {
  3740. for (i = 0; i < total_pools; i++) {
  3741. struct pool *pool = pools[i];
  3742. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  3743. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  3744. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  3745. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  3746. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  3747. if (pool->accepted || pool->rejected)
  3748. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3749. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3750. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  3751. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  3752. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  3753. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  3754. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  3755. }
  3756. }
  3757. applog(LOG_WARNING, "Summary of per device statistics:\n");
  3758. for (i = 0; i < total_devices; ++i) {
  3759. if (devices[i]->deven == DEV_ENABLED)
  3760. log_print_status(devices[i]);
  3761. }
  3762. if (opt_shares)
  3763. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  3764. fflush(stdout);
  3765. fflush(stderr);
  3766. if (opt_shares > total_accepted)
  3767. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  3768. }
  3769. static void clean_up(void)
  3770. {
  3771. #ifdef HAVE_OPENCL
  3772. clear_adl(nDevs);
  3773. #endif
  3774. #ifdef HAVE_LIBUSB
  3775. libusb_exit(NULL);
  3776. #endif
  3777. gettimeofday(&total_tv_end, NULL);
  3778. #ifdef HAVE_CURSES
  3779. disable_curses();
  3780. #endif
  3781. if (!opt_realquiet && successful_connect)
  3782. print_summary();
  3783. if (opt_n_threads)
  3784. free(cpus);
  3785. curl_global_cleanup();
  3786. }
  3787. void quit(int status, const char *format, ...)
  3788. {
  3789. va_list ap;
  3790. clean_up();
  3791. if (format) {
  3792. va_start(ap, format);
  3793. vfprintf(stderr, format, ap);
  3794. va_end(ap);
  3795. }
  3796. fprintf(stderr, "\n");
  3797. fflush(stderr);
  3798. #if defined(unix)
  3799. if (forkpid > 0) {
  3800. kill(forkpid, SIGTERM);
  3801. forkpid = 0;
  3802. }
  3803. #endif
  3804. exit(status);
  3805. }
  3806. #ifdef HAVE_CURSES
  3807. char *curses_input(const char *query)
  3808. {
  3809. char *input;
  3810. echo();
  3811. input = malloc(255);
  3812. if (!input)
  3813. quit(1, "Failed to malloc input");
  3814. leaveok(logwin, false);
  3815. wlogprint("%s:\n", query);
  3816. wgetnstr(logwin, input, 255);
  3817. if (!strlen(input))
  3818. strcpy(input, "-1");
  3819. leaveok(logwin, true);
  3820. noecho();
  3821. return input;
  3822. }
  3823. #endif
  3824. int add_pool_details(bool live, char *url, char *user, char *pass)
  3825. {
  3826. struct pool *pool;
  3827. if (total_pools == MAX_POOLS)
  3828. return ADD_POOL_MAXIMUM;
  3829. pool = add_pool();
  3830. pool->rpc_url = url;
  3831. pool->rpc_user = user;
  3832. pool->rpc_pass = pass;
  3833. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3834. if (!pool->rpc_userpass)
  3835. quit(1, "Failed to malloc userpass");
  3836. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3837. /* Test the pool is not idle if we're live running, otherwise
  3838. * it will be tested separately */
  3839. pool->enabled = true;
  3840. if (live && !pool_active(pool, false))
  3841. pool->idle = true;
  3842. return ADD_POOL_OK;
  3843. }
  3844. #ifdef HAVE_CURSES
  3845. static bool input_pool(bool live)
  3846. {
  3847. char *url = NULL, *user = NULL, *pass = NULL;
  3848. bool ret = false;
  3849. immedok(logwin, true);
  3850. if (total_pools == MAX_POOLS) {
  3851. wlogprint("Reached maximum number of pools.\n");
  3852. goto out;
  3853. }
  3854. wlogprint("Input server details.\n");
  3855. url = curses_input("URL");
  3856. if (!url)
  3857. goto out;
  3858. if (strncmp(url, "http://", 7) &&
  3859. strncmp(url, "https://", 8)) {
  3860. char *httpinput;
  3861. httpinput = malloc(255);
  3862. if (!httpinput)
  3863. quit(1, "Failed to malloc httpinput");
  3864. strcpy(httpinput, "http://");
  3865. strncat(httpinput, url, 248);
  3866. free(url);
  3867. url = httpinput;
  3868. }
  3869. user = curses_input("Username");
  3870. if (!user)
  3871. goto out;
  3872. pass = curses_input("Password");
  3873. if (!pass)
  3874. goto out;
  3875. ret = (add_pool_details(live, url, user, pass) == ADD_POOL_OK);
  3876. out:
  3877. immedok(logwin, false);
  3878. if (!ret) {
  3879. if (url)
  3880. free(url);
  3881. if (user)
  3882. free(user);
  3883. if (pass)
  3884. free(pass);
  3885. }
  3886. return ret;
  3887. }
  3888. #endif
  3889. #if defined(unix)
  3890. static void fork_monitor()
  3891. {
  3892. // Make a pipe: [readFD, writeFD]
  3893. int pfd[2];
  3894. int r = pipe(pfd);
  3895. if (r<0) {
  3896. perror("pipe - failed to create pipe for --monitor");
  3897. exit(1);
  3898. }
  3899. // Make stderr write end of pipe
  3900. fflush(stderr);
  3901. r = dup2(pfd[1], 2);
  3902. if (r<0) {
  3903. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  3904. exit(1);
  3905. }
  3906. r = close(pfd[1]);
  3907. if (r<0) {
  3908. perror("close - failed to close write end of pipe for --monitor");
  3909. exit(1);
  3910. }
  3911. // Don't allow a dying monitor to kill the main process
  3912. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  3913. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  3914. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  3915. perror("signal - failed to edit signal mask for --monitor");
  3916. exit(1);
  3917. }
  3918. // Fork a child process
  3919. forkpid = fork();
  3920. if (forkpid<0) {
  3921. perror("fork - failed to fork child process for --monitor");
  3922. exit(1);
  3923. }
  3924. // Child: launch monitor command
  3925. if (0==forkpid) {
  3926. // Make stdin read end of pipe
  3927. r = dup2(pfd[0], 0);
  3928. if (r<0) {
  3929. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  3930. exit(1);
  3931. }
  3932. close(pfd[0]);
  3933. if (r<0) {
  3934. perror("close - in child, failed to close read end of pipe for --monitor");
  3935. exit(1);
  3936. }
  3937. // Launch user specified command
  3938. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  3939. perror("execl - in child failed to exec user specified command for --monitor");
  3940. exit(1);
  3941. }
  3942. // Parent: clean up unused fds and bail
  3943. r = close(pfd[0]);
  3944. if (r<0) {
  3945. perror("close - failed to close read end of pipe for --monitor");
  3946. exit(1);
  3947. }
  3948. }
  3949. #endif // defined(unix)
  3950. #ifdef HAVE_CURSES
  3951. void enable_curses(void) {
  3952. int x,y;
  3953. lock_curses();
  3954. if (curses_active) {
  3955. unlock_curses();
  3956. return;
  3957. }
  3958. mainwin = initscr();
  3959. getmaxyx(mainwin, y, x);
  3960. statuswin = newwin(logstart, x, 0, 0);
  3961. leaveok(statuswin, true);
  3962. logwin = newwin(y - logcursor, 0, logcursor, 0);
  3963. idlok(logwin, true);
  3964. scrollok(logwin, true);
  3965. leaveok(logwin, true);
  3966. cbreak();
  3967. noecho();
  3968. curses_active = true;
  3969. statusy = logstart;
  3970. unlock_curses();
  3971. }
  3972. #endif
  3973. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  3974. #ifndef WANT_CPUMINE
  3975. struct device_api cpu_api;
  3976. struct device_api cpu_api = {
  3977. .name = "CPU",
  3978. };
  3979. #endif
  3980. #ifdef USE_BITFORCE
  3981. extern struct device_api bitforce_api;
  3982. #endif
  3983. #ifdef USE_ICARUS
  3984. extern struct device_api icarus_api;
  3985. #endif
  3986. #ifdef USE_ZTEX
  3987. extern struct device_api ztex_api;
  3988. #endif
  3989. static int cgminer_id_count = 0;
  3990. void enable_device(struct cgpu_info *cgpu)
  3991. {
  3992. cgpu->deven = DEV_ENABLED;
  3993. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  3994. mining_threads += cgpu->threads;
  3995. #ifdef HAVE_OPENCL
  3996. if (cgpu->api == &opencl_api) {
  3997. gpu_threads += cgpu->threads;
  3998. }
  3999. #endif
  4000. }
  4001. struct _cgpu_devid_counter {
  4002. char name[4];
  4003. int lastid;
  4004. UT_hash_handle hh;
  4005. };
  4006. bool add_cgpu(struct cgpu_info*cgpu)
  4007. {
  4008. static struct _cgpu_devid_counter *devids = NULL;
  4009. struct _cgpu_devid_counter *d;
  4010. HASH_FIND_STR(devids, cgpu->api->name, d);
  4011. if (d)
  4012. cgpu->device_id = ++d->lastid;
  4013. else
  4014. {
  4015. d = malloc(sizeof(*d));
  4016. memcpy(d->name, cgpu->api->name, sizeof(d->name));
  4017. cgpu->device_id = d->lastid = 0;
  4018. HASH_ADD_STR(devids, name, d);
  4019. }
  4020. devices[total_devices++] = cgpu;
  4021. return true;
  4022. }
  4023. int main(int argc, char *argv[])
  4024. {
  4025. struct block *block, *tmpblock;
  4026. struct work *work, *tmpwork;
  4027. bool pools_active = false;
  4028. struct sigaction handler;
  4029. struct thr_info *thr;
  4030. unsigned int k;
  4031. int i, j;
  4032. /* This dangerous functions tramples random dynamically allocated
  4033. * variables so do it before anything at all */
  4034. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  4035. quit(1, "Failed to curl_global_init");
  4036. initial_args = malloc(sizeof(char *) * (argc + 1));
  4037. for (i = 0; i < argc; i++)
  4038. initial_args[i] = strdup(argv[i]);
  4039. initial_args[argc] = NULL;
  4040. #ifdef HAVE_LIBUSB
  4041. libusb_init(NULL);
  4042. #endif
  4043. mutex_init(&hash_lock);
  4044. mutex_init(&qd_lock);
  4045. #ifdef HAVE_CURSES
  4046. mutex_init(&curses_lock);
  4047. #endif
  4048. mutex_init(&control_lock);
  4049. mutex_init(&sharelog_lock);
  4050. mutex_init(&ch_lock);
  4051. rwlock_init(&blk_lock);
  4052. rwlock_init(&netacc_lock);
  4053. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  4054. #ifdef WANT_CPUMINE
  4055. init_max_name_len();
  4056. #endif
  4057. handler.sa_handler = &sighandler;
  4058. handler.sa_flags = 0;
  4059. sigemptyset(&handler.sa_mask);
  4060. sigaction(SIGTERM, &handler, &termhandler);
  4061. sigaction(SIGINT, &handler, &inthandler);
  4062. opt_kernel_path = alloca(PATH_MAX);
  4063. strcpy(opt_kernel_path, CGMINER_PREFIX);
  4064. cgminer_path = alloca(PATH_MAX);
  4065. strcpy(cgminer_path, dirname(argv[0]));
  4066. strcat(cgminer_path, "/");
  4067. #ifdef WANT_CPUMINE
  4068. // Hack to make cgminer silent when called recursively on WIN32
  4069. int skip_to_bench = 0;
  4070. #if defined(WIN32)
  4071. char buf[32];
  4072. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  4073. skip_to_bench = 1;
  4074. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  4075. skip_to_bench = 1;
  4076. #endif // defined(WIN32)
  4077. #endif
  4078. devcursor = 8;
  4079. logstart = devcursor + 1;
  4080. logcursor = logstart + 1;
  4081. block = calloc(sizeof(struct block), 1);
  4082. if (unlikely(!block))
  4083. quit (1, "main OOM");
  4084. for (i = 0; i < 36; i++)
  4085. strcat(block->hash, "0");
  4086. HASH_ADD_STR(blocks, hash, block);
  4087. strcpy(current_block, block->hash);
  4088. INIT_LIST_HEAD(&scan_devices);
  4089. memset(gpus, 0, sizeof(gpus));
  4090. for (i = 0; i < MAX_GPUDEVICES; i++)
  4091. gpus[i].dynamic = true;
  4092. memset(devices, 0, sizeof(devices));
  4093. /* parse command line */
  4094. opt_register_table(opt_config_table,
  4095. "Options for both config file and command line");
  4096. opt_register_table(opt_cmdline_table,
  4097. "Options for command line only");
  4098. opt_parse(&argc, argv, applog_and_exit);
  4099. if (argc != 1)
  4100. quit(1, "Unexpected extra commandline arguments");
  4101. if (!config_loaded)
  4102. load_default_config();
  4103. if (opt_benchmark) {
  4104. struct pool *pool;
  4105. want_longpoll = false;
  4106. pool = calloc(sizeof(struct pool), 1);
  4107. pool->pool_no = 0;
  4108. pools[total_pools++] = pool;
  4109. pthread_mutex_init(&pool->pool_lock, NULL);
  4110. pool->rpc_url = malloc(255);
  4111. strcpy(pool->rpc_url, "Benchmark");
  4112. pool->rpc_user = pool->rpc_url;
  4113. pool->rpc_pass = pool->rpc_url;
  4114. pool->enabled = true;
  4115. pool->idle = false;
  4116. successful_connect = true;
  4117. }
  4118. #ifdef HAVE_CURSES
  4119. if (opt_realquiet || devices_enabled == -1)
  4120. use_curses = false;
  4121. if (use_curses)
  4122. enable_curses();
  4123. #endif
  4124. applog(LOG_WARNING, "Started %s", packagename);
  4125. if (cnfbuf) {
  4126. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  4127. switch (fileconf_load) {
  4128. case 0:
  4129. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  4130. applog(LOG_WARNING, "Configuration file could not be used.");
  4131. break;
  4132. case -1:
  4133. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  4134. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  4135. break;
  4136. default:
  4137. break;
  4138. }
  4139. free(cnfbuf);
  4140. cnfbuf = NULL;
  4141. }
  4142. strcat(opt_kernel_path, "/");
  4143. if (want_per_device_stats)
  4144. opt_log_output = true;
  4145. #ifdef WANT_CPUMINE
  4146. if (0<=opt_bench_algo) {
  4147. double rate = bench_algo_stage3(opt_bench_algo);
  4148. if (!skip_to_bench) {
  4149. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  4150. } else {
  4151. // Write result to shared memory for parent
  4152. #if defined(WIN32)
  4153. char unique_name[64];
  4154. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  4155. HANDLE map_handle = CreateFileMapping(
  4156. INVALID_HANDLE_VALUE, // use paging file
  4157. NULL, // default security attributes
  4158. PAGE_READWRITE, // read/write access
  4159. 0, // size: high 32-bits
  4160. 4096, // size: low 32-bits
  4161. unique_name // name of map object
  4162. );
  4163. if (NULL!=map_handle) {
  4164. void *shared_mem = MapViewOfFile(
  4165. map_handle, // object to map view of
  4166. FILE_MAP_WRITE, // read/write access
  4167. 0, // high offset: map from
  4168. 0, // low offset: beginning
  4169. 0 // default: map entire file
  4170. );
  4171. if (NULL!=shared_mem)
  4172. CopyMemory(shared_mem, &rate, sizeof(rate));
  4173. (void)UnmapViewOfFile(shared_mem);
  4174. }
  4175. (void)CloseHandle(map_handle);
  4176. }
  4177. #endif
  4178. }
  4179. exit(0);
  4180. }
  4181. #endif
  4182. #ifdef HAVE_OPENCL
  4183. if (!opt_nogpu)
  4184. opencl_api.api_detect();
  4185. #endif
  4186. #ifdef USE_ICARUS
  4187. icarus_api.api_detect();
  4188. #endif
  4189. #ifdef USE_BITFORCE
  4190. bitforce_api.api_detect();
  4191. #endif
  4192. #ifdef USE_ZTEX
  4193. ztex_api.api_detect();
  4194. #endif
  4195. #ifdef WANT_CPUMINE
  4196. cpu_api.api_detect();
  4197. #endif
  4198. if (devices_enabled == -1) {
  4199. applog(LOG_ERR, "Devices detected:");
  4200. for (i = 0; i < total_devices; ++i) {
  4201. struct cgpu_info *cgpu = devices[i];
  4202. if (cgpu->name)
  4203. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->name, cgpu->api->dname);
  4204. else
  4205. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->api->dname);
  4206. }
  4207. quit(0, "%d devices listed", total_devices);
  4208. }
  4209. mining_threads = 0;
  4210. gpu_threads = 0;
  4211. if (devices_enabled) {
  4212. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  4213. if (devices_enabled & (1 << i)) {
  4214. if (i >= total_devices)
  4215. quit (1, "Command line options set a device that doesn't exist");
  4216. enable_device(devices[i]);
  4217. } else if (i < total_devices) {
  4218. if (opt_removedisabled) {
  4219. if (devices[i]->api == &cpu_api)
  4220. --opt_n_threads;
  4221. } else {
  4222. enable_device(devices[i]);
  4223. }
  4224. devices[i]->deven = DEV_DISABLED;
  4225. }
  4226. }
  4227. total_devices = cgminer_id_count;
  4228. } else {
  4229. for (i = 0; i < total_devices; ++i)
  4230. enable_device(devices[i]);
  4231. }
  4232. if (!total_devices)
  4233. quit(1, "All devices disabled, cannot mine!");
  4234. load_temp_cutoffs();
  4235. logstart += total_devices;
  4236. logcursor = logstart + 1;
  4237. #ifdef HAVE_CURSES
  4238. check_winsizes();
  4239. #endif
  4240. if (!total_pools) {
  4241. applog(LOG_WARNING, "Need to specify at least one pool server.");
  4242. #ifdef HAVE_CURSES
  4243. if (!use_curses || !input_pool(false))
  4244. #endif
  4245. quit(1, "Pool setup failed");
  4246. }
  4247. for (i = 0; i < total_pools; i++) {
  4248. struct pool *pool = pools[i];
  4249. if (!pool->rpc_userpass) {
  4250. if (!pool->rpc_user || !pool->rpc_pass)
  4251. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  4252. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4253. if (!pool->rpc_userpass)
  4254. quit(1, "Failed to malloc userpass");
  4255. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4256. } else {
  4257. pool->rpc_user = malloc(strlen(pool->rpc_userpass) + 1);
  4258. if (!pool->rpc_user)
  4259. quit(1, "Failed to malloc user");
  4260. strcpy(pool->rpc_user, pool->rpc_userpass);
  4261. pool->rpc_user = strtok(pool->rpc_user, ":");
  4262. if (!pool->rpc_user)
  4263. quit(1, "Failed to find colon delimiter in userpass");
  4264. }
  4265. }
  4266. /* Set the currentpool to pool 0 */
  4267. currentpool = pools[0];
  4268. #ifdef HAVE_SYSLOG_H
  4269. if (use_syslog)
  4270. openlog(PACKAGE, LOG_PID, LOG_USER);
  4271. #endif
  4272. #if defined(unix)
  4273. if (opt_stderr_cmd)
  4274. fork_monitor();
  4275. #endif // defined(unix)
  4276. total_threads = mining_threads + 7;
  4277. work_restart = calloc(total_threads, sizeof(*work_restart));
  4278. if (!work_restart)
  4279. quit(1, "Failed to calloc work_restart");
  4280. thr_info = calloc(total_threads, sizeof(*thr));
  4281. if (!thr_info)
  4282. quit(1, "Failed to calloc thr_info");
  4283. /* init workio thread info */
  4284. work_thr_id = mining_threads;
  4285. thr = &thr_info[work_thr_id];
  4286. thr->id = work_thr_id;
  4287. thr->q = tq_new();
  4288. if (!thr->q)
  4289. quit(1, "Failed to tq_new");
  4290. /* start work I/O thread */
  4291. if (thr_info_create(thr, NULL, workio_thread, thr))
  4292. quit(1, "workio thread create failed");
  4293. stage_thr_id = mining_threads + 1;
  4294. thr = &thr_info[stage_thr_id];
  4295. thr->q = tq_new();
  4296. if (!thr->q)
  4297. quit(1, "Failed to tq_new");
  4298. /* start stage thread */
  4299. if (thr_info_create(thr, NULL, stage_thread, thr))
  4300. quit(1, "stage thread create failed");
  4301. pthread_detach(thr->pth);
  4302. /* Create a unique get work queue */
  4303. getq = tq_new();
  4304. if (!getq)
  4305. quit(1, "Failed to create getq");
  4306. /* We use the getq mutex as the staged lock */
  4307. stgd_lock = &getq->mutex;
  4308. if (opt_benchmark)
  4309. goto begin_bench;
  4310. for (i = 0; i < total_pools; i++) {
  4311. struct pool *pool = pools[i];
  4312. pool->enabled = true;
  4313. pool->idle = true;
  4314. }
  4315. applog(LOG_NOTICE, "Probing for an alive pool");
  4316. do {
  4317. /* Look for at least one active pool before starting */
  4318. for (i = 0; i < total_pools; i++) {
  4319. struct pool *pool = pools[i];
  4320. if (pool_active(pool, false)) {
  4321. if (!currentpool)
  4322. currentpool = pool;
  4323. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  4324. pools_active = true;
  4325. break;
  4326. } else {
  4327. if (pool == currentpool)
  4328. currentpool = NULL;
  4329. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  4330. }
  4331. }
  4332. if (!pools_active) {
  4333. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  4334. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  4335. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  4336. for (i = 0; i < total_pools; i++) {
  4337. struct pool *pool;
  4338. pool = pools[i];
  4339. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  4340. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  4341. }
  4342. #ifdef HAVE_CURSES
  4343. if (use_curses) {
  4344. halfdelay(150);
  4345. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  4346. if (getch() != ERR)
  4347. quit(0, "No servers could be used! Exiting.");
  4348. nocbreak();
  4349. } else
  4350. #endif
  4351. quit(0, "No servers could be used! Exiting.");
  4352. }
  4353. } while (!pools_active);
  4354. begin_bench:
  4355. total_mhashes_done = 0;
  4356. for (i = 0; i < total_devices; i++) {
  4357. struct cgpu_info *cgpu = devices[i];
  4358. cgpu->rolling = cgpu->total_mhashes = 0;
  4359. }
  4360. gettimeofday(&total_tv_start, NULL);
  4361. gettimeofday(&total_tv_end, NULL);
  4362. get_datestamp(datestamp, &total_tv_start);
  4363. #ifndef HAVE_OPENCL
  4364. opt_g_threads = 0;
  4365. #endif
  4366. // Start threads
  4367. k = 0;
  4368. for (i = 0; i < total_devices; ++i) {
  4369. struct cgpu_info *cgpu = devices[i];
  4370. for (j = 0; j < cgpu->threads; ++j, ++k) {
  4371. thr = &thr_info[k];
  4372. thr->id = k;
  4373. thr->cgpu = cgpu;
  4374. thr->device_thread = j;
  4375. thr->q = tq_new();
  4376. if (!thr->q)
  4377. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->api->name, cgpu->device_id, i);
  4378. /* Enable threads for devices set not to mine but disable
  4379. * their queue in case we wish to enable them later */
  4380. if (cgpu->deven != DEV_DISABLED) {
  4381. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  4382. tq_push(thr->q, &ping);
  4383. }
  4384. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  4385. continue;
  4386. thread_reportout(thr);
  4387. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  4388. quit(1, "thread %d create failed", thr->id);
  4389. cgpu->thread = thr;
  4390. }
  4391. }
  4392. #ifdef HAVE_OPENCL
  4393. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  4394. for (i = 0; i < nDevs; i++)
  4395. pause_dynamic_threads(i);
  4396. #endif
  4397. #ifdef WANT_CPUMINE
  4398. applog(LOG_INFO, "%d cpu miner threads started, "
  4399. "using SHA256 '%s' algorithm.",
  4400. opt_n_threads,
  4401. algo_names[opt_algo]);
  4402. #endif
  4403. gettimeofday(&total_tv_start, NULL);
  4404. gettimeofday(&total_tv_end, NULL);
  4405. watchpool_thr_id = mining_threads + 2;
  4406. thr = &thr_info[watchpool_thr_id];
  4407. /* start watchpool thread */
  4408. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  4409. quit(1, "watchpool thread create failed");
  4410. pthread_detach(thr->pth);
  4411. watchdog_thr_id = mining_threads + 3;
  4412. thr = &thr_info[watchdog_thr_id];
  4413. /* start watchdog thread */
  4414. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  4415. quit(1, "watchdog thread create failed");
  4416. pthread_detach(thr->pth);
  4417. /* Create reinit gpu thread */
  4418. gpur_thr_id = mining_threads + 4;
  4419. thr = &thr_info[gpur_thr_id];
  4420. thr->q = tq_new();
  4421. if (!thr->q)
  4422. quit(1, "tq_new failed for gpur_thr_id");
  4423. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  4424. quit(1, "reinit_gpu thread create failed");
  4425. /* Create API socket thread */
  4426. api_thr_id = mining_threads + 5;
  4427. thr = &thr_info[api_thr_id];
  4428. if (thr_info_create(thr, NULL, api_thread, thr))
  4429. quit(1, "API thread create failed");
  4430. pthread_detach(thr->pth);
  4431. #ifdef HAVE_CURSES
  4432. /* Create curses input thread for keyboard input. Create this last so
  4433. * that we know all threads are created since this can call kill_work
  4434. * to try and shut down ll previous threads. */
  4435. input_thr_id = mining_threads + 6;
  4436. thr = &thr_info[input_thr_id];
  4437. if (thr_info_create(thr, NULL, input_thread, thr))
  4438. quit(1, "input thread create failed");
  4439. pthread_detach(thr->pth);
  4440. #endif
  4441. /* main loop - simply wait for workio thread to exit. This is not the
  4442. * normal exit path and only occurs should the workio_thread die
  4443. * unexpectedly */
  4444. pthread_join(thr_info[work_thr_id].pth, NULL);
  4445. applog(LOG_INFO, "workio thread dead, exiting.");
  4446. clean_up();
  4447. /* Not really necessary, but let's clean this up too anyway */
  4448. HASH_ITER(hh, staged_work, work, tmpwork) {
  4449. HASH_DEL(staged_work, work);
  4450. free_work(work);
  4451. }
  4452. HASH_ITER(hh, blocks, block, tmpblock) {
  4453. HASH_DEL(blocks, block);
  4454. free(block);
  4455. }
  4456. #if defined(unix)
  4457. if (forkpid > 0) {
  4458. kill(forkpid, SIGTERM);
  4459. forkpid = 0;
  4460. }
  4461. #endif
  4462. return 0;
  4463. }