hid-nintendo.c 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * HID driver for Nintendo Switch Joy-Cons and Pro Controllers
  4. *
  5. * Copyright (c) 2019-2021 Daniel J. Ogorchock <djogorchock@gmail.com>
  6. * Portions Copyright (c) 2020 Nadia Holmquist Pedersen <nadia@nhp.sh>
  7. * Copyright (c) 2022 Emily Strickland <linux@emily.st>
  8. * Copyright (c) 2023 Ryan McClelland <rymcclel@gmail.com>
  9. *
  10. * The following resources/projects were referenced for this driver:
  11. * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
  12. * https://gitlab.com/pjranki/joycon-linux-kernel (Peter Rankin)
  13. * https://github.com/FrotBot/SwitchProConLinuxUSB
  14. * https://github.com/MTCKC/ProconXInput
  15. * https://github.com/Davidobot/BetterJoyForCemu
  16. * hid-wiimote kernel hid driver
  17. * hid-logitech-hidpp driver
  18. * hid-sony driver
  19. *
  20. * This driver supports the Nintendo Switch Joy-Cons and Pro Controllers. The
  21. * Pro Controllers can either be used over USB or Bluetooth.
  22. *
  23. * This driver also incorporates support for Nintendo Switch Online controllers
  24. * for the NES, SNES, Sega Genesis, and N64.
  25. *
  26. * The driver will retrieve the factory calibration info from the controllers,
  27. * so little to no user calibration should be required.
  28. *
  29. */
  30. #include "hid-ids.h"
  31. #include <linux/unaligned.h>
  32. #include <linux/delay.h>
  33. #include <linux/device.h>
  34. #include <linux/kernel.h>
  35. #include <linux/hid.h>
  36. #include <linux/idr.h>
  37. #include <linux/input.h>
  38. #include <linux/jiffies.h>
  39. #include <linux/leds.h>
  40. #include <linux/module.h>
  41. #include <linux/power_supply.h>
  42. #include <linux/spinlock.h>
  43. /*
  44. * Reference the url below for the following HID report defines:
  45. * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
  46. */
  47. /* Output Reports */
  48. #define JC_OUTPUT_RUMBLE_AND_SUBCMD 0x01
  49. #define JC_OUTPUT_FW_UPDATE_PKT 0x03
  50. #define JC_OUTPUT_RUMBLE_ONLY 0x10
  51. #define JC_OUTPUT_MCU_DATA 0x11
  52. #define JC_OUTPUT_USB_CMD 0x80
  53. /* Subcommand IDs */
  54. #define JC_SUBCMD_STATE 0x00
  55. #define JC_SUBCMD_MANUAL_BT_PAIRING 0x01
  56. #define JC_SUBCMD_REQ_DEV_INFO 0x02
  57. #define JC_SUBCMD_SET_REPORT_MODE 0x03
  58. #define JC_SUBCMD_TRIGGERS_ELAPSED 0x04
  59. #define JC_SUBCMD_GET_PAGE_LIST_STATE 0x05
  60. #define JC_SUBCMD_SET_HCI_STATE 0x06
  61. #define JC_SUBCMD_RESET_PAIRING_INFO 0x07
  62. #define JC_SUBCMD_LOW_POWER_MODE 0x08
  63. #define JC_SUBCMD_SPI_FLASH_READ 0x10
  64. #define JC_SUBCMD_SPI_FLASH_WRITE 0x11
  65. #define JC_SUBCMD_RESET_MCU 0x20
  66. #define JC_SUBCMD_SET_MCU_CONFIG 0x21
  67. #define JC_SUBCMD_SET_MCU_STATE 0x22
  68. #define JC_SUBCMD_SET_PLAYER_LIGHTS 0x30
  69. #define JC_SUBCMD_GET_PLAYER_LIGHTS 0x31
  70. #define JC_SUBCMD_SET_HOME_LIGHT 0x38
  71. #define JC_SUBCMD_ENABLE_IMU 0x40
  72. #define JC_SUBCMD_SET_IMU_SENSITIVITY 0x41
  73. #define JC_SUBCMD_WRITE_IMU_REG 0x42
  74. #define JC_SUBCMD_READ_IMU_REG 0x43
  75. #define JC_SUBCMD_ENABLE_VIBRATION 0x48
  76. #define JC_SUBCMD_GET_REGULATED_VOLTAGE 0x50
  77. /* Input Reports */
  78. #define JC_INPUT_BUTTON_EVENT 0x3F
  79. #define JC_INPUT_SUBCMD_REPLY 0x21
  80. #define JC_INPUT_IMU_DATA 0x30
  81. #define JC_INPUT_MCU_DATA 0x31
  82. #define JC_INPUT_USB_RESPONSE 0x81
  83. /* Feature Reports */
  84. #define JC_FEATURE_LAST_SUBCMD 0x02
  85. #define JC_FEATURE_OTA_FW_UPGRADE 0x70
  86. #define JC_FEATURE_SETUP_MEM_READ 0x71
  87. #define JC_FEATURE_MEM_READ 0x72
  88. #define JC_FEATURE_ERASE_MEM_SECTOR 0x73
  89. #define JC_FEATURE_MEM_WRITE 0x74
  90. #define JC_FEATURE_LAUNCH 0x75
  91. /* USB Commands */
  92. #define JC_USB_CMD_CONN_STATUS 0x01
  93. #define JC_USB_CMD_HANDSHAKE 0x02
  94. #define JC_USB_CMD_BAUDRATE_3M 0x03
  95. #define JC_USB_CMD_NO_TIMEOUT 0x04
  96. #define JC_USB_CMD_EN_TIMEOUT 0x05
  97. #define JC_USB_RESET 0x06
  98. #define JC_USB_PRE_HANDSHAKE 0x91
  99. #define JC_USB_SEND_UART 0x92
  100. /* Magic value denoting presence of user calibration */
  101. #define JC_CAL_USR_MAGIC_0 0xB2
  102. #define JC_CAL_USR_MAGIC_1 0xA1
  103. #define JC_CAL_USR_MAGIC_SIZE 2
  104. /* SPI storage addresses of user calibration data */
  105. #define JC_CAL_USR_LEFT_MAGIC_ADDR 0x8010
  106. #define JC_CAL_USR_LEFT_DATA_ADDR 0x8012
  107. #define JC_CAL_USR_LEFT_DATA_END 0x801A
  108. #define JC_CAL_USR_RIGHT_MAGIC_ADDR 0x801B
  109. #define JC_CAL_USR_RIGHT_DATA_ADDR 0x801D
  110. #define JC_CAL_STICK_DATA_SIZE \
  111. (JC_CAL_USR_LEFT_DATA_END - JC_CAL_USR_LEFT_DATA_ADDR + 1)
  112. /* SPI storage addresses of factory calibration data */
  113. #define JC_CAL_FCT_DATA_LEFT_ADDR 0x603d
  114. #define JC_CAL_FCT_DATA_RIGHT_ADDR 0x6046
  115. /* SPI storage addresses of IMU factory calibration data */
  116. #define JC_IMU_CAL_FCT_DATA_ADDR 0x6020
  117. #define JC_IMU_CAL_FCT_DATA_END 0x6037
  118. #define JC_IMU_CAL_DATA_SIZE \
  119. (JC_IMU_CAL_FCT_DATA_END - JC_IMU_CAL_FCT_DATA_ADDR + 1)
  120. /* SPI storage addresses of IMU user calibration data */
  121. #define JC_IMU_CAL_USR_MAGIC_ADDR 0x8026
  122. #define JC_IMU_CAL_USR_DATA_ADDR 0x8028
  123. /* The raw analog joystick values will be mapped in terms of this magnitude */
  124. #define JC_MAX_STICK_MAG 32767
  125. #define JC_STICK_FUZZ 250
  126. #define JC_STICK_FLAT 500
  127. /* Hat values for pro controller's d-pad */
  128. #define JC_MAX_DPAD_MAG 1
  129. #define JC_DPAD_FUZZ 0
  130. #define JC_DPAD_FLAT 0
  131. /* Under most circumstances IMU reports are pushed every 15ms; use as default */
  132. #define JC_IMU_DFLT_AVG_DELTA_MS 15
  133. /* How many samples to sum before calculating average IMU report delta */
  134. #define JC_IMU_SAMPLES_PER_DELTA_AVG 300
  135. /* Controls how many dropped IMU packets at once trigger a warning message */
  136. #define JC_IMU_DROPPED_PKT_WARNING 3
  137. /*
  138. * The controller's accelerometer has a sensor resolution of 16bits and is
  139. * configured with a range of +-8000 milliGs. Therefore, the resolution can be
  140. * calculated thus: (2^16-1)/(8000 * 2) = 4.096 digits per milliG
  141. * Resolution per G (rather than per millliG): 4.096 * 1000 = 4096 digits per G
  142. * Alternatively: 1/4096 = .0002441 Gs per digit
  143. */
  144. #define JC_IMU_MAX_ACCEL_MAG 32767
  145. #define JC_IMU_ACCEL_RES_PER_G 4096
  146. #define JC_IMU_ACCEL_FUZZ 10
  147. #define JC_IMU_ACCEL_FLAT 0
  148. /*
  149. * The controller's gyroscope has a sensor resolution of 16bits and is
  150. * configured with a range of +-2000 degrees/second.
  151. * Digits per dps: (2^16 -1)/(2000*2) = 16.38375
  152. * dps per digit: 16.38375E-1 = .0610
  153. *
  154. * STMicro recommends in the datasheet to add 15% to the dps/digit. This allows
  155. * the full sensitivity range to be saturated without clipping. This yields more
  156. * accurate results, so it's the technique this driver uses.
  157. * dps per digit (corrected): .0610 * 1.15 = .0702
  158. * digits per dps (corrected): .0702E-1 = 14.247
  159. *
  160. * Now, 14.247 truncating to 14 loses a lot of precision, so we rescale the
  161. * min/max range by 1000.
  162. */
  163. #define JC_IMU_PREC_RANGE_SCALE 1000
  164. /* Note: change mag and res_per_dps if prec_range_scale is ever altered */
  165. #define JC_IMU_MAX_GYRO_MAG 32767000 /* (2^16-1)*1000 */
  166. #define JC_IMU_GYRO_RES_PER_DPS 14247 /* (14.247*1000) */
  167. #define JC_IMU_GYRO_FUZZ 10
  168. #define JC_IMU_GYRO_FLAT 0
  169. /* frequency/amplitude tables for rumble */
  170. struct joycon_rumble_freq_data {
  171. u16 high;
  172. u8 low;
  173. u16 freq; /* Hz*/
  174. };
  175. struct joycon_rumble_amp_data {
  176. u8 high;
  177. u16 low;
  178. u16 amp;
  179. };
  180. #if IS_ENABLED(CONFIG_NINTENDO_FF)
  181. /*
  182. * These tables are from
  183. * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md
  184. */
  185. static const struct joycon_rumble_freq_data joycon_rumble_frequencies[] = {
  186. /* high, low, freq */
  187. { 0x0000, 0x01, 41 }, { 0x0000, 0x02, 42 }, { 0x0000, 0x03, 43 },
  188. { 0x0000, 0x04, 44 }, { 0x0000, 0x05, 45 }, { 0x0000, 0x06, 46 },
  189. { 0x0000, 0x07, 47 }, { 0x0000, 0x08, 48 }, { 0x0000, 0x09, 49 },
  190. { 0x0000, 0x0A, 50 }, { 0x0000, 0x0B, 51 }, { 0x0000, 0x0C, 52 },
  191. { 0x0000, 0x0D, 53 }, { 0x0000, 0x0E, 54 }, { 0x0000, 0x0F, 55 },
  192. { 0x0000, 0x10, 57 }, { 0x0000, 0x11, 58 }, { 0x0000, 0x12, 59 },
  193. { 0x0000, 0x13, 60 }, { 0x0000, 0x14, 62 }, { 0x0000, 0x15, 63 },
  194. { 0x0000, 0x16, 64 }, { 0x0000, 0x17, 66 }, { 0x0000, 0x18, 67 },
  195. { 0x0000, 0x19, 69 }, { 0x0000, 0x1A, 70 }, { 0x0000, 0x1B, 72 },
  196. { 0x0000, 0x1C, 73 }, { 0x0000, 0x1D, 75 }, { 0x0000, 0x1e, 77 },
  197. { 0x0000, 0x1f, 78 }, { 0x0000, 0x20, 80 }, { 0x0400, 0x21, 82 },
  198. { 0x0800, 0x22, 84 }, { 0x0c00, 0x23, 85 }, { 0x1000, 0x24, 87 },
  199. { 0x1400, 0x25, 89 }, { 0x1800, 0x26, 91 }, { 0x1c00, 0x27, 93 },
  200. { 0x2000, 0x28, 95 }, { 0x2400, 0x29, 97 }, { 0x2800, 0x2a, 99 },
  201. { 0x2c00, 0x2b, 102 }, { 0x3000, 0x2c, 104 }, { 0x3400, 0x2d, 106 },
  202. { 0x3800, 0x2e, 108 }, { 0x3c00, 0x2f, 111 }, { 0x4000, 0x30, 113 },
  203. { 0x4400, 0x31, 116 }, { 0x4800, 0x32, 118 }, { 0x4c00, 0x33, 121 },
  204. { 0x5000, 0x34, 123 }, { 0x5400, 0x35, 126 }, { 0x5800, 0x36, 129 },
  205. { 0x5c00, 0x37, 132 }, { 0x6000, 0x38, 135 }, { 0x6400, 0x39, 137 },
  206. { 0x6800, 0x3a, 141 }, { 0x6c00, 0x3b, 144 }, { 0x7000, 0x3c, 147 },
  207. { 0x7400, 0x3d, 150 }, { 0x7800, 0x3e, 153 }, { 0x7c00, 0x3f, 157 },
  208. { 0x8000, 0x40, 160 }, { 0x8400, 0x41, 164 }, { 0x8800, 0x42, 167 },
  209. { 0x8c00, 0x43, 171 }, { 0x9000, 0x44, 174 }, { 0x9400, 0x45, 178 },
  210. { 0x9800, 0x46, 182 }, { 0x9c00, 0x47, 186 }, { 0xa000, 0x48, 190 },
  211. { 0xa400, 0x49, 194 }, { 0xa800, 0x4a, 199 }, { 0xac00, 0x4b, 203 },
  212. { 0xb000, 0x4c, 207 }, { 0xb400, 0x4d, 212 }, { 0xb800, 0x4e, 217 },
  213. { 0xbc00, 0x4f, 221 }, { 0xc000, 0x50, 226 }, { 0xc400, 0x51, 231 },
  214. { 0xc800, 0x52, 236 }, { 0xcc00, 0x53, 241 }, { 0xd000, 0x54, 247 },
  215. { 0xd400, 0x55, 252 }, { 0xd800, 0x56, 258 }, { 0xdc00, 0x57, 263 },
  216. { 0xe000, 0x58, 269 }, { 0xe400, 0x59, 275 }, { 0xe800, 0x5a, 281 },
  217. { 0xec00, 0x5b, 287 }, { 0xf000, 0x5c, 293 }, { 0xf400, 0x5d, 300 },
  218. { 0xf800, 0x5e, 306 }, { 0xfc00, 0x5f, 313 }, { 0x0001, 0x60, 320 },
  219. { 0x0401, 0x61, 327 }, { 0x0801, 0x62, 334 }, { 0x0c01, 0x63, 341 },
  220. { 0x1001, 0x64, 349 }, { 0x1401, 0x65, 357 }, { 0x1801, 0x66, 364 },
  221. { 0x1c01, 0x67, 372 }, { 0x2001, 0x68, 381 }, { 0x2401, 0x69, 389 },
  222. { 0x2801, 0x6a, 397 }, { 0x2c01, 0x6b, 406 }, { 0x3001, 0x6c, 415 },
  223. { 0x3401, 0x6d, 424 }, { 0x3801, 0x6e, 433 }, { 0x3c01, 0x6f, 443 },
  224. { 0x4001, 0x70, 453 }, { 0x4401, 0x71, 462 }, { 0x4801, 0x72, 473 },
  225. { 0x4c01, 0x73, 483 }, { 0x5001, 0x74, 494 }, { 0x5401, 0x75, 504 },
  226. { 0x5801, 0x76, 515 }, { 0x5c01, 0x77, 527 }, { 0x6001, 0x78, 538 },
  227. { 0x6401, 0x79, 550 }, { 0x6801, 0x7a, 562 }, { 0x6c01, 0x7b, 574 },
  228. { 0x7001, 0x7c, 587 }, { 0x7401, 0x7d, 600 }, { 0x7801, 0x7e, 613 },
  229. { 0x7c01, 0x7f, 626 }, { 0x8001, 0x00, 640 }, { 0x8401, 0x00, 654 },
  230. { 0x8801, 0x00, 668 }, { 0x8c01, 0x00, 683 }, { 0x9001, 0x00, 698 },
  231. { 0x9401, 0x00, 713 }, { 0x9801, 0x00, 729 }, { 0x9c01, 0x00, 745 },
  232. { 0xa001, 0x00, 761 }, { 0xa401, 0x00, 778 }, { 0xa801, 0x00, 795 },
  233. { 0xac01, 0x00, 812 }, { 0xb001, 0x00, 830 }, { 0xb401, 0x00, 848 },
  234. { 0xb801, 0x00, 867 }, { 0xbc01, 0x00, 886 }, { 0xc001, 0x00, 905 },
  235. { 0xc401, 0x00, 925 }, { 0xc801, 0x00, 945 }, { 0xcc01, 0x00, 966 },
  236. { 0xd001, 0x00, 987 }, { 0xd401, 0x00, 1009 }, { 0xd801, 0x00, 1031 },
  237. { 0xdc01, 0x00, 1053 }, { 0xe001, 0x00, 1076 }, { 0xe401, 0x00, 1100 },
  238. { 0xe801, 0x00, 1124 }, { 0xec01, 0x00, 1149 }, { 0xf001, 0x00, 1174 },
  239. { 0xf401, 0x00, 1199 }, { 0xf801, 0x00, 1226 }, { 0xfc01, 0x00, 1253 }
  240. };
  241. #define joycon_max_rumble_amp (1003)
  242. static const struct joycon_rumble_amp_data joycon_rumble_amplitudes[] = {
  243. /* high, low, amp */
  244. { 0x00, 0x0040, 0 },
  245. { 0x02, 0x8040, 10 }, { 0x04, 0x0041, 12 }, { 0x06, 0x8041, 14 },
  246. { 0x08, 0x0042, 17 }, { 0x0a, 0x8042, 20 }, { 0x0c, 0x0043, 24 },
  247. { 0x0e, 0x8043, 28 }, { 0x10, 0x0044, 33 }, { 0x12, 0x8044, 40 },
  248. { 0x14, 0x0045, 47 }, { 0x16, 0x8045, 56 }, { 0x18, 0x0046, 67 },
  249. { 0x1a, 0x8046, 80 }, { 0x1c, 0x0047, 95 }, { 0x1e, 0x8047, 112 },
  250. { 0x20, 0x0048, 117 }, { 0x22, 0x8048, 123 }, { 0x24, 0x0049, 128 },
  251. { 0x26, 0x8049, 134 }, { 0x28, 0x004a, 140 }, { 0x2a, 0x804a, 146 },
  252. { 0x2c, 0x004b, 152 }, { 0x2e, 0x804b, 159 }, { 0x30, 0x004c, 166 },
  253. { 0x32, 0x804c, 173 }, { 0x34, 0x004d, 181 }, { 0x36, 0x804d, 189 },
  254. { 0x38, 0x004e, 198 }, { 0x3a, 0x804e, 206 }, { 0x3c, 0x004f, 215 },
  255. { 0x3e, 0x804f, 225 }, { 0x40, 0x0050, 230 }, { 0x42, 0x8050, 235 },
  256. { 0x44, 0x0051, 240 }, { 0x46, 0x8051, 245 }, { 0x48, 0x0052, 251 },
  257. { 0x4a, 0x8052, 256 }, { 0x4c, 0x0053, 262 }, { 0x4e, 0x8053, 268 },
  258. { 0x50, 0x0054, 273 }, { 0x52, 0x8054, 279 }, { 0x54, 0x0055, 286 },
  259. { 0x56, 0x8055, 292 }, { 0x58, 0x0056, 298 }, { 0x5a, 0x8056, 305 },
  260. { 0x5c, 0x0057, 311 }, { 0x5e, 0x8057, 318 }, { 0x60, 0x0058, 325 },
  261. { 0x62, 0x8058, 332 }, { 0x64, 0x0059, 340 }, { 0x66, 0x8059, 347 },
  262. { 0x68, 0x005a, 355 }, { 0x6a, 0x805a, 362 }, { 0x6c, 0x005b, 370 },
  263. { 0x6e, 0x805b, 378 }, { 0x70, 0x005c, 387 }, { 0x72, 0x805c, 395 },
  264. { 0x74, 0x005d, 404 }, { 0x76, 0x805d, 413 }, { 0x78, 0x005e, 422 },
  265. { 0x7a, 0x805e, 431 }, { 0x7c, 0x005f, 440 }, { 0x7e, 0x805f, 450 },
  266. { 0x80, 0x0060, 460 }, { 0x82, 0x8060, 470 }, { 0x84, 0x0061, 480 },
  267. { 0x86, 0x8061, 491 }, { 0x88, 0x0062, 501 }, { 0x8a, 0x8062, 512 },
  268. { 0x8c, 0x0063, 524 }, { 0x8e, 0x8063, 535 }, { 0x90, 0x0064, 547 },
  269. { 0x92, 0x8064, 559 }, { 0x94, 0x0065, 571 }, { 0x96, 0x8065, 584 },
  270. { 0x98, 0x0066, 596 }, { 0x9a, 0x8066, 609 }, { 0x9c, 0x0067, 623 },
  271. { 0x9e, 0x8067, 636 }, { 0xa0, 0x0068, 650 }, { 0xa2, 0x8068, 665 },
  272. { 0xa4, 0x0069, 679 }, { 0xa6, 0x8069, 694 }, { 0xa8, 0x006a, 709 },
  273. { 0xaa, 0x806a, 725 }, { 0xac, 0x006b, 741 }, { 0xae, 0x806b, 757 },
  274. { 0xb0, 0x006c, 773 }, { 0xb2, 0x806c, 790 }, { 0xb4, 0x006d, 808 },
  275. { 0xb6, 0x806d, 825 }, { 0xb8, 0x006e, 843 }, { 0xba, 0x806e, 862 },
  276. { 0xbc, 0x006f, 881 }, { 0xbe, 0x806f, 900 }, { 0xc0, 0x0070, 920 },
  277. { 0xc2, 0x8070, 940 }, { 0xc4, 0x0071, 960 }, { 0xc6, 0x8071, 981 },
  278. { 0xc8, 0x0072, joycon_max_rumble_amp }
  279. };
  280. static const u16 JC_RUMBLE_DFLT_LOW_FREQ = 160;
  281. static const u16 JC_RUMBLE_DFLT_HIGH_FREQ = 320;
  282. static const unsigned short JC_RUMBLE_ZERO_AMP_PKT_CNT = 5;
  283. #endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */
  284. static const u16 JC_RUMBLE_PERIOD_MS = 50;
  285. /* States for controller state machine */
  286. enum joycon_ctlr_state {
  287. JOYCON_CTLR_STATE_INIT,
  288. JOYCON_CTLR_STATE_READ,
  289. JOYCON_CTLR_STATE_REMOVED,
  290. JOYCON_CTLR_STATE_SUSPENDED,
  291. };
  292. /* Controller type received as part of device info */
  293. enum joycon_ctlr_type {
  294. JOYCON_CTLR_TYPE_JCL = 0x01,
  295. JOYCON_CTLR_TYPE_JCR = 0x02,
  296. JOYCON_CTLR_TYPE_PRO = 0x03,
  297. JOYCON_CTLR_TYPE_NESL = 0x09,
  298. JOYCON_CTLR_TYPE_NESR = 0x0A,
  299. JOYCON_CTLR_TYPE_SNES = 0x0B,
  300. JOYCON_CTLR_TYPE_GEN = 0x0D,
  301. JOYCON_CTLR_TYPE_N64 = 0x0C,
  302. };
  303. struct joycon_stick_cal {
  304. s32 max;
  305. s32 min;
  306. s32 center;
  307. };
  308. struct joycon_imu_cal {
  309. s16 offset[3];
  310. s16 scale[3];
  311. };
  312. /*
  313. * All the controller's button values are stored in a u32.
  314. * They can be accessed with bitwise ANDs.
  315. */
  316. #define JC_BTN_Y BIT(0)
  317. #define JC_BTN_X BIT(1)
  318. #define JC_BTN_B BIT(2)
  319. #define JC_BTN_A BIT(3)
  320. #define JC_BTN_SR_R BIT(4)
  321. #define JC_BTN_SL_R BIT(5)
  322. #define JC_BTN_R BIT(6)
  323. #define JC_BTN_ZR BIT(7)
  324. #define JC_BTN_MINUS BIT(8)
  325. #define JC_BTN_PLUS BIT(9)
  326. #define JC_BTN_RSTICK BIT(10)
  327. #define JC_BTN_LSTICK BIT(11)
  328. #define JC_BTN_HOME BIT(12)
  329. #define JC_BTN_CAP BIT(13) /* capture button */
  330. #define JC_BTN_DOWN BIT(16)
  331. #define JC_BTN_UP BIT(17)
  332. #define JC_BTN_RIGHT BIT(18)
  333. #define JC_BTN_LEFT BIT(19)
  334. #define JC_BTN_SR_L BIT(20)
  335. #define JC_BTN_SL_L BIT(21)
  336. #define JC_BTN_L BIT(22)
  337. #define JC_BTN_ZL BIT(23)
  338. struct joycon_ctlr_button_mapping {
  339. u32 code;
  340. u32 bit;
  341. };
  342. /*
  343. * D-pad is configured as buttons for the left Joy-Con only!
  344. */
  345. static const struct joycon_ctlr_button_mapping left_joycon_button_mappings[] = {
  346. { BTN_TL, JC_BTN_L, },
  347. { BTN_TL2, JC_BTN_ZL, },
  348. { BTN_SELECT, JC_BTN_MINUS, },
  349. { BTN_THUMBL, JC_BTN_LSTICK, },
  350. { BTN_DPAD_UP, JC_BTN_UP, },
  351. { BTN_DPAD_DOWN, JC_BTN_DOWN, },
  352. { BTN_DPAD_LEFT, JC_BTN_LEFT, },
  353. { BTN_DPAD_RIGHT, JC_BTN_RIGHT, },
  354. { BTN_Z, JC_BTN_CAP, },
  355. { /* sentinel */ },
  356. };
  357. /*
  358. * The unused *right*-side triggers become the SL/SR triggers for the *left*
  359. * Joy-Con, if and only if we're not using a charging grip.
  360. */
  361. static const struct joycon_ctlr_button_mapping left_joycon_s_button_mappings[] = {
  362. { BTN_TR, JC_BTN_SL_L, },
  363. { BTN_TR2, JC_BTN_SR_L, },
  364. { /* sentinel */ },
  365. };
  366. static const struct joycon_ctlr_button_mapping right_joycon_button_mappings[] = {
  367. { BTN_EAST, JC_BTN_A, },
  368. { BTN_SOUTH, JC_BTN_B, },
  369. { BTN_NORTH, JC_BTN_X, },
  370. { BTN_WEST, JC_BTN_Y, },
  371. { BTN_TR, JC_BTN_R, },
  372. { BTN_TR2, JC_BTN_ZR, },
  373. { BTN_START, JC_BTN_PLUS, },
  374. { BTN_THUMBR, JC_BTN_RSTICK, },
  375. { BTN_MODE, JC_BTN_HOME, },
  376. { /* sentinel */ },
  377. };
  378. /*
  379. * The unused *left*-side triggers become the SL/SR triggers for the *right*
  380. * Joy-Con, if and only if we're not using a charging grip.
  381. */
  382. static const struct joycon_ctlr_button_mapping right_joycon_s_button_mappings[] = {
  383. { BTN_TL, JC_BTN_SL_R, },
  384. { BTN_TL2, JC_BTN_SR_R, },
  385. { /* sentinel */ },
  386. };
  387. static const struct joycon_ctlr_button_mapping procon_button_mappings[] = {
  388. { BTN_EAST, JC_BTN_A, },
  389. { BTN_SOUTH, JC_BTN_B, },
  390. { BTN_NORTH, JC_BTN_X, },
  391. { BTN_WEST, JC_BTN_Y, },
  392. { BTN_TL, JC_BTN_L, },
  393. { BTN_TR, JC_BTN_R, },
  394. { BTN_TL2, JC_BTN_ZL, },
  395. { BTN_TR2, JC_BTN_ZR, },
  396. { BTN_SELECT, JC_BTN_MINUS, },
  397. { BTN_START, JC_BTN_PLUS, },
  398. { BTN_THUMBL, JC_BTN_LSTICK, },
  399. { BTN_THUMBR, JC_BTN_RSTICK, },
  400. { BTN_MODE, JC_BTN_HOME, },
  401. { BTN_Z, JC_BTN_CAP, },
  402. { /* sentinel */ },
  403. };
  404. static const struct joycon_ctlr_button_mapping nescon_button_mappings[] = {
  405. { BTN_SOUTH, JC_BTN_A, },
  406. { BTN_EAST, JC_BTN_B, },
  407. { BTN_TL, JC_BTN_L, },
  408. { BTN_TR, JC_BTN_R, },
  409. { BTN_SELECT, JC_BTN_MINUS, },
  410. { BTN_START, JC_BTN_PLUS, },
  411. { /* sentinel */ },
  412. };
  413. static const struct joycon_ctlr_button_mapping snescon_button_mappings[] = {
  414. { BTN_EAST, JC_BTN_A, },
  415. { BTN_SOUTH, JC_BTN_B, },
  416. { BTN_NORTH, JC_BTN_X, },
  417. { BTN_WEST, JC_BTN_Y, },
  418. { BTN_TL, JC_BTN_L, },
  419. { BTN_TR, JC_BTN_R, },
  420. { BTN_TL2, JC_BTN_ZL, },
  421. { BTN_TR2, JC_BTN_ZR, },
  422. { BTN_SELECT, JC_BTN_MINUS, },
  423. { BTN_START, JC_BTN_PLUS, },
  424. { /* sentinel */ },
  425. };
  426. /*
  427. * "A", "B", and "C" are mapped positionally, rather than by label (e.g., "A"
  428. * gets assigned to BTN_EAST instead of BTN_A).
  429. */
  430. static const struct joycon_ctlr_button_mapping gencon_button_mappings[] = {
  431. { BTN_SOUTH, JC_BTN_A, },
  432. { BTN_EAST, JC_BTN_B, },
  433. { BTN_WEST, JC_BTN_R, },
  434. { BTN_SELECT, JC_BTN_ZR, },
  435. { BTN_START, JC_BTN_PLUS, },
  436. { BTN_MODE, JC_BTN_HOME, },
  437. { BTN_Z, JC_BTN_CAP, },
  438. { /* sentinel */ },
  439. };
  440. /*
  441. * N64's C buttons get assigned to d-pad directions and registered as buttons.
  442. */
  443. static const struct joycon_ctlr_button_mapping n64con_button_mappings[] = {
  444. { BTN_A, JC_BTN_A, },
  445. { BTN_B, JC_BTN_B, },
  446. { BTN_TL2, JC_BTN_ZL, }, /* Z */
  447. { BTN_TL, JC_BTN_L, },
  448. { BTN_TR, JC_BTN_R, },
  449. { BTN_TR2, JC_BTN_LSTICK, }, /* ZR */
  450. { BTN_START, JC_BTN_PLUS, },
  451. { BTN_SELECT, JC_BTN_Y, }, /* C UP */
  452. { BTN_X, JC_BTN_ZR, }, /* C DOWN */
  453. { BTN_Y, JC_BTN_X, }, /* C LEFT */
  454. { BTN_C, JC_BTN_MINUS, }, /* C RIGHT */
  455. { BTN_MODE, JC_BTN_HOME, },
  456. { BTN_Z, JC_BTN_CAP, },
  457. { /* sentinel */ },
  458. };
  459. enum joycon_msg_type {
  460. JOYCON_MSG_TYPE_NONE,
  461. JOYCON_MSG_TYPE_USB,
  462. JOYCON_MSG_TYPE_SUBCMD,
  463. };
  464. struct joycon_rumble_output {
  465. u8 output_id;
  466. u8 packet_num;
  467. u8 rumble_data[8];
  468. } __packed;
  469. struct joycon_subcmd_request {
  470. u8 output_id; /* must be 0x01 for subcommand, 0x10 for rumble only */
  471. u8 packet_num; /* incremented every send */
  472. u8 rumble_data[8];
  473. u8 subcmd_id;
  474. u8 data[]; /* length depends on the subcommand */
  475. } __packed;
  476. struct joycon_subcmd_reply {
  477. u8 ack; /* MSB 1 for ACK, 0 for NACK */
  478. u8 id; /* id of requested subcmd */
  479. u8 data[]; /* will be at most 35 bytes */
  480. } __packed;
  481. struct joycon_imu_data {
  482. s16 accel_x;
  483. s16 accel_y;
  484. s16 accel_z;
  485. s16 gyro_x;
  486. s16 gyro_y;
  487. s16 gyro_z;
  488. } __packed;
  489. struct joycon_input_report {
  490. u8 id;
  491. u8 timer;
  492. u8 bat_con; /* battery and connection info */
  493. u8 button_status[3];
  494. u8 left_stick[3];
  495. u8 right_stick[3];
  496. u8 vibrator_report;
  497. union {
  498. struct joycon_subcmd_reply subcmd_reply;
  499. /* IMU input reports contain 3 samples */
  500. u8 imu_raw_bytes[sizeof(struct joycon_imu_data) * 3];
  501. };
  502. } __packed;
  503. #define JC_MAX_RESP_SIZE (sizeof(struct joycon_input_report) + 35)
  504. #define JC_RUMBLE_DATA_SIZE 8
  505. #define JC_RUMBLE_QUEUE_SIZE 8
  506. static const char * const joycon_player_led_names[] = {
  507. LED_FUNCTION_PLAYER1,
  508. LED_FUNCTION_PLAYER2,
  509. LED_FUNCTION_PLAYER3,
  510. LED_FUNCTION_PLAYER4,
  511. };
  512. #define JC_NUM_LEDS ARRAY_SIZE(joycon_player_led_names)
  513. #define JC_NUM_LED_PATTERNS 8
  514. /* Taken from https://www.nintendo.com/my/support/qa/detail/33822 */
  515. static const enum led_brightness joycon_player_led_patterns[JC_NUM_LED_PATTERNS][JC_NUM_LEDS] = {
  516. { 1, 0, 0, 0 },
  517. { 1, 1, 0, 0 },
  518. { 1, 1, 1, 0 },
  519. { 1, 1, 1, 1 },
  520. { 1, 0, 0, 1 },
  521. { 1, 0, 1, 0 },
  522. { 1, 0, 1, 1 },
  523. { 0, 1, 1, 0 },
  524. };
  525. /* Each physical controller is associated with a joycon_ctlr struct */
  526. struct joycon_ctlr {
  527. struct hid_device *hdev;
  528. struct input_dev *input;
  529. u32 player_id;
  530. struct led_classdev leds[JC_NUM_LEDS]; /* player leds */
  531. struct led_classdev home_led;
  532. enum joycon_ctlr_state ctlr_state;
  533. spinlock_t lock;
  534. u8 mac_addr[6];
  535. char *mac_addr_str;
  536. enum joycon_ctlr_type ctlr_type;
  537. /* The following members are used for synchronous sends/receives */
  538. enum joycon_msg_type msg_type;
  539. u8 subcmd_num;
  540. struct mutex output_mutex;
  541. u8 input_buf[JC_MAX_RESP_SIZE];
  542. wait_queue_head_t wait;
  543. bool received_resp;
  544. u8 usb_ack_match;
  545. u8 subcmd_ack_match;
  546. bool received_input_report;
  547. unsigned int last_input_report_msecs;
  548. unsigned int last_subcmd_sent_msecs;
  549. unsigned int consecutive_valid_report_deltas;
  550. /* factory calibration data */
  551. struct joycon_stick_cal left_stick_cal_x;
  552. struct joycon_stick_cal left_stick_cal_y;
  553. struct joycon_stick_cal right_stick_cal_x;
  554. struct joycon_stick_cal right_stick_cal_y;
  555. struct joycon_imu_cal accel_cal;
  556. struct joycon_imu_cal gyro_cal;
  557. /* prevents needlessly recalculating these divisors every sample */
  558. s32 imu_cal_accel_divisor[3];
  559. s32 imu_cal_gyro_divisor[3];
  560. /* power supply data */
  561. struct power_supply *battery;
  562. struct power_supply_desc battery_desc;
  563. u8 battery_capacity;
  564. bool battery_charging;
  565. bool host_powered;
  566. /* rumble */
  567. u8 rumble_data[JC_RUMBLE_QUEUE_SIZE][JC_RUMBLE_DATA_SIZE];
  568. int rumble_queue_head;
  569. int rumble_queue_tail;
  570. struct workqueue_struct *rumble_queue;
  571. struct work_struct rumble_worker;
  572. unsigned int rumble_msecs;
  573. u16 rumble_ll_freq;
  574. u16 rumble_lh_freq;
  575. u16 rumble_rl_freq;
  576. u16 rumble_rh_freq;
  577. unsigned short rumble_zero_countdown;
  578. /* imu */
  579. struct input_dev *imu_input;
  580. bool imu_first_packet_received; /* helps in initiating timestamp */
  581. unsigned int imu_timestamp_us; /* timestamp we report to userspace */
  582. unsigned int imu_last_pkt_ms; /* used to calc imu report delta */
  583. /* the following are used to track the average imu report time delta */
  584. unsigned int imu_delta_samples_count;
  585. unsigned int imu_delta_samples_sum;
  586. unsigned int imu_avg_delta_ms;
  587. };
  588. /* Helper macros for checking controller type */
  589. #define jc_type_is_joycon(ctlr) \
  590. (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONL || \
  591. ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONR || \
  592. ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP)
  593. #define jc_type_is_procon(ctlr) \
  594. (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_PROCON)
  595. #define jc_type_is_chrggrip(ctlr) \
  596. (ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP)
  597. /* Does this controller have inputs associated with left joycon? */
  598. #define jc_type_has_left(ctlr) \
  599. (ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL || \
  600. ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO || \
  601. ctlr->ctlr_type == JOYCON_CTLR_TYPE_N64)
  602. /* Does this controller have inputs associated with right joycon? */
  603. #define jc_type_has_right(ctlr) \
  604. (ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR || \
  605. ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO)
  606. /*
  607. * Controller device helpers
  608. *
  609. * These look at the device ID known to the HID subsystem to identify a device,
  610. * but take caution: some NSO devices lie about themselves (NES Joy-Cons and
  611. * Sega Genesis controller). See type helpers below.
  612. *
  613. * These helpers are most useful early during the HID probe or in conjunction
  614. * with the capability helpers below.
  615. */
  616. static inline bool joycon_device_is_chrggrip(struct joycon_ctlr *ctlr)
  617. {
  618. return ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP;
  619. }
  620. /*
  621. * Controller type helpers
  622. *
  623. * These are slightly different than the device-ID-based helpers above. They are
  624. * generally more reliable, since they can distinguish between, e.g., Genesis
  625. * versus SNES, or NES Joy-Cons versus regular Switch Joy-Cons. They're most
  626. * useful for reporting available inputs. For other kinds of distinctions, see
  627. * the capability helpers below.
  628. *
  629. * They have two major drawbacks: (1) they're not available until after we set
  630. * the reporting method and then request the device info; (2) they can't
  631. * distinguish all controllers (like the Charging Grip from the Pro controller.)
  632. */
  633. static inline bool joycon_type_is_left_joycon(struct joycon_ctlr *ctlr)
  634. {
  635. return ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL;
  636. }
  637. static inline bool joycon_type_is_right_joycon(struct joycon_ctlr *ctlr)
  638. {
  639. return ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR;
  640. }
  641. static inline bool joycon_type_is_procon(struct joycon_ctlr *ctlr)
  642. {
  643. return ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO;
  644. }
  645. static inline bool joycon_type_is_snescon(struct joycon_ctlr *ctlr)
  646. {
  647. return ctlr->ctlr_type == JOYCON_CTLR_TYPE_SNES;
  648. }
  649. static inline bool joycon_type_is_gencon(struct joycon_ctlr *ctlr)
  650. {
  651. return ctlr->ctlr_type == JOYCON_CTLR_TYPE_GEN;
  652. }
  653. static inline bool joycon_type_is_n64con(struct joycon_ctlr *ctlr)
  654. {
  655. return ctlr->ctlr_type == JOYCON_CTLR_TYPE_N64;
  656. }
  657. static inline bool joycon_type_is_left_nescon(struct joycon_ctlr *ctlr)
  658. {
  659. return ctlr->ctlr_type == JOYCON_CTLR_TYPE_NESL;
  660. }
  661. static inline bool joycon_type_is_right_nescon(struct joycon_ctlr *ctlr)
  662. {
  663. return ctlr->ctlr_type == JOYCON_CTLR_TYPE_NESR;
  664. }
  665. static inline bool joycon_type_is_any_joycon(struct joycon_ctlr *ctlr)
  666. {
  667. return joycon_type_is_left_joycon(ctlr) ||
  668. joycon_type_is_right_joycon(ctlr) ||
  669. joycon_device_is_chrggrip(ctlr);
  670. }
  671. static inline bool joycon_type_is_any_nescon(struct joycon_ctlr *ctlr)
  672. {
  673. return joycon_type_is_left_nescon(ctlr) ||
  674. joycon_type_is_right_nescon(ctlr);
  675. }
  676. /*
  677. * Controller capability helpers
  678. *
  679. * These helpers combine the use of the helpers above to detect certain
  680. * capabilities during initialization. They are always accurate but (since they
  681. * use type helpers) cannot be used early in the HID probe.
  682. */
  683. static inline bool joycon_has_imu(struct joycon_ctlr *ctlr)
  684. {
  685. return joycon_device_is_chrggrip(ctlr) ||
  686. joycon_type_is_any_joycon(ctlr) ||
  687. joycon_type_is_procon(ctlr);
  688. }
  689. static inline bool joycon_has_joysticks(struct joycon_ctlr *ctlr)
  690. {
  691. return joycon_device_is_chrggrip(ctlr) ||
  692. joycon_type_is_any_joycon(ctlr) ||
  693. joycon_type_is_procon(ctlr) ||
  694. joycon_type_is_n64con(ctlr);
  695. }
  696. static inline bool joycon_has_rumble(struct joycon_ctlr *ctlr)
  697. {
  698. return joycon_device_is_chrggrip(ctlr) ||
  699. joycon_type_is_any_joycon(ctlr) ||
  700. joycon_type_is_procon(ctlr) ||
  701. joycon_type_is_n64con(ctlr);
  702. }
  703. static inline bool joycon_using_usb(struct joycon_ctlr *ctlr)
  704. {
  705. return ctlr->hdev->bus == BUS_USB;
  706. }
  707. static int __joycon_hid_send(struct hid_device *hdev, u8 *data, size_t len)
  708. {
  709. u8 *buf;
  710. int ret;
  711. buf = kmemdup(data, len, GFP_KERNEL);
  712. if (!buf)
  713. return -ENOMEM;
  714. ret = hid_hw_output_report(hdev, buf, len);
  715. kfree(buf);
  716. if (ret < 0)
  717. hid_dbg(hdev, "Failed to send output report ret=%d\n", ret);
  718. return ret;
  719. }
  720. static void joycon_wait_for_input_report(struct joycon_ctlr *ctlr)
  721. {
  722. int ret;
  723. /*
  724. * If we are in the proper reporting mode, wait for an input
  725. * report prior to sending the subcommand. This improves
  726. * reliability considerably.
  727. */
  728. if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) {
  729. unsigned long flags;
  730. spin_lock_irqsave(&ctlr->lock, flags);
  731. ctlr->received_input_report = false;
  732. spin_unlock_irqrestore(&ctlr->lock, flags);
  733. ret = wait_event_timeout(ctlr->wait,
  734. ctlr->received_input_report,
  735. HZ / 4);
  736. /* We will still proceed, even with a timeout here */
  737. if (!ret)
  738. hid_warn(ctlr->hdev,
  739. "timeout waiting for input report\n");
  740. }
  741. }
  742. /*
  743. * Sending subcommands and/or rumble data at too high a rate can cause bluetooth
  744. * controller disconnections.
  745. */
  746. #define JC_INPUT_REPORT_MIN_DELTA 8
  747. #define JC_INPUT_REPORT_MAX_DELTA 17
  748. #define JC_SUBCMD_TX_OFFSET_MS 4
  749. #define JC_SUBCMD_VALID_DELTA_REQ 3
  750. #define JC_SUBCMD_RATE_MAX_ATTEMPTS 500
  751. #define JC_SUBCMD_RATE_LIMITER_USB_MS 20
  752. #define JC_SUBCMD_RATE_LIMITER_BT_MS 60
  753. #define JC_SUBCMD_RATE_LIMITER_MS(ctlr) ((ctlr)->hdev->bus == BUS_USB ? JC_SUBCMD_RATE_LIMITER_USB_MS : JC_SUBCMD_RATE_LIMITER_BT_MS)
  754. static void joycon_enforce_subcmd_rate(struct joycon_ctlr *ctlr)
  755. {
  756. unsigned int current_ms;
  757. unsigned long subcmd_delta;
  758. int consecutive_valid_deltas = 0;
  759. int attempts = 0;
  760. unsigned long flags;
  761. if (unlikely(ctlr->ctlr_state != JOYCON_CTLR_STATE_READ))
  762. return;
  763. do {
  764. joycon_wait_for_input_report(ctlr);
  765. current_ms = jiffies_to_msecs(jiffies);
  766. subcmd_delta = current_ms - ctlr->last_subcmd_sent_msecs;
  767. spin_lock_irqsave(&ctlr->lock, flags);
  768. consecutive_valid_deltas = ctlr->consecutive_valid_report_deltas;
  769. spin_unlock_irqrestore(&ctlr->lock, flags);
  770. attempts++;
  771. } while ((consecutive_valid_deltas < JC_SUBCMD_VALID_DELTA_REQ ||
  772. subcmd_delta < JC_SUBCMD_RATE_LIMITER_MS(ctlr)) &&
  773. ctlr->ctlr_state == JOYCON_CTLR_STATE_READ &&
  774. attempts < JC_SUBCMD_RATE_MAX_ATTEMPTS);
  775. if (attempts >= JC_SUBCMD_RATE_MAX_ATTEMPTS) {
  776. hid_warn(ctlr->hdev, "%s: exceeded max attempts", __func__);
  777. return;
  778. }
  779. ctlr->last_subcmd_sent_msecs = current_ms;
  780. /*
  781. * Wait a short time after receiving an input report before
  782. * transmitting. This should reduce odds of a TX coinciding with an RX.
  783. * Minimizing concurrent BT traffic with the controller seems to lower
  784. * the rate of disconnections.
  785. */
  786. msleep(JC_SUBCMD_TX_OFFSET_MS);
  787. }
  788. static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len,
  789. u32 timeout)
  790. {
  791. int ret;
  792. int tries = 2;
  793. /*
  794. * The controller occasionally seems to drop subcommands. In testing,
  795. * doing one retry after a timeout appears to always work.
  796. */
  797. while (tries--) {
  798. joycon_enforce_subcmd_rate(ctlr);
  799. ret = __joycon_hid_send(ctlr->hdev, data, len);
  800. if (ret < 0) {
  801. memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
  802. return ret;
  803. }
  804. ret = wait_event_timeout(ctlr->wait, ctlr->received_resp,
  805. timeout);
  806. if (!ret) {
  807. hid_dbg(ctlr->hdev,
  808. "synchronous send/receive timed out\n");
  809. if (tries) {
  810. hid_dbg(ctlr->hdev,
  811. "retrying sync send after timeout\n");
  812. }
  813. memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
  814. ret = -ETIMEDOUT;
  815. } else {
  816. ret = 0;
  817. break;
  818. }
  819. }
  820. ctlr->received_resp = false;
  821. return ret;
  822. }
  823. static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd, u32 timeout)
  824. {
  825. int ret;
  826. u8 buf[2] = {JC_OUTPUT_USB_CMD};
  827. buf[1] = cmd;
  828. ctlr->usb_ack_match = cmd;
  829. ctlr->msg_type = JOYCON_MSG_TYPE_USB;
  830. ret = joycon_hid_send_sync(ctlr, buf, sizeof(buf), timeout);
  831. if (ret)
  832. hid_dbg(ctlr->hdev, "send usb command failed; ret=%d\n", ret);
  833. return ret;
  834. }
  835. static int joycon_send_subcmd(struct joycon_ctlr *ctlr,
  836. struct joycon_subcmd_request *subcmd,
  837. size_t data_len, u32 timeout)
  838. {
  839. int ret;
  840. unsigned long flags;
  841. spin_lock_irqsave(&ctlr->lock, flags);
  842. /*
  843. * If the controller has been removed, just return ENODEV so the LED
  844. * subsystem doesn't print invalid errors on removal.
  845. */
  846. if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) {
  847. spin_unlock_irqrestore(&ctlr->lock, flags);
  848. return -ENODEV;
  849. }
  850. memcpy(subcmd->rumble_data, ctlr->rumble_data[ctlr->rumble_queue_tail],
  851. JC_RUMBLE_DATA_SIZE);
  852. spin_unlock_irqrestore(&ctlr->lock, flags);
  853. subcmd->output_id = JC_OUTPUT_RUMBLE_AND_SUBCMD;
  854. subcmd->packet_num = ctlr->subcmd_num;
  855. if (++ctlr->subcmd_num > 0xF)
  856. ctlr->subcmd_num = 0;
  857. ctlr->subcmd_ack_match = subcmd->subcmd_id;
  858. ctlr->msg_type = JOYCON_MSG_TYPE_SUBCMD;
  859. ret = joycon_hid_send_sync(ctlr, (u8 *)subcmd,
  860. sizeof(*subcmd) + data_len, timeout);
  861. if (ret < 0)
  862. hid_dbg(ctlr->hdev, "send subcommand failed; ret=%d\n", ret);
  863. else
  864. ret = 0;
  865. return ret;
  866. }
  867. /* Supply nibbles for flash and on. Ones correspond to active */
  868. static int joycon_set_player_leds(struct joycon_ctlr *ctlr, u8 flash, u8 on)
  869. {
  870. struct joycon_subcmd_request *req;
  871. u8 buffer[sizeof(*req) + 1] = { 0 };
  872. req = (struct joycon_subcmd_request *)buffer;
  873. req->subcmd_id = JC_SUBCMD_SET_PLAYER_LIGHTS;
  874. req->data[0] = (flash << 4) | on;
  875. hid_dbg(ctlr->hdev, "setting player leds\n");
  876. return joycon_send_subcmd(ctlr, req, 1, HZ/4);
  877. }
  878. static int joycon_set_home_led(struct joycon_ctlr *ctlr, enum led_brightness brightness)
  879. {
  880. struct joycon_subcmd_request *req;
  881. u8 buffer[sizeof(*req) + 5] = { 0 };
  882. u8 *data;
  883. req = (struct joycon_subcmd_request *)buffer;
  884. req->subcmd_id = JC_SUBCMD_SET_HOME_LIGHT;
  885. data = req->data;
  886. data[0] = 0x01;
  887. data[1] = brightness << 4;
  888. data[2] = brightness | (brightness << 4);
  889. data[3] = 0x11;
  890. data[4] = 0x11;
  891. hid_dbg(ctlr->hdev, "setting home led brightness\n");
  892. return joycon_send_subcmd(ctlr, req, 5, HZ/4);
  893. }
  894. static int joycon_request_spi_flash_read(struct joycon_ctlr *ctlr,
  895. u32 start_addr, u8 size, u8 **reply)
  896. {
  897. struct joycon_subcmd_request *req;
  898. struct joycon_input_report *report;
  899. u8 buffer[sizeof(*req) + 5] = { 0 };
  900. u8 *data;
  901. int ret;
  902. if (!reply)
  903. return -EINVAL;
  904. req = (struct joycon_subcmd_request *)buffer;
  905. req->subcmd_id = JC_SUBCMD_SPI_FLASH_READ;
  906. data = req->data;
  907. put_unaligned_le32(start_addr, data);
  908. data[4] = size;
  909. hid_dbg(ctlr->hdev, "requesting SPI flash data\n");
  910. ret = joycon_send_subcmd(ctlr, req, 5, HZ);
  911. if (ret) {
  912. hid_err(ctlr->hdev, "failed reading SPI flash; ret=%d\n", ret);
  913. } else {
  914. report = (struct joycon_input_report *)ctlr->input_buf;
  915. /* The read data starts at the 6th byte */
  916. *reply = &report->subcmd_reply.data[5];
  917. }
  918. return ret;
  919. }
  920. /*
  921. * User calibration's presence is denoted with a magic byte preceding it.
  922. * returns 0 if magic val is present, 1 if not present, < 0 on error
  923. */
  924. static int joycon_check_for_cal_magic(struct joycon_ctlr *ctlr, u32 flash_addr)
  925. {
  926. int ret;
  927. u8 *reply;
  928. ret = joycon_request_spi_flash_read(ctlr, flash_addr,
  929. JC_CAL_USR_MAGIC_SIZE, &reply);
  930. if (ret)
  931. return ret;
  932. return reply[0] != JC_CAL_USR_MAGIC_0 || reply[1] != JC_CAL_USR_MAGIC_1;
  933. }
  934. static int joycon_read_stick_calibration(struct joycon_ctlr *ctlr, u16 cal_addr,
  935. struct joycon_stick_cal *cal_x,
  936. struct joycon_stick_cal *cal_y,
  937. bool left_stick)
  938. {
  939. s32 x_max_above;
  940. s32 x_min_below;
  941. s32 y_max_above;
  942. s32 y_min_below;
  943. u8 *raw_cal;
  944. int ret;
  945. ret = joycon_request_spi_flash_read(ctlr, cal_addr,
  946. JC_CAL_STICK_DATA_SIZE, &raw_cal);
  947. if (ret)
  948. return ret;
  949. /* stick calibration parsing: note the order differs based on stick */
  950. if (left_stick) {
  951. x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0,
  952. 12);
  953. y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4,
  954. 12);
  955. cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0,
  956. 12);
  957. cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4,
  958. 12);
  959. x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0,
  960. 12);
  961. y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4,
  962. 12);
  963. } else {
  964. cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0,
  965. 12);
  966. cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4,
  967. 12);
  968. x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0,
  969. 12);
  970. y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4,
  971. 12);
  972. x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0,
  973. 12);
  974. y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4,
  975. 12);
  976. }
  977. cal_x->max = cal_x->center + x_max_above;
  978. cal_x->min = cal_x->center - x_min_below;
  979. cal_y->max = cal_y->center + y_max_above;
  980. cal_y->min = cal_y->center - y_min_below;
  981. /* check if calibration values are plausible */
  982. if (cal_x->min >= cal_x->center || cal_x->center >= cal_x->max ||
  983. cal_y->min >= cal_y->center || cal_y->center >= cal_y->max)
  984. ret = -EINVAL;
  985. return ret;
  986. }
  987. static const u16 DFLT_STICK_CAL_CEN = 2000;
  988. static const u16 DFLT_STICK_CAL_MAX = 3500;
  989. static const u16 DFLT_STICK_CAL_MIN = 500;
  990. static void joycon_use_default_calibration(struct hid_device *hdev,
  991. struct joycon_stick_cal *cal_x,
  992. struct joycon_stick_cal *cal_y,
  993. const char *stick, int ret)
  994. {
  995. hid_warn(hdev,
  996. "Failed to read %s stick cal, using defaults; e=%d\n",
  997. stick, ret);
  998. cal_x->center = cal_y->center = DFLT_STICK_CAL_CEN;
  999. cal_x->max = cal_y->max = DFLT_STICK_CAL_MAX;
  1000. cal_x->min = cal_y->min = DFLT_STICK_CAL_MIN;
  1001. }
  1002. static int joycon_request_calibration(struct joycon_ctlr *ctlr)
  1003. {
  1004. u16 left_stick_addr = JC_CAL_FCT_DATA_LEFT_ADDR;
  1005. u16 right_stick_addr = JC_CAL_FCT_DATA_RIGHT_ADDR;
  1006. int ret;
  1007. hid_dbg(ctlr->hdev, "requesting cal data\n");
  1008. /* check if user stick calibrations are present */
  1009. if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_LEFT_MAGIC_ADDR)) {
  1010. left_stick_addr = JC_CAL_USR_LEFT_DATA_ADDR;
  1011. hid_info(ctlr->hdev, "using user cal for left stick\n");
  1012. } else {
  1013. hid_info(ctlr->hdev, "using factory cal for left stick\n");
  1014. }
  1015. if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_RIGHT_MAGIC_ADDR)) {
  1016. right_stick_addr = JC_CAL_USR_RIGHT_DATA_ADDR;
  1017. hid_info(ctlr->hdev, "using user cal for right stick\n");
  1018. } else {
  1019. hid_info(ctlr->hdev, "using factory cal for right stick\n");
  1020. }
  1021. /* read the left stick calibration data */
  1022. ret = joycon_read_stick_calibration(ctlr, left_stick_addr,
  1023. &ctlr->left_stick_cal_x,
  1024. &ctlr->left_stick_cal_y,
  1025. true);
  1026. if (ret)
  1027. joycon_use_default_calibration(ctlr->hdev,
  1028. &ctlr->left_stick_cal_x,
  1029. &ctlr->left_stick_cal_y,
  1030. "left", ret);
  1031. /* read the right stick calibration data */
  1032. ret = joycon_read_stick_calibration(ctlr, right_stick_addr,
  1033. &ctlr->right_stick_cal_x,
  1034. &ctlr->right_stick_cal_y,
  1035. false);
  1036. if (ret)
  1037. joycon_use_default_calibration(ctlr->hdev,
  1038. &ctlr->right_stick_cal_x,
  1039. &ctlr->right_stick_cal_y,
  1040. "right", ret);
  1041. hid_dbg(ctlr->hdev, "calibration:\n"
  1042. "l_x_c=%d l_x_max=%d l_x_min=%d\n"
  1043. "l_y_c=%d l_y_max=%d l_y_min=%d\n"
  1044. "r_x_c=%d r_x_max=%d r_x_min=%d\n"
  1045. "r_y_c=%d r_y_max=%d r_y_min=%d\n",
  1046. ctlr->left_stick_cal_x.center,
  1047. ctlr->left_stick_cal_x.max,
  1048. ctlr->left_stick_cal_x.min,
  1049. ctlr->left_stick_cal_y.center,
  1050. ctlr->left_stick_cal_y.max,
  1051. ctlr->left_stick_cal_y.min,
  1052. ctlr->right_stick_cal_x.center,
  1053. ctlr->right_stick_cal_x.max,
  1054. ctlr->right_stick_cal_x.min,
  1055. ctlr->right_stick_cal_y.center,
  1056. ctlr->right_stick_cal_y.max,
  1057. ctlr->right_stick_cal_y.min);
  1058. return 0;
  1059. }
  1060. /*
  1061. * These divisors are calculated once rather than for each sample. They are only
  1062. * dependent on the IMU calibration values. They are used when processing the
  1063. * IMU input reports.
  1064. */
  1065. static void joycon_calc_imu_cal_divisors(struct joycon_ctlr *ctlr)
  1066. {
  1067. int i, divz = 0;
  1068. for (i = 0; i < 3; i++) {
  1069. ctlr->imu_cal_accel_divisor[i] = ctlr->accel_cal.scale[i] -
  1070. ctlr->accel_cal.offset[i];
  1071. ctlr->imu_cal_gyro_divisor[i] = ctlr->gyro_cal.scale[i] -
  1072. ctlr->gyro_cal.offset[i];
  1073. if (ctlr->imu_cal_accel_divisor[i] == 0) {
  1074. ctlr->imu_cal_accel_divisor[i] = 1;
  1075. divz++;
  1076. }
  1077. if (ctlr->imu_cal_gyro_divisor[i] == 0) {
  1078. ctlr->imu_cal_gyro_divisor[i] = 1;
  1079. divz++;
  1080. }
  1081. }
  1082. if (divz)
  1083. hid_warn(ctlr->hdev, "inaccurate IMU divisors (%d)\n", divz);
  1084. }
  1085. static const s16 DFLT_ACCEL_OFFSET /*= 0*/;
  1086. static const s16 DFLT_ACCEL_SCALE = 16384;
  1087. static const s16 DFLT_GYRO_OFFSET /*= 0*/;
  1088. static const s16 DFLT_GYRO_SCALE = 13371;
  1089. static int joycon_request_imu_calibration(struct joycon_ctlr *ctlr)
  1090. {
  1091. u16 imu_cal_addr = JC_IMU_CAL_FCT_DATA_ADDR;
  1092. u8 *raw_cal;
  1093. int ret;
  1094. int i;
  1095. /* check if user calibration exists */
  1096. if (!joycon_check_for_cal_magic(ctlr, JC_IMU_CAL_USR_MAGIC_ADDR)) {
  1097. imu_cal_addr = JC_IMU_CAL_USR_DATA_ADDR;
  1098. hid_info(ctlr->hdev, "using user cal for IMU\n");
  1099. } else {
  1100. hid_info(ctlr->hdev, "using factory cal for IMU\n");
  1101. }
  1102. /* request IMU calibration data */
  1103. hid_dbg(ctlr->hdev, "requesting IMU cal data\n");
  1104. ret = joycon_request_spi_flash_read(ctlr, imu_cal_addr,
  1105. JC_IMU_CAL_DATA_SIZE, &raw_cal);
  1106. if (ret) {
  1107. hid_warn(ctlr->hdev,
  1108. "Failed to read IMU cal, using defaults; ret=%d\n",
  1109. ret);
  1110. for (i = 0; i < 3; i++) {
  1111. ctlr->accel_cal.offset[i] = DFLT_ACCEL_OFFSET;
  1112. ctlr->accel_cal.scale[i] = DFLT_ACCEL_SCALE;
  1113. ctlr->gyro_cal.offset[i] = DFLT_GYRO_OFFSET;
  1114. ctlr->gyro_cal.scale[i] = DFLT_GYRO_SCALE;
  1115. }
  1116. joycon_calc_imu_cal_divisors(ctlr);
  1117. return ret;
  1118. }
  1119. /* IMU calibration parsing */
  1120. for (i = 0; i < 3; i++) {
  1121. int j = i * 2;
  1122. ctlr->accel_cal.offset[i] = get_unaligned_le16(raw_cal + j);
  1123. ctlr->accel_cal.scale[i] = get_unaligned_le16(raw_cal + j + 6);
  1124. ctlr->gyro_cal.offset[i] = get_unaligned_le16(raw_cal + j + 12);
  1125. ctlr->gyro_cal.scale[i] = get_unaligned_le16(raw_cal + j + 18);
  1126. }
  1127. joycon_calc_imu_cal_divisors(ctlr);
  1128. hid_dbg(ctlr->hdev, "IMU calibration:\n"
  1129. "a_o[0]=%d a_o[1]=%d a_o[2]=%d\n"
  1130. "a_s[0]=%d a_s[1]=%d a_s[2]=%d\n"
  1131. "g_o[0]=%d g_o[1]=%d g_o[2]=%d\n"
  1132. "g_s[0]=%d g_s[1]=%d g_s[2]=%d\n",
  1133. ctlr->accel_cal.offset[0],
  1134. ctlr->accel_cal.offset[1],
  1135. ctlr->accel_cal.offset[2],
  1136. ctlr->accel_cal.scale[0],
  1137. ctlr->accel_cal.scale[1],
  1138. ctlr->accel_cal.scale[2],
  1139. ctlr->gyro_cal.offset[0],
  1140. ctlr->gyro_cal.offset[1],
  1141. ctlr->gyro_cal.offset[2],
  1142. ctlr->gyro_cal.scale[0],
  1143. ctlr->gyro_cal.scale[1],
  1144. ctlr->gyro_cal.scale[2]);
  1145. return 0;
  1146. }
  1147. static int joycon_set_report_mode(struct joycon_ctlr *ctlr)
  1148. {
  1149. struct joycon_subcmd_request *req;
  1150. u8 buffer[sizeof(*req) + 1] = { 0 };
  1151. req = (struct joycon_subcmd_request *)buffer;
  1152. req->subcmd_id = JC_SUBCMD_SET_REPORT_MODE;
  1153. req->data[0] = 0x30; /* standard, full report mode */
  1154. hid_dbg(ctlr->hdev, "setting controller report mode\n");
  1155. return joycon_send_subcmd(ctlr, req, 1, HZ);
  1156. }
  1157. static int joycon_enable_rumble(struct joycon_ctlr *ctlr)
  1158. {
  1159. struct joycon_subcmd_request *req;
  1160. u8 buffer[sizeof(*req) + 1] = { 0 };
  1161. req = (struct joycon_subcmd_request *)buffer;
  1162. req->subcmd_id = JC_SUBCMD_ENABLE_VIBRATION;
  1163. req->data[0] = 0x01; /* note: 0x00 would disable */
  1164. hid_dbg(ctlr->hdev, "enabling rumble\n");
  1165. return joycon_send_subcmd(ctlr, req, 1, HZ/4);
  1166. }
  1167. static int joycon_enable_imu(struct joycon_ctlr *ctlr)
  1168. {
  1169. struct joycon_subcmd_request *req;
  1170. u8 buffer[sizeof(*req) + 1] = { 0 };
  1171. req = (struct joycon_subcmd_request *)buffer;
  1172. req->subcmd_id = JC_SUBCMD_ENABLE_IMU;
  1173. req->data[0] = 0x01; /* note: 0x00 would disable */
  1174. hid_dbg(ctlr->hdev, "enabling IMU\n");
  1175. return joycon_send_subcmd(ctlr, req, 1, HZ);
  1176. }
  1177. static s32 joycon_map_stick_val(struct joycon_stick_cal *cal, s32 val)
  1178. {
  1179. s32 center = cal->center;
  1180. s32 min = cal->min;
  1181. s32 max = cal->max;
  1182. s32 new_val;
  1183. if (val > center) {
  1184. new_val = (val - center) * JC_MAX_STICK_MAG;
  1185. new_val /= (max - center);
  1186. } else {
  1187. new_val = (center - val) * -JC_MAX_STICK_MAG;
  1188. new_val /= (center - min);
  1189. }
  1190. new_val = clamp(new_val, (s32)-JC_MAX_STICK_MAG, (s32)JC_MAX_STICK_MAG);
  1191. return new_val;
  1192. }
  1193. static void joycon_input_report_parse_imu_data(struct joycon_ctlr *ctlr,
  1194. struct joycon_input_report *rep,
  1195. struct joycon_imu_data *imu_data)
  1196. {
  1197. u8 *raw = rep->imu_raw_bytes;
  1198. int i;
  1199. for (i = 0; i < 3; i++) {
  1200. struct joycon_imu_data *data = &imu_data[i];
  1201. data->accel_x = get_unaligned_le16(raw + 0);
  1202. data->accel_y = get_unaligned_le16(raw + 2);
  1203. data->accel_z = get_unaligned_le16(raw + 4);
  1204. data->gyro_x = get_unaligned_le16(raw + 6);
  1205. data->gyro_y = get_unaligned_le16(raw + 8);
  1206. data->gyro_z = get_unaligned_le16(raw + 10);
  1207. /* point to next imu sample */
  1208. raw += sizeof(struct joycon_imu_data);
  1209. }
  1210. }
  1211. static void joycon_parse_imu_report(struct joycon_ctlr *ctlr,
  1212. struct joycon_input_report *rep)
  1213. {
  1214. struct joycon_imu_data imu_data[3] = {0}; /* 3 reports per packet */
  1215. struct input_dev *idev = ctlr->imu_input;
  1216. unsigned int msecs = jiffies_to_msecs(jiffies);
  1217. unsigned int last_msecs = ctlr->imu_last_pkt_ms;
  1218. int i;
  1219. int value[6];
  1220. joycon_input_report_parse_imu_data(ctlr, rep, imu_data);
  1221. /*
  1222. * There are complexities surrounding how we determine the timestamps we
  1223. * associate with the samples we pass to userspace. The IMU input
  1224. * reports do not provide us with a good timestamp. There's a quickly
  1225. * incrementing 8-bit counter per input report, but it is not very
  1226. * useful for this purpose (it is not entirely clear what rate it
  1227. * increments at or if it varies based on packet push rate - more on
  1228. * the push rate below...).
  1229. *
  1230. * The reverse engineering work done on the joy-cons and pro controllers
  1231. * by the community seems to indicate the following:
  1232. * - The controller samples the IMU every 1.35ms. It then does some of
  1233. * its own processing, probably averaging the samples out.
  1234. * - Each imu input report contains 3 IMU samples, (usually 5ms apart).
  1235. * - In the standard reporting mode (which this driver uses exclusively)
  1236. * input reports are pushed from the controller as follows:
  1237. * * joy-con (bluetooth): every 15 ms
  1238. * * joy-cons (in charging grip via USB): every 15 ms
  1239. * * pro controller (USB): every 15 ms
  1240. * * pro controller (bluetooth): every 8 ms (this is the wildcard)
  1241. *
  1242. * Further complicating matters is that some bluetooth stacks are known
  1243. * to alter the controller's packet rate by hardcoding the bluetooth
  1244. * SSR for the switch controllers (android's stack currently sets the
  1245. * SSR to 11ms for both the joy-cons and pro controllers).
  1246. *
  1247. * In my own testing, I've discovered that my pro controller either
  1248. * reports IMU sample batches every 11ms or every 15ms. This rate is
  1249. * stable after connecting. It isn't 100% clear what determines this
  1250. * rate. Importantly, even when sending every 11ms, none of the samples
  1251. * are duplicates. This seems to indicate that the time deltas between
  1252. * reported samples can vary based on the input report rate.
  1253. *
  1254. * The solution employed in this driver is to keep track of the average
  1255. * time delta between IMU input reports. In testing, this value has
  1256. * proven to be stable, staying at 15ms or 11ms, though other hardware
  1257. * configurations and bluetooth stacks could potentially see other rates
  1258. * (hopefully this will become more clear as more people use the
  1259. * driver).
  1260. *
  1261. * Keeping track of the average report delta allows us to submit our
  1262. * timestamps to userspace based on that. Each report contains 3
  1263. * samples, so the IMU sampling rate should be avg_time_delta/3. We can
  1264. * also use this average to detect events where we have dropped a
  1265. * packet. The userspace timestamp for the samples will be adjusted
  1266. * accordingly to prevent unwanted behvaior.
  1267. */
  1268. if (!ctlr->imu_first_packet_received) {
  1269. ctlr->imu_timestamp_us = 0;
  1270. ctlr->imu_delta_samples_count = 0;
  1271. ctlr->imu_delta_samples_sum = 0;
  1272. ctlr->imu_avg_delta_ms = JC_IMU_DFLT_AVG_DELTA_MS;
  1273. ctlr->imu_first_packet_received = true;
  1274. } else {
  1275. unsigned int delta = msecs - last_msecs;
  1276. unsigned int dropped_pkts;
  1277. unsigned int dropped_threshold;
  1278. /* avg imu report delta housekeeping */
  1279. ctlr->imu_delta_samples_sum += delta;
  1280. ctlr->imu_delta_samples_count++;
  1281. if (ctlr->imu_delta_samples_count >=
  1282. JC_IMU_SAMPLES_PER_DELTA_AVG) {
  1283. ctlr->imu_avg_delta_ms = ctlr->imu_delta_samples_sum /
  1284. ctlr->imu_delta_samples_count;
  1285. ctlr->imu_delta_samples_count = 0;
  1286. ctlr->imu_delta_samples_sum = 0;
  1287. }
  1288. /* don't ever want divide by zero shenanigans */
  1289. if (ctlr->imu_avg_delta_ms == 0) {
  1290. ctlr->imu_avg_delta_ms = 1;
  1291. hid_warn(ctlr->hdev, "calculated avg imu delta of 0\n");
  1292. }
  1293. /* useful for debugging IMU sample rate */
  1294. hid_dbg(ctlr->hdev,
  1295. "imu_report: ms=%u last_ms=%u delta=%u avg_delta=%u\n",
  1296. msecs, last_msecs, delta, ctlr->imu_avg_delta_ms);
  1297. /* check if any packets have been dropped */
  1298. dropped_threshold = ctlr->imu_avg_delta_ms * 3 / 2;
  1299. dropped_pkts = (delta - min(delta, dropped_threshold)) /
  1300. ctlr->imu_avg_delta_ms;
  1301. ctlr->imu_timestamp_us += 1000 * ctlr->imu_avg_delta_ms;
  1302. if (dropped_pkts > JC_IMU_DROPPED_PKT_WARNING) {
  1303. hid_warn(ctlr->hdev,
  1304. "compensating for %u dropped IMU reports\n",
  1305. dropped_pkts);
  1306. hid_warn(ctlr->hdev,
  1307. "delta=%u avg_delta=%u\n",
  1308. delta, ctlr->imu_avg_delta_ms);
  1309. }
  1310. }
  1311. ctlr->imu_last_pkt_ms = msecs;
  1312. /* Each IMU input report contains three samples */
  1313. for (i = 0; i < 3; i++) {
  1314. input_event(idev, EV_MSC, MSC_TIMESTAMP,
  1315. ctlr->imu_timestamp_us);
  1316. /*
  1317. * These calculations (which use the controller's calibration
  1318. * settings to improve the final values) are based on those
  1319. * found in the community's reverse-engineering repo (linked at
  1320. * top of driver). For hid-nintendo, we make sure that the final
  1321. * value given to userspace is always in terms of the axis
  1322. * resolution we provided.
  1323. *
  1324. * Currently only the gyro calculations subtract the calibration
  1325. * offsets from the raw value itself. In testing, doing the same
  1326. * for the accelerometer raw values decreased accuracy.
  1327. *
  1328. * Note that the gyro values are multiplied by the
  1329. * precision-saving scaling factor to prevent large inaccuracies
  1330. * due to truncation of the resolution value which would
  1331. * otherwise occur. To prevent overflow (without resorting to 64
  1332. * bit integer math), the mult_frac macro is used.
  1333. */
  1334. value[0] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
  1335. (imu_data[i].gyro_x -
  1336. ctlr->gyro_cal.offset[0])),
  1337. ctlr->gyro_cal.scale[0],
  1338. ctlr->imu_cal_gyro_divisor[0]);
  1339. value[1] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
  1340. (imu_data[i].gyro_y -
  1341. ctlr->gyro_cal.offset[1])),
  1342. ctlr->gyro_cal.scale[1],
  1343. ctlr->imu_cal_gyro_divisor[1]);
  1344. value[2] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
  1345. (imu_data[i].gyro_z -
  1346. ctlr->gyro_cal.offset[2])),
  1347. ctlr->gyro_cal.scale[2],
  1348. ctlr->imu_cal_gyro_divisor[2]);
  1349. value[3] = ((s32)imu_data[i].accel_x *
  1350. ctlr->accel_cal.scale[0]) /
  1351. ctlr->imu_cal_accel_divisor[0];
  1352. value[4] = ((s32)imu_data[i].accel_y *
  1353. ctlr->accel_cal.scale[1]) /
  1354. ctlr->imu_cal_accel_divisor[1];
  1355. value[5] = ((s32)imu_data[i].accel_z *
  1356. ctlr->accel_cal.scale[2]) /
  1357. ctlr->imu_cal_accel_divisor[2];
  1358. hid_dbg(ctlr->hdev, "raw_gyro: g_x=%d g_y=%d g_z=%d\n",
  1359. imu_data[i].gyro_x, imu_data[i].gyro_y,
  1360. imu_data[i].gyro_z);
  1361. hid_dbg(ctlr->hdev, "raw_accel: a_x=%d a_y=%d a_z=%d\n",
  1362. imu_data[i].accel_x, imu_data[i].accel_y,
  1363. imu_data[i].accel_z);
  1364. /*
  1365. * The right joy-con has 2 axes negated, Y and Z. This is due to
  1366. * the orientation of the IMU in the controller. We negate those
  1367. * axes' values in order to be consistent with the left joy-con
  1368. * and the pro controller:
  1369. * X: positive is pointing toward the triggers
  1370. * Y: positive is pointing to the left
  1371. * Z: positive is pointing up (out of the buttons/sticks)
  1372. * The axes follow the right-hand rule.
  1373. */
  1374. if (jc_type_is_joycon(ctlr) && jc_type_has_right(ctlr)) {
  1375. int j;
  1376. /* negate all but x axis */
  1377. for (j = 1; j < 6; ++j) {
  1378. if (j == 3)
  1379. continue;
  1380. value[j] *= -1;
  1381. }
  1382. }
  1383. input_report_abs(idev, ABS_RX, value[0]);
  1384. input_report_abs(idev, ABS_RY, value[1]);
  1385. input_report_abs(idev, ABS_RZ, value[2]);
  1386. input_report_abs(idev, ABS_X, value[3]);
  1387. input_report_abs(idev, ABS_Y, value[4]);
  1388. input_report_abs(idev, ABS_Z, value[5]);
  1389. input_sync(idev);
  1390. /* convert to micros and divide by 3 (3 samples per report). */
  1391. ctlr->imu_timestamp_us += ctlr->imu_avg_delta_ms * 1000 / 3;
  1392. }
  1393. }
  1394. static void joycon_handle_rumble_report(struct joycon_ctlr *ctlr, struct joycon_input_report *rep)
  1395. {
  1396. unsigned long flags;
  1397. unsigned long msecs = jiffies_to_msecs(jiffies);
  1398. spin_lock_irqsave(&ctlr->lock, flags);
  1399. if (IS_ENABLED(CONFIG_NINTENDO_FF) && rep->vibrator_report &&
  1400. ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED &&
  1401. (msecs - ctlr->rumble_msecs) >= JC_RUMBLE_PERIOD_MS &&
  1402. (ctlr->rumble_queue_head != ctlr->rumble_queue_tail ||
  1403. ctlr->rumble_zero_countdown > 0)) {
  1404. /*
  1405. * When this value reaches 0, we know we've sent multiple
  1406. * packets to the controller instructing it to disable rumble.
  1407. * We can safely stop sending periodic rumble packets until the
  1408. * next ff effect.
  1409. */
  1410. if (ctlr->rumble_zero_countdown > 0)
  1411. ctlr->rumble_zero_countdown--;
  1412. queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);
  1413. }
  1414. spin_unlock_irqrestore(&ctlr->lock, flags);
  1415. }
  1416. static void joycon_parse_battery_status(struct joycon_ctlr *ctlr, struct joycon_input_report *rep)
  1417. {
  1418. u8 tmp;
  1419. unsigned long flags;
  1420. spin_lock_irqsave(&ctlr->lock, flags);
  1421. tmp = rep->bat_con;
  1422. ctlr->host_powered = tmp & BIT(0);
  1423. ctlr->battery_charging = tmp & BIT(4);
  1424. tmp = tmp >> 5;
  1425. switch (tmp) {
  1426. case 0: /* empty */
  1427. ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
  1428. break;
  1429. case 1: /* low */
  1430. ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
  1431. break;
  1432. case 2: /* medium */
  1433. ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
  1434. break;
  1435. case 3: /* high */
  1436. ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
  1437. break;
  1438. case 4: /* full */
  1439. ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
  1440. break;
  1441. default:
  1442. ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
  1443. hid_warn(ctlr->hdev, "Invalid battery status\n");
  1444. break;
  1445. }
  1446. spin_unlock_irqrestore(&ctlr->lock, flags);
  1447. }
  1448. static void joycon_report_left_stick(struct joycon_ctlr *ctlr,
  1449. struct joycon_input_report *rep)
  1450. {
  1451. u16 raw_x;
  1452. u16 raw_y;
  1453. s32 x;
  1454. s32 y;
  1455. raw_x = hid_field_extract(ctlr->hdev, rep->left_stick, 0, 12);
  1456. raw_y = hid_field_extract(ctlr->hdev, rep->left_stick + 1, 4, 12);
  1457. x = joycon_map_stick_val(&ctlr->left_stick_cal_x, raw_x);
  1458. y = -joycon_map_stick_val(&ctlr->left_stick_cal_y, raw_y);
  1459. input_report_abs(ctlr->input, ABS_X, x);
  1460. input_report_abs(ctlr->input, ABS_Y, y);
  1461. }
  1462. static void joycon_report_right_stick(struct joycon_ctlr *ctlr,
  1463. struct joycon_input_report *rep)
  1464. {
  1465. u16 raw_x;
  1466. u16 raw_y;
  1467. s32 x;
  1468. s32 y;
  1469. raw_x = hid_field_extract(ctlr->hdev, rep->right_stick, 0, 12);
  1470. raw_y = hid_field_extract(ctlr->hdev, rep->right_stick + 1, 4, 12);
  1471. x = joycon_map_stick_val(&ctlr->right_stick_cal_x, raw_x);
  1472. y = -joycon_map_stick_val(&ctlr->right_stick_cal_y, raw_y);
  1473. input_report_abs(ctlr->input, ABS_RX, x);
  1474. input_report_abs(ctlr->input, ABS_RY, y);
  1475. }
  1476. static void joycon_report_dpad(struct joycon_ctlr *ctlr,
  1477. struct joycon_input_report *rep)
  1478. {
  1479. int hatx = 0;
  1480. int haty = 0;
  1481. u32 btns = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24);
  1482. if (btns & JC_BTN_LEFT)
  1483. hatx = -1;
  1484. else if (btns & JC_BTN_RIGHT)
  1485. hatx = 1;
  1486. if (btns & JC_BTN_UP)
  1487. haty = -1;
  1488. else if (btns & JC_BTN_DOWN)
  1489. haty = 1;
  1490. input_report_abs(ctlr->input, ABS_HAT0X, hatx);
  1491. input_report_abs(ctlr->input, ABS_HAT0Y, haty);
  1492. }
  1493. static void joycon_report_buttons(struct joycon_ctlr *ctlr,
  1494. struct joycon_input_report *rep,
  1495. const struct joycon_ctlr_button_mapping button_mappings[])
  1496. {
  1497. const struct joycon_ctlr_button_mapping *button;
  1498. u32 status = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24);
  1499. for (button = button_mappings; button->code; button++)
  1500. input_report_key(ctlr->input, button->code, status & button->bit);
  1501. }
  1502. static void joycon_parse_report(struct joycon_ctlr *ctlr,
  1503. struct joycon_input_report *rep)
  1504. {
  1505. unsigned long flags;
  1506. unsigned long msecs = jiffies_to_msecs(jiffies);
  1507. unsigned long report_delta_ms = msecs - ctlr->last_input_report_msecs;
  1508. if (joycon_has_rumble(ctlr))
  1509. joycon_handle_rumble_report(ctlr, rep);
  1510. joycon_parse_battery_status(ctlr, rep);
  1511. if (joycon_type_is_left_joycon(ctlr)) {
  1512. joycon_report_left_stick(ctlr, rep);
  1513. joycon_report_buttons(ctlr, rep, left_joycon_button_mappings);
  1514. if (!joycon_device_is_chrggrip(ctlr))
  1515. joycon_report_buttons(ctlr, rep, left_joycon_s_button_mappings);
  1516. } else if (joycon_type_is_right_joycon(ctlr)) {
  1517. joycon_report_right_stick(ctlr, rep);
  1518. joycon_report_buttons(ctlr, rep, right_joycon_button_mappings);
  1519. if (!joycon_device_is_chrggrip(ctlr))
  1520. joycon_report_buttons(ctlr, rep, right_joycon_s_button_mappings);
  1521. } else if (joycon_type_is_procon(ctlr)) {
  1522. joycon_report_left_stick(ctlr, rep);
  1523. joycon_report_right_stick(ctlr, rep);
  1524. joycon_report_dpad(ctlr, rep);
  1525. joycon_report_buttons(ctlr, rep, procon_button_mappings);
  1526. } else if (joycon_type_is_any_nescon(ctlr)) {
  1527. joycon_report_dpad(ctlr, rep);
  1528. joycon_report_buttons(ctlr, rep, nescon_button_mappings);
  1529. } else if (joycon_type_is_snescon(ctlr)) {
  1530. joycon_report_dpad(ctlr, rep);
  1531. joycon_report_buttons(ctlr, rep, snescon_button_mappings);
  1532. } else if (joycon_type_is_gencon(ctlr)) {
  1533. joycon_report_dpad(ctlr, rep);
  1534. joycon_report_buttons(ctlr, rep, gencon_button_mappings);
  1535. } else if (joycon_type_is_n64con(ctlr)) {
  1536. joycon_report_left_stick(ctlr, rep);
  1537. joycon_report_dpad(ctlr, rep);
  1538. joycon_report_buttons(ctlr, rep, n64con_button_mappings);
  1539. }
  1540. input_sync(ctlr->input);
  1541. spin_lock_irqsave(&ctlr->lock, flags);
  1542. ctlr->last_input_report_msecs = msecs;
  1543. /*
  1544. * Was this input report a reasonable time delta compared to the prior
  1545. * report? We use this information to decide when a safe time is to send
  1546. * rumble packets or subcommand packets.
  1547. */
  1548. if (report_delta_ms >= JC_INPUT_REPORT_MIN_DELTA &&
  1549. report_delta_ms <= JC_INPUT_REPORT_MAX_DELTA) {
  1550. if (ctlr->consecutive_valid_report_deltas < JC_SUBCMD_VALID_DELTA_REQ)
  1551. ctlr->consecutive_valid_report_deltas++;
  1552. } else {
  1553. ctlr->consecutive_valid_report_deltas = 0;
  1554. }
  1555. /*
  1556. * Our consecutive valid report tracking is only relevant for
  1557. * bluetooth-connected controllers. For USB devices, we're beholden to
  1558. * USB's underlying polling rate anyway. Always set to the consecutive
  1559. * delta requirement.
  1560. */
  1561. if (ctlr->hdev->bus == BUS_USB)
  1562. ctlr->consecutive_valid_report_deltas = JC_SUBCMD_VALID_DELTA_REQ;
  1563. spin_unlock_irqrestore(&ctlr->lock, flags);
  1564. /*
  1565. * Immediately after receiving a report is the most reliable time to
  1566. * send a subcommand to the controller. Wake any subcommand senders
  1567. * waiting for a report.
  1568. */
  1569. if (unlikely(mutex_is_locked(&ctlr->output_mutex))) {
  1570. spin_lock_irqsave(&ctlr->lock, flags);
  1571. ctlr->received_input_report = true;
  1572. spin_unlock_irqrestore(&ctlr->lock, flags);
  1573. wake_up(&ctlr->wait);
  1574. }
  1575. /* parse IMU data if present */
  1576. if ((rep->id == JC_INPUT_IMU_DATA) && joycon_has_imu(ctlr))
  1577. joycon_parse_imu_report(ctlr, rep);
  1578. }
  1579. static int joycon_send_rumble_data(struct joycon_ctlr *ctlr)
  1580. {
  1581. int ret;
  1582. unsigned long flags;
  1583. struct joycon_rumble_output rumble_output = { 0 };
  1584. spin_lock_irqsave(&ctlr->lock, flags);
  1585. /*
  1586. * If the controller has been removed, just return ENODEV so the LED
  1587. * subsystem doesn't print invalid errors on removal.
  1588. */
  1589. if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) {
  1590. spin_unlock_irqrestore(&ctlr->lock, flags);
  1591. return -ENODEV;
  1592. }
  1593. memcpy(rumble_output.rumble_data,
  1594. ctlr->rumble_data[ctlr->rumble_queue_tail],
  1595. JC_RUMBLE_DATA_SIZE);
  1596. spin_unlock_irqrestore(&ctlr->lock, flags);
  1597. rumble_output.output_id = JC_OUTPUT_RUMBLE_ONLY;
  1598. rumble_output.packet_num = ctlr->subcmd_num;
  1599. if (++ctlr->subcmd_num > 0xF)
  1600. ctlr->subcmd_num = 0;
  1601. joycon_enforce_subcmd_rate(ctlr);
  1602. ret = __joycon_hid_send(ctlr->hdev, (u8 *)&rumble_output,
  1603. sizeof(rumble_output));
  1604. return ret;
  1605. }
  1606. static void joycon_rumble_worker(struct work_struct *work)
  1607. {
  1608. struct joycon_ctlr *ctlr = container_of(work, struct joycon_ctlr,
  1609. rumble_worker);
  1610. unsigned long flags;
  1611. bool again = true;
  1612. int ret;
  1613. while (again) {
  1614. mutex_lock(&ctlr->output_mutex);
  1615. ret = joycon_send_rumble_data(ctlr);
  1616. mutex_unlock(&ctlr->output_mutex);
  1617. /* -ENODEV means the controller was just unplugged */
  1618. spin_lock_irqsave(&ctlr->lock, flags);
  1619. if (ret < 0 && ret != -ENODEV &&
  1620. ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED)
  1621. hid_warn(ctlr->hdev, "Failed to set rumble; e=%d", ret);
  1622. ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
  1623. if (ctlr->rumble_queue_tail != ctlr->rumble_queue_head) {
  1624. if (++ctlr->rumble_queue_tail >= JC_RUMBLE_QUEUE_SIZE)
  1625. ctlr->rumble_queue_tail = 0;
  1626. } else {
  1627. again = false;
  1628. }
  1629. spin_unlock_irqrestore(&ctlr->lock, flags);
  1630. }
  1631. }
  1632. #if IS_ENABLED(CONFIG_NINTENDO_FF)
  1633. static struct joycon_rumble_freq_data joycon_find_rumble_freq(u16 freq)
  1634. {
  1635. const size_t length = ARRAY_SIZE(joycon_rumble_frequencies);
  1636. const struct joycon_rumble_freq_data *data = joycon_rumble_frequencies;
  1637. int i = 0;
  1638. if (freq > data[0].freq) {
  1639. for (i = 1; i < length - 1; i++) {
  1640. if (freq > data[i - 1].freq && freq <= data[i].freq)
  1641. break;
  1642. }
  1643. }
  1644. return data[i];
  1645. }
  1646. static struct joycon_rumble_amp_data joycon_find_rumble_amp(u16 amp)
  1647. {
  1648. const size_t length = ARRAY_SIZE(joycon_rumble_amplitudes);
  1649. const struct joycon_rumble_amp_data *data = joycon_rumble_amplitudes;
  1650. int i = 0;
  1651. if (amp > data[0].amp) {
  1652. for (i = 1; i < length - 1; i++) {
  1653. if (amp > data[i - 1].amp && amp <= data[i].amp)
  1654. break;
  1655. }
  1656. }
  1657. return data[i];
  1658. }
  1659. static void joycon_encode_rumble(u8 *data, u16 freq_low, u16 freq_high, u16 amp)
  1660. {
  1661. struct joycon_rumble_freq_data freq_data_low;
  1662. struct joycon_rumble_freq_data freq_data_high;
  1663. struct joycon_rumble_amp_data amp_data;
  1664. freq_data_low = joycon_find_rumble_freq(freq_low);
  1665. freq_data_high = joycon_find_rumble_freq(freq_high);
  1666. amp_data = joycon_find_rumble_amp(amp);
  1667. data[0] = (freq_data_high.high >> 8) & 0xFF;
  1668. data[1] = (freq_data_high.high & 0xFF) + amp_data.high;
  1669. data[2] = freq_data_low.low + ((amp_data.low >> 8) & 0xFF);
  1670. data[3] = amp_data.low & 0xFF;
  1671. }
  1672. static const u16 JOYCON_MAX_RUMBLE_HIGH_FREQ = 1253;
  1673. static const u16 JOYCON_MIN_RUMBLE_HIGH_FREQ = 82;
  1674. static const u16 JOYCON_MAX_RUMBLE_LOW_FREQ = 626;
  1675. static const u16 JOYCON_MIN_RUMBLE_LOW_FREQ = 41;
  1676. static void joycon_clamp_rumble_freqs(struct joycon_ctlr *ctlr)
  1677. {
  1678. unsigned long flags;
  1679. spin_lock_irqsave(&ctlr->lock, flags);
  1680. ctlr->rumble_ll_freq = clamp(ctlr->rumble_ll_freq,
  1681. JOYCON_MIN_RUMBLE_LOW_FREQ,
  1682. JOYCON_MAX_RUMBLE_LOW_FREQ);
  1683. ctlr->rumble_lh_freq = clamp(ctlr->rumble_lh_freq,
  1684. JOYCON_MIN_RUMBLE_HIGH_FREQ,
  1685. JOYCON_MAX_RUMBLE_HIGH_FREQ);
  1686. ctlr->rumble_rl_freq = clamp(ctlr->rumble_rl_freq,
  1687. JOYCON_MIN_RUMBLE_LOW_FREQ,
  1688. JOYCON_MAX_RUMBLE_LOW_FREQ);
  1689. ctlr->rumble_rh_freq = clamp(ctlr->rumble_rh_freq,
  1690. JOYCON_MIN_RUMBLE_HIGH_FREQ,
  1691. JOYCON_MAX_RUMBLE_HIGH_FREQ);
  1692. spin_unlock_irqrestore(&ctlr->lock, flags);
  1693. }
  1694. static int joycon_set_rumble(struct joycon_ctlr *ctlr, u16 amp_r, u16 amp_l,
  1695. bool schedule_now)
  1696. {
  1697. u8 data[JC_RUMBLE_DATA_SIZE];
  1698. u16 amp;
  1699. u16 freq_r_low;
  1700. u16 freq_r_high;
  1701. u16 freq_l_low;
  1702. u16 freq_l_high;
  1703. unsigned long flags;
  1704. int next_rq_head;
  1705. spin_lock_irqsave(&ctlr->lock, flags);
  1706. freq_r_low = ctlr->rumble_rl_freq;
  1707. freq_r_high = ctlr->rumble_rh_freq;
  1708. freq_l_low = ctlr->rumble_ll_freq;
  1709. freq_l_high = ctlr->rumble_lh_freq;
  1710. /* limit number of silent rumble packets to reduce traffic */
  1711. if (amp_l != 0 || amp_r != 0)
  1712. ctlr->rumble_zero_countdown = JC_RUMBLE_ZERO_AMP_PKT_CNT;
  1713. spin_unlock_irqrestore(&ctlr->lock, flags);
  1714. /* right joy-con */
  1715. amp = amp_r * (u32)joycon_max_rumble_amp / 65535;
  1716. joycon_encode_rumble(data + 4, freq_r_low, freq_r_high, amp);
  1717. /* left joy-con */
  1718. amp = amp_l * (u32)joycon_max_rumble_amp / 65535;
  1719. joycon_encode_rumble(data, freq_l_low, freq_l_high, amp);
  1720. spin_lock_irqsave(&ctlr->lock, flags);
  1721. next_rq_head = ctlr->rumble_queue_head + 1;
  1722. if (next_rq_head >= JC_RUMBLE_QUEUE_SIZE)
  1723. next_rq_head = 0;
  1724. /* Did we overrun the circular buffer?
  1725. * If so, be sure we keep the latest intended rumble state.
  1726. */
  1727. if (next_rq_head == ctlr->rumble_queue_tail) {
  1728. hid_dbg(ctlr->hdev, "rumble queue is full");
  1729. /* overwrite the prior value at the end of the circular buf */
  1730. next_rq_head = ctlr->rumble_queue_head;
  1731. }
  1732. ctlr->rumble_queue_head = next_rq_head;
  1733. memcpy(ctlr->rumble_data[ctlr->rumble_queue_head], data,
  1734. JC_RUMBLE_DATA_SIZE);
  1735. /* don't wait for the periodic send (reduces latency) */
  1736. if (schedule_now && ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED)
  1737. queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);
  1738. spin_unlock_irqrestore(&ctlr->lock, flags);
  1739. return 0;
  1740. }
  1741. static int joycon_play_effect(struct input_dev *dev, void *data,
  1742. struct ff_effect *effect)
  1743. {
  1744. struct joycon_ctlr *ctlr = input_get_drvdata(dev);
  1745. if (effect->type != FF_RUMBLE)
  1746. return 0;
  1747. return joycon_set_rumble(ctlr,
  1748. effect->u.rumble.weak_magnitude,
  1749. effect->u.rumble.strong_magnitude,
  1750. true);
  1751. }
  1752. #endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */
  1753. static void joycon_config_left_stick(struct input_dev *idev)
  1754. {
  1755. input_set_abs_params(idev,
  1756. ABS_X,
  1757. -JC_MAX_STICK_MAG,
  1758. JC_MAX_STICK_MAG,
  1759. JC_STICK_FUZZ,
  1760. JC_STICK_FLAT);
  1761. input_set_abs_params(idev,
  1762. ABS_Y,
  1763. -JC_MAX_STICK_MAG,
  1764. JC_MAX_STICK_MAG,
  1765. JC_STICK_FUZZ,
  1766. JC_STICK_FLAT);
  1767. }
  1768. static void joycon_config_right_stick(struct input_dev *idev)
  1769. {
  1770. input_set_abs_params(idev,
  1771. ABS_RX,
  1772. -JC_MAX_STICK_MAG,
  1773. JC_MAX_STICK_MAG,
  1774. JC_STICK_FUZZ,
  1775. JC_STICK_FLAT);
  1776. input_set_abs_params(idev,
  1777. ABS_RY,
  1778. -JC_MAX_STICK_MAG,
  1779. JC_MAX_STICK_MAG,
  1780. JC_STICK_FUZZ,
  1781. JC_STICK_FLAT);
  1782. }
  1783. static void joycon_config_dpad(struct input_dev *idev)
  1784. {
  1785. input_set_abs_params(idev,
  1786. ABS_HAT0X,
  1787. -JC_MAX_DPAD_MAG,
  1788. JC_MAX_DPAD_MAG,
  1789. JC_DPAD_FUZZ,
  1790. JC_DPAD_FLAT);
  1791. input_set_abs_params(idev,
  1792. ABS_HAT0Y,
  1793. -JC_MAX_DPAD_MAG,
  1794. JC_MAX_DPAD_MAG,
  1795. JC_DPAD_FUZZ,
  1796. JC_DPAD_FLAT);
  1797. }
  1798. static void joycon_config_buttons(struct input_dev *idev,
  1799. const struct joycon_ctlr_button_mapping button_mappings[])
  1800. {
  1801. const struct joycon_ctlr_button_mapping *button;
  1802. for (button = button_mappings; button->code; button++)
  1803. input_set_capability(idev, EV_KEY, button->code);
  1804. }
  1805. static void joycon_config_rumble(struct joycon_ctlr *ctlr)
  1806. {
  1807. #if IS_ENABLED(CONFIG_NINTENDO_FF)
  1808. /* set up rumble */
  1809. input_set_capability(ctlr->input, EV_FF, FF_RUMBLE);
  1810. input_ff_create_memless(ctlr->input, NULL, joycon_play_effect);
  1811. ctlr->rumble_ll_freq = JC_RUMBLE_DFLT_LOW_FREQ;
  1812. ctlr->rumble_lh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
  1813. ctlr->rumble_rl_freq = JC_RUMBLE_DFLT_LOW_FREQ;
  1814. ctlr->rumble_rh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
  1815. joycon_clamp_rumble_freqs(ctlr);
  1816. joycon_set_rumble(ctlr, 0, 0, false);
  1817. ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
  1818. #endif
  1819. }
  1820. static int joycon_imu_input_create(struct joycon_ctlr *ctlr)
  1821. {
  1822. struct hid_device *hdev;
  1823. const char *imu_name;
  1824. int ret;
  1825. hdev = ctlr->hdev;
  1826. /* configure the imu input device */
  1827. ctlr->imu_input = devm_input_allocate_device(&hdev->dev);
  1828. if (!ctlr->imu_input)
  1829. return -ENOMEM;
  1830. ctlr->imu_input->id.bustype = hdev->bus;
  1831. ctlr->imu_input->id.vendor = hdev->vendor;
  1832. ctlr->imu_input->id.product = hdev->product;
  1833. ctlr->imu_input->id.version = hdev->version;
  1834. ctlr->imu_input->uniq = ctlr->mac_addr_str;
  1835. ctlr->imu_input->phys = hdev->phys;
  1836. imu_name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s (IMU)", ctlr->input->name);
  1837. if (!imu_name)
  1838. return -ENOMEM;
  1839. ctlr->imu_input->name = imu_name;
  1840. input_set_drvdata(ctlr->imu_input, ctlr);
  1841. /* configure imu axes */
  1842. input_set_abs_params(ctlr->imu_input, ABS_X,
  1843. -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
  1844. JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
  1845. input_set_abs_params(ctlr->imu_input, ABS_Y,
  1846. -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
  1847. JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
  1848. input_set_abs_params(ctlr->imu_input, ABS_Z,
  1849. -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
  1850. JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
  1851. input_abs_set_res(ctlr->imu_input, ABS_X, JC_IMU_ACCEL_RES_PER_G);
  1852. input_abs_set_res(ctlr->imu_input, ABS_Y, JC_IMU_ACCEL_RES_PER_G);
  1853. input_abs_set_res(ctlr->imu_input, ABS_Z, JC_IMU_ACCEL_RES_PER_G);
  1854. input_set_abs_params(ctlr->imu_input, ABS_RX,
  1855. -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
  1856. JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
  1857. input_set_abs_params(ctlr->imu_input, ABS_RY,
  1858. -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
  1859. JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
  1860. input_set_abs_params(ctlr->imu_input, ABS_RZ,
  1861. -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
  1862. JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
  1863. input_abs_set_res(ctlr->imu_input, ABS_RX, JC_IMU_GYRO_RES_PER_DPS);
  1864. input_abs_set_res(ctlr->imu_input, ABS_RY, JC_IMU_GYRO_RES_PER_DPS);
  1865. input_abs_set_res(ctlr->imu_input, ABS_RZ, JC_IMU_GYRO_RES_PER_DPS);
  1866. __set_bit(EV_MSC, ctlr->imu_input->evbit);
  1867. __set_bit(MSC_TIMESTAMP, ctlr->imu_input->mscbit);
  1868. __set_bit(INPUT_PROP_ACCELEROMETER, ctlr->imu_input->propbit);
  1869. ret = input_register_device(ctlr->imu_input);
  1870. if (ret)
  1871. return ret;
  1872. return 0;
  1873. }
  1874. static int joycon_input_create(struct joycon_ctlr *ctlr)
  1875. {
  1876. struct hid_device *hdev;
  1877. int ret;
  1878. hdev = ctlr->hdev;
  1879. ctlr->input = devm_input_allocate_device(&hdev->dev);
  1880. if (!ctlr->input)
  1881. return -ENOMEM;
  1882. ctlr->input->id.bustype = hdev->bus;
  1883. ctlr->input->id.vendor = hdev->vendor;
  1884. ctlr->input->id.product = hdev->product;
  1885. ctlr->input->id.version = hdev->version;
  1886. ctlr->input->uniq = ctlr->mac_addr_str;
  1887. ctlr->input->name = hdev->name;
  1888. ctlr->input->phys = hdev->phys;
  1889. input_set_drvdata(ctlr->input, ctlr);
  1890. ret = input_register_device(ctlr->input);
  1891. if (ret)
  1892. return ret;
  1893. if (joycon_type_is_right_joycon(ctlr)) {
  1894. joycon_config_right_stick(ctlr->input);
  1895. joycon_config_buttons(ctlr->input, right_joycon_button_mappings);
  1896. if (!joycon_device_is_chrggrip(ctlr))
  1897. joycon_config_buttons(ctlr->input, right_joycon_s_button_mappings);
  1898. } else if (joycon_type_is_left_joycon(ctlr)) {
  1899. joycon_config_left_stick(ctlr->input);
  1900. joycon_config_buttons(ctlr->input, left_joycon_button_mappings);
  1901. if (!joycon_device_is_chrggrip(ctlr))
  1902. joycon_config_buttons(ctlr->input, left_joycon_s_button_mappings);
  1903. } else if (joycon_type_is_procon(ctlr)) {
  1904. joycon_config_left_stick(ctlr->input);
  1905. joycon_config_right_stick(ctlr->input);
  1906. joycon_config_dpad(ctlr->input);
  1907. joycon_config_buttons(ctlr->input, procon_button_mappings);
  1908. } else if (joycon_type_is_any_nescon(ctlr)) {
  1909. joycon_config_dpad(ctlr->input);
  1910. joycon_config_buttons(ctlr->input, nescon_button_mappings);
  1911. } else if (joycon_type_is_snescon(ctlr)) {
  1912. joycon_config_dpad(ctlr->input);
  1913. joycon_config_buttons(ctlr->input, snescon_button_mappings);
  1914. } else if (joycon_type_is_gencon(ctlr)) {
  1915. joycon_config_dpad(ctlr->input);
  1916. joycon_config_buttons(ctlr->input, gencon_button_mappings);
  1917. } else if (joycon_type_is_n64con(ctlr)) {
  1918. joycon_config_dpad(ctlr->input);
  1919. joycon_config_left_stick(ctlr->input);
  1920. joycon_config_buttons(ctlr->input, n64con_button_mappings);
  1921. }
  1922. if (joycon_has_imu(ctlr)) {
  1923. ret = joycon_imu_input_create(ctlr);
  1924. if (ret)
  1925. return ret;
  1926. }
  1927. if (joycon_has_rumble(ctlr))
  1928. joycon_config_rumble(ctlr);
  1929. return 0;
  1930. }
  1931. /* Because the subcommand sets all the leds at once, the brightness argument is ignored */
  1932. static int joycon_player_led_brightness_set(struct led_classdev *led,
  1933. enum led_brightness brightness)
  1934. {
  1935. struct device *dev = led->dev->parent;
  1936. struct hid_device *hdev = to_hid_device(dev);
  1937. struct joycon_ctlr *ctlr;
  1938. int val = 0;
  1939. int i;
  1940. int ret;
  1941. ctlr = hid_get_drvdata(hdev);
  1942. if (!ctlr) {
  1943. hid_err(hdev, "No controller data\n");
  1944. return -ENODEV;
  1945. }
  1946. for (i = 0; i < JC_NUM_LEDS; i++)
  1947. val |= ctlr->leds[i].brightness << i;
  1948. mutex_lock(&ctlr->output_mutex);
  1949. ret = joycon_set_player_leds(ctlr, 0, val);
  1950. mutex_unlock(&ctlr->output_mutex);
  1951. return ret;
  1952. }
  1953. static int joycon_home_led_brightness_set(struct led_classdev *led,
  1954. enum led_brightness brightness)
  1955. {
  1956. struct device *dev = led->dev->parent;
  1957. struct hid_device *hdev = to_hid_device(dev);
  1958. struct joycon_ctlr *ctlr;
  1959. int ret;
  1960. ctlr = hid_get_drvdata(hdev);
  1961. if (!ctlr) {
  1962. hid_err(hdev, "No controller data\n");
  1963. return -ENODEV;
  1964. }
  1965. mutex_lock(&ctlr->output_mutex);
  1966. ret = joycon_set_home_led(ctlr, brightness);
  1967. mutex_unlock(&ctlr->output_mutex);
  1968. return ret;
  1969. }
  1970. static DEFINE_IDA(nintendo_player_id_allocator);
  1971. static int joycon_leds_create(struct joycon_ctlr *ctlr)
  1972. {
  1973. struct hid_device *hdev = ctlr->hdev;
  1974. struct device *dev = &hdev->dev;
  1975. const char *d_name = dev_name(dev);
  1976. struct led_classdev *led;
  1977. int led_val = 0;
  1978. char *name;
  1979. int ret;
  1980. int i;
  1981. int player_led_pattern;
  1982. /* configure the player LEDs */
  1983. ctlr->player_id = U32_MAX;
  1984. ret = ida_alloc(&nintendo_player_id_allocator, GFP_KERNEL);
  1985. if (ret < 0) {
  1986. hid_warn(hdev, "Failed to allocate player ID, skipping; ret=%d\n", ret);
  1987. goto home_led;
  1988. }
  1989. ctlr->player_id = ret;
  1990. player_led_pattern = ret % JC_NUM_LED_PATTERNS;
  1991. hid_info(ctlr->hdev, "assigned player %d led pattern", player_led_pattern + 1);
  1992. for (i = 0; i < JC_NUM_LEDS; i++) {
  1993. name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
  1994. d_name,
  1995. "green",
  1996. joycon_player_led_names[i]);
  1997. if (!name)
  1998. return -ENOMEM;
  1999. led = &ctlr->leds[i];
  2000. led->name = name;
  2001. led->brightness = joycon_player_led_patterns[player_led_pattern][i];
  2002. led->max_brightness = 1;
  2003. led->brightness_set_blocking =
  2004. joycon_player_led_brightness_set;
  2005. led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;
  2006. led_val |= joycon_player_led_patterns[player_led_pattern][i] << i;
  2007. }
  2008. mutex_lock(&ctlr->output_mutex);
  2009. ret = joycon_set_player_leds(ctlr, 0, led_val);
  2010. mutex_unlock(&ctlr->output_mutex);
  2011. if (ret) {
  2012. hid_warn(hdev, "Failed to set players LEDs, skipping registration; ret=%d\n", ret);
  2013. goto home_led;
  2014. }
  2015. for (i = 0; i < JC_NUM_LEDS; i++) {
  2016. led = &ctlr->leds[i];
  2017. ret = devm_led_classdev_register(&hdev->dev, led);
  2018. if (ret) {
  2019. hid_err(hdev, "Failed to register player %d LED; ret=%d\n", i + 1, ret);
  2020. return ret;
  2021. }
  2022. }
  2023. home_led:
  2024. /* configure the home LED */
  2025. if (jc_type_has_right(ctlr)) {
  2026. name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
  2027. d_name,
  2028. "blue",
  2029. LED_FUNCTION_PLAYER5);
  2030. if (!name)
  2031. return -ENOMEM;
  2032. led = &ctlr->home_led;
  2033. led->name = name;
  2034. led->brightness = 0;
  2035. led->max_brightness = 0xF;
  2036. led->brightness_set_blocking = joycon_home_led_brightness_set;
  2037. led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;
  2038. /* Set the home LED to 0 as default state */
  2039. mutex_lock(&ctlr->output_mutex);
  2040. ret = joycon_set_home_led(ctlr, 0);
  2041. mutex_unlock(&ctlr->output_mutex);
  2042. if (ret) {
  2043. hid_warn(hdev, "Failed to set home LED, skipping registration; ret=%d\n", ret);
  2044. return 0;
  2045. }
  2046. ret = devm_led_classdev_register(&hdev->dev, led);
  2047. if (ret) {
  2048. hid_err(hdev, "Failed to register home LED; ret=%d\n", ret);
  2049. return ret;
  2050. }
  2051. }
  2052. return 0;
  2053. }
  2054. static int joycon_battery_get_property(struct power_supply *supply,
  2055. enum power_supply_property prop,
  2056. union power_supply_propval *val)
  2057. {
  2058. struct joycon_ctlr *ctlr = power_supply_get_drvdata(supply);
  2059. unsigned long flags;
  2060. int ret = 0;
  2061. u8 capacity;
  2062. bool charging;
  2063. bool powered;
  2064. spin_lock_irqsave(&ctlr->lock, flags);
  2065. capacity = ctlr->battery_capacity;
  2066. charging = ctlr->battery_charging;
  2067. powered = ctlr->host_powered;
  2068. spin_unlock_irqrestore(&ctlr->lock, flags);
  2069. switch (prop) {
  2070. case POWER_SUPPLY_PROP_PRESENT:
  2071. val->intval = 1;
  2072. break;
  2073. case POWER_SUPPLY_PROP_SCOPE:
  2074. val->intval = POWER_SUPPLY_SCOPE_DEVICE;
  2075. break;
  2076. case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
  2077. val->intval = capacity;
  2078. break;
  2079. case POWER_SUPPLY_PROP_STATUS:
  2080. if (charging)
  2081. val->intval = POWER_SUPPLY_STATUS_CHARGING;
  2082. else if (capacity == POWER_SUPPLY_CAPACITY_LEVEL_FULL &&
  2083. powered)
  2084. val->intval = POWER_SUPPLY_STATUS_FULL;
  2085. else
  2086. val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
  2087. break;
  2088. default:
  2089. ret = -EINVAL;
  2090. break;
  2091. }
  2092. return ret;
  2093. }
  2094. static enum power_supply_property joycon_battery_props[] = {
  2095. POWER_SUPPLY_PROP_PRESENT,
  2096. POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  2097. POWER_SUPPLY_PROP_SCOPE,
  2098. POWER_SUPPLY_PROP_STATUS,
  2099. };
  2100. static int joycon_power_supply_create(struct joycon_ctlr *ctlr)
  2101. {
  2102. struct hid_device *hdev = ctlr->hdev;
  2103. struct power_supply_config supply_config = { .drv_data = ctlr, };
  2104. const char * const name_fmt = "nintendo_switch_controller_battery_%s";
  2105. int ret = 0;
  2106. /* Set initially to unknown before receiving first input report */
  2107. ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
  2108. /* Configure the battery's description */
  2109. ctlr->battery_desc.properties = joycon_battery_props;
  2110. ctlr->battery_desc.num_properties =
  2111. ARRAY_SIZE(joycon_battery_props);
  2112. ctlr->battery_desc.get_property = joycon_battery_get_property;
  2113. ctlr->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
  2114. ctlr->battery_desc.use_for_apm = 0;
  2115. ctlr->battery_desc.name = devm_kasprintf(&hdev->dev, GFP_KERNEL,
  2116. name_fmt,
  2117. dev_name(&hdev->dev));
  2118. if (!ctlr->battery_desc.name)
  2119. return -ENOMEM;
  2120. ctlr->battery = devm_power_supply_register(&hdev->dev,
  2121. &ctlr->battery_desc,
  2122. &supply_config);
  2123. if (IS_ERR(ctlr->battery)) {
  2124. ret = PTR_ERR(ctlr->battery);
  2125. hid_err(hdev, "Failed to register battery; ret=%d\n", ret);
  2126. return ret;
  2127. }
  2128. return power_supply_powers(ctlr->battery, &hdev->dev);
  2129. }
  2130. static int joycon_read_info(struct joycon_ctlr *ctlr)
  2131. {
  2132. int ret;
  2133. int i;
  2134. int j;
  2135. struct joycon_subcmd_request req = { 0 };
  2136. struct joycon_input_report *report;
  2137. req.subcmd_id = JC_SUBCMD_REQ_DEV_INFO;
  2138. ret = joycon_send_subcmd(ctlr, &req, 0, HZ);
  2139. if (ret) {
  2140. hid_err(ctlr->hdev, "Failed to get joycon info; ret=%d\n", ret);
  2141. return ret;
  2142. }
  2143. report = (struct joycon_input_report *)ctlr->input_buf;
  2144. for (i = 4, j = 0; j < 6; i++, j++)
  2145. ctlr->mac_addr[j] = report->subcmd_reply.data[i];
  2146. ctlr->mac_addr_str = devm_kasprintf(&ctlr->hdev->dev, GFP_KERNEL,
  2147. "%02X:%02X:%02X:%02X:%02X:%02X",
  2148. ctlr->mac_addr[0],
  2149. ctlr->mac_addr[1],
  2150. ctlr->mac_addr[2],
  2151. ctlr->mac_addr[3],
  2152. ctlr->mac_addr[4],
  2153. ctlr->mac_addr[5]);
  2154. if (!ctlr->mac_addr_str)
  2155. return -ENOMEM;
  2156. hid_info(ctlr->hdev, "controller MAC = %s\n", ctlr->mac_addr_str);
  2157. /*
  2158. * Retrieve the type so we can distinguish the controller type
  2159. * Unfortantly the hdev->product can't always be used due to a ?bug?
  2160. * with the NSO Genesis controller. Over USB, it will report the
  2161. * PID as 0x201E, but over bluetooth it will report the PID as 0x2017
  2162. * which is the same as the NSO SNES controller. This is different from
  2163. * the rest of the controllers which will report the same PID over USB
  2164. * and bluetooth.
  2165. */
  2166. ctlr->ctlr_type = report->subcmd_reply.data[2];
  2167. hid_dbg(ctlr->hdev, "controller type = 0x%02X\n", ctlr->ctlr_type);
  2168. return 0;
  2169. }
  2170. static int joycon_init(struct hid_device *hdev)
  2171. {
  2172. struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
  2173. int ret = 0;
  2174. mutex_lock(&ctlr->output_mutex);
  2175. /* if handshake command fails, assume ble pro controller */
  2176. if (joycon_using_usb(ctlr) && !joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ)) {
  2177. hid_dbg(hdev, "detected USB controller\n");
  2178. /* set baudrate for improved latency */
  2179. ret = joycon_send_usb(ctlr, JC_USB_CMD_BAUDRATE_3M, HZ);
  2180. if (ret) {
  2181. /*
  2182. * We can function with the default baudrate.
  2183. * Provide a warning, and continue on.
  2184. */
  2185. hid_warn(hdev, "Failed to set baudrate (ret=%d), continuing anyway\n", ret);
  2186. }
  2187. /* handshake */
  2188. ret = joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ);
  2189. if (ret) {
  2190. hid_err(hdev, "Failed handshake; ret=%d\n", ret);
  2191. goto out_unlock;
  2192. }
  2193. /*
  2194. * Set no timeout (to keep controller in USB mode).
  2195. * This doesn't send a response, so ignore the timeout.
  2196. */
  2197. joycon_send_usb(ctlr, JC_USB_CMD_NO_TIMEOUT, HZ/10);
  2198. } else if (jc_type_is_chrggrip(ctlr)) {
  2199. hid_err(hdev, "Failed charging grip handshake\n");
  2200. ret = -ETIMEDOUT;
  2201. goto out_unlock;
  2202. }
  2203. /* needed to retrieve the controller type */
  2204. ret = joycon_read_info(ctlr);
  2205. if (ret) {
  2206. hid_err(hdev, "Failed to retrieve controller info; ret=%d\n",
  2207. ret);
  2208. goto out_unlock;
  2209. }
  2210. if (joycon_has_joysticks(ctlr)) {
  2211. /* get controller calibration data, and parse it */
  2212. ret = joycon_request_calibration(ctlr);
  2213. if (ret) {
  2214. /*
  2215. * We can function with default calibration, but it may be
  2216. * inaccurate. Provide a warning, and continue on.
  2217. */
  2218. hid_warn(hdev, "Analog stick positions may be inaccurate\n");
  2219. }
  2220. }
  2221. if (joycon_has_imu(ctlr)) {
  2222. /* get IMU calibration data, and parse it */
  2223. ret = joycon_request_imu_calibration(ctlr);
  2224. if (ret) {
  2225. /*
  2226. * We can function with default calibration, but it may be
  2227. * inaccurate. Provide a warning, and continue on.
  2228. */
  2229. hid_warn(hdev, "Unable to read IMU calibration data\n");
  2230. }
  2231. /* Enable the IMU */
  2232. ret = joycon_enable_imu(ctlr);
  2233. if (ret) {
  2234. hid_err(hdev, "Failed to enable the IMU; ret=%d\n", ret);
  2235. goto out_unlock;
  2236. }
  2237. }
  2238. /* Set the reporting mode to 0x30, which is the full report mode */
  2239. ret = joycon_set_report_mode(ctlr);
  2240. if (ret) {
  2241. hid_err(hdev, "Failed to set report mode; ret=%d\n", ret);
  2242. goto out_unlock;
  2243. }
  2244. if (joycon_has_rumble(ctlr)) {
  2245. /* Enable rumble */
  2246. ret = joycon_enable_rumble(ctlr);
  2247. if (ret) {
  2248. hid_err(hdev, "Failed to enable rumble; ret=%d\n", ret);
  2249. goto out_unlock;
  2250. }
  2251. }
  2252. out_unlock:
  2253. mutex_unlock(&ctlr->output_mutex);
  2254. return ret;
  2255. }
  2256. /* Common handler for parsing inputs */
  2257. static int joycon_ctlr_read_handler(struct joycon_ctlr *ctlr, u8 *data,
  2258. int size)
  2259. {
  2260. if (data[0] == JC_INPUT_SUBCMD_REPLY || data[0] == JC_INPUT_IMU_DATA ||
  2261. data[0] == JC_INPUT_MCU_DATA) {
  2262. if (size >= 12) /* make sure it contains the input report */
  2263. joycon_parse_report(ctlr,
  2264. (struct joycon_input_report *)data);
  2265. }
  2266. return 0;
  2267. }
  2268. static int joycon_ctlr_handle_event(struct joycon_ctlr *ctlr, u8 *data,
  2269. int size)
  2270. {
  2271. int ret = 0;
  2272. bool match = false;
  2273. struct joycon_input_report *report;
  2274. if (unlikely(mutex_is_locked(&ctlr->output_mutex)) &&
  2275. ctlr->msg_type != JOYCON_MSG_TYPE_NONE) {
  2276. switch (ctlr->msg_type) {
  2277. case JOYCON_MSG_TYPE_USB:
  2278. if (size < 2)
  2279. break;
  2280. if (data[0] == JC_INPUT_USB_RESPONSE &&
  2281. data[1] == ctlr->usb_ack_match)
  2282. match = true;
  2283. break;
  2284. case JOYCON_MSG_TYPE_SUBCMD:
  2285. if (size < sizeof(struct joycon_input_report) ||
  2286. data[0] != JC_INPUT_SUBCMD_REPLY)
  2287. break;
  2288. report = (struct joycon_input_report *)data;
  2289. if (report->subcmd_reply.id == ctlr->subcmd_ack_match)
  2290. match = true;
  2291. break;
  2292. default:
  2293. break;
  2294. }
  2295. if (match) {
  2296. memcpy(ctlr->input_buf, data,
  2297. min(size, (int)JC_MAX_RESP_SIZE));
  2298. ctlr->msg_type = JOYCON_MSG_TYPE_NONE;
  2299. ctlr->received_resp = true;
  2300. wake_up(&ctlr->wait);
  2301. /* This message has been handled */
  2302. return 1;
  2303. }
  2304. }
  2305. if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ)
  2306. ret = joycon_ctlr_read_handler(ctlr, data, size);
  2307. return ret;
  2308. }
  2309. static int nintendo_hid_event(struct hid_device *hdev,
  2310. struct hid_report *report, u8 *raw_data, int size)
  2311. {
  2312. struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
  2313. if (size < 1)
  2314. return -EINVAL;
  2315. return joycon_ctlr_handle_event(ctlr, raw_data, size);
  2316. }
  2317. static int nintendo_hid_probe(struct hid_device *hdev,
  2318. const struct hid_device_id *id)
  2319. {
  2320. int ret;
  2321. struct joycon_ctlr *ctlr;
  2322. hid_dbg(hdev, "probe - start\n");
  2323. ctlr = devm_kzalloc(&hdev->dev, sizeof(*ctlr), GFP_KERNEL);
  2324. if (!ctlr) {
  2325. ret = -ENOMEM;
  2326. goto err;
  2327. }
  2328. ctlr->hdev = hdev;
  2329. ctlr->ctlr_state = JOYCON_CTLR_STATE_INIT;
  2330. ctlr->rumble_queue_head = 0;
  2331. ctlr->rumble_queue_tail = 0;
  2332. hid_set_drvdata(hdev, ctlr);
  2333. mutex_init(&ctlr->output_mutex);
  2334. init_waitqueue_head(&ctlr->wait);
  2335. spin_lock_init(&ctlr->lock);
  2336. ctlr->rumble_queue = alloc_workqueue("hid-nintendo-rumble_wq",
  2337. WQ_FREEZABLE | WQ_MEM_RECLAIM, 0);
  2338. if (!ctlr->rumble_queue) {
  2339. ret = -ENOMEM;
  2340. goto err;
  2341. }
  2342. INIT_WORK(&ctlr->rumble_worker, joycon_rumble_worker);
  2343. ret = hid_parse(hdev);
  2344. if (ret) {
  2345. hid_err(hdev, "HID parse failed\n");
  2346. goto err_wq;
  2347. }
  2348. /*
  2349. * Patch the hw version of pro controller/joycons, so applications can
  2350. * distinguish between the default HID mappings and the mappings defined
  2351. * by the Linux game controller spec. This is important for the SDL2
  2352. * library, which has a game controller database, which uses device ids
  2353. * in combination with version as a key.
  2354. */
  2355. hdev->version |= 0x8000;
  2356. ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
  2357. if (ret) {
  2358. hid_err(hdev, "HW start failed\n");
  2359. goto err_wq;
  2360. }
  2361. ret = hid_hw_open(hdev);
  2362. if (ret) {
  2363. hid_err(hdev, "cannot start hardware I/O\n");
  2364. goto err_stop;
  2365. }
  2366. hid_device_io_start(hdev);
  2367. ret = joycon_init(hdev);
  2368. if (ret) {
  2369. hid_err(hdev, "Failed to initialize controller; ret=%d\n", ret);
  2370. goto err_close;
  2371. }
  2372. /* Initialize the leds */
  2373. ret = joycon_leds_create(ctlr);
  2374. if (ret) {
  2375. hid_err(hdev, "Failed to create leds; ret=%d\n", ret);
  2376. goto err_close;
  2377. }
  2378. /* Initialize the battery power supply */
  2379. ret = joycon_power_supply_create(ctlr);
  2380. if (ret) {
  2381. hid_err(hdev, "Failed to create power_supply; ret=%d\n", ret);
  2382. goto err_ida;
  2383. }
  2384. ret = joycon_input_create(ctlr);
  2385. if (ret) {
  2386. hid_err(hdev, "Failed to create input device; ret=%d\n", ret);
  2387. goto err_ida;
  2388. }
  2389. ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;
  2390. hid_dbg(hdev, "probe - success\n");
  2391. return 0;
  2392. err_ida:
  2393. ida_free(&nintendo_player_id_allocator, ctlr->player_id);
  2394. err_close:
  2395. hid_hw_close(hdev);
  2396. err_stop:
  2397. hid_hw_stop(hdev);
  2398. err_wq:
  2399. destroy_workqueue(ctlr->rumble_queue);
  2400. err:
  2401. hid_err(hdev, "probe - fail = %d\n", ret);
  2402. return ret;
  2403. }
  2404. static void nintendo_hid_remove(struct hid_device *hdev)
  2405. {
  2406. struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
  2407. unsigned long flags;
  2408. hid_dbg(hdev, "remove\n");
  2409. /* Prevent further attempts at sending subcommands. */
  2410. spin_lock_irqsave(&ctlr->lock, flags);
  2411. ctlr->ctlr_state = JOYCON_CTLR_STATE_REMOVED;
  2412. spin_unlock_irqrestore(&ctlr->lock, flags);
  2413. destroy_workqueue(ctlr->rumble_queue);
  2414. ida_free(&nintendo_player_id_allocator, ctlr->player_id);
  2415. hid_hw_close(hdev);
  2416. hid_hw_stop(hdev);
  2417. }
  2418. #ifdef CONFIG_PM
  2419. static int nintendo_hid_resume(struct hid_device *hdev)
  2420. {
  2421. struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
  2422. int ret;
  2423. hid_dbg(hdev, "resume\n");
  2424. if (!joycon_using_usb(ctlr)) {
  2425. hid_dbg(hdev, "no-op resume for bt ctlr\n");
  2426. ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;
  2427. return 0;
  2428. }
  2429. ret = joycon_init(hdev);
  2430. if (ret)
  2431. hid_err(hdev,
  2432. "Failed to restore controller after resume: %d\n",
  2433. ret);
  2434. else
  2435. ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;
  2436. return ret;
  2437. }
  2438. static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message)
  2439. {
  2440. struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
  2441. hid_dbg(hdev, "suspend: %d\n", message.event);
  2442. /*
  2443. * Avoid any blocking loops in suspend/resume transitions.
  2444. *
  2445. * joycon_enforce_subcmd_rate() can result in repeated retries if for
  2446. * whatever reason the controller stops providing input reports.
  2447. *
  2448. * This has been observed with bluetooth controllers which lose
  2449. * connectivity prior to suspend (but not long enough to result in
  2450. * complete disconnection).
  2451. */
  2452. ctlr->ctlr_state = JOYCON_CTLR_STATE_SUSPENDED;
  2453. return 0;
  2454. }
  2455. #endif
  2456. static const struct hid_device_id nintendo_hid_devices[] = {
  2457. { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
  2458. USB_DEVICE_ID_NINTENDO_PROCON) },
  2459. { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
  2460. USB_DEVICE_ID_NINTENDO_SNESCON) },
  2461. { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
  2462. USB_DEVICE_ID_NINTENDO_GENCON) },
  2463. { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
  2464. USB_DEVICE_ID_NINTENDO_N64CON) },
  2465. { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
  2466. USB_DEVICE_ID_NINTENDO_PROCON) },
  2467. { HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
  2468. USB_DEVICE_ID_NINTENDO_CHRGGRIP) },
  2469. { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
  2470. USB_DEVICE_ID_NINTENDO_JOYCONL) },
  2471. { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
  2472. USB_DEVICE_ID_NINTENDO_JOYCONR) },
  2473. { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
  2474. USB_DEVICE_ID_NINTENDO_SNESCON) },
  2475. { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
  2476. USB_DEVICE_ID_NINTENDO_GENCON) },
  2477. { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
  2478. USB_DEVICE_ID_NINTENDO_N64CON) },
  2479. { }
  2480. };
  2481. MODULE_DEVICE_TABLE(hid, nintendo_hid_devices);
  2482. static struct hid_driver nintendo_hid_driver = {
  2483. .name = "nintendo",
  2484. .id_table = nintendo_hid_devices,
  2485. .probe = nintendo_hid_probe,
  2486. .remove = nintendo_hid_remove,
  2487. .raw_event = nintendo_hid_event,
  2488. #ifdef CONFIG_PM
  2489. .resume = nintendo_hid_resume,
  2490. .suspend = nintendo_hid_suspend,
  2491. #endif
  2492. };
  2493. static int __init nintendo_init(void)
  2494. {
  2495. return hid_register_driver(&nintendo_hid_driver);
  2496. }
  2497. static void __exit nintendo_exit(void)
  2498. {
  2499. hid_unregister_driver(&nintendo_hid_driver);
  2500. ida_destroy(&nintendo_player_id_allocator);
  2501. }
  2502. module_init(nintendo_init);
  2503. module_exit(nintendo_exit);
  2504. MODULE_LICENSE("GPL");
  2505. MODULE_AUTHOR("Ryan McClelland <rymcclel@gmail.com>");
  2506. MODULE_AUTHOR("Emily Strickland <linux@emily.st>");
  2507. MODULE_AUTHOR("Daniel J. Ogorchock <djogorchock@gmail.com>");
  2508. MODULE_DESCRIPTION("Driver for Nintendo Switch Controllers");