cgminer.c 146 KB

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