hid-nintendo.c 73 KB

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