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

Sound, the kernel's side (from sound2), on main's kernel; iOS plays into it on the phone

vcvkk27ddc1b20725
diff --git a/xnu/files/bsd/dev/redwood_audio.c b/xnu/files/bsd/dev/redwood_audio.c
new file mode 100644
index 0000000..47e675e
--- /dev/null
+++ b/xnu/files/bsd/dev/redwood_audio.c
@@ -0,0 +1,281 @@
+/*
+ * /dev/redwood-audio: the sound that iOS plays (see sys/redwood_audio.h).
+ *
+ * What is written goes two ways:
+ *
+ * to a sink a driver that plays it: the virtio sound device under QEMU
+ * (redwood_virtio_sound.c). On the phone there is none yet (redwood_speaker.c
+ * is where it begins).
+ *
+ * into a recording, with boot-arg rec_sound=N: the first N seconds of sound are also kept
+ * in one piece of memory that is left in place when the kernel returns to the
+ * loader, which hands it to the host ("xl sound"; under QEMU, the monitor's
+ * pmemsave), where tools/sound.py makes a WAV file of it. Only what is played
+ * takes room, the silence in between does not: every write is stored with the
+ * time it was made.
+ *
+ * struct rec_header, then per write: struct rec_block, frames * 4 bytes
+ *
+ * When the writer has stopped, a line in the log says how long it wrote, at what rate, how much
+ * of it was not silence and how loud: the only way to "hear" a machine one cannot listen to.
+ * (The audio server writes for as long as its device runs, a second or two beyond the sound.)
+ */
+#include <kern/clock.h>
+#include <kern/locks.h>
+#include <kern/thread_call.h>
+#include <libkern/libkern.h>
+#include <mach/mach_types.h>
+#include <mach/vm_param.h>
+#include <miscfs/devfs/devfs.h>
+#include <pexpert/pexpert.h>
+#include <sys/conf.h>
+#include <sys/errno.h>
+#include <sys/proc.h>
+#include <sys/redwood_audio.h>
+#include <sys/systm.h>
+#include <sys/uio.h>
+#include <vm/vm_kern.h>
+
+extern uint64_t kvtophys(vm_offset_t va); /* pmap_paddr_t */
+
+#define CHUNK_FRAMES 1024 /* what one pass of write() moves */
+#define QUIET_MS 500 /* no write for this long: the writer has stopped */
+#define SILENCE 8 /* samples no larger than this are silence */
+#define REC_MAX_SECONDS 1200 /* 220 MB */
+
+struct rec_header {
+ char magic[8]; /* "RWSND001" */
+ uint32_t rate, channels; /* REDWOOD_AUDIO_RATE, REDWOOD_AUDIO_CHANNELS; the samples are 16-bit */
+ uint32_t blocks;
+ uint32_t reserved;
+};
+struct rec_block {
+ uint64_t nanoseconds; /* when it was written, since the kernel started */
+ uint32_t frames;
+ uint32_t reserved;
+};
+
+/* { physical address, bytes, kernel address } of the recording, for the loader: osfmk/arm64/loader_return.c */
+extern uint64_t loader_sound[3];
+
+static LCK_GRP_DECLARE(audio_lck_grp, "redwood-audio");
+static LCK_MTX_DECLARE(audio_lock, &audio_lck_grp);
+
+static redwood_audio_sink_t audio_sink;
+
+static uint8_t *rec_base;
+static uint64_t rec_size, rec_used;
+static uint64_t rec_frames, rec_frames_max;
+
+/* the stretch of writing in progress */
+static uint64_t stretch_first, stretch_last; /* mach_absolute_time() of its first and its latest write */
+static uint64_t stretch_frames, stretch_latest; /* frames written, and how many of them by the latest write */
+static uint64_t stretch_sound, stretch_lost; /* frames in writes that were not silence; frames the sink did not take */
+static uint32_t stretch_peak; /* the largest sample, as an absolute value */
+static thread_call_t report_call;
+static bool report_armed;
+
+static void
+audio_report(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
+{
+ uint64_t frames, latest, sound, lost, deadline, since = 0, lasted = 0;
+ uint32_t loudest;
+
+ lck_mtx_lock(&audio_lock);
+ absolutetime_to_nanoseconds(mach_absolute_time() - stretch_last, &since);
+ if (since < QUIET_MS * NSEC_PER_MSEC) {
+ /* still writing: look again later */
+ clock_interval_to_deadline(2 * QUIET_MS, NSEC_PER_MSEC, &deadline);
+ thread_call_enter_delayed(report_call, deadline);
+ lck_mtx_unlock(&audio_lock);
+ return;
+ }
+ absolutetime_to_nanoseconds(stretch_last - stretch_first, &lasted);
+ frames = stretch_frames;
+ latest = stretch_latest;
+ sound = stretch_sound;
+ lost = stretch_lost;
+ loudest = stretch_peak;
+ stretch_frames = stretch_sound = stretch_lost = 0;
+ stretch_peak = 0;
+ report_armed = false;
+ lck_mtx_unlock(&audio_lock);
+
+ printf("redwood-audio: %llu.%02llu s written", frames / REDWOOD_AUDIO_RATE,
+ frames % REDWOOD_AUDIO_RATE * 100 / REDWOOD_AUDIO_RATE);
+ if (lasted >= NSEC_PER_SEC) {
+ /* what was written before the latest write took the time between the first and the latest */
+ printf(" at %llu frames a second", (frames - latest) * NSEC_PER_SEC / lasted);
+ }
+ printf(", %llu.%02llu s of it sound, peak %u%% of full scale", sound / REDWOOD_AUDIO_RATE,
+ sound % REDWOOD_AUDIO_RATE * 100 / REDWOOD_AUDIO_RATE, loudest * 100 / 32768);
+ if (lost) {
+ printf(", %llu ms lost (the sink was full)", lost * 1000 / REDWOOD_AUDIO_RATE);
+ }
+ printf("\n");
+}
+
+/* With audio_lock held. */
+static void
+audio_record(const int16_t *frames, uint32_t count)
+{
+ struct rec_header *header = (struct rec_header *)rec_base;
+ struct rec_block *block;
+ uint64_t bytes = (uint64_t)count * REDWOOD_AUDIO_FRAME;
+
+ if (rec_base == NULL || rec_frames >= rec_frames_max || rec_used + sizeof(*block) + bytes > rec_size) {
+ return;
+ }
+ block = (struct rec_block *)(rec_base + rec_used);
+ absolutetime_to_nanoseconds(mach_absolute_time(), &block->nanoseconds);
+ block->frames = count;
+ block->reserved = 0;
+ memcpy(block + 1, frames, bytes);
+ rec_used += sizeof(*block) + bytes;
+ rec_frames += count;
+ header->blocks++;
+ loader_sound[1] = rec_used;
+ if (rec_frames >= rec_frames_max) {
+ printf("redwood-audio: recording finished: %llu s in %u writes\n", rec_frames / REDWOOD_AUDIO_RATE, header->blocks);
+ }
+}
+
+static void
+audio_play(const int16_t *frames, uint32_t count)
+{
+ uint32_t loudest = 0, taken = 0;
+ uint64_t deadline;
+
+ for (uint32_t i = 0; i < count * REDWOOD_AUDIO_CHANNELS; i++) {
+ uint32_t level = frames[i] < 0 ? -(int32_t)frames[i] : frames[i];
+
+ if (level > loudest) {
+ loudest = level;
+ }
+ }
+ lck_mtx_lock(&audio_lock);
+ audio_record(frames, count);
+ if (audio_sink != NULL) {
+ taken = audio_sink(frames, count);
+ stretch_lost += count - taken;
+ }
+ stretch_last = mach_absolute_time();
+ if (stretch_frames == 0) {
+ stretch_first = stretch_last;
+ }
+ stretch_frames += count;
+ stretch_latest = count;
+ if (loudest > SILENCE) {
+ stretch_sound += count;
+ }
+ if (loudest > stretch_peak) {
+ stretch_peak = loudest;
+ }
+ if (!report_armed && report_call != NULL) {
+ report_armed = true;
+ clock_interval_to_deadline(2 * QUIET_MS, NSEC_PER_MSEC, &deadline);
+ thread_call_enter_delayed(report_call, deadline);
+ }
+ lck_mtx_unlock(&audio_lock);
+}
+
+void
+redwood_audio_set_sink(const char *name, redwood_audio_sink_t sink)
+{
+ lck_mtx_lock(&audio_lock);
+ audio_sink = sink;
+ lck_mtx_unlock(&audio_lock);
+ printf("redwood-audio: sound goes to %s\n", name);
+}
+
+static int
+audio_open(__unused dev_t dev, __unused int flags, __unused int devtype, __unused struct proc *p)
+{
+ return 0;
+}
+
+static int
+audio_close(__unused dev_t dev, __unused int flags, __unused int devtype, __unused struct proc *p)
+{
+ return 0;
+}
+
+static int
+audio_write(__unused dev_t dev, struct uio *uio, __unused int ioflag)
+{
+ int16_t frames[CHUNK_FRAMES * REDWOOD_AUDIO_CHANNELS];
+ int error = 0;
+
+ while (uio_resid(uio) >= REDWOOD_AUDIO_FRAME) {
+ user_ssize_t bytes = uio_resid(uio);
+
+ if (bytes > (user_ssize_t)sizeof(frames)) {
+ bytes = sizeof(frames);
+ }
+ bytes -= bytes % REDWOOD_AUDIO_FRAME;
+ error = uiomove((caddr_t)frames, (int)bytes, uio);
+ if (error) {
+ break;
+ }
+ audio_play(frames, (uint32_t)(bytes / REDWOOD_AUDIO_FRAME));
+ }
+ return error;
+}
+
+static const struct cdevsw audio_cdevsw = {
+ .d_open = audio_open, .d_close = audio_close, .d_read = eno_rdwrt, .d_write = audio_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
+};
+
+static void
+audio_recording_init(void)
+{
+ struct rec_header *header;
+ uint32_t seconds = 0;
+ vm_offset_t memory = 0;
+ uint64_t size;
+
+ if (!PE_parse_boot_argn("rec_sound", &seconds, sizeof(seconds)) || seconds == 0) {
+ return;
+ }
+ if (seconds > REC_MAX_SECONDS) {
+ seconds = REC_MAX_SECONDS;
+ }
+ /* the samples, and a block header for every write of ten milliseconds or more */
+ size = sizeof(*header) + (uint64_t)seconds * (REDWOOD_AUDIO_RATE * REDWOOD_AUDIO_FRAME + 100 * sizeof(struct rec_block));
+ size = round_page(size);
+ /* one piece of physical memory: the loader will send it over USB as it lies */
+ if (kmem_alloc_contig(kernel_map, &memory, size, PAGE_MASK, 0, 0, KMA_KOBJECT | KMA_ZERO | KMA_DATA,
+ VM_KERN_MEMORY_IOKIT) != KERN_SUCCESS) {
+ printf("redwood-audio: no memory for a recording of %u s (%llu MB)\n", seconds, size >> 20);
+ return;
+ }
+ header = (struct rec_header *)memory;
+ memcpy(header->magic, "RWSND001", 8);
+ header->rate = REDWOOD_AUDIO_RATE;
+ header->channels = REDWOOD_AUDIO_CHANNELS;
+ rec_size = size;
+ rec_used = sizeof(*header);
+ rec_frames_max = (uint64_t)seconds * REDWOOD_AUDIO_RATE;
+ rec_base = (uint8_t *)memory;
+ loader_sound[0] = kvtophys(memory);
+ loader_sound[1] = rec_used;
+ loader_sound[2] = (uint64_t)memory;
+ printf("redwood-audio: recording the first %u s of sound, into %llu MB at %#llx\n", seconds, size >> 20, loader_sound[0]);
+}
+
+void
+redwood_audio_init(void)
+{
+ int major = cdevsw_add(-1, &audio_cdevsw);
+
+ if (major < 0 || devfs_make_node(makedev(major, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666, "redwood-audio") == NULL) {
+ printf("redwood-audio: cannot create the device\n");
+ return;
+ }
+ report_call = thread_call_allocate(audio_report, NULL);
+ audio_recording_init();
+ redwood_virtio_sound_init();
+ redwood_speaker_init();
+}
diff --git a/xnu/files/bsd/dev/redwood_speaker.c b/xnu/files/bsd/dev/redwood_speaker.c
new file mode 100644
index 0000000..aeeaeb5
--- /dev/null
+++ b/xnu/files/bsd/dev/redwood_speaker.c
@@ -0,0 +1,378 @@
+/*
+ * The speakers of the POCO X5 Pro (redwood): so far only a look at what is there.
+ * Only with boot-arg speaker_probe=N: every address below belongs to this phone.
+ * speaker_probe=1 reads registers and nothing else: pins, power (below)
+ * speaker_probe=2 ... and asks the amplifiers who they are, for which two pins are
+ * reconfigured for the time it takes (I2C, below)
+ * NEITHER HAS BEEN RUN ON THE PHONE YET.
+ *
+ * Each of the phone's two speakers has an amplifier of its own, an Awinic AW882xx ("smart
+ * PA"), which is set up over I2C (bus of the SoC's serial engine 3, GPIO 12 data and 13 clock;
+ * addresses 0x34, the bottom speaker, and 0x35, the top one) and takes its samples from the
+ * SoC's first I2S interface ("MI2S 0": GPIO 97 bit clock, 100 word select, 98 and 99 data).
+ * That interface belongs to the audio subsystem (LPASS), which under Android is run by the
+ * audio DSP: there, sound goes from the kernel to the DSP's firmware as messages, and the
+ * firmware drives the interface. None of that is running here, and before anything is built
+ * the questions are which amplifier it is and whether it is powered without Android.
+ *
+ * pins how the firmware left the pins involved: their configuration and level are read
+ * from the pin controller, nothing is written
+ * power the names under which the audio subsystem's supplies can be asked for (read from
+ * the command database the boot loader left in memory), and whether its bus clock
+ * runs (one register of the global clock controller, read)
+ * I2C register 0 (the chip ID) and three more of each amplifier, read through the two
+ * pins driven by hand, open-drain: a pin is either pulled low or let go. This
+ * WRITES the configuration of GPIO 12 and 13 (to "GPIO, pull-up", and the output
+ * enable for every low bit) and puts back what was there before; if the bus is not
+ * at rest when the pins are let go, nothing more is done. The amplifiers are only
+ * read: the writes on the bus are their addresses and the numbers of the registers
+ * to read. They stay in the power-down state they start in.
+ *
+ * (Whether the secure world would start the audio DSP for us cannot be asked without doing it:
+ * its "is this image supported" answers no for every image, the GPU's included, which it then
+ * authenticates and starts all the same -- see redwood_adreno.c.)
+ *
+ * Register layouts: Linux sound/soc/codecs/aw88261.c and aw88395/, drivers/pinctrl/qcom/
+ * pinctrl-sc7280.c, drivers/clk/qcom/gcc-sc7280.c, drivers/soc/qcom/cmd-db.c, and the phone's
+ * own device tree.
+ */
+#include <kern/clock.h>
+#include <kern/thread.h>
+#include <libkern/libkern.h>
+#include <mach/mach_types.h>
+#include <pexpert/pexpert.h>
+#include <sys/redwood_audio.h>
+#include <sys/systm.h>
+
+extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
+extern vm_offset_t ml_io_map_wcomb(vm_offset_t phys_addr, vm_size_t size);
+extern kern_return_t thread_terminate(thread_t thread);
+
+static vm_offset_t tlmm, gcc, cmd_db;
+static uint32_t probe_level;
+
+static inline uint32_t
+rd(vm_offset_t address)
+{
+ return *(volatile uint32_t *)address;
+}
+
+static inline void
+wr(vm_offset_t address, uint32_t value)
+{
+ *(volatile uint32_t *)address = value;
+}
+
+/* ---- pins ------------------------------------------------------------------------------------------ */
+
+#define TLMM_PHYS 0x0f100000UL
+#define TLMM_SIZE 0x100000UL
+#define GPIO_CFG(n) (tlmm + 0x1000UL * (n)) /* [1:0] pull, [5:2] function, [8:6] drive, [9] output */
+#define GPIO_IO(n) (tlmm + 0x1000UL * (n) + 4) /* bit 0 in, bit 1 out */
+#define CFG_PULL_UP 3
+#define CFG_OUTPUT (1u << 9)
+
+/* the serial engine's first pin is the data line, the second the clock (should the board differ, see show_amplifiers) */
+static unsigned PIN_SDA = 12, PIN_SCL = 13;
+
+static const struct {
+ unsigned pin;
+ const char *what;
+} pins[] = {
+ { 12, "I2C data" }, { 13, "I2C clock" }, { 96, "MI2S 0 master clock" }, { 97, "MI2S 0 bit clock" },
+ { 100, "MI2S 0 word select" }, { 98, "MI2S 0 data 0" }, { 99, "MI2S 0 data 1" }, { 102, "top amplifier's interrupt" },
+ { 45, "bottom amplifier's interrupt" },
+};
+
+static void
+show_pins(void)
+{
+ for (unsigned i = 0; i < sizeof(pins) / sizeof(pins[0]); i++) {
+ uint32_t cfg = rd(GPIO_CFG(pins[i].pin)), io = rd(GPIO_IO(pins[i].pin));
+
+ printf("speaker: gpio%u (%s): function %u, pull %u, %u mA, %s, reads %u\n", pins[i].pin, pins[i].what,
+ (cfg >> 2) & 15, cfg & 3, (((cfg >> 6) & 7) + 1) * 2, (cfg & CFG_OUTPUT) ? (io & 2 ? "drives high" : "drives low") :
+ "input", io & 1);
+ }
+}
+
+/* ---- I2C by hand ----------------------------------------------------------------------------------- */
+
+static void
+half_bit(void)
+{
+ delay_for_interval(10, NSEC_PER_USEC); /* 50 kHz at most; the bus does not mind slower */
+}
+
+/* A line is pulled low (the pin drives 0) or let go (the pin is an input and the pull-up raises it). */
+static void
+line(unsigned pin, bool high)
+{
+ wr(GPIO_IO(pin), 0);
+ wr(GPIO_CFG(pin), CFG_PULL_UP | (high ? 0 : CFG_OUTPUT));
+}
+
+static bool
+level(unsigned pin)
+{
+ return rd(GPIO_IO(pin)) & 1;
+}
+
+static void
+i2c_start(void)
+{
+ line(PIN_SDA, true);
+ line(PIN_SCL, true);
+ half_bit();
+ line(PIN_SDA, false);
+ half_bit();
+ line(PIN_SCL, false);
+ half_bit();
+}
+
+static void
+i2c_stop(void)
+{
+ line(PIN_SDA, false);
+ half_bit();
+ line(PIN_SCL, true);
+ half_bit();
+ line(PIN_SDA, true);
+ half_bit();
+}
+
+/* One bit out (the other side's bit in, if we let the data line go): the clock goes up and down once. */
+static bool
+i2c_bit(bool out)
+{
+ bool in;
+
+ line(PIN_SDA, out);
+ half_bit();
+ line(PIN_SCL, true);
+ half_bit();
+ in = level(PIN_SDA);
+ line(PIN_SCL, false);
+ return in;
+}
+
+/* Returns true if the byte was acknowledged. */
+static bool
+i2c_write(uint8_t byte)
+{
+ for (int bit = 7; bit >= 0; bit--) {
+ i2c_bit((byte >> bit) & 1);
+ }
+ return !i2c_bit(true);
+}
+
+static uint8_t
+i2c_read(bool more)
+{
+ uint8_t byte = 0;
+
+ for (int bit = 7; bit >= 0; bit--) {
+ byte = (uint8_t)(byte << 1 | i2c_bit(true));
+ }
+ i2c_bit(!more); /* acknowledge all but the last byte */
+ return byte;
+}
+
+/* A 16-bit register of an Awinic amplifier, most significant byte first. Returns false if nobody answers. */
+static bool
+amplifier_read(uint8_t address, uint8_t reg, uint16_t *value)
+{
+ bool answered;
+
+ i2c_start();
+ answered = i2c_write((uint8_t)(address << 1)) && i2c_write(reg);
+ if (answered) {
+ i2c_start();
+ answered = i2c_write((uint8_t)(address << 1 | 1));
+ }
+ if (answered) {
+ *value = (uint16_t)(i2c_read(true) << 8);
+ *value |= i2c_read(false);
+ }
+ i2c_stop();
+ return answered;
+}
+
+static const char *
+amplifier_name(uint16_t id)
+{
+ switch (id) {
+ case 0x1852: return "AW88194/AW88195";
+ case 0x2013: return "AW88264";
+ case 0x2032: return "AW88266";
+ case 0x2049: return "AW88395";
+ case 0x2055: return "AW88256";
+ case 0x2066: return "AW88166";
+ case 0x2071: return "AW88350";
+ case 0x2113: return "AW88261";
+ case 0x2183: return "AW88399";
+ case 0x2308: return "AW88230";
+ }
+ return "an amplifier this list does not know";
+}
+
+static void
+show_amplifiers(void)
+{
+ static const struct {
+ uint8_t address;
+ const char *where;
+ } amplifiers[] = { { 0x34, "bottom" }, { 0x35, "top" } };
+ /* the chip ID, then registers that every chip of the family has at the same place and that reading does not change */
+ static const struct {
+ uint8_t reg;
+ const char *name;
+ } more[] = { { 0x01, "status" }, { 0x04, "system control" }, { 0x06, "I2S control" } };
+ const unsigned first = PIN_SDA, second = PIN_SCL;
+ uint32_t first_cfg = rd(GPIO_CFG(first)), second_cfg = rd(GPIO_CFG(second));
+ uint32_t first_io = rd(GPIO_IO(first)), second_io = rd(GPIO_IO(second));
+ unsigned found = 0;
+
+ line(PIN_SDA, true);
+ line(PIN_SCL, true);
+ delay_for_interval(1, NSEC_PER_MSEC);
+ if (!level(PIN_SDA) || !level(PIN_SCL)) {
+ /* nothing of ours on a bus that is not at rest: its supply may be off, and then so are the amplifiers */
+ printf("speaker: the I2C bus is not idle (gpio%u reads %u, gpio%u reads %u): no supply for its pull-ups? Not touched\n",
+ PIN_SDA, level(PIN_SDA), PIN_SCL, level(PIN_SCL));
+ } else {
+ /* as the pins should be, and if nobody answers, the other way round */
+ for (int attempt = 0; attempt < 2 && found == 0; attempt++) {
+ if (attempt == 1) {
+ PIN_SDA = second;
+ PIN_SCL = first;
+ printf("speaker: once more with gpio%u as the data line and gpio%u as the clock\n", PIN_SDA, PIN_SCL);
+ }
+ for (unsigned i = 0; i < sizeof(amplifiers) / sizeof(amplifiers[0]); i++) {
+ uint16_t id = 0, value = 0;
+
+ if (!amplifier_read(amplifiers[i].address, 0x00, &id)) {
+ printf("speaker: nobody at I2C address %#x (the %s amplifier): not powered, or not there\n",
+ amplifiers[i].address, amplifiers[i].where);
+ continue;
+ }
+ found++;
+ printf("speaker: the %s amplifier (I2C address %#x) is there: chip ID %#06x, %s\n", amplifiers[i].where,
+ amplifiers[i].address, id, amplifier_name(id));
+ for (unsigned r = 0; r < sizeof(more) / sizeof(more[0]); r++) {
+ if (amplifier_read(amplifiers[i].address, more[r].reg, &value)) {
+ printf("speaker: register %#04x (%s) = %#06x\n", more[r].reg, more[r].name, value);
+ }
+ }
+ }
+ }
+ }
+ /* as the firmware left them */
+ wr(GPIO_IO(first), first_io & 2);
+ wr(GPIO_IO(second), second_io & 2);
+ wr(GPIO_CFG(first), first_cfg);
+ wr(GPIO_CFG(second), second_cfg);
+}
+
+/* ---- power and clock of the audio subsystem --------------------------------------------------------- */
+
+#define CMD_DB_PHYS 0x80860000UL
+#define CMD_DB_SIZE 0x20000UL
+#define GCC_PHYS 0x00100000UL
+#define GCC_SIZE 0x60000UL
+#define GCC_CFG_NOC_LPASS_CBCR (gcc + 0x47020) /* bit 0: asked for, bit 31: off */
+
+struct cmd_db_slave {
+ uint16_t id, header_offset, data_offset, count, version, reserved[3];
+};
+struct cmd_db_header {
+ uint32_t version;
+ uint8_t magic[4];
+ struct cmd_db_slave slave[8];
+ uint32_t checksum, reserved;
+ uint8_t data[];
+};
+struct cmd_db_entry {
+ char id[8];
+ uint32_t priority[2];
+ uint32_t address;
+ uint16_t length, offset;
+};
+
+/* The RPMh address of a resource by its name in the command database the boot loader left; 0 = none. */
+static uint32_t
+rpmh_address(const char *name)
+{
+ const struct cmd_db_header *db = (const struct cmd_db_header *)cmd_db;
+ char id[8] = { 0 };
+
+ if (db->magic[0] != 0xdb || db->magic[1] != 0x30 || db->magic[2] != 0x03 || db->magic[3] != 0x0c) {
+ return 0;
+ }
+ strlcpy(id, name, sizeof(id));
+ for (unsigned s = 0; s < 8; s++) {
+ const struct cmd_db_slave *slave = &db->slave[s];
+ const struct cmd_db_entry *entry = (const struct cmd_db_entry *)(db->data + slave->header_offset);
+
+ if (slave->id == 0 || slave->header_offset >= CMD_DB_SIZE - 0x1000 || slave->count > 512) {
+ continue;
+ }
+ for (unsigned i = 0; i < slave->count; i++) {
+ if (memcmp(entry[i].id, id, sizeof(id)) == 0) {
+ return entry[i].address;
+ }
+ }
+ }
+ return 0;
+}
+
+static void
+show_power(void)
+{
+ /* the subsystem's two supplies and, for the DSP, the processor's own two and the crystal */
+ static const char *const supplies[] = { "lcx.lvl", "lmx.lvl", "cx.lvl", "mx.lvl", "xo.lvl" };
+
+ for (unsigned i = 0; i < sizeof(supplies) / sizeof(supplies[0]); i++) {
+ uint32_t address = rpmh_address(supplies[i]);
+
+ if (address) {
+ printf("speaker: supply \"%s\" can be asked for at RPMh address %#x\n", supplies[i], address);
+ } else {
+ printf("speaker: no supply \"%s\" in the command database\n", supplies[i]);
+ }
+ }
+ /*
+ * (The audio subsystem's bus clock, GCC_CFG_NOC_LPASS_CBCR, is not read: on the phone that read
+ * stops the kernel with a synchronous external abort -- the register is not the main processors'
+ * to read while the audio subsystem belongs to its DSP.)
+ */
+}
+
+static void
+probe_thread(__unused void *parameter, __unused wait_result_t result)
+{
+ tlmm = ml_io_map(TLMM_PHYS, TLMM_SIZE);
+ gcc = ml_io_map(GCC_PHYS, GCC_SIZE);
+ cmd_db = ml_io_map_wcomb(CMD_DB_PHYS, CMD_DB_SIZE); /* memory, not registers: no alignment rules */
+ printf("speaker: a look at the phone's sound hardware (level %u; nothing is switched on)\n", probe_level);
+ show_pins();
+ show_power();
+ if (probe_level >= 2) {
+ show_amplifiers();
+ }
+ printf("speaker: done\n");
+ thread_terminate(current_thread());
+}
+
+void
+redwood_speaker_init(void)
+{
+ thread_t thread;
+
+ if (!PE_parse_boot_argn("speaker_probe", &probe_level, sizeof(probe_level)) || probe_level == 0) {
+ return;
+ }
+ if (kernel_thread_start(probe_thread, NULL, &thread) == KERN_SUCCESS) {
+ thread_deallocate(thread);
+ }
+}
diff --git a/xnu/files/bsd/dev/redwood_virtio_sound.c b/xnu/files/bsd/dev/redwood_virtio_sound.c
new file mode 100644
index 0000000..aafe202
--- /dev/null
+++ b/xnu/files/bsd/dev/redwood_virtio_sound.c
@@ -0,0 +1,406 @@
+/*
+ * A virtio sound device as the sink of /dev/redwood-audio (see sys/redwood_audio.h).
+ *
+ * Under QEMU's "virt" machine a "virtio-sound-device" plays what iOS plays: through the host's
+ * sound system, or into a file ("-audiodev wav"), whichever back end QEMU is given. Like the
+ * input devices (redwood_virtio_input.c) it sits on the machine's virtio-mmio bus, which must
+ * be the current one, not "legacy". Only with boot-arg virtio_sound=1: the bus address is
+ * QEMU's and means nothing on the phone.
+ *
+ * The device has four queues; two are used. Over the control queue its first output stream is
+ * set to the one format of /dev/redwood-audio and started, once and for good: a started stream
+ * that is given nothing plays nothing. The samples go out over the transmit queue, a hundredth
+ * of a second to a buffer. The device gives a buffer back when it has played it, which is what
+ * paces us: what does not fit into the buffers waits in a ring, and what does not fit into the
+ * ring is lost.
+ *
+ * No interrupt is used; while there is sound on its way the queue is looked at 200 times a
+ * second, otherwise not at all.
+ *
+ * The protocol: Virtual I/O Device (VIRTIO) Version 1.2, section 5.14 "Sound Device".
+ */
+#include <kern/clock.h>
+#include <kern/locks.h>
+#include <kern/thread_call.h>
+#include <libkern/libkern.h>
+#include <mach/mach_types.h>
+#include <mach/vm_param.h>
+#include <pexpert/pexpert.h>
+#include <sys/redwood_audio.h>
+#include <sys/systm.h>
+#include <vm/vm_kern.h>
+
+extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
+extern uint64_t kvtophys(vm_offset_t va); /* pmap_paddr_t */
+
+#define VIRTIO_BUS 0x0a000000UL /* QEMU virt: 32 transports of 0x200 bytes */
+#define VIRTIO_SLOTS 32
+#define VIRTIO_SLOT_SIZE 0x200
+
+#define VIRTIO_MAGIC 0x000 /* "virt" */
+#define VIRTIO_VERSION 0x004
+#define VIRTIO_DEVICE_ID 0x008
+#define VIRTIO_DRIVER_FEATURES 0x020
+#define VIRTIO_DRIVER_FEATURES_SEL 0x024
+#define VIRTIO_QUEUE_SEL 0x030
+#define VIRTIO_QUEUE_NUM_MAX 0x034
+#define VIRTIO_QUEUE_NUM 0x038
+#define VIRTIO_QUEUE_READY 0x044
+#define VIRTIO_QUEUE_NOTIFY 0x050
+#define VIRTIO_STATUS 0x070
+#define VIRTIO_QUEUE_DESC 0x080
+#define VIRTIO_QUEUE_DRIVER 0x090
+#define VIRTIO_QUEUE_DEVICE 0x0a0
+#define VIRTIO_CONFIG 0x100
+
+#define VIRTIO_ID_SOUND 25
+#define STATUS_ACKNOWLEDGE 1
+#define STATUS_DRIVER 2
+#define STATUS_DRIVER_OK 4
+#define STATUS_FEATURES_OK 8
+
+#define QUEUE_CONTROL 0
+#define QUEUE_TX 2
+#define QUEUE_SIZE 64
+#define DESC_F_NEXT 1
+#define DESC_F_WRITE 2
+#define AVAIL_F_NO_INTERRUPT 1
+
+struct vq_desc {
+ uint64_t addr;
+ uint32_t len;
+ uint16_t flags;
+ uint16_t next;
+};
+struct vq_avail {
+ uint16_t flags;
+ uint16_t idx;
+ uint16_t ring[QUEUE_SIZE];
+};
+struct vq_used {
+ uint16_t flags;
+ uint16_t idx;
+ struct {
+ uint32_t id;
+ uint32_t len;
+ } ring[QUEUE_SIZE];
+};
+
+/* the sound device's own messages */
+#define SND_R_PCM_INFO 0x0100
+#define SND_R_PCM_SET_PARAMS 0x0101
+#define SND_R_PCM_PREPARE 0x0102
+#define SND_R_PCM_START 0x0104
+#define SND_S_OK 0x8000
+#define SND_D_OUTPUT 0
+#define SND_PCM_FMT_S16 5
+#define SND_PCM_RATE_48000 7
+
+struct snd_query_info {
+ uint32_t code;
+ uint32_t start_id, count, size;
+};
+#define SND_PCM_INFO_SIZE 32 /* hda_fn_nid, features, formats (64 bits), rates (64 bits), ... */
+#define SND_PCM_INFO_DIRECTION 24 /* ... direction, channels_min, channels_max (a byte each) */
+struct snd_pcm_hdr {
+ uint32_t code;
+ uint32_t stream_id;
+};
+struct snd_pcm_set_params {
+ uint32_t code;
+ uint32_t stream_id;
+ uint32_t buffer_bytes, period_bytes;
+ uint32_t features;
+ uint8_t channels, format, rate, padding;
+};
+struct snd_pcm_status {
+ uint32_t status;
+ uint32_t latency_bytes;
+};
+
+#define PERIOD_FRAMES (REDWOOD_AUDIO_RATE / 100)
+#define PERIOD_BYTES (PERIOD_FRAMES * REDWOOD_AUDIO_FRAME)
+#define TX_BUFFERS (QUEUE_SIZE / 2) /* two descriptors each: 0.32 s in the device at most */
+#define RING_FRAMES 16384 /* a power of two: 0.34 s more */
+#define MAX_STREAMS 8
+
+/* one transmit buffer: what the device reads, then what it writes */
+struct tx_buffer {
+ uint32_t stream_id;
+ int16_t frames[PERIOD_FRAMES * REDWOOD_AUDIO_CHANNELS];
+ struct snd_pcm_status status;
+};
+
+/* what the device reads and writes: the two queues' rings in the first page, then the buffers */
+#define OFFSET_DESC(q) ((q) ? 0x2000 : 0x0000)
+#define OFFSET_AVAIL(q) ((q) ? 0x2400 : 0x0400)
+#define OFFSET_USED(q) ((q) ? 0x2800 : 0x0800)
+#define OFFSET_CONTROL 0x1000 /* a request, and at +0x800 the answer */
+#define OFFSET_TX 0x4000
+#define SHARED_SIZE round_page(OFFSET_TX + TX_BUFFERS * sizeof(struct tx_buffer))
+
+struct queue {
+ struct vq_desc * desc;
+ struct vq_avail * avail;
+ struct vq_used * used;
+ uint16_t seen; /* how far the used ring has been read */
+};
+
+static vm_offset_t regs;
+static vm_offset_t shared;
+static uint64_t shared_phys;
+static struct queue control, tx;
+static uint32_t stream;
+
+static LCK_GRP_DECLARE(sound_lck_grp, "redwood-virtio-sound");
+static LCK_MTX_DECLARE(sound_lock, &sound_lck_grp);
+static int16_t ring[RING_FRAMES * REDWOOD_AUDIO_CHANNELS];
+static uint32_t ring_head, ring_tail; /* in frames; play from head, add at tail */
+static uint16_t tx_free[TX_BUFFERS];
+static uint32_t tx_free_count;
+static thread_call_t poll_call;
+static bool poll_armed;
+
+static inline uint32_t
+reg_read(uint32_t reg)
+{
+ return *(volatile uint32_t *)(regs + reg);
+}
+
+static inline void
+reg_write(uint32_t reg, uint32_t value)
+{
+ *(volatile uint32_t *)(regs + reg) = value;
+}
+
+static inline void
+reg_write64(uint32_t reg, uint64_t value)
+{
+ reg_write(reg, (uint32_t)value);
+ reg_write(reg + 4, (uint32_t)(value >> 32));
+}
+
+static bool
+queue_setup(struct queue *q, uint32_t index, int which)
+{
+ q->desc = (struct vq_desc *)(shared + OFFSET_DESC(which));
+ q->avail = (struct vq_avail *)(shared + OFFSET_AVAIL(which));
+ q->used = (struct vq_used *)(shared + OFFSET_USED(which));
+ q->avail->flags = AVAIL_F_NO_INTERRUPT;
+ reg_write(VIRTIO_QUEUE_SEL, index);
+ if (reg_read(VIRTIO_QUEUE_NUM_MAX) < QUEUE_SIZE) {
+ printf("virtio-sound: queue %u of %u\n", index, reg_read(VIRTIO_QUEUE_NUM_MAX));
+ return false;
+ }
+ reg_write(VIRTIO_QUEUE_NUM, QUEUE_SIZE);
+ reg_write64(VIRTIO_QUEUE_DESC, shared_phys + OFFSET_DESC(which));
+ reg_write64(VIRTIO_QUEUE_DRIVER, shared_phys + OFFSET_AVAIL(which));
+ reg_write64(VIRTIO_QUEUE_DEVICE, shared_phys + OFFSET_USED(which));
+ __builtin_arm_dmb(0xb); /* ISH */
+ reg_write(VIRTIO_QUEUE_READY, 1);
+ return true;
+}
+
+/* Hand the device the descriptor chain that starts at `first`. */
+static void
+queue_add(struct queue *q, uint32_t index, uint16_t first)
+{
+ q->avail->ring[q->avail->idx % QUEUE_SIZE] = first;
+ __builtin_arm_dmb(0xb);
+ q->avail->idx++;
+ __builtin_arm_dmb(0xb);
+ reg_write(VIRTIO_QUEUE_NOTIFY, index);
+}
+
+/*
+ * One request over the control queue; the answer begins with a status word. Only while the
+ * driver starts: the answer is waited for.
+ */
+static bool
+control_request(const void *request, uint32_t request_size, void *answer, uint32_t answer_size)
+{
+ uint8_t *out = (uint8_t *)(shared + OFFSET_CONTROL), *in = out + 0x800;
+
+ memcpy(out, request, request_size);
+ bzero(in, answer_size);
+ control.desc[0] = (struct vq_desc){ .addr = shared_phys + OFFSET_CONTROL, .len = request_size, .flags = DESC_F_NEXT, .next = 1 };
+ control.desc[1] = (struct vq_desc){ .addr = shared_phys + OFFSET_CONTROL + 0x800, .len = answer_size, .flags = DESC_F_WRITE };
+ queue_add(&control, QUEUE_CONTROL, 0);
+ for (int tries = 0; control.seen == *(volatile uint16_t *)&control.used->idx; tries++) {
+ if (tries == 1000) {
+ printf("virtio-sound: no answer to request %#x\n", *(const uint32_t *)request);
+ return false;
+ }
+ delay_for_interval(1, NSEC_PER_MSEC);
+ }
+ control.seen++;
+ memcpy(answer, in, answer_size);
+ if (*(const uint32_t *)answer != SND_S_OK) {
+ printf("virtio-sound: request %#x refused: %#x\n", *(const uint32_t *)request, *(const uint32_t *)answer);
+ return false;
+ }
+ return true;
+}
+
+/* With sound_lock held: take back the buffers the device has played, give it what waits in the ring. */
+static void
+sound_pump(void)
+{
+ while (tx.seen != *(volatile uint16_t *)&tx.used->idx) {
+ tx_free[tx_free_count++] = (uint16_t)(tx.used->ring[tx.seen++ % QUEUE_SIZE].id / 2);
+ }
+ while (tx_free_count != 0 && ring_tail - ring_head >= PERIOD_FRAMES) {
+ uint16_t n = tx_free[--tx_free_count];
+ struct tx_buffer *buffer = (struct tx_buffer *)(shared + OFFSET_TX) + n;
+
+ buffer->stream_id = stream;
+ for (uint32_t i = 0; i < PERIOD_FRAMES; i++, ring_head++) {
+ buffer->frames[2 * i] = ring[2 * (ring_head % RING_FRAMES)];
+ buffer->frames[2 * i + 1] = ring[2 * (ring_head % RING_FRAMES) + 1];
+ }
+ queue_add(&tx, QUEUE_TX, (uint16_t)(2 * n));
+ }
+}
+
+static void
+sound_poll(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
+{
+ uint64_t deadline;
+
+ lck_mtx_lock(&sound_lock);
+ sound_pump();
+ /* as long as the device has buffers of ours, or there is a whole one to give it */
+ poll_armed = tx_free_count != TX_BUFFERS || ring_tail - ring_head >= PERIOD_FRAMES;
+ if (poll_armed) {
+ clock_interval_to_deadline(5, NSEC_PER_MSEC, &deadline);
+ thread_call_enter_delayed(poll_call, deadline);
+ }
+ lck_mtx_unlock(&sound_lock);
+}
+
+/* The sink: see sys/redwood_audio.h. */
+static uint32_t
+sound_play(const int16_t *frames, uint32_t count)
+{
+ uint32_t room, taken;
+ uint64_t deadline;
+
+ lck_mtx_lock(&sound_lock);
+ room = RING_FRAMES - (ring_tail - ring_head);
+ taken = count < room ? count : room;
+ for (uint32_t i = 0; i < taken; i++, ring_tail++) {
+ ring[2 * (ring_tail % RING_FRAMES)] = frames[2 * i];
+ ring[2 * (ring_tail % RING_FRAMES) + 1] = frames[2 * i + 1];
+ }
+ sound_pump();
+ if (!poll_armed) {
+ poll_armed = true;
+ clock_interval_to_deadline(5, NSEC_PER_MSEC, &deadline);
+ thread_call_enter_delayed(poll_call, deadline);
+ }
+ lck_mtx_unlock(&sound_lock);
+ return taken;
+}
+
+static bool
+sound_attach(int slot)
+{
+ uint8_t streams[sizeof(uint32_t) + MAX_STREAMS * SND_PCM_INFO_SIZE]; /* a status word, then the streams */
+ struct snd_query_info query = { .code = SND_R_PCM_INFO, .size = SND_PCM_INFO_SIZE };
+ struct snd_pcm_set_params params = { .code = SND_R_PCM_SET_PARAMS, .buffer_bytes = TX_BUFFERS * PERIOD_BYTES,
+ .period_bytes = PERIOD_BYTES, .channels = REDWOOD_AUDIO_CHANNELS,
+ .format = SND_PCM_FMT_S16, .rate = SND_PCM_RATE_48000 };
+ struct snd_pcm_hdr command = { 0 };
+ uint32_t status, count;
+
+ if (kmem_alloc_contig(kernel_map, &shared, SHARED_SIZE, PAGE_MASK, 0, 0, KMA_KOBJECT | KMA_ZERO | KMA_DATA,
+ VM_KERN_MEMORY_IOKIT) != KERN_SUCCESS) {
+ return false;
+ }
+ shared_phys = kvtophys(shared);
+
+ reg_write(VIRTIO_STATUS, 0); /* reset */
+ reg_write(VIRTIO_STATUS, STATUS_ACKNOWLEDGE);
+ reg_write(VIRTIO_STATUS, STATUS_ACKNOWLEDGE | STATUS_DRIVER);
+ reg_write(VIRTIO_DRIVER_FEATURES_SEL, 0);
+ reg_write(VIRTIO_DRIVER_FEATURES, 0);
+ reg_write(VIRTIO_DRIVER_FEATURES_SEL, 1);
+ reg_write(VIRTIO_DRIVER_FEATURES, 1); /* bit 32: VIRTIO_F_VERSION_1 */
+ reg_write(VIRTIO_STATUS, STATUS_ACKNOWLEDGE | STATUS_DRIVER | STATUS_FEATURES_OK);
+ if (!(reg_read(VIRTIO_STATUS) & STATUS_FEATURES_OK)) {
+ printf("virtio-sound: slot %d: features refused\n", slot);
+ return false;
+ }
+ if (!queue_setup(&control, QUEUE_CONTROL, 0) || !queue_setup(&tx, QUEUE_TX, 1)) {
+ return false;
+ }
+ /* every transmit buffer is a chain of two descriptors that never changes */
+ for (uint16_t n = 0; n < TX_BUFFERS; n++) {
+ uint64_t buffer = shared_phys + OFFSET_TX + (uint64_t)n * sizeof(struct tx_buffer);
+
+ tx.desc[2 * n] = (struct vq_desc){ .addr = buffer, .len = offsetof(struct tx_buffer, status), .flags = DESC_F_NEXT,
+ .next = (uint16_t)(2 * n + 1) };
+ tx.desc[2 * n + 1] = (struct vq_desc){ .addr = buffer + offsetof(struct tx_buffer, status),
+ .len = sizeof(struct snd_pcm_status), .flags = DESC_F_WRITE };
+ tx_free[tx_free_count++] = n;
+ }
+ reg_write(VIRTIO_STATUS, STATUS_ACKNOWLEDGE | STATUS_DRIVER | STATUS_FEATURES_OK | STATUS_DRIVER_OK);
+
+ /* the first stream that plays */
+ count = *(volatile uint32_t *)(regs + VIRTIO_CONFIG + 4);
+ if (count > MAX_STREAMS) {
+ count = MAX_STREAMS;
+ }
+ query.count = count;
+ if (count == 0 || !control_request(&query, sizeof(query), streams, sizeof(uint32_t) + count * SND_PCM_INFO_SIZE)) {
+ return false;
+ }
+ for (stream = 0; stream < count; stream++) {
+ if (streams[sizeof(uint32_t) + stream * SND_PCM_INFO_SIZE + SND_PCM_INFO_DIRECTION] == SND_D_OUTPUT) {
+ break;
+ }
+ }
+ if (stream == count) {
+ printf("virtio-sound: slot %d: no output stream among %u\n", slot, count);
+ return false;
+ }
+ params.stream_id = command.stream_id = stream;
+ if (!control_request(&params, sizeof(params), &status, sizeof(status))) {
+ return false;
+ }
+ command.code = SND_R_PCM_PREPARE;
+ if (!control_request(&command, sizeof(command), &status, sizeof(status))) {
+ return false;
+ }
+ command.code = SND_R_PCM_START;
+ return control_request(&command, sizeof(command), &status, sizeof(status));
+}
+
+void
+redwood_virtio_sound_init(void)
+{
+ uint32_t enabled = 0;
+ vm_offset_t bus;
+
+ if (!PE_parse_boot_argn("virtio_sound", &enabled, sizeof(enabled)) || !enabled) {
+ return;
+ }
+ bus = ml_io_map(VIRTIO_BUS, VIRTIO_SLOTS * VIRTIO_SLOT_SIZE);
+ for (int slot = 0; slot < VIRTIO_SLOTS; slot++) {
+ regs = bus + (vm_offset_t)slot * VIRTIO_SLOT_SIZE;
+ if (reg_read(VIRTIO_MAGIC) != 0x74726976 || reg_read(VIRTIO_DEVICE_ID) != VIRTIO_ID_SOUND) {
+ continue;
+ }
+ if (reg_read(VIRTIO_VERSION) != 2) {
+ printf("virtio-sound: slot %d is a legacy transport; start QEMU with -global virtio-mmio.force-legacy=false\n", slot);
+ continue;
+ }
+ if (sound_attach(slot)) {
+ printf("virtio-sound: device in slot %d, stream %u\n", slot, stream);
+ poll_call = thread_call_allocate(sound_poll, NULL);
+ redwood_audio_set_sink("the virtio sound device", sound_play);
+ }
+ return;
+ }
+ printf("virtio-sound: no sound device\n");
+}
diff --git a/xnu/files/bsd/sys/redwood_audio.h b/xnu/files/bsd/sys/redwood_audio.h
new file mode 100644
index 0000000..9cefd3f
--- /dev/null
+++ b/xnu/files/bsd/sys/redwood_audio.h
@@ -0,0 +1,39 @@
+/*
+ * /dev/redwood-audio: the sound iOS plays, on its way to whatever can make it heard.
+ *
+ * iOS expects its output devices from Apple's audio drivers through IOAudio2; neither exists
+ * here. Instead the audio server (mediaserverd) is given a plug-in of ours that presents one
+ * stereo output device, and the plug-in writes what the server has mixed for that device
+ * here. In the kernel the samples go to a sink -- a driver for something that plays them --
+ * and, if asked for, into a recording that outlives the kernel (see dev/redwood_audio.c).
+ *
+ * write(): whole frames in the format below. Never blocks: the writer is the audio server's
+ * real-time thread, which paces itself (48000 frames a second while anything
+ * plays, nothing at all otherwise). What the sink cannot take is dropped.
+ */
+#ifndef _SYS_REDWOOD_AUDIO_H_
+#define _SYS_REDWOOD_AUDIO_H_
+
+#include <stdint.h>
+
+#define REDWOOD_AUDIO_DEVICE "/dev/redwood-audio"
+
+/* The one format: 16-bit signed little-endian samples, left then right. */
+#define REDWOOD_AUDIO_RATE 48000
+#define REDWOOD_AUDIO_CHANNELS 2
+#define REDWOOD_AUDIO_FRAME 4 /* bytes */
+
+#ifdef KERNEL
+/*
+ * For drivers. A sink is offered frames as they are written and says how many it took (the
+ * rest are lost); it is called from the writer's thread and must not wait.
+ */
+typedef uint32_t (*redwood_audio_sink_t)(const int16_t *frames, uint32_t count);
+
+void redwood_audio_set_sink(const char *name, redwood_audio_sink_t sink);
+void redwood_audio_init(void);
+void redwood_virtio_sound_init(void); /* boot-arg virtio_sound=1: QEMU's virtio sound device */
+void redwood_speaker_init(void); /* boot-arg speaker_probe=N: a look at the phone's speaker amplifiers */
+#endif
+
+#endif /* _SYS_REDWOOD_AUDIO_H_ */
diff --git a/xnu/files/osfmk/arm64/loader_return.c b/xnu/files/osfmk/arm64/loader_return.c
index 59318b2..e5081aa 100644
--- a/xnu/files/osfmk/arm64/loader_return.c
+++ b/xnu/files/osfmk/arm64/loader_return.c
@@ -153,6 +153,8 @@ struct loader_live {
uint64_t log_head, log_ring; /* sizes of the two parts */
const uint64_t *recording; /* loader_recording: { physical address, length } of a screen recording */
volatile uint64_t stop; /* the loader's to write: the host has asked for the run to end */
+ uint64_t magic2; /* "XNULIVE2": what follows is there (a loader may meet an older kernel) */
+ const uint64_t *sound; /* loader_sound: the same for a recording of the sound */
};
/*
@@ -160,11 +162,14 @@ struct loader_live {
* loader to hand to the host once the kernel is back. { physical address, bytes, kernel address }.
*/
uint64_t loader_recording[3];
+/* ... and of the sound (/dev/redwood-audio makes one with boot-arg rec_sound). */
+uint64_t loader_sound[3];
struct loader_live loader_live = {
.magic = 0x214556494c554e58ULL, .log = loader_log, .log_len = &loader_log_len, .log_ring_at = &loader_log_ring_at,
.log_wrapped = &loader_log_wrapped, .log_head = LOADER_LOG_HEAD, .log_ring = LOADER_LOG_RING,
.recording = loader_recording,
+ .magic2 = 0x324556494c554e58ULL, .sound = loader_sound,
};
/* Valid from the first instruction of C code: does not depend on gVirtBase/gPhysBase being set up. */
@@ -229,6 +234,11 @@ loader_jump(uint64_t reason, uint64_t code)
}
__asm__ volatile ("dc cvac, %0" : : "r" ((uintptr_t)loader_recording));
__asm__ volatile ("dc cvac, %0" : : "r" ((uintptr_t)loader_recording + 16));
+ for (uintptr_t p = loader_sound[2] & ~63UL; p < loader_sound[2] + loader_sound[1]; p += 64) {
+ __asm__ volatile ("dc cvac, %0" : : "r" (p));
+ }
+ __asm__ volatile ("dc cvac, %0" : : "r" ((uintptr_t)loader_sound));
+ __asm__ volatile ("dc cvac, %0" : : "r" ((uintptr_t)loader_sound + 16));
__asm__ volatile ("dsb sy");
register uint64_t r_ttbr0 __asm__("x0") = static_kvtophys(loader_l1);
diff --git a/xnu/redwood.patch b/xnu/redwood.patch
index 2deeb4d..3d5edd6 100644
--- a/xnu/redwood.patch
+++ b/xnu/redwood.patch
@@ -46,10 +46,10 @@ index 222158a93918..68bb0f3e56bf 100755
######################################################################
# HISTORY
diff --git a/bsd/conf/files b/bsd/conf/files
-index 44274016a4cf..fb5e9cb8a444 100644
+index 44274016a4cf..1750e10d3697 100644
--- a/bsd/conf/files
+++ b/bsd/conf/files
-@@ -109,6 +109,21 @@ bsd/dev/munge.c optional config_requires_u32_munging
+@@ -109,6 +109,24 @@ bsd/dev/munge.c optional config_requires_u32_munging
bsd/dev/unix_startup.c standard
bsd/dev/monotonic.c optional monotonic
@@ -63,6 +63,9 @@ index 44274016a4cf..fb5e9cb8a444 100644
+bsd/dev/redwood_apple80211.c standard
+bsd/dev/redwood_cpufreq.c standard
+bsd/dev/redwood_adreno.c standard
++bsd/dev/redwood_audio.c standard
++bsd/dev/redwood_virtio_sound.c standard
++bsd/dev/redwood_speaker.c standard
+bsd/dev/redwood_wifi.c standard
+bsd/dev/redwood_qmi.c standard
+bsd/dev/redwood_wlfw.c standard
@@ -71,7 +74,7 @@ index 44274016a4cf..fb5e9cb8a444 100644
bsd/dev/dev_perfmon.c optional config_perfmon
bsd/libkern/crc32.c standard
-@@ -155,6 +170,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs
+@@ -155,6 +173,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs
bsd/miscfs/mockfs/mockfs_fsnode.c optional mockfs
bsd/miscfs/mockfs/mockfs_vfsops.c optional mockfs
bsd/miscfs/mockfs/mockfs_vnops.c optional mockfs
@@ -82,7 +85,7 @@ index 44274016a4cf..fb5e9cb8a444 100644
bsd/miscfs/routefs/routefs_ops.c optional routefs
-@@ -361,6 +380,7 @@ bsd/security/audit/audit_syscalls.c standard
+@@ -361,6 +383,7 @@ bsd/security/audit/audit_syscalls.c standard
bsd/security/audit/audit_worker.c optional config_audit
bsd/pthread/pthread_shims.c standard
@@ -90,7 +93,7 @@ index 44274016a4cf..fb5e9cb8a444 100644
bsd/pthread/pthread_priority.c standard
bsd/pthread/pthread_workqueue.c standard
-@@ -383,6 +403,7 @@ bsd/kern/kern_debug.c standard
+@@ -383,6 +406,7 @@ bsd/kern/kern_debug.c standard
bsd/kern/kern_symfile.c standard
bsd/kern/kern_descrip.c standard
bsd/kern/kern_guarded.c standard
@@ -283,18 +286,19 @@ index 3e6bffa8c48e..43cffb98bdcc 100644
mdevremoveall(void)
{
diff --git a/bsd/kern/bsd_init.c b/bsd/kern/bsd_init.c
-index 4df41ba1f61b..abe2352d6a61 100644
+index 4df41ba1f61b..d532c567ba6b 100644
--- a/bsd/kern/bsd_init.c
+++ b/bsd/kern/bsd_init.c
-@@ -147,6 +147,7 @@
+@@ -147,6 +147,8 @@
#include <net/if_ether.h> /* for ether_family_init() */
#include <net/if_gif.h> /* for gif_init() */
#include <miscfs/devfs/devfsdefs.h> /* for devfs_kernel_mount() */
+#include <sys/redwood_input.h>
++#include <sys/redwood_audio.h>
#include <vm/vm_kern.h> /* for kmem_suballoc() */
#include <sys/proc_uuid_policy.h> /* proc_uuid_policy_init() */
#include <netinet/flow_divert.h> /* flow_divert_init() */
-@@ -490,7 +491,7 @@ bsd_init(void)
+@@ -490,7 +492,7 @@ bsd_init(void)
platform_stall_panic_or_spin(PLATFORM_STALL_XNU_LOCATION_BSD_INIT);
#endif
@@ -303,11 +307,12 @@ index 4df41ba1f61b..abe2352d6a61 100644
#if DEBUG_BSDINIT
#define bsd_init_kprintf(x, ...) kprintf("bsd_init: " x, ## __VA_ARGS__)
-@@ -976,6 +977,7 @@ bsd_init(void)
+@@ -976,6 +978,8 @@ bsd_init(void)
bsd_init_kprintf("calling devfs_kernel_mount\n");
devfs_kernel_mount(mounthere);
+ redwood_input_init(); /* /dev/redwood-touch */
++ redwood_audio_init(); /* /dev/redwood-audio */
}
#endif /* DEVFS */
@@ -667,6 +672,33 @@ index 4ca22ee4371a..e95e618b4cb6 100644
uio_t uio;
int spacetype = IS_64BIT_PROCESS(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;
+diff --git a/bsd/kern/sys_work_interval.c b/bsd/kern/sys_work_interval.c
+index b544bf307dfe..85e34caf9f62 100644
+--- a/bsd/kern/sys_work_interval.c
++++ b/bsd/kern/sys_work_interval.c
+@@ -265,6 +265,22 @@ work_interval_ctl(__unused proc_t p, struct work_interval_ctl_args *uap,
+
+ break;
+
++ case 6:
++ case 7:
++ case 8:
++ /*
++ * (redwood) Not in the open source: what os_workgroup_interval_start(), _update() and
++ * _finish() of iOS send, for the performance controller, which is not here either.
++ * CoreAudio does it in every I/O cycle and logs an error each time it is refused: fifty
++ * lines a second from the audio server's real-time thread. For its threads, and only
++ * for them, there is nothing to do and nothing wrong. (The window server asks for its
++ * frames too, and is used to the refusal.)
++ */
++ if (kern_work_interval_type_of_thread(current_thread()) == WORK_INTERVAL_TYPE_COREAUDIO) {
++ return 0;
++ }
++ return ENOTSUP;
++
+ default:
+ return ENOTSUP;
+ }
diff --git a/bsd/kern/uipc_syscalls.c b/bsd/kern/uipc_syscalls.c
index dce802fc36f1..e2e6b3a3f3db 100644
--- a/bsd/kern/uipc_syscalls.c
@@ -2414,6 +2446,42 @@ index bec97fbf7243..203e1f48783f 100644
#endif
#if CONFIG_DTRACE
+diff --git a/osfmk/kern/work_interval.c b/osfmk/kern/work_interval.c
+index f2b9ce24bd8d..3aed167fe32e 100644
+--- a/osfmk/kern/work_interval.c
++++ b/osfmk/kern/work_interval.c
+@@ -683,6 +683,18 @@ work_interval_get_priority(thread_t thread)
+ return priority;
+ }
+
++/*
++ * (redwood) What kind of work the thread's work interval is for: one of WORK_INTERVAL_TYPE_*,
++ * or WORK_INTERVAL_TYPE_LAST for a thread that has joined none.
++ */
++uint32_t
++kern_work_interval_type_of_thread(thread_t thread)
++{
++ const struct work_interval *work_interval = thread->th_work_interval;
++
++ return work_interval ? work_interval->wi_create_flags & WORK_INTERVAL_TYPE_MASK : WORK_INTERVAL_TYPE_LAST;
++}
++
+ /*
+ * Switch to a policy driven by the work interval (if applicable).
+ */
+diff --git a/osfmk/kern/work_interval.h b/osfmk/kern/work_interval.h
+index 8b46efb05c86..e161ca426b1a 100644
+--- a/osfmk/kern/work_interval.h
++++ b/osfmk/kern/work_interval.h
+@@ -83,6 +83,8 @@ extern kern_return_t
+ kern_work_interval_notify(thread_t thread, struct kern_work_interval_args* kwi_args);
+ extern kern_return_t
+ kern_work_interval_set_name(mach_port_name_t port_name, char *name, size_t len);
++extern uint32_t
++kern_work_interval_type_of_thread(thread_t thread);
+ extern kern_return_t
+ kern_work_interval_set_workload_id(mach_port_name_t port_name,
+ struct kern_work_interval_workload_id_args *workload_id_args);
diff --git a/pexpert/arm/pe_fiq.c b/pexpert/arm/pe_fiq.c
index 3ad743fc3efb..ce036c5a2c26 100644
--- a/pexpert/arm/pe_fiq.c