main.c 142 KB

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