cgminer.c 140 KB

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