Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

Camera: cam=5 streams the wide camera to programs (/dev/redwood-camera)

vcvkkd104949ef8b7
diff --git a/README.md b/README.md
index 818722d..462bc4c 100644
--- a/README.md
+++ b/README.md
@@ -287,7 +287,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #
| `sound=N` | с `adsp=1`, шаг 3 звука, путь к динамикам, как его строит Android (числа — из живого дерева устройств телефона, его путей микшера и его ядра): `sound=1` — ножки TDM (GPIO 97–100) отданы интерфейсу, звуковой процессор включает его тактовую частоту (3,072 МГц), группу и порт 0x9000 (PRI_TDM_RX_0) и запускает его; по ножкам видно, что тактовый сигнал и синхронизация кадров идут. `sound=2` — ещё и поток: наша память видна процессору через SMMU (поток 0x1801), путь ADM к порту, поток ASM, и в него 3 с пишется тон 1 кГц −20 дБ полной шкалы; процессор забирает его с частотой 48 кГц. Усилители выключены. `sound=3` — ещё и усилители: настраиваются из профиля «Music» конфигурации Android (`/vendor/etc/aw882xx_acf.bin` телефона в `fw-audio/`, в git не попадает, `userland/build.sh` кладёт её в `/fw` образа системы), каждая запись читается обратно, при любом расхождении или сбое оба сразу выключаются; громкость плавно поднимается до `sound_below` восьмых долей дБ ниже уровня Android (по умолчанию 240, то есть на 30 дБ тише; выше уровня Android — никогда), тон звучит 3 с, потом всё затихает, выключается и возвращается как было. `sound=4` — то, что играет iOS (`/dev/redwood-audio`), до конца сеанса: порт и поток работают всё время (без звука в них идёт тишина), усилители настраиваются один раз и выключены, а когда в записи iOS появляется не тишина, включаются и быстро (как у драйвера Android) выводятся на `sound_below`; после трёх секунд тишины снова выключаются. Звук доходит до усилителей через 160 мс после записи, усилители готовы через 65 мс. У динамика в модуле HAL есть регулятор громкости, его значение уходит в ядро (`ioctl` `REDWOOD_AUDIO_SET_VOLUME`) и задаёт уровень усилителей ниже потолка (0 — усилители не включаются), но iOS ставит его только раз, на максимум, а громкость кнопок и Пункта управления применяет к самим отсчётам (программная громкость для динамика iPhone X в таблицах VirtualAudio); при громкости 0 iOS пишет тишину, и усилители тоже не включаются. Проверка — `RC_JOBS=rc.jobs.volume`. По пути к усилителям — сторож (см. выше): `sound_gain=N` (восьмые доли дБ, 0–96), `sound_guard_as=N` (для проверки: сторож считает усилители на N ниже уровня Android и сдерживает, как сдерживал бы там). `sound_secs=S` (не больше 3 с тоном), `sound_pause=MS`. Подробности в начале `bsd/dev/redwood_sound.c` и `bsd/dev/redwood_speaker.c` |
| `haptic=N` | моторчик вибрации: Awinic AW86927 на I2C (шина QUP SE9, GPIO 36/37, адрес 0x5a; сброс — GPIO 35), линейный мотор с резонансом 175,5 Гц; всё — из живого дерева устройств Android, его журнала и регистров (`bsd/dev/redwood_haptic.c`). `haptic=1` — только читать: из загрузчика Android сброс держит чип выключенным, он не отвечает. `haptic=2` — сброс отпущен, как это делает драйвер Android, регистры прочитаны и сравнены с Android. `haptic=3` — ещё и настройка Android (каждая запись читается обратно; аналоговые регистры — за разблокировкой 0x5b) и волновые формы Android (`/vendor/firmware/aw8697_haptic.bin` телефона в `fw-haptic/`, в git не попадает; `userland/build.sh` кладёт его в `fw/` малого образа) в ОЗУ чипа, с проверкой чтением. `haptic=4` — ещё и одна короткая форма (`haptic_effect=1…10`) один раз, с усилением Android. `haptic=5` — моторчик для iOS до конца сеанса: всё, что iOS играет на своём устройстве «Actuator» (системные отклики и вибрация звонка, CoreHaptics приложений, отклики UIKit — например, меню иконки по долгому нажатию), звуковой модуль HAL отдаёт в `/dev/redwood-haptic`, и ядро играет по нему формы Android: каждую волну iOS — коротким толчком (форма 1), а длинную — повтором формы 11, пока iOS играет, но не дольше 1 с, после чего мотор столько же отдыхает; усиление — по громкости волны iOS: от трети полной шкалы и выше — усиление Android (0x80), ниже — до пяти восьмых его у самых тихих, и никогда не выше Android (волны iOS для Taptic Engine почти всегда гораздо тише полной шкалы, и в прямой пропорции большинство откликов выходило на десятой доле усиления Android — их было не почувствовать). Проверка обычных касаний: `RC_JOBS=rc.jobs.haptic2` (долгое нажатие на иконку, переключатель в Настройках). Без `haptic=5` iOS играет на «Actuator» как обычно, но в мотор ничего не идёт. Проверка: `RC_JOBS=rc.jobs.haptic`. Любая неисправность, о которой говорит чип, несовпадение при чтении или неотвеченный байт — чип снова в сброс до конца сеанса; не дольше 1 с на эффект; в конце сеанса и при панике — сброс |
| `torch=N` | фонарик: светодиодный модуль вспышки PM8350C (SPMI, ведомый 2, регистры 0xee00; задний светодиод — канал 0), значения Android: его фонарик горит на 125 мА через канал 0 (прочитано у включённого фонарика Android), шаг тока 12,5 мА, порядок записей — драйвера Xiaomi `leds-qti-flash.c` (`bsd/dev/redwood_torch.c`). `torch=1` — только читать: канал арбитра, тип модуля, регистры, температурная тревога PMIC. `torch=2` — ещё и зажечь один раз на 125 мА на `torch_secs` (по умолчанию 2 с). `torch=3` — фонарик для iOS: `/dev/redwood-torch` принимает уровень 0…1000 (тысячные тока Android, не выше 125 мА); загрузчик с `torch=N` добавляет в дерево `/product/camera` со свойством `flash` айфона (кнопка фонарика в Пункте управления), а `libredwood-media.dylib` отдаёт FigFlashlight в mediaserverd своё «устройство» вместо отсутствующей камеры (`userland/src/inject_media.c`). Пределы: записи — только в шесть регистров этого модуля, каждая читается обратно, канал арбитра перепроверяется; не дольше `torch_max_s` подряд (по умолчанию 30 с, не больше 120), потом темно, пока iOS не попросит снова; 10 раз в секунду — флаги неисправности и перегрева модуля, температурная тревога PMIC и температура батареи (не выше 45 °C; из battmgr при `adsp=1` или из `battery=1`) — что-то не так, и фонарик гаснет до конца сеанса; в конце сеанса и при панике — погашен. Проверка: `RC_JOBS=rc.jobs.torch` (`torch_test` — как программа, через AVFlashlight; потом кнопка в Пункте управления) |
-| `cam=N` | камеры: макрокамера — OmniVision OV02B10 (2 Мп, камера 2 Android, «redwood_aac_ov02b10_macro»); всё — из живого дерева устройств (cam-sensor2), файла модуля камеры Android (`/vendor/lib64/camera/com.qti.sensormodule.redwood_aac_ov02b10_macro.bin`: адрес, где и как читается ID чипа, порядок включения) и драйверов ядра Android (`bsd/dev/redwood_camera.c`). Датчик — на CCI 1, ведущий 0 (GPIO 73/74, здесь I2C вручную, как у других драйверов), адрес 0x3c; сброс — GPIO 77; MCLK — mclk2 camcc на 19,2 МГц на GPIO 66 (у Android эти 19,2 МГц — от PLL2 camcc, здесь — от самого кварца, без PLL); питание — LDO6 (1,8 В, DOVDD) и LDO7 (2,8 В, AVDD) PM8008i, который на I2C последовательного движка 1 (GPIO 4/5, адреса 0x08 и 0x09) и выходит из сброса по GPIO 3 PM8350C, как его выводит Android. `cam=1` — только смотреть: тактовые частоты и домен питания камеры, ножки, сброс PM8008i и, если он не в сбросе, сам PM8008i. `cam=2` — ещё и включить датчик в порядке файла модуля (у макрокамеры: сброс низкий, 1 мс; DOVDD; AVDD, 2 мс; верхний домен питания камеры и MCLK, 4 мс; сброс высокий, 9 мс), прочитать ID чипа так, как читает Android (16-битный регистр по 16-битному адресу 0x0203; ждёт 0x002b), и выключить в обратном порядке. Пределы: напряжения — только Android (1,8 и 2,8 В у макрокамеры, 1,0 и 1,8 В у широкой), записи — только в перечисленные регистры (у каждого устройства — список, проверяется при каждой записи), каждая читается обратно; неотвеченный байт, регулятор не готов вовремя или сообщает о перегрузке по току, запись не читается обратно — всё выключается и больше ничего не пишется; в конце сеанса и при панике включённое выключается, найденное включённым остаётся включённым. `cam_after=S` — через сколько секунд после старта (по умолчанию 20). `cam=3` — путь кадра без датчика: генератор тестовой картинки CSID-lite 0 (RAW10 1600×1200, цветные полосы) → его путь RDI 0 → IFE-lite 0, чей мастер записи 0 пишет кадр в память через SMMU (поток 0x800, маска 0x4e0, в свободный контекст с нашими таблицами); для этого — голоса RPMh за CX на SVS и MX на SVS_L1 (через вторую TCS DRV 2, в конце отдаются), PLL0 camcc (1,2 ГГц), RCG и ветви камеры на частотах уровня «svs» из дерева устройств (cphy_rx, CSID, IFE-lite — 400 МГц, таймер PHY — 300, camnoc — 150, slow_ahb — 80), всё — по драйверам Android (`camcc-yupik.c`, `cam_ife_csid_lite17x.h`, `cam_vfe_lite16x.h`, `cam_vfe_bus_ver2.c`). `cam=4` — кадры самого датчика: питание и ID, как при `cam=2`, его таблицы Android — инициализация (108 записей), режим (1600×1200 RAW10, одна линия, 665,6 Мбит/с, 30 кадров/с), «пуск», таблица экспозиции; CSIPHY 2 (v1.2.1, D-PHY, линия данных 0 и линия такта; число отсчётов установления — из файла модуля для этого режима, 20, `cam_settle=N` — своё), приёмник CSID-lite 0 от PHY 2 и тот же путь RDI 0 → IFE-lite 0 → SMMU → память; несколько кадров подряд в два места, последний остаётся; потом «стоп» и всё выключается. Таблицы читаются при запуске из `fw/camera-ov02b10.tab` малого образа: его делает `tools/camsensor.py` из файла модуля датчика Android (`fw-camera/com.qti.sensormodule.redwood_aac_ov02b10_macro.bin` с телефона; ни он, ни таблицы в git не попадают). `cam_pattern=1` — тестовые полосы самого датчика вместо изображения, `cam_frames=N` — сколько кадров (по умолчанию 8), `cam_shutter=СТРОК`, `cam_gain=N` — своя экспозиция и усиление. Память с кадрами загрузчик отдаёт после сеанса: `./xl camera [префикс]` забирает её и через `tools/camraw.py` делает картинки (`префикс-N.png` — по пикселю на ячейку 2×2 Байера, серый мир, гамма 2,2; `префикс-N-raw.png` — сырые значения; порядок Байера изображения датчика — RGGB: в снимке комнаты друг за другом следуют второй и третий отсчёты ячейки, то есть зелёные; его собственные полосы приходят со сдвигом на строку, как GBRG; `--bayer N` — другой порядок; `cam_vblank=СТРОК` — удлинить кадр для выдержки длиннее 1200 строк). `cam_sensor=wide` — то же для основной широкоугольной камеры, Samsung S5KHM2SD (108 Мп, камера 0 Android, «redwood_sunny_s5khm2sd_wide», cam-sensor0): CCI 0, ведущий 1 (GPIO 71/72), адрес 0x20, ID чипа 0xfad2 по адресу 0x0000; сброс — GPIO 21; MCLK — mclk1 camcc (19,2 МГц, GPIO 65); питание — LDO1 (1,0 В, VDIG) и LDO5 (1,8 В, VIO) PM8008i и VANA 2,8 В от постоянного регулятора, который включает GPIO 106 (всё — напряжения дерева устройств); порядок включения и выключения, ID, таблицы и режимы — из её файла модуля (`fw-camera/com.qti.sensormodule.redwood_sunny_s5khm2sd_wide.bin` → `fw/camera-s5khm2sd.tab`, формат RWCTAB02 — все режимы, порядок питания, назначение линий; инициализация — 1441 запись; шесть режимов, от 12000×9000 до 1920×1080 на 240 кадрах/с). Кадры — по трём трио C-PHY в CSIPHY 1 (трёхфазные таблицы v1.2.1 Android и строка таблицы скоростей, покрывающая скорость трио; число отсчётов установления — из файла модуля, 34), CSID-lite 0 — в режиме C-PHY. `cam_mode=N` — режим из таблицы датчика (по умолчанию — с наименьшим числом пикселей: у широкой — 1920×1080 RAW10 на 120 кадрах/с, 3,11 Гбит/с на трио). Порядок Байера широкой — GBRG (в снимке комнаты друг за другом следуют первый и четвёртый отсчёты; красный против синего — по сырым уровням обеих камер при одном тёплом свете), заголовок кадра говорит его сам. Экспозиция широкой — регистры SMIA внутри group hold 0x0104: `cam_vblank` — длина кадра 0x0340, `cam_shutter` — выдержка 0x0202, `cam_gain` — аналоговое усиление 0x0204 (32 — 1×) |
+| `cam=N` | камеры: макрокамера — OmniVision OV02B10 (2 Мп, камера 2 Android, «redwood_aac_ov02b10_macro»); всё — из живого дерева устройств (cam-sensor2), файла модуля камеры Android (`/vendor/lib64/camera/com.qti.sensormodule.redwood_aac_ov02b10_macro.bin`: адрес, где и как читается ID чипа, порядок включения) и драйверов ядра Android (`bsd/dev/redwood_camera.c`). Датчик — на CCI 1, ведущий 0 (GPIO 73/74, здесь I2C вручную, как у других драйверов), адрес 0x3c; сброс — GPIO 77; MCLK — mclk2 camcc на 19,2 МГц на GPIO 66 (у Android эти 19,2 МГц — от PLL2 camcc, здесь — от самого кварца, без PLL); питание — LDO6 (1,8 В, DOVDD) и LDO7 (2,8 В, AVDD) PM8008i, который на I2C последовательного движка 1 (GPIO 4/5, адреса 0x08 и 0x09) и выходит из сброса по GPIO 3 PM8350C, как его выводит Android. `cam=1` — только смотреть: тактовые частоты и домен питания камеры, ножки, сброс PM8008i и, если он не в сбросе, сам PM8008i. `cam=2` — ещё и включить датчик в порядке файла модуля (у макрокамеры: сброс низкий, 1 мс; DOVDD; AVDD, 2 мс; верхний домен питания камеры и MCLK, 4 мс; сброс высокий, 9 мс), прочитать ID чипа так, как читает Android (16-битный регистр по 16-битному адресу 0x0203; ждёт 0x002b), и выключить в обратном порядке. Пределы: напряжения — только Android (1,8 и 2,8 В у макрокамеры, 1,0 и 1,8 В у широкой), записи — только в перечисленные регистры (у каждого устройства — список, проверяется при каждой записи), каждая читается обратно; неотвеченный байт, регулятор не готов вовремя или сообщает о перегрузке по току, запись не читается обратно — всё выключается и больше ничего не пишется; в конце сеанса и при панике включённое выключается, найденное включённым остаётся включённым. `cam_after=S` — через сколько секунд после старта (по умолчанию 20). `cam=3` — путь кадра без датчика: генератор тестовой картинки CSID-lite 0 (RAW10 1600×1200, цветные полосы) → его путь RDI 0 → IFE-lite 0, чей мастер записи 0 пишет кадр в память через SMMU (поток 0x800, маска 0x4e0, в свободный контекст с нашими таблицами); для этого — голоса RPMh за CX на SVS и MX на SVS_L1 (через вторую TCS DRV 2, в конце отдаются), PLL0 camcc (1,2 ГГц), RCG и ветви камеры на частотах уровня «svs» из дерева устройств (cphy_rx, CSID, IFE-lite — 400 МГц, таймер PHY — 300, camnoc — 150, slow_ahb — 80), всё — по драйверам Android (`camcc-yupik.c`, `cam_ife_csid_lite17x.h`, `cam_vfe_lite16x.h`, `cam_vfe_bus_ver2.c`). `cam=4` — кадры самого датчика: питание и ID, как при `cam=2`, его таблицы Android — инициализация (108 записей), режим (1600×1200 RAW10, одна линия, 665,6 Мбит/с, 30 кадров/с), «пуск», таблица экспозиции; CSIPHY 2 (v1.2.1, D-PHY, линия данных 0 и линия такта; число отсчётов установления — из файла модуля для этого режима, 20, `cam_settle=N` — своё), приёмник CSID-lite 0 от PHY 2 и тот же путь RDI 0 → IFE-lite 0 → SMMU → память; несколько кадров подряд в два места, последний остаётся; потом «стоп» и всё выключается. Таблицы читаются при запуске из `fw/camera-ov02b10.tab` малого образа: его делает `tools/camsensor.py` из файла модуля датчика Android (`fw-camera/com.qti.sensormodule.redwood_aac_ov02b10_macro.bin` с телефона; ни он, ни таблицы в git не попадают). `cam_pattern=1` — тестовые полосы самого датчика вместо изображения, `cam_frames=N` — сколько кадров (по умолчанию 8), `cam_shutter=СТРОК`, `cam_gain=N` — своя экспозиция и усиление. Память с кадрами загрузчик отдаёт после сеанса: `./xl camera [префикс]` забирает её и через `tools/camraw.py` делает картинки (`префикс-N.png` — по пикселю на ячейку 2×2 Байера, серый мир, гамма 2,2; `префикс-N-raw.png` — сырые значения; порядок Байера изображения датчика — RGGB: в снимке комнаты друг за другом следуют второй и третий отсчёты ячейки, то есть зелёные; его собственные полосы приходят со сдвигом на строку, как GBRG; `--bayer N` — другой порядок; `cam_vblank=СТРОК` — удлинить кадр для выдержки длиннее 1200 строк). `cam_sensor=wide` — то же для основной широкоугольной камеры, Samsung S5KHM2SD (108 Мп, камера 0 Android, «redwood_sunny_s5khm2sd_wide», cam-sensor0): CCI 0, ведущий 1 (GPIO 71/72), адрес 0x20, ID чипа 0xfad2 по адресу 0x0000; сброс — GPIO 21; MCLK — mclk1 camcc (19,2 МГц, GPIO 65); питание — LDO1 (1,0 В, VDIG) и LDO5 (1,8 В, VIO) PM8008i и VANA 2,8 В от постоянного регулятора, который включает GPIO 106 (всё — напряжения дерева устройств); порядок включения и выключения, ID, таблицы и режимы — из её файла модуля (`fw-camera/com.qti.sensormodule.redwood_sunny_s5khm2sd_wide.bin` → `fw/camera-s5khm2sd.tab`, формат RWCTAB02 — все режимы, порядок питания, назначение линий; инициализация — 1441 запись; шесть режимов, от 12000×9000 до 1920×1080 на 240 кадрах/с). Кадры — по трём трио C-PHY в CSIPHY 1 (трёхфазные таблицы v1.2.1 Android и строка таблицы скоростей, покрывающая скорость трио; число отсчётов установления — из файла модуля, 34), CSID-lite 0 — в режиме C-PHY. `cam_mode=N` — режим из таблицы датчика (по умолчанию — с наименьшим числом пикселей: у широкой — 1920×1080 RAW10 на 120 кадрах/с, 3,11 Гбит/с на трио). Порядок Байера широкой — GBRG (в снимке комнаты друг за другом следуют первый и четвёртый отсчёты; красный против синего — по сырым уровням обеих камер при одном тёплом свете), заголовок кадра говорит его сам. Экспозиция широкой — регистры SMIA внутри group hold 0x0104: `cam_vblank` — длина кадра 0x0340, `cam_shutter` — выдержка 0x0202, `cam_gain` — аналоговое усиление 0x0204 (32 — 1×). `cam=5` — широкая камера для iOS: устройство `/dev/redwood-camera` (`bsd/sys/redwood_camera.h`); первое чтение после открытия включает датчик и запускает кадры (режим — `cam_mode`, по умолчанию 1: 4000×3000 RAW10, 30 кадров/с), последнее закрытие, секунда без чтения или любая неисправность всё выключают (после неисправности — до конца сеанса). Кадры идут по кругу в три места памяти ядра (отображённые через SMMU постранично): одно пишет IFE, одно может копировать чтение, одно готово; когда кадр готов, адрес следующего места уходит мастеру записи, который берёт его на следующем начале кадра, а кадр, за которым адрес опоздал, не отдаётся. Строка RAW10 у мастера записи выровнена на 16 байт (4000 пикселей — 5008 байт, а не 5000). `read()` отдаёт заголовок (номер, время, выдержка, усиление, длина кадра и строки) и сам кадр; `write()` принимает выдержку и усиление (пишутся между кадрами в group hold, с пределами: усиление 1×…64×, кадр не длиннее 0xfff0 строк) или картинку для хоста (память под неё — `cam_keep_mb`, по умолчанию 24, берётся при загрузке одним куском; `./xl camera` её забирает, `tools/camraw.py` понимает NV12 и BGRA). Проверка — `RC_JOBS=rc.jobs.camera` (`camera_test raw`: кадры через `src/camera_isp.c` — замер, автоэкспозиция, баланс белого, гамма, NV12) |
| `mic=N` | с `adsp=1`, основной микрофон (`bsd/dev/redwood_mic.c`, значения Android). `mic=1` — только посмотреть: звуковой процессор голосует за блоки LPASS и даёт тактовые частоты макроса TX (19,2 МГц), регистры макросов TX и VA, ведущего SoundWire, ножек LPASS и сброса кодека читаются; без всех четырёх ни один регистр не трогается. `mic=2` — ещё и кодек поднят настолько, чтобы ответить по SoundWire: сброс (GPIO83) отпущен, как это делает Android, ножки ведущего (LPASS GPIO 0, 1, 2, 14) — в активное состояние Android, тактовые частоты макроса TX, ведущий запущен, устройство TX кодека перечислено и его номер прочитан. `mic=3` — ещё и запись с микрофона `mic_secs` секунд (по умолчанию 10, не больше 600): настройка кодека, как в `wcd938x_init_reg()`, смещение микрофона 2750 мВ, ADC1 в режиме «low power», «ADC1 Volume» 6, дециматор 1 и порт codec DMA, шина SoundWire как на пути Android «handset-mic» (выше). Каждая запись читается обратно, любое расхождение или отказ звукового процессора — всё останавливается. Для проверки: `mic_input=0` (дециматор слушает ноль — точная тишина), `mic_adc=0`, `mic_test=1` (без смещения), `mic_test=2` (вход ADC1 удержан), `mic_main=1`, `mic_tap=1` с `haptic=5`. `mic=4` — микрофон для iOS: путь до кодека поднимается, только пока iOS записывает (пока открыт `/dev/redwood-mic`, кольцо на 341 мс, чтение никогда не ждёт и держится в 40 мс за звуковым процессором), а в плагине звука `RedwoodAudio.driver` есть устройство «Codec» с одним входом и источником данных `imic` («Bottom»), из которого VirtualAudio, как на iPhone, делает «iPhone Microphone» (Built-In Microphone). Приложения записывают с него: «Диктофон» пишет и рисует волну (`RC_JOBS=rc.jobs.voicememos`), `record_test` (AVAudioRecorder) — 6,00 с из 6,00, на частоте мотора 175,5 Гц с `haptic=5` уровень растёт с −68 до −29 дБFS (`RC_JOBS=rc.jobs.mic`, с `sound=4 sound_below=720` — сначала беззвучная проверка динамиков). Программа без интерфейса, записывающая в фоне, получает оранжевую точку, но не плашку записи в строке состояния, и MediaSafetyNet в mediaserverd, как на iPhone, через девять секунд такой записи останавливает mediaserverd; записи `record_test` поэтому короче и с паузой между ними. В конце и при выключении звукового процессора всё возвращается как было: кодек снова в сбросе, ножки и регистры как были |
| `battmgr=0` | с `adsp=1` батарея не спрашивается. Без него (по умолчанию) ядро раз в 10 с спрашивает у звукового процессора, который у этого телефона и ведёт батарею с зарядкой (как Android — `qti_battery_charger`, Linux — `qcom_battmgr` поверх `pmic_glink`), по каналу `PMIC_RTR_ADSP_APPS` процент заряда, зарядку, напряжение, ток, температуру, заряд в мА·ч, ёмкость, циклы и что даёт порт USB — только читает, ни пределов, ни токов не задаёт — и показывает это iOS так же, как батарея iPhone: службой `RedwoodBattery` класса `IOPMPowerSource` (`iokit/Kernel/RedwoodBattery.cpp`). Её читает powerd, и дальше всё делает сама iOS: батарея с процентом и молнией в строке состояния, «58% Charged» на экране блокировки, виджет «Батареи», Настройки → Аккумулятор (переключатель «Заряд в процентах» работает; в образе он включён); перехваты батареи в SpringBoard при этой службе уступают iOS. Сверено с Android (`dumpsys battery` и `/sys/class/power_supply/battery` сразу после): 56 % и 58 %, «заряжается», напряжение, температура, заряд, ёмкость 3677 из 5000 мА·ч, 890 циклов совпадают. Номера свойств — этой прошивки: до 9-го как у Linux, дальше на один больше; `battmgr=2` пишет в журнал все. Те же числа — в `kern.redwood.battery_*`. С `battery=1` (путь загрузчика через UEFI) не включается. Историю заряда и расход по приложениям iOS 16 берёт из журнала энергии, который ведёт aggregated (`com.apple.powerlog.plxpclogger.xpc` и другие службы; база `CurrentPowerlog.PLSQL`); раньше он был в списке не запускаемых (`userland/mkjobs.py`), и страница «Аккумулятор» вечно крутила колёсико. Теперь она открывается сразу: в первые минуты — «As you use your iPhone, battery usage will be reported here» (так iOS говорит, пока данных о расходе нет), через час — график уровня заряда за 24 часа и список приложений («Connected to Charger», пока телефон на зарядке); экран всё это время iOS считала выключенным («Screen On 0m»), отчего — ещё не разобрано. Расход в процентах по приложениям iOS считает из энергии частей системы на кристалле, которую на iPhone сообщают счётчики IOReport («Energy Model»); их здесь нет. Не показывается износ в «Состоянии аккумулятора» (powerd ждёт серийный номер батареи, а его прошивка не даёт; вместо цифры колёсико). Проверка — `RC_JOBS=rc.jobs.battery` (`battery_test`), `RC_JOBS=rc.jobs.battery2` (страницы Настроек, в конце `battery_test powerlog`: что журнал энергии собрал — таблицы, строки, время), `RC_JOBS=rc.jobs.battery3` (то же после часа работы приложений) |
diff --git a/tools/camraw.py b/tools/camraw.py
index 6ac8b8e..79c864e 100755
--- a/tools/camraw.py
+++ b/tools/camraw.py
@@ -11,6 +11,8 @@ four, their low two bits together in the fifth. Each frame becomes PREFIX-N.png,
taking each 2x2 cell (bayer 0 RGGB, 1 GRBG, 2 GBRG, 3 BGGR) as one pixel -- half the resolution, no
interpolation -- with a plain grey-world white balance and a gamma of 2.2: a first look, not a
finished photograph; PREFIX-N-raw.png is the frame's raw values as they are (grey, 8 bits).
+Formats 2 and 3 are a picture iOS made of a frame (cam=5): NV12 (full-range YCbCr 4:2:0, the chroma plane
+after the luma one, both of the stride) or BGRA, which becomes PREFIX.png as it is.
--bayer N takes the frames for that order instead of the header's. The OV02B10's picture is RGGB
here (in a picture of a room the second and third sites of each cell track each other, the
greens; red against blue by plausible colours); its own colour bars (cam_pattern=1) come a line
@@ -60,6 +62,27 @@ def main():
sys.exit('camraw.py: not frames of the camera driver')
print(f'camraw.py: {sensor}: {width}x{height}, stride {stride}, format {fmt}, bayer {bayer}, {frames} frame(s) written whole, '
f'the last in place {last}')
+ if fmt in (2, 3):
+ # a picture iOS made of a frame (cam=5, camera_test or mediaserverd): NV12 (full range) or BGRA
+ base = 4096
+ rows = []
+ for y in range(height):
+ out = bytearray()
+ if fmt == 3:
+ line = data[base + y * stride:base + y * stride + 4 * width]
+ for x in range(width):
+ out += bytes((line[4 * x + 2], line[4 * x + 1], line[4 * x]))
+ else:
+ luma = data[base + y * stride:base + y * stride + width]
+ chroma = data[base + stride * height + (y // 2) * stride:base + stride * height + (y // 2) * stride + width]
+ for x in range(width):
+ yy, cb, cr = luma[x], chroma[x & ~1] - 128, chroma[(x & ~1) + 1] - 128
+ for v in (yy + 1.402 * cr, yy - 0.344136 * cb - 0.714136 * cr, yy + 1.772 * cb):
+ out.append(max(0, min(255, int(v + 0.5))))
+ rows.append(out)
+ png(f'{sys.argv[2]}.png', width, height, rows, 3)
+ print(f'camraw.py: {sys.argv[2]}.png ({width}x{height}, from {"NV12" if fmt == 2 else "BGRA"})')
+ return
count = max(frames, 1)
for n in range(count):
base = 4096 + n * frame_bytes
diff --git a/userland/build.sh b/userland/build.sh
index 3d09aad..f2cdfbb 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -113,6 +113,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then
$DYN -framework CoreFoundation -framework AudioToolbox -framework AVFoundation -lobjc -o obj/sound_test src/sound_test.c
$DYN -framework CoreFoundation -lMobileGestalt -o obj/mg_test src/mg_test.c
$DYN -framework CoreFoundation -framework AVFoundation -lobjc -o obj/torch_test src/torch_test.c
+ $DYN -O2 -o obj/camera_test src/camera_test.c src/camera_isp.c
# (the microphone as an application records: allowed to, by an entitlement, if ldid is there)
$DYN -framework CoreFoundation -framework AVFoundation -lobjc -o obj/record_test src/record_test.c &&
{ ${LDID:-ldid} -Ssrc/record_test.entitlements obj/record_test 2>/dev/null ||
@@ -172,6 +173,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then
[ -f obj/wifipw_test ] && cp obj/wifipw_test root/bin/
[ -f obj/sound_test ] && cp obj/sound_test root/bin/
[ -f obj/torch_test ] && cp obj/torch_test root/bin/
+ [ -f obj/camera_test ] && cp obj/camera_test root/bin/
[ -f obj/record_test ] && cp obj/record_test root/bin/
for f in $EXTRA; do cp "$f" root/bin/; done
mkdir -p root/lib
diff --git a/userland/rc.jobs.camera b/userland/rc.jobs.camera
new file mode 100644
index 0000000..2d46fbd
--- /dev/null
+++ b/userland/rc.jobs.camera
@@ -0,0 +1,7 @@
+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).
+# The wide camera for iOS, its frames (RC_JOBS=rc.jobs.camera, with cam=5): a program reads 150 of them from the
+# kernel's /dev/redwood-camera (camera_test raw: src/camera_isp.c's exposure and white balance at work on them), says
+# what came and how fast, and leaves the last one as a picture for the host (xl camera). The kernel's "camera:" lines
+# say when the sensor streamed and why it stopped.
+/redwood/bin/sound_test springboard
+/redwood/bin/camera_test raw 150
diff --git a/userland/src/camera_isp.c b/userland/src/camera_isp.c
new file mode 100644
index 0000000..4a816dc
--- /dev/null
+++ b/userland/src/camera_isp.c
@@ -0,0 +1,271 @@
+/*
+ * The wide camera's frames made into pictures by the processor (see camera_isp.h). A first version:
+ * one pixel per 2x2 cell (no interpolation), the nearest cell for each pixel of the picture, grey
+ * world white balance, no colour matrix, no lens shading, no noise reduction.
+ */
+#include <math.h>
+#include <string.h>
+#include "camera_isp.h"
+
+#define WHITE 959 /* 1023 less the black level of 64 */
+#define LUT_WHITE 3836 /* WHITE in the gamma table's steps */
+
+void
+isp_init(struct isp *isp)
+{
+ memset(isp, 0, sizeof(*isp));
+ isp->wb[0] = isp->wb[1] = isp->wb[2] = 1;
+ isp->digital = 1;
+ for (int i = 0; i < 4096; i++) {
+ double v = i >= LUT_WHITE ? 1 : (double)i / LUT_WHITE;
+
+ v = v <= 0.0031308 ? 12.92 * v : 1.055 * pow(v, 1 / 2.4) - 0.055;
+ isp->gamma[i] = (uint8_t)(v * 255 + 0.5);
+ }
+}
+
+/* where red and blue are in a cell (0 top left, 1 top right, 2 bottom left, 3 bottom right) */
+static void
+cell_places(uint32_t bayer, int *r, int *b)
+{
+ static const int red[4] = { 0, 1, 2, 3 }, blue[4] = { 3, 2, 1, 0 };
+
+ *r = red[bayer & 3];
+ *b = blue[bayer & 3];
+}
+
+/* the four values of the cell at cx of the pair of lines from `top' (above black, 0 and up) */
+static inline void
+cell(const uint8_t *top, size_t stride, uint32_t cx, int v[4])
+{
+ const uint8_t *g0 = top + (size_t)(cx >> 1) * 5, *g1 = g0 + stride;
+ unsigned o = (cx & 1) * 2;
+
+ v[0] = (g0[o] << 2 | (g0[4] >> (o * 2) & 3)) - 64;
+ v[1] = (g0[o + 1] << 2 | (g0[4] >> (o * 2 + 2) & 3)) - 64;
+ v[2] = (g1[o] << 2 | (g1[4] >> (o * 2) & 3)) - 64;
+ v[3] = (g1[o + 1] << 2 | (g1[4] >> (o * 2 + 2) & 3)) - 64;
+ for (int i = 0; i < 4; i++) {
+ v[i] = v[i] < 0 ? 0 : v[i];
+ }
+}
+
+void
+isp_measure(const struct redwood_camera_frame *f, const uint8_t *raw, struct isp_stats *s)
+{
+ uint32_t cells_w = f->width / 2, cells_h = f->height / 2;
+ double sum[3] = { 0, 0, 0 };
+ int r, b;
+
+ memset(s, 0, sizeof(*s));
+ cell_places(f->bayer, &r, &b);
+ for (uint32_t cy = 0; cy < cells_h; cy += 4) {
+ const uint8_t *top = raw + (size_t)cy * 2 * f->stride;
+
+ for (uint32_t cx = 0; cx < cells_w; cx += 4) {
+ int v[4], g = 0;
+
+ cell(top, f->stride, cx, v);
+ for (int i = 0; i < 4; i++) {
+ g += i != r && i != b ? v[i] : 0;
+ }
+ g /= 2;
+ sum[0] += v[r];
+ sum[1] += g;
+ sum[2] += v[b];
+ s->hist[g >> 4 > 63 ? 63 : g >> 4]++;
+ s->cells++;
+ }
+ }
+ for (int c = 0; c < 3; c++) {
+ s->mean[c] = s->cells ? sum[c] / s->cells : 0;
+ }
+ for (int i = 63, above = 0; i >= 0; i--) {
+ above += s->hist[i];
+ if (above * 100 >= (int)s->cells) {
+ s->bright = i * 16 + 8;
+ break;
+ }
+ }
+}
+
+/*
+ * Green's mean towards 15 % of white, unless that would put 1 % of the picture into white. The
+ * exposure, longest first: the frame's lines at the shortest frame, then gain to 16x, then frames up
+ * to max_frame_lines, then gain to the most; beyond that, digital gain (up to 4x).
+ */
+bool
+isp_ae(struct isp *isp, const struct redwood_camera_frame *f, const struct isp_stats *s, struct redwood_camera_command *c)
+{
+ double now = (double)f->exposure_lines * f->gain / f->gain_unity * isp->digital, ratio, want;
+ double target = 0.15 * WHITE, mean = s->mean[1] * isp->digital > 0.5 ? s->mean[1] * isp->digital : 0.5;
+ double bright = s->bright * isp->digital;
+ uint32_t fast = f->frame_lines_min - f->margin, longest = isp->max_frame_lines ? isp->max_frame_lines : 2 * f->frame_lines_min;
+ uint32_t lines, gain, frame_lines = 0;
+ double digital = 1;
+
+ if (isp->asked && (f->exposure_lines != isp->asked_lines || f->gain != isp->asked_gain)) {
+ return false; /* (the last change not in the frames yet) */
+ }
+ /* (the measured levels are the sensor's: digital gain is applied to the picture only) */
+ ratio = target / mean;
+ if (bright * ratio > 0.9 * WHITE && bright > 0) {
+ ratio = 0.9 * WHITE / bright > target / mean * 0.5 ? 0.9 * WHITE / bright : target / mean * 0.5;
+ }
+ ratio = ratio < 0.25 ? 0.25 : ratio > 4 ? 4 : ratio;
+ if (ratio > 0.94 && ratio < 1.06) {
+ return false;
+ }
+ want = now * pow(ratio, 0.7);
+ if (want <= fast) {
+ lines = want < 4 ? 4 : (uint32_t)want;
+ gain = f->gain_unity;
+ } else if (want <= (double)fast * 16) {
+ lines = fast;
+ gain = (uint32_t)(want / fast * f->gain_unity);
+ } else {
+ lines = (uint32_t)(want / 16);
+ lines = lines > longest - f->margin ? longest - f->margin : lines < fast ? fast : lines;
+ frame_lines = lines + f->margin;
+ double g = want / lines;
+
+ if (g > (double)f->gain_max / f->gain_unity) {
+ digital = g / ((double)f->gain_max / f->gain_unity);
+ digital = digital > 4 ? 4 : digital;
+ g = (double)f->gain_max / f->gain_unity;
+ }
+ gain = (uint32_t)(g * f->gain_unity);
+ }
+ isp->digital = (float)digital;
+ isp->asked_lines = lines;
+ isp->asked_gain = gain;
+ isp->asked_frame_lines = frame_lines;
+ isp->asked = true;
+ memset(c, 0, sizeof(*c));
+ c->command = REDWOOD_CAMERA_EXPOSURE;
+ c->a = lines;
+ c->b = gain;
+ c->c = frame_lines;
+ return true;
+}
+
+void
+isp_awb(struct isp *isp, const struct isp_stats *s)
+{
+ if (s->mean[0] < 2 || s->mean[2] < 2 || s->mean[1] < 2) {
+ return;
+ }
+ float r = (float)(s->mean[1] / s->mean[0]), b = (float)(s->mean[1] / s->mean[2]);
+
+ r = r < 0.5f ? 0.5f : r > 4 ? 4 : r;
+ b = b < 0.5f ? 0.5f : b > 4 ? 4 : b;
+ isp->wb[0] = isp->wb[0] * 0.8f + r * 0.2f;
+ isp->wb[2] = isp->wb[2] * 0.8f + b * 0.2f;
+}
+
+/* the part of the sensor's cells the picture shows: its middle, in the picture's proportions */
+static void
+crop(const struct redwood_camera_frame *f, uint32_t width, uint32_t height, uint32_t *x0, uint32_t *y0, uint32_t *cw, uint32_t *ch)
+{
+ uint32_t w = f->width / 2, h = f->height / 2;
+
+ if ((uint64_t)width * h > (uint64_t)height * w) {
+ *cw = w;
+ *ch = (uint32_t)((uint64_t)w * height / width);
+ } else {
+ *ch = h;
+ *cw = (uint32_t)((uint64_t)h * width / height);
+ }
+ *x0 = (w - *cw) / 2;
+ *y0 = (h - *ch) / 2;
+}
+
+/* one line of the picture as 8-bit R, G, B */
+static void
+render_line(const struct isp *isp, const struct redwood_camera_frame *f, const uint8_t *raw, uint32_t width, uint32_t height,
+ uint32_t row, uint8_t *rgb)
+{
+ uint32_t x0, y0, cw, ch, k[3];
+ int r, b;
+
+ crop(f, width, height, &x0, &y0, &cw, &ch);
+ cell_places(f->bayer, &r, &b);
+ for (int c = 0; c < 3; c++) {
+ k[c] = (uint32_t)(isp->wb[c] * isp->digital * 4 * 256);
+ }
+ const uint8_t *top = raw + (size_t)(y0 + (uint64_t)row * ch / height) * 2 * f->stride;
+ uint64_t step = ((uint64_t)cw << 16) / width, at = (uint64_t)x0 << 16;
+
+ for (uint32_t x = 0; x < width; x++, at += step) {
+ int v[4], g = 0;
+ uint32_t i;
+
+ cell(top, f->stride, (uint32_t)(at >> 16), v);
+ for (int j = 0; j < 4; j++) {
+ g += j != r && j != b ? v[j] : 0;
+ }
+ i = (uint32_t)v[r] * k[0] >> 8;
+ rgb[3 * x] = isp->gamma[i > 4095 ? 4095 : i];
+ i = (uint32_t)g * k[1] >> 9;
+ rgb[3 * x + 1] = isp->gamma[i > 4095 ? 4095 : i];
+ i = (uint32_t)v[b] * k[2] >> 8;
+ rgb[3 * x + 2] = isp->gamma[i > 4095 ? 4095 : i];
+ }
+}
+
+void
+isp_render_nv12(const struct isp *isp, const struct redwood_camera_frame *f, const uint8_t *raw, uint8_t *y, size_t y_stride,
+ uint8_t *uv, size_t uv_stride, uint32_t width, uint32_t height, uint32_t first_row, uint32_t end_row)
+{
+ uint8_t line[2][3 * 8192];
+
+ if (width > 8192) {
+ return;
+ }
+ for (uint32_t row = first_row & ~1u; row < end_row && row + 1 < height + 1; row += 2) {
+ render_line(isp, f, raw, width, height, row, line[0]);
+ render_line(isp, f, raw, width, height, row + 1 < height ? row + 1 : row, line[1]);
+ for (int l = 0; l < 2 && row + l < height; l++) {
+ uint8_t *out = y + (size_t)(row + l) * y_stride;
+ const uint8_t *p = line[l];
+
+ for (uint32_t x = 0; x < width; x++, p += 3) {
+ out[x] = (uint8_t)((77 * p[0] + 150 * p[1] + 29 * p[2]) >> 8);
+ }
+ }
+ uint8_t *o = uv + (size_t)(row / 2) * uv_stride;
+
+ for (uint32_t x = 0; x + 1 < width + 1; x += 2) {
+ uint32_t x1 = x + 1 < width ? x + 1 : x;
+ int R = line[0][3 * x] + line[0][3 * x1] + line[1][3 * x] + line[1][3 * x1];
+ int G = line[0][3 * x + 1] + line[0][3 * x1 + 1] + line[1][3 * x + 1] + line[1][3 * x1 + 1];
+ int B = line[0][3 * x + 2] + line[0][3 * x1 + 2] + line[1][3 * x + 2] + line[1][3 * x1 + 2];
+ int cb = ((-43 * R - 85 * G + 128 * B) >> 10) + 128, cr = ((128 * R - 107 * G - 21 * B) >> 10) + 128;
+
+ o[x] = (uint8_t)(cb < 0 ? 0 : cb > 255 ? 255 : cb);
+ o[x + 1] = (uint8_t)(cr < 0 ? 0 : cr > 255 ? 255 : cr);
+ }
+ }
+}
+
+void
+isp_render_bgra(const struct isp *isp, const struct redwood_camera_frame *f, const uint8_t *raw, uint8_t *out, size_t stride,
+ uint32_t width, uint32_t height, uint32_t first_row, uint32_t end_row)
+{
+ uint8_t line[3 * 8192];
+
+ if (width > 8192) {
+ return;
+ }
+ for (uint32_t row = first_row; row < end_row && row < height; row++) {
+ uint8_t *o = out + (size_t)row * stride;
+
+ render_line(isp, f, raw, width, height, row, line);
+ for (uint32_t x = 0; x < width; x++) {
+ o[4 * x] = line[3 * x + 2];
+ o[4 * x + 1] = line[3 * x + 1];
+ o[4 * x + 2] = line[3 * x];
+ o[4 * x + 3] = 255;
+ }
+ }
+}
diff --git a/userland/src/camera_isp.h b/userland/src/camera_isp.h
new file mode 100644
index 0000000..0b22fd4
--- /dev/null
+++ b/userland/src/camera_isp.h
@@ -0,0 +1,47 @@
+/*
+ * What the phone's ISP would do with the wide camera's RAW10 frames, done by the processor instead
+ * (src/camera_isp.c): the levels of a frame, the exposure for the next ones (AE), the white balance
+ * (AWB), and a picture: each 2x2 Bayer cell one pixel of colour, scaled to the size asked for, the
+ * gains, a gamma, as 8-bit YCbCr 4:2:0 (NV12, full range: CoreVideo's 420f) or BGRA.
+ */
+#ifndef CAMERA_ISP_H
+#define CAMERA_ISP_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include "redwood_camera.h"
+
+struct isp_stats {
+ double mean[3]; /* R, G, B above black, in 10-bit steps */
+ double bright; /* the level of green that 1 % of the cells are above */
+ uint32_t hist[64]; /* green above black, 16 steps a bin */
+ uint32_t cells;
+};
+
+struct isp {
+ float wb[3]; /* the white balance's gains, green 1 */
+ float digital; /* more gain, for what AE cannot reach with the sensor's */
+ uint8_t gamma[4096]; /* linear (959 above black is 3836) to 8 bits, sRGB's curve */
+ uint32_t asked_lines, asked_gain, asked_frame_lines; /* what AE asked for last */
+ bool asked;
+ uint32_t max_frame_lines; /* the longest frame AE may ask for (0: twice the shortest) */
+};
+
+void isp_init(struct isp *isp);
+/* the levels, from every 4th cell of every 4th pair of lines */
+void isp_measure(const struct redwood_camera_frame *f, const uint8_t *raw, struct isp_stats *s);
+/* the exposure for the frames to come: true, and the command filled in, when it should change */
+bool isp_ae(struct isp *isp, const struct redwood_camera_frame *f, const struct isp_stats *s, struct redwood_camera_command *c);
+/* the white balance: grey world, a little of the way at a time */
+void isp_awb(struct isp *isp, const struct isp_stats *s);
+/*
+ * A picture of the frame, width x height, of the sensor's middle part with the picture's proportions
+ * (rows from first_row to end_row only, for doing it in pieces). NV12: y and uv planes; BGRA: y only.
+ */
+void isp_render_nv12(const struct isp *isp, const struct redwood_camera_frame *f, const uint8_t *raw, uint8_t *y, size_t y_stride,
+ uint8_t *uv, size_t uv_stride, uint32_t width, uint32_t height, uint32_t first_row, uint32_t end_row);
+void isp_render_bgra(const struct isp *isp, const struct redwood_camera_frame *f, const uint8_t *raw, uint8_t *out, size_t stride,
+ uint32_t width, uint32_t height, uint32_t first_row, uint32_t end_row);
+
+#endif
diff --git a/userland/src/camera_test.c b/userland/src/camera_test.c
new file mode 100644
index 0000000..3cc0adb
--- /dev/null
+++ b/userland/src/camera_test.c
@@ -0,0 +1,165 @@
+/*
+ * camera_test: the wide camera's frames as a program gets them (cam=5).
+ *
+ * usage: camera_test raw [FRAMES] [noae] [keepraw]
+ * reads FRAMES frames (default 150) from the kernel's /dev/redwood-camera, with src/camera_isp.c's
+ * exposure (unless noae: the kernel's, boot-args cam_shutter and cam_gain) and white balance working
+ * on them, says what came and how fast, and leaves the last one as a picture for the host (xl
+ * camera: logs/, never the repository): one pixel a cell, NV12, or with keepraw the frame itself.
+ */
+#include <errno.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <mach/mach_time.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include "camera_isp.h"
+
+static double
+ms_since(uint64_t then)
+{
+ static mach_timebase_info_data_t tb;
+
+ if (tb.denom == 0) {
+ mach_timebase_info(&tb);
+ }
+ return (double)(mach_absolute_time() - then) * tb.numer / tb.denom / 1e6;
+}
+
+static double
+ticks_ms(uint64_t ticks)
+{
+ static mach_timebase_info_data_t tb;
+
+ if (tb.denom == 0) {
+ mach_timebase_info(&tb);
+ }
+ return (double)ticks * tb.numer / tb.denom / 1e6;
+}
+
+static int
+raw(int frames, bool ae, bool keep_raw)
+{
+ struct redwood_camera_frame head, *f;
+ struct isp isp;
+ struct isp_stats s;
+ uint64_t started = mach_absolute_time(), previous = 0, first_seq = 0;
+ size_t bytes;
+ int device = open(REDWOOD_CAMERA_DEVICE, O_RDWR), got = 0, failures = 0;
+ ssize_t n;
+
+ if (device < 0) {
+ perror("camera_test: " REDWOOD_CAMERA_DEVICE);
+ return 1;
+ }
+ for (int tries = 0; (n = read(device, &head, sizeof(head))) < 0 && errno == EAGAIN && tries < 3; tries++) {
+ }
+ if (n != (ssize_t)sizeof(head) || memcmp(head.magic, REDWOOD_CAMERA_MAGIC, 8) != 0) {
+ perror("camera_test: the first frame's header");
+ return 1;
+ }
+ printf("camera_test: the first frame after %.0f ms: %ux%u, stride %u, Bayer %u, black %u, %u lines of %u ns a frame "
+ "(%.2f frames/s at the shortest), exposure %u lines, gain %u (%u is 1x)\n", ms_since(started), head.width, head.height,
+ head.stride, head.bayer, head.black, head.frame_lines_min, head.line_ns, 1e9 / ((double)head.frame_lines_min * head.line_ns),
+ head.exposure_lines, head.gain, head.gain_unity);
+ bytes = sizeof(head) + (size_t)head.stride * head.height;
+ f = malloc(bytes);
+ isp_init(&isp);
+ while (got < frames && failures < 5) {
+ struct redwood_camera_command c;
+ uint64_t t0 = mach_absolute_time();
+
+ n = read(device, f, bytes);
+ if (n != (ssize_t)bytes) {
+ printf("camera_test: a read gave %zd of %zu bytes (%s)\n", n, bytes, n < 0 ? strerror(errno) : "short");
+ failures++;
+ continue;
+ }
+ double read_ms = ms_since(t0);
+ const uint8_t *raw = (const uint8_t *)f + f->header_bytes;
+
+ got++;
+ first_seq = first_seq ? first_seq : f->sequence;
+ isp_measure(f, raw, &s);
+ isp_awb(&isp, &s);
+ if (ae && isp_ae(&isp, f, &s, &c) && write(device, &c, sizeof(c)) != (ssize_t)sizeof(c)) {
+ perror("camera_test: the exposure");
+ }
+ if (got <= 3 || got % 15 == 0) {
+ printf("camera_test: frame %llu (%d read): %.1f ms after the last, read in %.1f ms; exposure %.2f ms (%u lines), gain "
+ "%.2fx, digital %.2fx, frame %.1f ms; R %.1f G %.1f B %.1f above black, 1 %% above %.0f; wb %.2f %.2f\n",
+ f->sequence, got, previous ? ticks_ms(f->time - previous) : 0.0, read_ms,
+ f->exposure_lines * (double)f->line_ns / 1e6, f->exposure_lines, (double)f->gain / f->gain_unity, isp.digital,
+ f->frame_lines * (double)f->line_ns / 1e6, s.mean[0], s.mean[1], s.mean[2], s.bright, isp.wb[0], isp.wb[2]);
+ }
+ previous = f->time;
+ }
+ if (got == 0) {
+ return 1;
+ }
+ printf("camera_test: %d frames of %llu (%llu skipped) in %.1f s\n", got, f->sequence - first_seq + 1,
+ f->sequence - first_seq + 1 - got, ms_since(started) / 1000);
+
+ if (keep_raw) {
+ struct redwood_camera_command *k = (struct redwood_camera_command *)((uint8_t *)f + f->header_bytes) - 1;
+ uint32_t frame_bytes = f->stride * f->height, w = f->width, h = f->height, stride = f->stride;
+
+ /* (the command goes over the end of the header, just before the frame's bytes) */
+ memset(k, 0, sizeof(*k));
+ k->command = REDWOOD_CAMERA_KEEP;
+ k->bytes = frame_bytes;
+ k->a = w;
+ k->b = h;
+ k->c = stride;
+ k->d = 1;
+ if (write(device, k, sizeof(*k) + frame_bytes) != (ssize_t)(sizeof(*k) + frame_bytes)) {
+ perror("camera_test: the frame for the host");
+ } else {
+ printf("camera_test: the frame (RAW10) is the host's (xl camera)\n");
+ }
+ close(device);
+ return 0;
+ }
+ /* the last one, as a picture for the host: one pixel per cell, NV12 */
+ uint32_t w = f->width / 2, h = f->height / 2;
+ size_t picture = (size_t)w * h * 3 / 2;
+ struct redwood_camera_command *keep = malloc(sizeof(*keep) + picture);
+ uint8_t *y = (uint8_t *)(keep + 1);
+ uint64_t t0 = mach_absolute_time();
+
+ isp_render_nv12(&isp, f, (const uint8_t *)f + f->header_bytes, y, w, y + (size_t)w * h, w, w, h, 0, h);
+ printf("camera_test: the picture (%ux%u NV12) made in %.1f ms\n", w, h, ms_since(t0));
+ memset(keep, 0, sizeof(*keep));
+ keep->command = REDWOOD_CAMERA_KEEP;
+ keep->bytes = (uint32_t)picture;
+ keep->a = w;
+ keep->b = h;
+ keep->c = w;
+ keep->d = 2;
+ if (write(device, keep, sizeof(*keep) + picture) != (ssize_t)(sizeof(*keep) + picture)) {
+ perror("camera_test: the picture for the host");
+ } else {
+ printf("camera_test: the picture is the host's (xl camera)\n");
+ }
+ close(device);
+ return 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ setvbuf(stdout, NULL, _IOLBF, 0);
+ if (argc >= 2 && strcmp(argv[1], "raw") == 0) {
+ bool ae = true, keep_raw = false;
+
+ for (int i = 3; i < argc; i++) {
+ ae = ae && strcmp(argv[i], "noae") != 0;
+ keep_raw = keep_raw || strcmp(argv[i], "keepraw") == 0;
+ }
+ return raw(argc >= 3 ? atoi(argv[2]) : 150, ae, keep_raw);
+ }
+ fprintf(stderr, "usage: camera_test raw [FRAMES] [noae] [keepraw]\n");
+ return 2;
+}
diff --git a/userland/src/redwood_camera.h b/userland/src/redwood_camera.h
new file mode 100644
index 0000000..9056f78
--- /dev/null
+++ b/userland/src/redwood_camera.h
@@ -0,0 +1,56 @@
+/*
+ * /dev/redwood-camera: the phone's wide camera for iOS (boot-arg cam=5; the kernel's bsd/dev/redwood_camera.c,
+ * whose bsd/sys/redwood_camera.h this is a copy of).
+ *
+ * open() the first one powers the sensor up and starts its frames (the sensor's mode: boot-arg
+ * cam_mode, else the module file's 4000x3000 one); the last close puts everything down
+ * again, and so does a second without a read.
+ * read() waits (at most a second) for the newest frame not read yet: a struct
+ * redwood_camera_frame, then as many of the frame's bytes as the buffer has room for.
+ * A buffer of the header's size learns the frame's size and nothing else is copied.
+ * EIO when the camera has had a fault: it stays off for the rest of the run.
+ * write() commands: a struct redwood_camera_command, then what it says follows.
+ */
+#ifndef _SYS_REDWOOD_CAMERA_H_
+#define _SYS_REDWOOD_CAMERA_H_
+
+#include <stdint.h>
+
+#define REDWOOD_CAMERA_DEVICE "/dev/redwood-camera"
+#define REDWOOD_CAMERA_MAGIC "RWFRAME1"
+
+struct redwood_camera_frame {
+ char magic[8]; /* REDWOOD_CAMERA_MAGIC */
+ uint32_t header_bytes; /* this structure's size: the frame's bytes follow */
+ uint32_t width, height; /* pixels */
+ uint32_t stride; /* bytes from one line to the next */
+ uint32_t format; /* 1: MIPI RAW10, four pixels in five bytes */
+ uint32_t bayer; /* the order of a 2x2 cell: 0 RGGB, 1 GRBG, 2 GBRG, 3 BGGR */
+ uint32_t black; /* the black level, in 10-bit steps */
+ uint64_t sequence; /* the frame's number since the sensor started, from 1 */
+ uint64_t time; /* when the frame was done, in mach_absolute_time()'s units */
+ uint32_t exposure_lines; /* the exposure it was taken with, in lines ... */
+ uint32_t line_ns; /* ... of this many nanoseconds */
+ uint32_t gain; /* the sensor's analog gain register ... */
+ uint32_t gain_unity; /* ... which is this for 1x */
+ uint32_t gain_max; /* the most it may be given */
+ uint32_t frame_lines; /* the frame's length in lines (frames a second: 1e9 / (frame_lines * line_ns)) */
+ uint32_t frame_lines_min; /* the mode's own length: the shortest frame */
+ uint32_t frame_lines_max; /* the longest frame it may be given */
+ uint32_t margin; /* exposure_lines is at most frame_lines - margin */
+ uint32_t reserved[7];
+};
+
+enum {
+ REDWOOD_CAMERA_EXPOSURE = 1, /* a: lines, b: gain, c: frame lines (0: the shortest that holds the exposure) */
+ REDWOOD_CAMERA_KEEP = 2, /* a picture for the host: a width, b height, c stride, d format (1 the frame's RAW10, 2 NV12,
+ * 3 BGRA); bytes follow */
+};
+
+struct redwood_camera_command {
+ uint32_t command;
+ uint32_t bytes; /* of what follows this structure */
+ uint32_t a, b, c, d;
+};
+
+#endif /* _SYS_REDWOOD_CAMERA_H_ */
diff --git a/xnu/files/bsd/dev/redwood_camera.c b/xnu/files/bsd/dev/redwood_camera.c
index eb46cf1..b5444d7 100644
--- a/xnu/files/bsd/dev/redwood_camera.c
+++ b/xnu/files/bsd/dev/redwood_camera.c
@@ -68,7 +68,11 @@
#include <pexpert/pexpert.h>
#include <vm/memory_types.h>
#include <sys/systm.h>
+#include <sys/conf.h>
+#include <sys/uio.h>
+#include <miscfs/devfs/devfs.h>
#include <sys/redwood_audio.h>
+#include <sys/redwood_camera.h>
#include <sys/redwood_input.h>
extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
@@ -2023,6 +2027,11 @@ smmu_down(void)
#define CSID_TPG_COMMON_GEN_CFG 0x648
#define TPG_VC 0xa
#define RAW10_DT 0x2b
+/*
+ * A line's bytes as the write master lays them out: RAW10 (four pixels in five bytes), the line
+ * rounded up to 16 bytes, the bus's width (a 4000-pixel line takes 5008, not 5000).
+ */
+#define RAW10_STRIDE(width) (((width) * 10 / 8 + 15) & ~15u)
#define IFE_HW_VERSION 0x0000
#define IFE_GLOBAL_RESET 0x0018
@@ -2190,7 +2199,7 @@ tpg_start(void)
/* cam_vfe_top_reset(), cam_vfe_bus_init_hw(), cam_vfe_bus_start_wm() and update_wm() for RDI 0 in frame mode. */
static bool
-ife_config(uint64_t address, uint32_t frame_bytes)
+ife_config(uint64_t address, uint32_t frame_bytes, uint32_t frame_inc)
{
blk_put(ife, "IFE", IFE_IRQ_MASK0, 1u << 31, false);
blk_put(ife, "IFE", IFE_GLOBAL_RESET, 0x3f9f, false);
@@ -2210,7 +2219,7 @@ ife_config(uint64_t address, uint32_t frame_bytes)
!blk_put(ife, "IFE", WM0_STRIDE, 0xff01, true) || !blk_put(ife, "IFE", WM0_FRAMEDROP_PERIOD, 0, true) ||
!blk_put(ife, "IFE", WM0_FRAMEDROP_PATTERN, 1, true) || !blk_put(ife, "IFE", WM0_IRQ_SUB_PERIOD, 0, true) ||
!blk_put(ife, "IFE", WM0_IRQ_SUB_PATTERN, 1, true) || !blk_put(ife, "IFE", BUS_IRQ_MASK1, 1, false) ||
- !blk_put(ife, "IFE", WM0_IMAGE_ADDR, (uint32_t)address, false) || !blk_put(ife, "IFE", WM0_FRAME_INC, frame_bytes, true) ||
+ !blk_put(ife, "IFE", WM0_IMAGE_ADDR, (uint32_t)address, false) || !blk_put(ife, "IFE", WM0_FRAME_INC, frame_inc, true) ||
!blk_put(ife, "IFE", WM0_CFG, 3, true)) {
return false;
}
@@ -2293,7 +2302,7 @@ capture_tpg(void)
struct cam_header *h;
if (!frames_alloc(width, height, stride, 0) || !titan_up() || !smmu_up() || !csid_reset() ||
- !csid_config(-1, 4, 0x3210, TPG_VC, width, height, false) || !ife_config(FRAME_ADDRESSES + CAM_HEADER_BYTES, stride * height)) {
+ !csid_config(-1, 4, 0x3210, TPG_VC, width, height, false) || !ife_config(FRAME_ADDRESSES + CAM_HEADER_BYTES, stride * height, stride * height)) {
titan_down();
return;
}
@@ -2654,7 +2663,7 @@ capture_sensor(void)
snprintf(res, sizeof(res), "res%u", mode_n);
width = mode->width;
height = mode->height;
- stride = width * 10 / 8;
+ stride = RAW10_STRIDE(width);
rate = (uint64_t)mode->pixel_clock * 10 / (mode->lanes ? mode->lanes : 1);
(void)PE_parse_boot_argn("cam_frames", &wanted, sizeof(wanted));
wanted = wanted < 1 ? 1 : wanted > 300 ? 300 : wanted;
@@ -2673,7 +2682,7 @@ capture_sensor(void)
if (!power_up() || !healthy() || !read_chip_id() || !sensor_table("init") || !sensor_table(res) || !healthy() ||
!titan_up() || !smmu_up() || !csid_reset() ||
!csid_config((int)hw->csiphy, mode->lanes, ctab->lane_assign & ((1u << (4 * mode->lanes)) - 1), 0, width, height,
- mode->cphy != 0) || !ife_config(FRAME_ADDRESSES + CAM_HEADER_BYTES, stride * height) ||
+ mode->cphy != 0) || !ife_config(FRAME_ADDRESSES + CAM_HEADER_BYTES, stride * height, stride * height) ||
!csiphy_up(mode->lanes, mode->cphy != 0, ctab->lane_assign, settle, rate)) {
csiphy_down();
titan_down();
@@ -2732,6 +2741,565 @@ capture_sensor(void)
}
}
+/* ---- cam=5: the wide camera for iOS (/dev/redwood-camera) ------------------------------------------- */
+
+/*
+ * The sensor's frames for a program (iOS's camera stack in mediaserverd, libredwood-media.dylib), for
+ * as long as it holds /dev/redwood-camera open (sys/redwood_camera.h): the sensor powered up and
+ * streaming at the first read after the open, everything down again at the last close, after
+ * IDLE_MS without a read, and on any fault (and then for the rest of the run). The sequence is
+ * cam=4's. The frames go into three places in turn (kernel memory, mapped page by page through the
+ * SMMU): one the IFE writes, one a read may be copying, one ready.
+ *
+ * Which place the IFE writes: when one is done, the next place's address goes to the write master,
+ * which takes it at the next start of frame (the register update, latched at RDI 0's SOF). Polled
+ * every millisecond: a frame done and the next frame's SOF seen in the same look mean the address
+ * came too late, and the frame just done is being written over (the write master's frame increment
+ * is 0 here: without a new address it writes the next frame where the last went, not past it) --
+ * it is not given out, and the next one done there is. The exposure the program asks for is written between two frames, after
+ * the address, in the sensor's group hold; it counts from the second frame after.
+ *
+ * A picture for the host (REDWOOD_CAMERA_KEEP: what the program made of a frame) goes into one
+ * piece of memory the loader hands over after the run, as cam=3 and cam=4's frames do (xl camera).
+ */
+#define RING 3
+#define PLACE_SPARE (256u << 10) /* room after each frame: some come longer than the mode's lines */
+#define IDLE_MS 1000
+#define FRAME_TIMEOUT_MS 1500
+#define EXPOSURE_MARGIN 40
+#define GAIN_UNITY 32 /* the S5KHM2SD's 0x0204: 32 is 1x (cam=4) */
+#define GAIN_MAX 0x800
+#define FRAME_LINES_MAX 0xfff0
+#define RDI0_SOF (1u << 27) /* IFE_IRQ_STATUS0 (cam_vfe_lite16x.h: sof_irq_mask of RDI 0) */
+#define WM0_DONE 1u /* BUS_IRQ_STATUS1 */
+
+enum { PLACE_FREE, PLACE_WRITING, PLACE_READY, PLACE_READING };
+
+static LCK_GRP_DECLARE(ios_lck_grp, "redwood-camera");
+static LCK_MTX_DECLARE(ios_lock, &ios_lck_grp);
+static struct {
+ uint8_t state;
+ uint64_t sequence, time;
+ uint32_t exposure_lines, gain, frame_lines;
+} place[RING];
+static vm_offset_t ring;
+static uint64_t ring_bytes, ring_tables_bytes, ring_place_bytes;
+static uint32_t ring_frame_bytes, ios_odd_frames;
+static const struct ctab_mode *ios_mode;
+static uint32_t ios_mode_n, ios_line_ns;
+static volatile bool ios_open, ios_streaming, ios_wanted; /* open; frames coming; a read wants them */
+static uint64_t ios_last_read, ios_given, ios_frames_done, ios_writes_late;
+static struct { uint32_t lines, gain, frame_lines; bool pending; } ios_ask;
+static struct { uint32_t lines, gain, frame_lines; uint64_t from; } ios_now, ios_next;
+static vm_offset_t keep;
+static uint64_t keep_bytes;
+
+static uint64_t
+ios_ms(void)
+{
+ uint64_t ns;
+
+ absolutetime_to_nanoseconds(mach_absolute_time(), &ns);
+ return ns / NSEC_PER_MSEC;
+}
+
+/* exposure_lines, gain, frame_lines within what the sensor takes (frame_lines 0: the shortest that holds the exposure) */
+static void
+exposure_limits(uint32_t *lines, uint32_t *gain, uint32_t *frame_lines)
+{
+ uint32_t shortest = ios_mode->frame_length;
+
+ *gain = *gain < GAIN_UNITY ? GAIN_UNITY : *gain > GAIN_MAX ? GAIN_MAX : *gain;
+ *lines = *lines < 4 ? 4 : *lines > FRAME_LINES_MAX - EXPOSURE_MARGIN ? FRAME_LINES_MAX - EXPOSURE_MARGIN : *lines;
+ if (*frame_lines == 0) {
+ *frame_lines = *lines + EXPOSURE_MARGIN > shortest ? *lines + EXPOSURE_MARGIN : shortest;
+ }
+ *frame_lines = *frame_lines < shortest ? shortest : *frame_lines > FRAME_LINES_MAX ? FRAME_LINES_MAX : *frame_lines;
+ if (*lines > *frame_lines - EXPOSURE_MARGIN) {
+ *lines = *frame_lines - EXPOSURE_MARGIN;
+ }
+}
+
+static bool
+exposure_write(uint32_t lines, uint32_t gain, uint32_t frame_lines)
+{
+ if (!sensor_table("holdon") || !sensor_write(0x0340, (uint16_t)frame_lines, true) || !sensor_write(0x0202, (uint16_t)lines, true) ||
+ !sensor_write(0x0204, (uint16_t)gain, true) || !sensor_table("holdoff")) {
+ give_up("a sensor write nobody acknowledged");
+ return false;
+ }
+ return true;
+}
+
+static void
+ring_free(void)
+{
+ if (page_tables != 0) {
+ kmem_free(kernel_map, page_tables, ring_tables_bytes);
+ page_tables = 0;
+ }
+ if (ring != 0) {
+ kmem_free(kernel_map, ring, ring_bytes);
+ ring = 0;
+ }
+ frames = 0;
+ frames_bytes = 0;
+}
+
+static bool
+ring_alloc(uint32_t frame_bytes)
+{
+ ring_frame_bytes = frame_bytes;
+ ring_place_bytes = round_page(frame_bytes) + PLACE_SPARE;
+ ring_bytes = RING * ring_place_bytes;
+ if (kmem_alloc(kernel_map, &ring, ring_bytes, KMA_KOBJECT | KMA_ZERO | KMA_DATA, VM_KERN_MEMORY_IOKIT) != KERN_SUCCESS) {
+ say("camera: no memory for %u frames (%llu KB)\n", RING, ring_bytes >> 10);
+ ring = 0;
+ return false;
+ }
+ for (vm_offset_t line = ring; line < ring + ring_bytes; line += 64) {
+ __asm__ volatile ("dc civac, %0" : : "r" (line));
+ }
+ __asm__ volatile ("dsb sy");
+ frames = ring; /* (what smmu_up() maps) */
+ frames_bytes = ring_bytes;
+ ring_tables_bytes = (2 + ((ring_bytes + 0x1fffff) >> 21)) * 4096;
+ return true;
+}
+
+/* The session's end, whatever ended it: the sensor's "off", the blocks, the supplies, the memory. */
+static void
+ios_stop(const char *why)
+{
+ lck_mtx_lock(&ios_lock);
+ ios_streaming = false;
+ for (int i = 0; i < RING; i++) {
+ place[i].state = PLACE_FREE;
+ }
+ lck_mtx_unlock(&ios_lock);
+ wakeup(&ios_frames_done);
+ if (!broken) {
+ (void)sensor_table("off");
+ }
+ show_paths("at the end");
+ smmu_faults();
+ csiphy_down();
+ titan_down();
+ power_down();
+ ring_free();
+ say("camera: the frames for iOS stopped (%s): %llu done, %llu given, %llu written over\n", why, ios_frames_done, ios_given,
+ ios_writes_late);
+}
+
+static const char *ios_res(void);
+
+static bool
+ios_start(void)
+{
+ uint32_t lines, gain, frame_lines;
+
+ ios_frames_done = ios_given = ios_writes_late = 0;
+ ios_odd_frames = 0;
+ if (!ring_alloc(RAW10_STRIDE(ios_mode->width) * ios_mode->height)) {
+ return false;
+ }
+ if (!power_up() || !healthy() || !read_chip_id() || !sensor_table("init") || !sensor_table(ios_res()) || !healthy() ||
+ !titan_up() || !smmu_up() || !csid_reset() ||
+ !csid_config((int)hw->csiphy, ios_mode->lanes, ctab->lane_assign & ((1u << (4 * ios_mode->lanes)) - 1), 0, ios_mode->width,
+ ios_mode->height, ios_mode->cphy != 0) || !ife_config(FRAME_ADDRESSES, ring_frame_bytes, 0) ||
+ !csiphy_up(ios_mode->lanes, ios_mode->cphy != 0, ctab->lane_assign, ios_mode->settle,
+ (uint64_t)ios_mode->pixel_clock * 10 / ios_mode->lanes)) {
+ return false;
+ }
+ lck_mtx_lock(&ios_lock);
+ for (int i = 0; i < RING; i++) {
+ place[i].state = PLACE_FREE;
+ }
+ place[0].state = PLACE_WRITING;
+ lines = ios_ask.lines;
+ gain = ios_ask.gain;
+ frame_lines = ios_ask.frame_lines;
+ ios_ask.pending = false;
+ lck_mtx_unlock(&ios_lock);
+ exposure_limits(&lines, &gain, &frame_lines);
+ if (!sensor_table("on") || !exposure_write(lines, gain, frame_lines)) {
+ return false;
+ }
+ ios_now.lines = ios_next.lines = lines;
+ ios_now.gain = ios_next.gain = gain;
+ ios_now.frame_lines = ios_next.frame_lines = frame_lines;
+ ios_next.from = 0;
+ say("camera: the frames for iOS: mode %u, %ux%u, %u lines of %u ns a frame at the shortest; exposure %u lines, gain %#x, "
+ "frame %u lines\n", ios_mode_n, ios_mode->width, ios_mode->height, ios_mode->frame_length, ios_line_ns, lines, gain, frame_lines);
+ return true;
+}
+
+static void
+ios_session(void)
+{
+ int writing = 0, next = -1;
+ uint64_t last_frame;
+
+ if (!ios_start()) {
+ give_up("the camera did not start");
+ ios_stop("it did not start");
+ return;
+ }
+ last_frame = ios_ms();
+ blk_put(ife, "IFE", IFE_IRQ_CLEAR0, 0xffffffff, false);
+ blk_put(ife, "IFE", IFE_IRQ_GLOBAL_CLEAR, 1, false);
+ lck_mtx_lock(&ios_lock);
+ ios_streaming = true;
+ ios_last_read = ios_ms();
+ lck_mtx_unlock(&ios_lock);
+ while (!broken && ios_open) {
+ uint32_t top, bus;
+ uint64_t now;
+
+ wait_ms(1);
+ now = ios_ms();
+ top = rd(ife + IFE_IRQ_STATUS0);
+ bus = rd(ife + BUS_IRQ_STATUS1);
+ if (!(top & RDI0_SOF) && !(bus & WM0_DONE)) {
+ if (now - last_frame > FRAME_TIMEOUT_MS) {
+ show_paths("no frame");
+ give_up("no frame for 1.5 s");
+ break;
+ }
+ if (now - ios_last_read > IDLE_MS) {
+ break;
+ }
+ continue;
+ }
+ blk_put(ife, "IFE", IFE_IRQ_CLEAR0, top & RDI0_SOF, false);
+ blk_put(ife, "IFE", IFE_IRQ_GLOBAL_CLEAR, 1, false);
+ blk_put(ife, "IFE", BUS_IRQ_CLEAR1, bus & WM0_DONE, false);
+ blk_put(ife, "IFE", BUS_IRQ_GLOBAL_CLEAR, 1, false);
+ lck_mtx_lock(&ios_lock);
+ if (bus & WM0_DONE) {
+ uint32_t ping = rd(csid + CSID_RDI0_BYTES_PING), pong = rd(csid + CSID_RDI0_BYTES_PONG);
+ uint32_t data = ios_mode->width * 10 / 8 * ios_mode->height;
+
+ last_frame = now;
+ ios_frames_done++;
+ if ((ping != data || (pong != data && ios_frames_done > 1)) && ios_odd_frames++ < 8) {
+ say("camera: frame %llu: the CSID counted %u and %u bytes (the mode's frame is %u)\n", ios_frames_done, ping, pong,
+ data);
+ }
+ if (ios_frames_done >= ios_next.from && ios_next.from != 0) {
+ ios_now = ios_next;
+ ios_next.from = 0;
+ }
+ place[writing].state = PLACE_READY;
+ place[writing].sequence = ios_frames_done;
+ place[writing].time = mach_absolute_time();
+ place[writing].exposure_lines = ios_now.lines;
+ place[writing].gain = ios_now.gain;
+ place[writing].frame_lines = ios_now.frame_lines;
+ }
+ if (top & RDI0_SOF) {
+ if (next >= 0) {
+ writing = next;
+ next = -1;
+ } else if (bus & WM0_DONE) {
+ ios_writes_late++; /* the address came after this SOF: the frame just done is written over */
+ }
+ place[writing].state = PLACE_WRITING;
+ }
+ if ((bus & WM0_DONE) && next < 0) {
+ for (int i = 0; i < RING; i++) {
+ int c = (writing + 1 + i) % RING;
+
+ if (c != writing && place[c].state != PLACE_READING && (next < 0 || place[c].sequence < place[next].sequence)) {
+ next = c;
+ }
+ }
+ if (next >= 0) {
+ blk_put(ife, "IFE", WM0_IMAGE_ADDR, (uint32_t)(FRAME_ADDRESSES + (uint64_t)next * ring_place_bytes), false);
+ blk_put(ife, "IFE", IFE_REG_UPDATE, 0x2, false);
+ }
+ }
+ bool ask = (bus & WM0_DONE) && ios_ask.pending;
+ uint32_t lines = ios_ask.lines, gain = ios_ask.gain, frame_lines = ios_ask.frame_lines;
+
+ ios_ask.pending = ios_ask.pending && !ask;
+ lck_mtx_unlock(&ios_lock);
+ if (bus & WM0_DONE) {
+ wakeup(&ios_frames_done);
+ }
+ if (ask) {
+ exposure_limits(&lines, &gain, &frame_lines);
+ if (lines != ios_now.lines || gain != ios_now.gain || frame_lines != ios_now.frame_lines) {
+ if (!exposure_write(lines, gain, frame_lines)) {
+ break;
+ }
+ ios_next.lines = lines;
+ ios_next.gain = gain;
+ ios_next.frame_lines = frame_lines;
+ ios_next.from = ios_frames_done + 2;
+ }
+ }
+ if ((bus & WM0_DONE) && ios_frames_done % 30 == 0) {
+ uint32_t fsr = rd(smmu_context + SMMU_CB_FSR);
+
+ if (!healthy()) {
+ break;
+ }
+ if (fsr & SMMU_FSR_ALL) {
+ smmu_faults();
+ give_up("the SMMU refused the IFE");
+ break;
+ }
+ if (ios_frames_done == 30 || ios_frames_done % 900 == 0) {
+ show_paths("streaming");
+ }
+ }
+ }
+ ios_stop(broken ? "a fault" : !ios_open ? "closed" : "nobody reads");
+}
+
+static const char *
+ios_res(void)
+{
+ static char res[8];
+
+ snprintf(res, sizeof(res), "res%u", ios_mode_n);
+ return res;
+}
+
+static int
+camdev_open(__unused dev_t dev, __unused int flags, __unused int type, __unused struct proc *p)
+{
+ if (broken) {
+ return EIO;
+ }
+ ios_open = true;
+ return 0;
+}
+
+/* (the last close) */
+static int
+camdev_close(__unused dev_t dev, __unused int flags, __unused int type, __unused struct proc *p)
+{
+ ios_open = false;
+ ios_wanted = false;
+ wakeup(&ios_open);
+ return 0;
+}
+
+static int
+camdev_read(__unused dev_t dev, struct uio *uio, __unused int ioflag)
+{
+ struct redwood_camera_frame f;
+ uint64_t since = ios_ms();
+ int b = -1, error = 0;
+
+ lck_mtx_lock(&ios_lock);
+ ios_last_read = ios_ms();
+ if (!ios_streaming && !ios_wanted) {
+ ios_wanted = true;
+ wakeup(&ios_open);
+ }
+ for (;;) {
+ if (broken) {
+ lck_mtx_unlock(&ios_lock);
+ return EIO;
+ }
+ b = -1;
+ for (int i = 0; i < RING; i++) {
+ if (place[i].state == PLACE_READY && place[i].sequence > ios_given && (b < 0 || place[i].sequence > place[b].sequence)) {
+ b = i;
+ }
+ }
+ if (b >= 0) {
+ break;
+ }
+ if (ios_ms() - since > (ios_streaming ? 3000u : 15000u)) { /* (the sensor's tables take seconds) */
+ lck_mtx_unlock(&ios_lock);
+ return EAGAIN;
+ }
+ struct timespec ts = { 0, 100 * NSEC_PER_MSEC };
+ error = msleep(&ios_frames_done, &ios_lock, PZERO | PCATCH, "redwood-camera", &ts);
+ if (error != 0 && error != EWOULDBLOCK) {
+ lck_mtx_unlock(&ios_lock);
+ return error;
+ }
+ ios_last_read = ios_ms();
+ }
+ place[b].state = PLACE_READING;
+ ios_given = place[b].sequence;
+ bzero(&f, sizeof(f));
+ memcpy(f.magic, REDWOOD_CAMERA_MAGIC, 8);
+ f.header_bytes = sizeof(f);
+ f.width = ios_mode->width;
+ f.height = ios_mode->height;
+ f.stride = RAW10_STRIDE(ios_mode->width);
+ f.format = 1;
+ f.bayer = hw->bayer;
+ f.black = 64;
+ f.sequence = place[b].sequence;
+ f.time = place[b].time;
+ f.exposure_lines = place[b].exposure_lines;
+ f.line_ns = ios_line_ns;
+ f.gain = place[b].gain;
+ f.gain_unity = GAIN_UNITY;
+ f.gain_max = GAIN_MAX;
+ f.frame_lines = place[b].frame_lines;
+ f.frame_lines_min = ios_mode->frame_length;
+ f.frame_lines_max = FRAME_LINES_MAX;
+ f.margin = EXPOSURE_MARGIN;
+ lck_mtx_unlock(&ios_lock);
+
+ error = uiomove((caddr_t)&f, (int)MIN(sizeof(f), (size_t)uio_resid(uio)), uio);
+ if (error == 0 && uio_resid(uio) > 0) {
+ vm_offset_t at = ring + (uint64_t)b * ring_place_bytes;
+ uint32_t n = (uint32_t)MIN((uint64_t)ring_frame_bytes, (uint64_t)uio_resid(uio));
+
+ uint64_t t0 = mach_absolute_time(), t1, t2;
+
+ /* (what the IFE wrote went past the processor's caches) */
+ for (vm_offset_t line = at & ~63ul; line < at + n; line += 64) {
+ __asm__ volatile ("dc civac, %0" : : "r" (line));
+ }
+ __asm__ volatile ("dsb sy");
+ t1 = mach_absolute_time();
+ error = uiomove((caddr_t)at, (int)n, uio);
+ t2 = mach_absolute_time();
+ if (f.sequence <= 3 || f.sequence % 300 == 0) {
+ uint64_t a, b;
+
+ absolutetime_to_nanoseconds(t1 - t0, &a);
+ absolutetime_to_nanoseconds(t2 - t1, &b);
+ say("camera: frame %llu read: %u bytes, the caches' lines forgotten in %llu us, copied in %llu us\n", f.sequence, n,
+ a / 1000, b / 1000);
+ }
+ }
+ lck_mtx_lock(&ios_lock);
+ if (place[b].state == PLACE_READING) {
+ place[b].state = PLACE_READY;
+ }
+ ios_last_read = ios_ms();
+ lck_mtx_unlock(&ios_lock);
+ return error;
+}
+
+/* REDWOOD_CAMERA_KEEP: a picture for the host, in one piece of memory the loader hands over. */
+static int
+keep_picture(const struct redwood_camera_command *c, struct uio *uio)
+{
+ struct cam_header *h;
+ uint64_t want = round_page(CAM_HEADER_BYTES + (uint64_t)c->bytes);
+
+ if (c->bytes == 0 || c->d < 1 || c->d > 3 || (uint64_t)c->c * c->b > (uint64_t)c->bytes * 2) {
+ return EINVAL;
+ }
+ if (keep == 0 || keep_bytes < want) {
+ return ENOSPC; /* (the piece is made when the device is, while there is memory in one piece) */
+ }
+ h = (struct cam_header *)keep;
+ bzero(h, CAM_HEADER_BYTES);
+ memcpy(h->magic, "RWCAM001", 8);
+ h->width = c->a;
+ h->height = c->b;
+ h->stride = c->c;
+ h->format = c->d;
+ h->bayer = c->d == 1 ? hw->bayer : 0;
+ h->frame_bytes = c->bytes;
+ h->source = 2;
+ strlcpy(h->sensor, "iOS", sizeof(h->sensor));
+ int error = uiomove((caddr_t)(keep + CAM_HEADER_BYTES), (int)MIN((uint64_t)c->bytes, (uint64_t)uio_resid(uio)), uio);
+ h->frames = error == 0 ? 1 : 0;
+ for (vm_offset_t line = keep; line < keep + want; line += 64) {
+ __asm__ volatile ("dc cvac, %0" : : "r" (line));
+ }
+ __asm__ volatile ("dsb sy");
+ loader_recording[0] = kvtophys(keep);
+ loader_recording[1] = want;
+ loader_recording[2] = (uint64_t)keep;
+ say("camera: a picture from iOS for the host: %ux%u, format %u, %u bytes\n", c->a, c->b, c->d, c->bytes);
+ return error;
+}
+
+static int
+camdev_write(__unused dev_t dev, struct uio *uio, __unused int ioflag)
+{
+ struct redwood_camera_command c;
+ int error;
+
+ if (uio_resid(uio) < (user_ssize_t)sizeof(c) || (error = uiomove((caddr_t)&c, sizeof(c), uio)) != 0) {
+ return EINVAL;
+ }
+ if (c.command == REDWOOD_CAMERA_EXPOSURE) {
+ lck_mtx_lock(&ios_lock);
+ ios_ask.lines = c.a;
+ ios_ask.gain = c.b;
+ ios_ask.frame_lines = c.c;
+ ios_ask.pending = true;
+ lck_mtx_unlock(&ios_lock);
+ return 0;
+ }
+ if (c.command == REDWOOD_CAMERA_KEEP) {
+ return keep_picture(&c, uio);
+ }
+ return EINVAL;
+}
+
+static const struct cdevsw camdev_cdevsw = {
+ .d_open = camdev_open, .d_close = camdev_close, .d_read = camdev_read, .d_write = camdev_write,
+ .d_ioctl = eno_ioctl, .d_stop = eno_stop, .d_reset = eno_reset, .d_select = eno_select,
+ .d_mmap = eno_mmap, .d_strategy = eno_strat, .d_type = 0
+};
+
+/* cam=5: the device, and a session whenever a read wants frames, until a fault. */
+static void
+serve_ios(void)
+{
+ int major;
+ uint32_t mode_n = 1;
+
+ if (!ctab_load()) {
+ return;
+ }
+ (void)PE_parse_boot_argn("cam_mode", &mode_n, sizeof(mode_n));
+ if (mode_n >= ctab->modes) {
+ mode_n = 0;
+ }
+ ios_mode_n = mode_n;
+ ios_mode = &ctab_modes[mode_n];
+ if (ios_mode->lanes < 1 || ios_mode->lanes > (ios_mode->cphy ? 3u : 4u) || ios_mode->data_type != RAW10_DT ||
+ ios_mode->width % 4 != 0 || ios_mode->fps_milli == 0 || ios_mode->frame_length == 0) {
+ say("camera: mode %u is not what this is written for\n", mode_n);
+ return;
+ }
+ ios_line_ns = (uint32_t)(1000000000000ull / ((uint64_t)ios_mode->fps_milli * ios_mode->frame_length));
+ /* the first exposure, until the program asks for its own: boot-args as cam=4's, else a room's */
+ ios_ask.lines = ios_mode->frame_length - EXPOSURE_MARGIN;
+ ios_ask.gain = 8 * GAIN_UNITY;
+ ios_ask.frame_lines = 0;
+ (void)PE_parse_boot_argn("cam_shutter", &ios_ask.lines, sizeof(ios_ask.lines));
+ (void)PE_parse_boot_argn("cam_gain", &ios_ask.gain, sizeof(ios_ask.gain));
+ major = cdevsw_add(-1, &camdev_cdevsw);
+ if (major < 0 || devfs_make_node(makedev(major, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666, "redwood-camera") == NULL) {
+ say("camera: /dev/redwood-camera cannot be made\n");
+ return;
+ }
+ say("camera: /dev/redwood-camera: the %s camera's frames for iOS (mode %u: %ux%u, %u.%03u frames/s at the most), whenever it "
+ "is read\n", hw->name, mode_n, ios_mode->width, ios_mode->height, ios_mode->fps_milli / 1000, ios_mode->fps_milli % 1000);
+ while (!broken) {
+ lck_mtx_lock(&ios_lock);
+ while (!broken && !(ios_open && ios_wanted)) {
+ (void)msleep(&ios_open, &ios_lock, PZERO, "redwood-camera-idle", NULL);
+ }
+ ios_wanted = false;
+ lck_mtx_unlock(&ios_lock);
+ if (broken) {
+ break;
+ }
+ ios_session();
+ }
+ say("camera: /dev/redwood-camera: no more frames in this run\n");
+}
+
/* ---- the look, and the thread ----------------------------------------------------------------------- */
static void
@@ -2792,13 +3360,14 @@ camera_thread(__unused void *parameter, __unused wait_result_t result)
arb_core = ml_io_map(ARB_CORE_PHYS, ARB_CORE_SIZE);
arb_cnfg = ml_io_map(ARB_CNFG_PHYS, ARB_CNFG_SIZE);
arb_observer = ml_io_map(ARB_OBSERVER_PHYS, ARB_OBSERVER_SIZE);
- if (PE_parse_boot_arg_str("cam_sensor", which, sizeof(which)) && strcmp(which, "wide") == 0) {
- hw = &sensors[1];
+ if ((PE_parse_boot_arg_str("cam_sensor", which, sizeof(which)) && strcmp(which, "wide") == 0) || level == 5) {
+ hw = &sensors[1]; /* (cam=5 is the wide one's: its exposure registers are the SMIA ones) */
}
cci_bus.name = hw->bus_name;
cci_bus.sda = hw->sda;
cci_bus.scl = hw->scl;
- say("camera: cam=%u: the %s camera%s\n", level, hw->name, level == 4 ? ": its frames through its CSIPHY and RDI 0 into memory" :
+ say("camera: cam=%u: the %s camera%s\n", level, hw->name, level == 5 ? ": its frames for iOS" :
+ level == 4 ? ": its frames through its CSIPHY and RDI 0 into memory" :
level == 3 ? ": the CSID's test pattern through RDI 0 into memory" :
level == 2 ? ": powered up, its chip ID read, powered down" : ": a look, reading only");
pgpio_find();
@@ -2811,6 +3380,9 @@ camera_thread(__unused void *parameter, __unused wait_result_t result)
if (level == 3) {
capture_tpg();
power_down();
+ } else if (level == 5) {
+ serve_ios();
+ power_down();
} else if (level == 4) {
capture_sensor();
power_down();
@@ -2835,7 +3407,23 @@ redwood_camera_init(void)
if (!PE_parse_boot_argn("cam", &level, sizeof(level)) || level == 0) {
return;
}
- level = level > 4 ? 4 : level;
+ level = level > 5 ? 5 : level;
+ if (level == 5) {
+ /*
+ * The memory for a picture for the host (cam_keep_mb, default 24: a 12-megapixel NV12 picture), in
+ * one piece: taken now, while the system's memory still is in large pieces.
+ */
+ uint32_t keep_mb = 24;
+
+ (void)PE_parse_boot_argn("cam_keep_mb", &keep_mb, sizeof(keep_mb));
+ keep_bytes = (uint64_t)(keep_mb > 64 ? 64 : keep_mb) << 20;
+ if (keep_bytes != 0 && kmem_alloc_contig(kernel_map, &keep, keep_bytes, PAGE_MASK, 0, 0, KMA_KOBJECT | KMA_ZERO | KMA_DATA,
+ VM_KERN_MEMORY_IOKIT) != KERN_SUCCESS) {
+ printf("camera: no memory in one piece for a picture for the host (%u MB)\n", keep_mb);
+ keep = 0;
+ keep_bytes = 0;
+ }
+ }
if (kernel_thread_start(camera_thread, NULL, &thread) == KERN_SUCCESS) {
thread_deallocate(thread);
}
diff --git a/xnu/files/bsd/sys/redwood_camera.h b/xnu/files/bsd/sys/redwood_camera.h
new file mode 100644
index 0000000..2d03123
--- /dev/null
+++ b/xnu/files/bsd/sys/redwood_camera.h
@@ -0,0 +1,55 @@
+/*
+ * /dev/redwood-camera: the phone's wide camera for iOS (boot-arg cam=5; bsd/dev/redwood_camera.c).
+ *
+ * open() the first one powers the sensor up and starts its frames (the sensor's mode: boot-arg
+ * cam_mode, else the module file's 4000x3000 one); the last close puts everything down
+ * again, and so does a second without a read.
+ * read() waits (at most a second) for the newest frame not read yet: a struct
+ * redwood_camera_frame, then as many of the frame's bytes as the buffer has room for.
+ * A buffer of the header's size learns the frame's size and nothing else is copied.
+ * EIO when the camera has had a fault: it stays off for the rest of the run.
+ * write() commands: a struct redwood_camera_command, then what it says follows.
+ */
+#ifndef _SYS_REDWOOD_CAMERA_H_
+#define _SYS_REDWOOD_CAMERA_H_
+
+#include <stdint.h>
+
+#define REDWOOD_CAMERA_DEVICE "/dev/redwood-camera"
+#define REDWOOD_CAMERA_MAGIC "RWFRAME1"
+
+struct redwood_camera_frame {
+ char magic[8]; /* REDWOOD_CAMERA_MAGIC */
+ uint32_t header_bytes; /* this structure's size: the frame's bytes follow */
+ uint32_t width, height; /* pixels */
+ uint32_t stride; /* bytes from one line to the next */
+ uint32_t format; /* 1: MIPI RAW10, four pixels in five bytes */
+ uint32_t bayer; /* the order of a 2x2 cell: 0 RGGB, 1 GRBG, 2 GBRG, 3 BGGR */
+ uint32_t black; /* the black level, in 10-bit steps */
+ uint64_t sequence; /* the frame's number since the sensor started, from 1 */
+ uint64_t time; /* when the frame was done, in mach_absolute_time()'s units */
+ uint32_t exposure_lines; /* the exposure it was taken with, in lines ... */
+ uint32_t line_ns; /* ... of this many nanoseconds */
+ uint32_t gain; /* the sensor's analog gain register ... */
+ uint32_t gain_unity; /* ... which is this for 1x */
+ uint32_t gain_max; /* the most it may be given */
+ uint32_t frame_lines; /* the frame's length in lines (frames a second: 1e9 / (frame_lines * line_ns)) */
+ uint32_t frame_lines_min; /* the mode's own length: the shortest frame */
+ uint32_t frame_lines_max; /* the longest frame it may be given */
+ uint32_t margin; /* exposure_lines is at most frame_lines - margin */
+ uint32_t reserved[7];
+};
+
+enum {
+ REDWOOD_CAMERA_EXPOSURE = 1, /* a: lines, b: gain, c: frame lines (0: the shortest that holds the exposure) */
+ REDWOOD_CAMERA_KEEP = 2, /* a picture for the host: a width, b height, c stride, d format (1 the frame's RAW10, 2 NV12,
+ * 3 BGRA); bytes follow */
+};
+
+struct redwood_camera_command {
+ uint32_t command;
+ uint32_t bytes; /* of what follows this structure */
+ uint32_t a, b, c, d;
+};
+
+#endif /* _SYS_REDWOOD_CAMERA_H_ */