cgminer.c 130 KB

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