cgminer.c 134 KB

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