Два џојстика, еден скршен Bluetooth чип и закрпа за кернелот, со ompTwo controllers, one broken Bluetooth chip and a kernel patch, with omp

· 10 мин. читање10 min read

Ова е продолжение на „Од заборавен ТВ бокс до ретро конзола“. Таму напишав дека џојстиците од 2,4 GHz со USB донгл се посигурни од Bluetooth-от на боксот. Потоа како за инат купив два Bluetooth џојстика хахаха. 😃

This is a follow-up to “From a forgotten TV box to a retro console”. There I wrote that 2.4 GHz pads with a USB dongle are more reliable than the box's Bluetooth. Then, as if out of spite, I bought two Bluetooth pads, hahaha. 😃

Ова е приказната како ги натерав да работат, двата одеднаш, на истиот стар Nexbox A95X-B7N со EmuELEC 4.8. Траеше една ноќ и на крајот заврши со поправка на баг во Линукс кернелот (кернелот е срцето на Линукс, делот што зборува директно со хардверот). Јас и не сум некој си кернел програмер. Цело време работев со помош на omp, AI агент за програмирање што работи во терминал: тој читаше логови, пишуваше код и се поврзуваше на боксот, а јас притискав копчиња, читав имплементација, предлагав решенија и одлучував кога да не се откажеме.

This is the story of getting them both working at once on the same old Nexbox A95X-B7N running EmuELEC 4.8. It took one night and ended with a bug fix in the Linux kernel (the kernel is the core of Linux, the part that talks straight to the hardware). And I'm not exactly a kernel developer. I worked with omp the whole time, an AI coding agent that runs in the terminal: it read logs, wrote code and logged into the box, while I pressed buttons, read the implementation, suggested fixes and decided when not to give up.

Резултатот: џојстикот го вози менито на EmuELEC, од Super Nintendo до листата PlayStation игри. 35 секунди, без звук.The result: the pad driving EmuELEC's menu, from Super Nintendo to the PlayStation game list. 35 seconds, no sound.

Кратката верзија: ако само сакаш два џојстика што работат, купи добри. 😃 Најсигурни се 2,4 GHz џојстиците со USB донгл, како што пишува во првиот пост; за било кои други, пред да купиш, провери дали некој ги користи со EmuELEC. Евтините Switch клонови како моите се спаруваат, ама сами не се враќаат, а за два одеднаш требаше закрпа за кернелот. Ако веќе ги имаш, продолжи: ова е приказната како ги натерав да работат.

The short version: if you just want two pads that work, buy good ones. 😃 2.4 GHz pads with a USB dongle are the safest bet, like the first post says; for anything else, check that someone uses them with EmuELEC before you buy. Cheap Switch clones like mine pair, but don't come back on their own, and two at once took a kernel patch. If you already have them, read on: this is how I got them working.

ЏојстицитеThe pads

Купив два DOYO „Pro 3 cross-platform wireless“: евтини, со RGB светла и распоред како на Switch Pro Controller, оригиналниот џојстик за Nintendo Switch. Кога ќе се поврзат, се претставуваат токму така: „Pro Controller“, со ознаките на Nintendo (057E:2009, бројките по кои системот препознава кој уред е). Значи се клонови на џојстикот за Switch, и тоа ќе биде битно.

I bought two DOYO “Pro 3 cross-platform wireless” pads: cheap, with RGB lights and the layout of the Switch Pro Controller, Nintendo's own Switch pad. When they connect, they introduce themselves exactly like that: “Pro Controller”, with Nintendo's IDs (057E:2009, the numbers the system uses to tell which device it is). So they're Switch pad clones, and that will matter.

Прво пробав на компјутерот, за да видам дали воопшто работат. Не оди: USB-C кабелот само ги полни (компјутерот не гледа никаков уред), а компјутерот нема Bluetooth. Значи сè се тестираше директно на боксот. Во првиот пост го исклучив Bluetooth-от на боксот, па прво го вклучив пак.

I tried the PC first, to check they work at all. No luck: the USB-C cable only charges them (the PC sees no device), and the PC has no Bluetooth. So all testing happened right on the box. I'd turned the box's Bluetooth off in the first post, so step one was turning it back on.

Кој од двата го заборавив?Which one did I just forget?

Првиот џојстик се спари од менито на EmuELEC без проблем. Вториот не сакаше. Отидов да го „заборавам“ и да пробам пак, ама во листата и двата се викаат „Pro Controller“. Ја погодив погрешната ставка: го избришав првиот.

The first pad paired from EmuELEC's menu just fine. The second wouldn't. I went to “forget” it and try again, but in the list both are called “Pro Controller”. I picked the wrong entry: I deleted the first one.

Од тука настана хаос. Повторното спарување враќаше org.bluez.Error.AlreadyExists и Authentication Failed: боксот сè уште чуваше стар клуч за џојстикот во кернелот, иако самиот уред беше избришан. Помогна рестарт: по рестартот Bluetooth меморијата беше чиста, и ги спаривме еден по еден, од терминал, каде што се гледа секој чекор. Терминалот го отвораш од менито (Setup system → Launch terminal), со приклучена тастатура, а Bluetooth програмата во него се вика bluetoothctl.

Chaos followed. Re-pairing returned org.bluez.Error.AlreadyExists and Authentication Failed: the box still held an old key for the pad in the kernel, even though the device itself was deleted. A reboot fixed it: after it, the Bluetooth memory was clean, and we paired them one by one from a terminal, where you see every step. You open the terminal from the menu (Setup system → Launch terminal) with a keyboard plugged in, and the Bluetooth program in it is called bluetoothctl.

Најкорисниот совет таа ноќ беше и најпростиот. Кога првиот џојстик проработи, omp напиша: „Стави му налепница „1“.“ Двата уреда се викаат исто, па единствената сигурна разлика е MAC адресата, нешто како сериски број на Bluetooth уредот (на пример, 98:B6:88:8C:10:60); налепницата е за луѓето.

The most useful advice that night was also the simplest. Once the first pad worked, omp wrote: “Put a “1” sticker on it.” Both devices have the same name, so the only reliable difference is the MAC address, a kind of serial number for a Bluetooth device (e.g. 98:B6:88:8C:10:60); the sticker is for humans.

omp in the terminal: the box rebooted with a clean Bluetooth memory, the first controller is paired, saved and connected, the box sees it as a Pro Controller, then: Put a 1 sticker on it, and steps for pairing the second controller.
omp по рестартот: првиот џојстик е спарен и зачуван. Адресата на боксот е заматена.omp after the reboot: the first pad is paired and saved. The box's address is blurred.

Спарен, ама не поврзанPaired, but not connected

Следен проблем: џојстикот се спарува, боксот го зачувува, а сепак не работи. Во менито пишува „Paired“, не „Connected“. Ова е најчестиот проблем со вакви клонови, па вреди да се објасни.

Next problem: the pad pairs, the box saves it, and it still doesn't work. The menu says “Paired”, not “Connected”. This is the most common problem with clones like these, so it's worth explaining.

Спарување значи двата уреда да си разменат клуч. Поврзување значи да се отворат канали низ кои патуваат копчињата. Кај џојстиците тоа се два канала (control и interrupt). Обичните џојстици сами ги отвораат. Овие чекаат боксот да ги отвори, како што прави Switch, а Bluetooth сервисот на Линукс (bluetoothd) тоа не го прави сам. Џојстикот чека околу 20 секунди и ја прекинува врската.

Pairing means the two devices exchange a key. Connecting means opening the channels the button presses travel through. For gamepads that's two channels (control and interrupt). Ordinary pads open them themselves. These wait for the box to open them, as a Switch does, and Linux's Bluetooth service (bluetoothd) doesn't do that on its own. The pad waits about 20 seconds and drops the link.

Како го видовме? Со btmon, алатка што го снима целиот Bluetooth сообраќај на боксот. Во снимката: џојстикот се поврзува, се отвора само каналот за опис на сервисите, па тишина, па „Connection Timeout“. Никој не го отвори каналот за копчиња. Решението е едноставно: веднаш по спарувањето, кажи му на боксот да се поврзе:

How did we see that? With btmon, a tool that records all of the box's Bluetooth traffic. In the recording: the pad connects, only the service-description channel opens, then silence, then “Connection Timeout”. Nobody opened the button channels. The fix is simple: right after pairing, tell the box to connect:

Во bluetoothctl: спари, верувај и поврзи веднаш (стави ја адресата на твојот џојстик)In bluetoothctl: pair, trust and connect right away (use your pad's address)
scan on
pair 98:B6:88:8C:10:60
trust 98:B6:88:8C:10:60
connect 98:B6:88:8C:10:60

pair ги разменува клучевите, trust му дозволува на џојстикот следниот пат да се поврзе без прашање, а connect ги отвора каналите. Адресата ќе ја видиш по scan on, додека џојстикот е во режим за спарување.

pair exchanges the keys, trust lets the pad connect next time without asking, and connect opens the channels. You'll see the address after scan on, while the pad is in pairing mode.

Моја работа беше физичкиот дел. omp пишуваше упатства на мониторот, јас ги правев на телевизорот: исклучи го џојстикот, стави го во режим за спарување (светлата брзо трепкаат), почекај. Набрзо јас со помош на omp напишав и мала Python скрипта за спарување што самата одговара кога џојстикот бара PIN.

My job was the physical part. omp wrote instructions on the monitor and I did them on the TV: turn the pad off, put it in pairing mode (lights blinking fast), wait. Soon, with omp's help, I also wrote a small Python pairing script that answers the pad's PIN request by itself.

omp: I've started a new pairing attempt. This time the box can answer the controller's PIN request. Then four steps: turn the controller off, keep the other one off, put it in pairing mode, wait about a minute.
Типична порака од таа ноќ: omp чека, јас притискам копчиња.A typical message from that night: omp waits, I press buttons.

Да зборуваме како SwitchSpeaking Switch

И со connect џојстиците одржуваа врска само додека трае спарувањето. Еднаш исклучени, не се враќаа. Тука omp прв пат крена раце: напиша дека EmuELEC (Linux 4.9, без драјвер за Nintendo џојстици) не може да ги задржи и дека со подесувања не се поправа.

Even with connect, the pads only stayed connected during the pairing session. Once off, they never came back. This is where omp threw in the towel for the first time: it wrote that EmuELEC (Linux 4.9, with no Nintendo pad driver) can't keep them and that no setting fixes it.

Прашав: „А што ако го напишеме драјверот?“ (драјвер е програмата што му кажува на системот како да зборува со некој уред). omp понуди два пата. А: да се пренесе Линукс драјверот за Nintendo (hid-nintendo, од Linux 5.16 нагоре) на стариот кернел 4.9. Часови работа, а клоновите често паѓаат на неговите проверки. Б: мал помошник на боксот што го прави она што го прави Switch по поврзувањето. Го избрав Б.

I asked: “How about we write the driver?” (a driver is the program that tells the system how to talk to a device). omp offered two routes. A: port Linux's Nintendo driver (hid-nintendo, Linux 5.16 and newer) to the old 4.9 kernel. Hours of work, and clones often fail its checks. B: a small helper on the box that does what a Switch does after connecting. I picked B.

Switch по поврзувањето му праќа на џојстикот низа кратки команди (subcommands). Протоколот е јавно документиран благодарение на dekuNukem, па помошникот ги праќа истите, директно на уредот (hidraw). Клонот ги прифати сите:

After connecting, a Switch sends the pad a series of short commands (subcommands). The protocol is publicly documented thanks to dekuNukem, so the helper sends the same ones, straight to the device (hidraw). The clone accepted all of them:

Командите што ги праќа помошникотThe commands the helper sends
КомандаCommandШто правиWhat it doesОдговорReply
0x02Информации за уредотDevice infoфирмвер 3.72, тип 3 (Pro Controller)firmware 3.72, type 3 (Pro Controller)
0x08 00Излези од „shipment mode“Leave shipment modeOK
0x03 3FЕдноставен режим: стандардни копчиња, мапирањето на EmuELEC остануваSimple mode: standard buttons, EmuELEC's mapping stays validOK
0x48 01Вклучи вибрацииVibration onOK
0x30Светло за играч 1 или 2Player 1 or 2 lightOK
omp: It works. The controller paired, the gamepad channel opened (Bluetooth channels 17 and 19), and it accepted every console command, followed by a table of commands, all OK, and: Its player-1 light should be on now. Now the real test, reconnecting.
Од извезениот разговор со omp: ракувањето успеа. Светлото за играч 1 засвети.From the exported omp chat: the handshake worked. The player-1 light came on.

Зошто Home не го враќаWhy Home never reconnects

„Сега вистинскиот тест, повторно поврзување.“ Не помина. Исклучен џојстик, притиснат Home: снимката на btmon е празна. Џојстикот воопшто не се ни обидува да го најде боксот. Пробавме сè што документацијата нуди и ништо не помогна.

“Now the real test, reconnecting.” It failed. Pad off, Home pressed: the btmon recording is empty. The pad doesn't even try to reach the box. We tried everything the documentation offers, and nothing helped.

За љубопитните: што сè пробавмеFor the curious: everything we tried
  • Ја прочитавме меморијата за спарување на џојстикот (флеш, адреса 0x2000, команда 0x10). Таму вистинскиот Pro Controller ја запишува конзолата. Кај клонот е празна.
  • Рачно спарување (0x01): генерички одговор, а клучот е сите нули. Не е имплементирано.
  • „Рестартирај се и поврзи се“ (0x06 01): вели OK, не прави ништо.
  • Го преименувавме боксот во „Nintendo Switch“. Ништо.
  • Read the pad's pairing memory (flash, address 0x2000, command 0x10). That's where a real Pro Controller stores its console. On the clone it's empty.
  • Manual pairing (0x01): a generic reply, and the key is all zeros. Not implemented.
  • “Reboot and reconnect” (0x06 01): says OK, does nothing.
  • Renamed the box to “Nintendo Switch”. Nothing.

Заклучок: фирмверот на клонот се враќа само на вистински Switch. Не може да се поправи од страна на боксот, па го прифатив: џојстикот го палиш со комбинацијата за спарување, Home + Y. Ги држиш, светлата брзо трепкаат, и по 5–10 секунди светне светлото за играч. Кај Switch клоновите, подобро е да се навикнеш отколку да се бориш.

Conclusion: the clone's firmware only reconnects to a real Switch. The box can't fix that, so I accepted it: you turn the pad on with the pairing combination, Home + Y. Hold them, the lights blink fast, and 5–10 seconds later the player light comes on. With Switch clones, getting used to that beats fighting it.

A hand holding Home and Y on a black controller on a wooden cabinet under the TV, with the second controller next to the TV stand.
„Вклучување“ на џојстикот: Home + Y, секој пат.“Turning on” a pad: Home + Y, every time.

ПомошникотThe helper

Сето ова го спакувавме во една Python скрипта, switchpad.py: omp ја пишуваше, јас ја читав и предлагав поправки. Се пушта при секое палење на боксот (од /storage/.config/custom_start.sh, фајл во кој пишуваш што да се пушти при палење, во делот „after“). Таа:

We packed all of this into one Python script, switchpad.py: omp wrote it, I read it and suggested fixes. It starts every time the box boots (from /storage/.config/custom_start.sh, a file where you list what to run at boot, in its “after” section). It:

Прашав дали Python е доволно брз за ваков слаб бокс. Одговорот: помошникот троши околу 9 MB RAM и занемарливо процесор, а не стои меѓу џојстикот и играта. Копчињата одат од кернелот директно до емулаторот, па нема никакво доцнење; помошникот само ги подесува работите и гледа.

I asked whether Python is fast enough for a weak box like this. The answer: the helper uses about 9 MB of RAM and a negligible bit of CPU, and it doesn't sit between the pad and the game. Button presses go from the kernel straight to the emulator, so there's no added lag; the helper only sets things up and watches.

Еден џојстик сега работеше. Вториот, не.

One pad now worked. The second one didn't.

Вториот џојстик и чипот што лажеThe second pad and a chip that lies

Со вклучен џојстик 1, џојстикот 2 се спаруваше, а потоа ништо. Секој сам работеше; заедно, никогаш. omp го вклучи debug логот на bluetoothd, а таму: search_cb() … error updating services: Connection timed out (110). Боксот пробал да го праша вториот џојстик кои сервиси ги има, и не добил одговор.

With pad 1 on, pad 2 would pair, and then nothing. Each worked alone; together, never. omp turned on bluetoothd's debug log, and there it was: search_cb() … error updating services: Connection timed out (110). The box tried to ask the second pad which services it has, and got no answer.

Списокот на врски кажа повеќе. Кернелот ја означува секоја врска со број (handle) и состојба. Џојстикот 1 е на врска 4, состојба 1 („поврзан“). Џојстикот 2 е на врска 6, состојба 7 („сè уште се подесува“). Во таа состојба кернелот не пушта никакви податоци, затоа и пребарувањето истекува.

The connection list said more. The kernel labels each connection with a number (a handle) and a state. Pad 1 is on connection 4, state 1 (“connected”). Pad 2 is on connection 6, state 7 (“still configuring”). In that state the kernel lets no data through, which is why the service search times out.

omp shows the connection list: controller 2 on handle 6 state 7, controller 1 on handle 4 state 1, explains that state 7 means still configuring, and runs btmon on the recording to inspect the encryption key size replies.
Моментот кога се најде проблемот: „state 7“ кај вториот џојстик.The moment the problem showed up: “state 7” on the second pad.

Еден од последните чекори при подесување на врската е кернелот да го праша Bluetooth чипот колку е долг клучот за шифрирање. Тоа е безбедносна проверка: кернелот не сака врски со прекраток клуч. Во снимката на btmon:

One of the last steps in setting up a connection is the kernel asking the Bluetooth chip how long the encryption key is. It's a security check: the kernel refuses connections with a key that's too short. In the btmon recording:

btmon: прашање за врска 6, одговор за врска 4 (скратено)btmon: a question about connection 6, an answer about connection 4 (shortened)
< HCI Command: Read Encryption Key Size (0x05|0x0008) plen 2
        Handle: 6 Address: 98:B6:EB:D1:16:BD
> HCI Event: Command Complete (0x0e) plen 7
      Read Encryption Key Size (0x05|0x0008) ncmd 2
        Status: Success (0x00)
        Handle: 4
        Key size: 16

Кернелот прашува за врската 6 (џојстик 2). Чипот одговара за врската 4 (џојстик 1). Кернелот го зема одговорот, ја наоѓа врската 4, која е веќе готова, и не прави ништо. Врската 6 засекогаш чека одговор што никогаш нема да дојде.

The kernel asks about connection 6 (pad 2). The chip answers about connection 4 (pad 1). The kernel takes the answer, finds connection 4, which is already done, and does nothing. Connection 6 waits forever for an answer that never comes.

Тоа е баг во фирмверот на Bluetooth чипот во боксот, Realtek вграден во плочата (поврзан преку UART, не преку USB). Со еден уред никогаш не се гледа, бидејќи тогаш има само една врска за која може да се одговори. Тука omp крена раце по втор пат: напиша дека со вградениот Bluetooth не може два џојстика, ги ограничи помошникот на еден, и предложи USB Bluetooth стик.

That's a bug in the firmware of the box's Bluetooth chip, a Realtek built into the board (wired over UART, not USB). With one device you never see it, because then there's only one connection to answer about. This is where omp threw in the towel a second time: it wrote that the built-in Bluetooth can't do two pads, limited the helper to one, and suggested a USB Bluetooth stick.

Закрпа за кернелотPatching the kernel

Напишав: „може ли и тој баг да го поправиме“. Одговорот: „Веројатно да, во кернелот на боксот, а не во чипот.“ Новите Линукс кернели имаат знаменце за вакви чипови: кај чип означен како скршен, го прескокнуваат прашањето и претпоставуваат стандарден клуч од 16 бајти. Кернелот 4.9 на боксот тоа го нема. Но Bluetooth делот од кернелот на EmuELEC е модул (bluetooth.ko), посебен фајл што се вчитува при палење, како додаток, па треба да се смени само тој, не целиот систем.

I typed: “can we fix that bug also”. The answer: “Probably yes, in the box's kernel rather than in the chip.” Newer Linux kernels have a flag for chips like this: for a chip flagged as broken, they skip the question and assume the standard 16-byte key. The box's 4.9 kernel doesn't have that. But EmuELEC's Bluetooth core is a module (bluetooth.ko), a separate file loaded at boot, like a plug-in, so only that file has to change, not the whole system.

Me at 04:15: can qwe dfix that bug also. omp: Probably yes, in the box's kernel rather than in the chip, explaining the HCI_QUIRK_BROKEN_READ_ENC_KEY_SIZE flag, that bluetooth.ko is a loadable module, and that it is checking the exact kernel source, configuration and MODVERSIONS.
Во 4:15 наутро, со правописот што оди со тоа.At 4:15 in the morning, with the spelling to match.

Закрпата прави едно: кернелот веќе знае за која врска прашал, па нека веруваме на тоа. Ако одговорот на чипот спомнува друга врска, кернелот го запишува тоа во логот и претпоставува стандардни 16 бајти, исто како што старата верзија прави кога чипот враќа грешка, и исто како новите кернели за чипови означени како скршени.

The patch does one thing: the kernel already knows which connection it asked about, so trust that. If the chip's answer names a different connection, the kernel logs it and assumes the standard 16 bytes, the same as the old code does when the chip returns an error, and the same as newer kernels do for chips flagged as broken.

За љубопитните: како го изградивме и ставивме модулот (Линукс, Docker)For the curious: how we built and installed the module (Linux, Docker)

Тешкиот дел не е самата закрпа, туку модулот да одговара точно на кернелот што веќе работи на боксот. Погрешен модул значи Bluetooth не се вчитува, или полошо, кернелот паѓа. Затоа сакав сè да се провери пред боксот да види било што. Чекорите:

The hard part isn't the patch itself, it's making the module match the kernel already running on the box exactly. A wrong module means Bluetooth won't load, or worse, the kernel crashes. So I wanted everything checked before the box saw any of it. The steps:

  1. Истиот изворен код. EmuELEC 4.8 го гради кернелот од CoreELEC linux-amlogic, на точно одреден commit (ab03043); хашот на симнатата архива одговараше на тој во EmuELEC. Плус 32-те закрпи на EmuELEC и неговата конфигурација за кернелот.
  2. Градење. Во Docker контејнер (Debian bookworm, gcc 12 за ARM64), make vmlinux modules. Помалку од три минути.
  3. Закрпата. Петнаесетина линии во net/bluetooth/hci_event.c (подолу).
  4. Проверка пред да се допре боксот. Ознаката на модулот (vermagic) е иста како на оригиналот, а иста е и проверката (CRC) на сите 197 функции од кернелот што модулот ги користи и на сите 43 што ги користат другите Bluetooth модули. Значи се разликува само поправката.
  5. Инсталација без менување на системот. Преку kernel overlays на EmuELEC (подолу).
  1. The same source. EmuELEC 4.8 builds its kernel from CoreELEC's linux-amlogic at one exact commit (ab03043); the downloaded archive's hash matched the one in EmuELEC. Plus EmuELEC's 32 patches and its kernel config.
  2. Build. In a Docker container (Debian bookworm, gcc 12 for ARM64), make vmlinux modules. Under three minutes.
  3. The patch. About fifteen lines in net/bluetooth/hci_event.c (below).
  4. Check before touching the box. The module's label (vermagic) matches the original, and so does the checksum (CRC) of all 197 kernel functions the module uses and all 43 that the other Bluetooth modules use. So the only difference is the fix.
  5. Install without modifying the system. Through EmuELEC's kernel overlays (below).
bluetooth-read-enc-key-size-handle.patchbluetooth-read-enc-key-size-handle.patch
--- a/net/bluetooth/hci_event.c
+++ b/net/bluetooth/hci_event.c
@@ -2547,7 +2547,9 @@
 				       u16 opcode, struct sk_buff *skb)
 {
 	const struct hci_rp_read_enc_key_size *rp;
+	const struct hci_cp_read_enc_key_size *cp;
 	struct hci_conn *conn;
+	bool mismatch = false;
 	u16 handle;
 
 	BT_DBG("%s status 0x%02x", hdev->name, status);
@@ -2561,6 +2563,20 @@
 	rp = (void *)skb->data;
 	handle = le16_to_cpu(rp->handle);
 
+	/* Some controllers (e.g. the Realtek UART chips on Amlogic TV boxes)
+	 * answer with the handle of a different connection once more than one
+	 * ACL link exists. The link we asked about would then never leave
+	 * BT_CONFIG, so trust the handle from our own command and fall back to
+	 * the default key size, as when the command fails.
+	 */
+	cp = hci_sent_cmd_data(hdev, HCI_OP_READ_ENC_KEY_SIZE);
+	if (cp && le16_to_cpu(cp->handle) != handle) {
+		BT_ERR("%s key size reply for handle %u, requested %u",
+		       hdev->name, handle, le16_to_cpu(cp->handle));
+		handle = le16_to_cpu(cp->handle);
+		mismatch = true;
+	}
+
 	hci_dev_lock(hdev);
 
 	conn = hci_conn_hash_lookup_handle(hdev, handle);
@@ -2571,7 +2587,7 @@
 	 * (which is the same we do also when this HCI command isn't
 	 * supported.
 	 */
-	if (rp->status) {
+	if (rp->status || mismatch) {
 		BT_ERR("%s failed to read key size for handle %u", hdev->name,
 		       handle);
 		conn->enc_key_size = HCI_LINK_KEY_SIZE;

Системот на EmuELEC е слика само за читање, па модулот не се копира врз оригиналот. Наместо тоа, EmuELEC има механизам наречен kernel overlays: .conf фајл во /storage/.cache/kernel-overlays/ покажува на папка со модули, а при палење модулите од таа папка се вчитуваат наместо оригиналните.

EmuELEC's system is a read-only image, so the module isn't copied over the original. Instead, EmuELEC has a mechanism called kernel overlays: a .conf file in /storage/.cache/kernel-overlays/ points to a folder of modules, and at boot the modules from that folder load instead of the originals.

Проверка на модулот и инсталација преку kernel overlayChecking the module and installing it as a kernel overlay
$ modinfo -F vermagic bluetooth.ko
4.9.269 SMP preempt mod_unload modversions aarch64

$ cat /storage/.cache/kernel-overlays/50-bt-keysize-fix.conf
/storage/switchpad/kernel-overlay

# the patched module
/storage/switchpad/kernel-overlay/lib/modules/4.9.269/kernel/net/bluetooth/bluetooth.ko

Самиот систем на боксот останува недопрен: за враќање назад, бришеш еден фајл и рестартираш. Ако некое ажурирање на EmuELEC донесе друга верзија на кернелот, модулот едноставно се игнорира (папката е за 4.9.269). Ако верзијата остане иста, а кернелот се смени, модулот повеќе нема да одговара, па пред ажурирање избриши го .conf фајлот, за секој случај. Ја вратив границата на помошникот на два џојстика, ја извадив картичката, ја ставив во боксот, ги вклучив двата.

The box's system itself stays untouched: to undo it, delete one file and reboot. If an EmuELEC update brings a different kernel version, the module is simply ignored (the folder is for 4.9.269). If the version stays the same but the kernel changes, the module won't match anymore, so delete the .conf file before updating, just in case. I set the helper's limit back to two pads, pulled the card, put it in the box and turned both pads on.

Me at 04:27: it worked. omp: Both controllers now work at the same time on the box's built-in Bluetooth, then how to play: turn each controller on with its pairing combination, wait for the player light, quit with Shutdown, and that Home alone won't reconnect these clones.
04:27. Двата џојстика, истовремено, на вградениот Bluetooth.04:27. Both pads, at the same time, on the built-in Bluetooth.
A TV showing EmuELEC's Neon Overdrive theme with PlayStation selected and 53 games, with two black controllers on the cabinet in front of it.
Играч 1 и играч 2.Player 1 and player 2.

Заклучи го пакLock it again

Во првиот пост го заклучив боксот: firewall вклучен (ѕидот што не пушта ништо однадвор), SSH исклучен (далечински пристап до терминалот на боксот). За omp да може да работи на боксот, двете ги отворав привремено (SSH во менито, systemctl stop iptables во терминалот на боксот). На крајот omp ги врати: RULES=public и ee_ssh.enabled=0, па проба да се поврзе и доби „Connection refused“. Тоа е точно она што сакаш да го видиш.

In the first post I locked the box down: firewall on (the wall that lets nothing in from outside), SSH off (remote access to the box's terminal). For omp to work on the box I opened both temporarily (SSH from the menu, systemctl stop iptables in the box's terminal). At the end omp put them back: RULES=public and ee_ssh.enabled=0, then tried to connect and got “Connection refused”. That's exactly what you want to see.

Една мала паника успат: терминалот на боксот замрзна и бев сигурен дека го „брикнав“ (го претворив во цигла, т.е. го расипав засекогаш). Само рестарт.

One small panic along the way: the box's terminal froze and I was sure I'd bricked it (turned it into a brick, broken for good). Just a reboot.

The monitor with omp: ssh: connect to host 192.168.0.43 port 22: Connection refused, and omp explaining that the firewall is off but the SSH service isn't running.
Порано таа ноќ: firewall-от веќе исклучен, SSH уште не пуштен, па „Connection refused“. Досадно додека бараш баг, токму тоа што сакаш кога боксот е пак заклучен.Earlier that night: firewall already off, SSH not started yet, so “Connection refused”. Annoying while debugging, exactly what you want once the box is locked again.

Како изгледа работата со ompWhat working with omp looks like

omp работеше на компјутерот и преку SSH на боксот: читаше логови, снимаше и читаше Bluetooth пакети, пишуваше скрипти, го најде и го изгради кернелот, ги провери модулите. Јас бев рацете: ги палев и гасев џојстиците, куцав на тастатурата на боксот кога SSH беше исклучен, ги вадев и ставав картичката. Ама не само рацете: ги читав неговите објаснувања и кодот, прашував кога нешто не ми седеше, предлагав што да пробаме и одлучував што оди на боксот, а што не.

omp ran on the PC and reached the box over SSH: it read logs, recorded and read Bluetooth packets, wrote scripts, found and built the kernel, and checked the modules. I was the hands: turning pads on and off, typing on the box's keyboard when SSH was off, pulling and inserting the card. But not just the hands: I read its explanations and its code, asked when something didn't add up, suggested what to try next and decided what went on the box and what didn't.

Најважното: omp двапати ми кажа дека не може. И двапати решението беше едно прашање од мене: „а ако го напишеме драјверот?“ и „може ли и тој баг да го поправиме?“. Агентот е одличен во копање и поправање, ама насоката и одлуката кога да не се откажеме беа мои.

The key part: omp told me twice that it couldn't be done. Both times the way forward was one question from me: “how about we write the driver?” and “can we fix that bug also?”. The agent is great at digging and fixing, but the direction, and the call on when not to give up, were mine.

Сликите од разговорот се од извоз на сесијата (omp --export прави HTML од целиот разговор).

The chat screenshots come from an export of the session (omp --export turns the whole conversation into HTML).

Што научивWhat I learned

Што следуваWhat's next

Направено со omp (oh-my-pi). Протоколот на Switch џојстиците: dekuNukem/Nintendo_Switch_Reverse_Engineering. Кернел: CoreELEC linux-amlogic и закрпите на EmuELEC. Bluetooth алатки: BlueZ (bluetoothctl, btmon).

Built with omp (oh-my-pi). Switch pad protocol: dekuNukem/Nintendo_Switch_Reverse_Engineering. Kernel: CoreELEC linux-amlogic and the EmuELEC patches. Bluetooth tools: BlueZ (bluetoothctl, btmon).