diff --git a/sys/arm/broadcom/bcm2835/bcm2835_audio.c b/sys/arm/broadcom/bcm2835/bcm2835_audio.c index 06bbc67bd7bd..1406fcc3d952 100644 --- a/sys/arm/broadcom/bcm2835/bcm2835_audio.c +++ b/sys/arm/broadcom/bcm2835/bcm2835_audio.c @@ -1,1011 +1,1133 @@ /*- * Copyright (c) 2015 Oleksandr Tymoshenko * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef HAVE_KERNEL_OPTION_HEADERS #include "opt_snd.h" #endif #include #include "mixer_if.h" #include "interface/compat/vchi_bsd.h" #include "interface/vchi/vchi.h" #include "interface/vchiq_arm/vchiq.h" #include "vc_vchi_audioserv_defs.h" /* Audio destination */ #define DEST_AUTO 0 #define DEST_HEADPHONES 1 #define DEST_HDMI 2 /* Playback state */ #define PLAYBACK_IDLE 0 #define PLAYBACK_PLAYING 1 #define PLAYBACK_STOPPING 2 /* Worker thread state */ #define WORKER_RUNNING 0 #define WORKER_STOPPING 1 #define WORKER_STOPPED 2 /* * Worker thread flags, set to 1 in flags_pending * when driver requests one or another operation * from worker. Cleared to 0 once worker performs * the operations. */ #define AUDIO_PARAMS (1 << 0) #define AUDIO_PLAY (1 << 1) #define AUDIO_STOP (1 << 2) #define VCHIQ_AUDIO_PACKET_SIZE 4000 #define VCHIQ_AUDIO_BUFFER_SIZE 10*VCHIQ_AUDIO_PACKET_SIZE #define VCHIQ_AUDIO_MAX_VOLUME /* volume in terms of 0.01dB */ #define VCHIQ_AUDIO_VOLUME_MIN -10239 #define VCHIQ_AUDIO_VOLUME(db100) (uint32_t)(-((db100) << 8)/100) /* dB levels with 5% volume step */ static int db_levels[] = { VCHIQ_AUDIO_VOLUME_MIN, -4605, -3794, -3218, -2772, -2407, -2099, -1832, -1597, -1386, -1195, -1021, -861, -713, -575, -446, -325, -210, -102, 0, }; static uint32_t bcm2835_audio_playfmt[] = { SND_FORMAT(AFMT_U8, 1, 0), SND_FORMAT(AFMT_U8, 2, 0), SND_FORMAT(AFMT_S8, 1, 0), SND_FORMAT(AFMT_S8, 2, 0), SND_FORMAT(AFMT_S16_LE, 1, 0), SND_FORMAT(AFMT_S16_LE, 2, 0), SND_FORMAT(AFMT_U16_LE, 1, 0), SND_FORMAT(AFMT_U16_LE, 2, 0), 0 }; static struct pcmchan_caps bcm2835_audio_playcaps = {8000, 48000, bcm2835_audio_playfmt, 0}; struct bcm2835_audio_info; struct bcm2835_audio_chinfo { struct bcm2835_audio_info *parent; struct pcm_channel *channel; struct snd_dbuf *buffer; uint32_t fmt, spd, blksz; /* Pointer to first unsubmitted sample */ uint32_t unsubmittedptr; /* * Number of bytes in "submitted but not played" * pseudo-buffer */ int available_space; int playback_state; uint64_t callbacks; uint64_t submitted_samples; uint64_t retrieved_samples; uint64_t underruns; int starved; + struct bcm_log_vars { + unsigned int bsize ; + int slept_for_lack_of_space ; + } log_vars; +#define DEFAULT_LOG_VALUES \ + ((struct bcm_log_vars) { .bsize = 0 , .slept_for_lack_of_space = 0 }) }; struct bcm2835_audio_info { device_t dev; unsigned int bufsz; struct bcm2835_audio_chinfo pch; uint32_t dest, volume; struct intr_config_hook intr_hook; /* VCHI data */ VCHI_INSTANCE_T vchi_instance; VCHI_CONNECTION_T *vchi_connection; VCHI_SERVICE_HANDLE_T vchi_handle; struct mtx lock; struct cv worker_cv; uint32_t flags_pending; int verbose_trace; /* Worker thread state */ int worker_state; }; #define BCM2835_AUDIO_LOCK(sc) mtx_lock(&(sc)->lock) #define BCM2835_AUDIO_LOCKED(sc) mtx_assert(&(sc)->lock, MA_OWNED) #define BCM2835_AUDIO_UNLOCK(sc) mtx_unlock(&(sc)->lock) #define BCM2835_LOG_ERROR(sc,...) \ do { \ device_printf((sc)->dev, __VA_ARGS__); \ } while(0) #define BCM2835_LOG_INFO(sc,...) \ do { \ if (sc->verbose_trace > 0) \ device_printf((sc)->dev, __VA_ARGS__); \ } while(0) #define BCM2835_LOG_WARN(sc,...) \ do { \ if (sc->verbose_trace > 1) \ device_printf((sc)->dev, __VA_ARGS__); \ } while(0) #define BCM2835_LOG_TRACE(sc,...) \ do { \ if(sc->verbose_trace > 2) \ device_printf((sc)->dev, __VA_ARGS__); \ } while(0) +/* Useful for circular buffer calcs */ +#define MOD_DIFF(front,rear,mod) (((mod) + (front) - (rear)) % (mod)) + + static const char * dest_description(uint32_t dest) { switch (dest) { case DEST_AUTO: return "AUTO"; break; case DEST_HEADPHONES: return "HEADPHONES"; break; case DEST_HDMI: return "HDMI"; break; default: return "UNKNOWN"; break; } } static void bcm2835_worker_update_params(struct bcm2835_audio_info *sc) { BCM2835_AUDIO_LOCKED(sc); sc->flags_pending |= AUDIO_PARAMS; cv_signal(&sc->worker_cv); } static void bcm2835_worker_play_start(struct bcm2835_audio_info *sc) { BCM2835_AUDIO_LOCK(sc); sc->flags_pending &= ~(AUDIO_STOP); sc->flags_pending |= AUDIO_PLAY; cv_signal(&sc->worker_cv); BCM2835_AUDIO_UNLOCK(sc); } static void bcm2835_worker_play_stop(struct bcm2835_audio_info *sc) { BCM2835_AUDIO_LOCK(sc); sc->flags_pending &= ~(AUDIO_PLAY); sc->flags_pending |= AUDIO_STOP; cv_signal(&sc->worker_cv); BCM2835_AUDIO_UNLOCK(sc); } static void bcm2835_audio_callback(void *param, const VCHI_CALLBACK_REASON_T reason, void *msg_handle) { struct bcm2835_audio_info *sc = (struct bcm2835_audio_info *)param; int32_t status; uint32_t msg_len; VC_AUDIO_MSG_T m; if (reason != VCHI_CALLBACK_MSG_AVAILABLE) return; status = vchi_msg_dequeue(sc->vchi_handle, &m, sizeof m, &msg_len, VCHI_FLAGS_NONE); if (status != 0) return; if (m.type == VC_AUDIO_MSG_TYPE_RESULT) { if (m.u.result.success) { device_printf(sc->dev, "msg type %08x failed\n", m.type); } } else if (m.type == VC_AUDIO_MSG_TYPE_COMPLETE) { - struct bcm2835_audio_chinfo *ch = m.u.complete.cookie; + unsigned int signaled = 0; + struct bcm2835_audio_chinfo *ch ; +#if defined(__aarch64__) + ch = (void *) ((((size_t)m.u.complete.callback) << 32) + | ((size_t)m.u.complete.cookie)); +#else + ch = (void *) (m.u.complete.cookie); +#endif int count = m.u.complete.count & 0xffff; int perr = (m.u.complete.count & (1U << 30)) != 0; + + BCM2835_LOG_TRACE(sc, "in:: count:0x%x perr:%d\n", + m.u.complete.count, perr); + ch->callbacks++; if (perr) ch->underruns++; BCM2835_AUDIO_LOCK(sc); if (ch->playback_state != PLAYBACK_IDLE) { /* Prevent LOR */ BCM2835_AUDIO_UNLOCK(sc); chn_intr(sc->pch.channel); BCM2835_AUDIO_LOCK(sc); } /* We should check again, state might have changed */ if (ch->playback_state != PLAYBACK_IDLE) { if (!perr) { if ((ch->available_space + count)> VCHIQ_AUDIO_BUFFER_SIZE) { device_printf(sc->dev, "inconsistent data in callback:\n"); device_printf(sc->dev, "available_space == %d, count = %d, perr=%d\n", ch->available_space, count, perr); device_printf(sc->dev, "retrieved_samples = %ju, submitted_samples = %ju\n", (uintmax_t)ch->retrieved_samples, (uintmax_t)ch->submitted_samples); } - ch->available_space += count; - ch->retrieved_samples += count; } - if (perr || (ch->available_space >= VCHIQ_AUDIO_PACKET_SIZE)) - cv_signal(&sc->worker_cv); + ch->available_space += count; + ch->retrieved_samples += count; + /* + * XXXMDC + * Experimental: if VC says it's empty, believe it + * Has to come after the usual adjustments + */ + if(perr){ + ch->available_space = VCHIQ_AUDIO_BUFFER_SIZE; + perr = ch->retrieved_samples; // shd be != 0 + } + + if ((ch->available_space >= 1*VCHIQ_AUDIO_PACKET_SIZE)){ + cv_signal(&sc->worker_cv); + signaled = 1; + } } BCM2835_AUDIO_UNLOCK(sc); + if(perr){ + BCM2835_LOG_WARN(sc, + "VC starved; reported %u for a total of %u\n" + "worker %s\n", count, perr, + (signaled ? "signaled": "not signaled")); + } } else BCM2835_LOG_WARN(sc, "%s: unknown m.type: %d\n", __func__, m.type); } /* VCHIQ stuff */ static void bcm2835_audio_init(struct bcm2835_audio_info *sc) { int status; /* Initialize and create a VCHI connection */ status = vchi_initialise(&sc->vchi_instance); if (status != 0) { BCM2835_LOG_ERROR(sc, "vchi_initialise failed: %d\n", status); return; } status = vchi_connect(NULL, 0, sc->vchi_instance); if (status != 0) { BCM2835_LOG_ERROR(sc, "vchi_connect failed: %d\n", status); return; } SERVICE_CREATION_T params = { VCHI_VERSION_EX(VC_AUDIOSERV_VER, VC_AUDIOSERV_MIN_VER), VC_AUDIO_SERVER_NAME, /* 4cc service code */ sc->vchi_connection, /* passed in fn pointers */ 0, /* rx fifo size */ 0, /* tx fifo size */ bcm2835_audio_callback, /* service callback */ sc, /* service callback parameter */ 1, 1, 0 /* want crc check on bulk transfers */ }; status = vchi_service_open(sc->vchi_instance, ¶ms, &sc->vchi_handle); if (status != 0) sc->vchi_handle = VCHIQ_SERVICE_HANDLE_INVALID; } static void bcm2835_audio_release(struct bcm2835_audio_info *sc) { int success; if (sc->vchi_handle != VCHIQ_SERVICE_HANDLE_INVALID) { success = vchi_service_close(sc->vchi_handle); if (success != 0) BCM2835_LOG_ERROR(sc, "vchi_service_close failed: %d\n", success); vchi_service_release(sc->vchi_handle); sc->vchi_handle = VCHIQ_SERVICE_HANDLE_INVALID; } vchi_disconnect(sc->vchi_instance); } static void bcm2835_audio_reset_channel(struct bcm2835_audio_chinfo *ch) { ch->available_space = VCHIQ_AUDIO_BUFFER_SIZE; ch->unsubmittedptr = 0; sndbuf_reset(ch->buffer); } static void bcm2835_audio_start(struct bcm2835_audio_chinfo *ch) { VC_AUDIO_MSG_T m; int ret; struct bcm2835_audio_info *sc = ch->parent; if (sc->vchi_handle != VCHIQ_SERVICE_HANDLE_INVALID) { m.type = VC_AUDIO_MSG_TYPE_START; ret = vchi_msg_queue(sc->vchi_handle, &m, sizeof m, VCHI_FLAGS_BLOCK_UNTIL_QUEUED, NULL); if (ret != 0) BCM2835_LOG_ERROR(sc, "%s: vchi_msg_queue failed (err %d)\n", __func__, ret); } } static void bcm2835_audio_stop(struct bcm2835_audio_chinfo *ch) { VC_AUDIO_MSG_T m; int ret; struct bcm2835_audio_info *sc = ch->parent; if (sc->vchi_handle != VCHIQ_SERVICE_HANDLE_INVALID) { m.type = VC_AUDIO_MSG_TYPE_STOP; m.u.stop.draining = 0; + BCM2835_LOG_INFO(sc,"sending stop\n"); ret = vchi_msg_queue(sc->vchi_handle, &m, sizeof m, VCHI_FLAGS_BLOCK_UNTIL_QUEUED, NULL); if (ret != 0) BCM2835_LOG_ERROR(sc, "%s: vchi_msg_queue failed (err %d)\n", __func__, ret); } } static void bcm2835_audio_open(struct bcm2835_audio_info *sc) { VC_AUDIO_MSG_T m; int ret; if (sc->vchi_handle != VCHIQ_SERVICE_HANDLE_INVALID) { m.type = VC_AUDIO_MSG_TYPE_OPEN; ret = vchi_msg_queue(sc->vchi_handle, &m, sizeof m, VCHI_FLAGS_BLOCK_UNTIL_QUEUED, NULL); if (ret != 0) BCM2835_LOG_ERROR(sc, "%s: vchi_msg_queue failed (err %d)\n", __func__, ret); } } static void bcm2835_audio_update_controls(struct bcm2835_audio_info *sc, uint32_t volume, uint32_t dest) { VC_AUDIO_MSG_T m; int ret, db; if (sc->vchi_handle != VCHIQ_SERVICE_HANDLE_INVALID) { m.type = VC_AUDIO_MSG_TYPE_CONTROL; m.u.control.dest = dest; if (volume > 99) volume = 99; db = db_levels[volume/5]; m.u.control.volume = VCHIQ_AUDIO_VOLUME(db); ret = vchi_msg_queue(sc->vchi_handle, &m, sizeof m, VCHI_FLAGS_BLOCK_UNTIL_QUEUED, NULL); if (ret != 0) BCM2835_LOG_ERROR(sc, "%s: vchi_msg_queue failed (err %d)\n", __func__, ret); } } static void bcm2835_audio_update_params(struct bcm2835_audio_info *sc, uint32_t fmt, uint32_t speed) { VC_AUDIO_MSG_T m; int ret; if (sc->vchi_handle != VCHIQ_SERVICE_HANDLE_INVALID) { m.type = VC_AUDIO_MSG_TYPE_CONFIG; m.u.config.channels = AFMT_CHANNEL(fmt); m.u.config.samplerate = speed; m.u.config.bps = AFMT_BIT(fmt); ret = vchi_msg_queue(sc->vchi_handle, &m, sizeof m, VCHI_FLAGS_BLOCK_UNTIL_QUEUED, NULL); if (ret != 0) BCM2835_LOG_ERROR(sc, "%s: vchi_msg_queue failed (err %d)\n", __func__, ret); } } static bool bcm2835_audio_buffer_should_sleep(struct bcm2835_audio_chinfo *ch) { + ch->log_vars.slept_for_lack_of_space = 0; if (ch->playback_state != PLAYBACK_PLAYING) return (true); /* Not enough data */ - if (sndbuf_getready(ch->buffer) < VCHIQ_AUDIO_PACKET_SIZE) { - printf("starve\n"); + /* XXXMDC Take unsubmitted stuff into account */ + if (sndbuf_getready(ch->buffer) + - MOD_DIFF( + ch->unsubmittedptr, + sndbuf_getreadyptr(ch->buffer), + ch->buffer->bufsize + ) < VCHIQ_AUDIO_PACKET_SIZE) { ch->starved++; return (true); } /* Not enough free space */ if (ch->available_space < VCHIQ_AUDIO_PACKET_SIZE) { + ch->log_vars.slept_for_lack_of_space = 1; return (true); } return (false); } static void bcm2835_audio_write_samples(struct bcm2835_audio_chinfo *ch, void *buf, uint32_t count) { struct bcm2835_audio_info *sc = ch->parent; VC_AUDIO_MSG_T m; int ret; if (sc->vchi_handle == VCHIQ_SERVICE_HANDLE_INVALID) { return; } m.type = VC_AUDIO_MSG_TYPE_WRITE; m.u.write.count = count; m.u.write.max_packet = VCHIQ_AUDIO_PACKET_SIZE; - m.u.write.callback = NULL; - m.u.write.cookie = ch; +#if defined(__aarch64__) + m.u.write.callback = (uint32_t)(((size_t) ch) >> 32) & 0xffffffff; + m.u.write.cookie = (uint32_t)(((size_t) ch) & 0xffffffff); +#else + m.u.write.callback = (uint32_t) NULL; + m.u.write.cookie = (uint32_t) ch; +#endif m.u.write.silence = 0; ret = vchi_msg_queue(sc->vchi_handle, &m, sizeof m, VCHI_FLAGS_BLOCK_UNTIL_QUEUED, NULL); if (ret != 0) BCM2835_LOG_ERROR(sc, "%s: vchi_msg_queue failed (err %d)\n", __func__, ret); while (count > 0) { int bytes = MIN((int)m.u.write.max_packet, (int)count); ret = vchi_msg_queue(sc->vchi_handle, buf, bytes, VCHI_FLAGS_BLOCK_UNTIL_QUEUED, NULL); if (ret != 0) BCM2835_LOG_ERROR(sc, "%s: vchi_msg_queue failed: %d\n", __func__, ret); buf = (char *)buf + bytes; count -= bytes; } } static void bcm2835_audio_worker(void *data) { struct bcm2835_audio_info *sc = (struct bcm2835_audio_info *)data; struct bcm2835_audio_chinfo *ch = &sc->pch; uint32_t speed, format; uint32_t volume, dest; uint32_t flags; uint32_t count, size, readyptr; uint8_t *buf; ch->playback_state = PLAYBACK_IDLE; while (1) { if (sc->worker_state != WORKER_RUNNING) break; BCM2835_AUDIO_LOCK(sc); /* * wait until there are flags set or buffer is ready * to consume more samples */ while ((sc->flags_pending == 0) && bcm2835_audio_buffer_should_sleep(ch)) { cv_wait_sig(&sc->worker_cv, &sc->lock); + if ((sc->flags_pending == 0) && + (ch->log_vars.slept_for_lack_of_space)) { + BCM2835_LOG_TRACE(sc, + "slept for lack of space\n"); + } } flags = sc->flags_pending; /* Clear pending flags */ sc->flags_pending = 0; BCM2835_AUDIO_UNLOCK(sc); /* Requested to change parameters */ if (flags & AUDIO_PARAMS) { BCM2835_AUDIO_LOCK(sc); speed = ch->spd; format = ch->fmt; volume = sc->volume; dest = sc->dest; BCM2835_AUDIO_UNLOCK(sc); if (ch->playback_state == PLAYBACK_IDLE) bcm2835_audio_update_params(sc, format, speed); bcm2835_audio_update_controls(sc, volume, dest); } /* Requested to stop playback */ if ((flags & AUDIO_STOP) && (ch->playback_state == PLAYBACK_PLAYING)) { bcm2835_audio_stop(ch); BCM2835_AUDIO_LOCK(sc); bcm2835_audio_reset_channel(&sc->pch); ch->playback_state = PLAYBACK_IDLE; + long sub_total = ch->submitted_samples; + long retd = ch->retrieved_samples; BCM2835_AUDIO_UNLOCK(sc); + BCM2835_LOG_INFO(sc, + "stopped audio. submitted a total of %lu " + "having been acked %lu\n", sub_total, retd); continue; } /* Requested to start playback */ if ((flags & AUDIO_PLAY) && (ch->playback_state == PLAYBACK_IDLE)) { + BCM2835_LOG_INFO(sc, "starting audio\n"); + unsigned int bsize = ch->buffer->bufsize; BCM2835_AUDIO_LOCK(sc); ch->playback_state = PLAYBACK_PLAYING; + ch->log_vars.bsize = bsize; BCM2835_AUDIO_UNLOCK(sc); + BCM2835_LOG_INFO(sc, "buffer size is %u\n", bsize); bcm2835_audio_start(ch); } if (ch->playback_state == PLAYBACK_IDLE) continue; if (sndbuf_getready(ch->buffer) == 0) continue; - count = sndbuf_getready(ch->buffer); + uint32_t i_count; + + /* XXXMDC Take unsubmitted stuff into account */ + count = i_count = sndbuf_getready(ch->buffer) + - MOD_DIFF(ch->unsubmittedptr, + sndbuf_getreadyptr(ch->buffer), + ch->buffer->bufsize); size = ch->buffer->bufsize; - readyptr = sndbuf_getreadyptr(ch->buffer); + readyptr = ch->unsubmittedptr; + + int size_changed = 0; + unsigned int available; BCM2835_AUDIO_LOCK(sc); - if (readyptr + count > size) + if (size != ch->log_vars.bsize) { + ch->log_vars.bsize = size; + size_changed = 1; + } + available = ch->available_space; + /* + * XXXMDC + * + * On arm64, got into situations where + * readyptr was less than a packet away + * from the end of the buffer, which led + * to count being set to 0 and, inexorably, starvation. + * Code below tries to take that into account. + * The problem might have been fixed with some of the + * other changes that were made in the meantime, + * but for now this works fine. + */ + if (readyptr + count > size) { count = size - readyptr; - count = min(count, ch->available_space); - count -= (count % VCHIQ_AUDIO_PACKET_SIZE); + } + if(count > ch->available_space){ + count = ch->available_space; + count -= (count % VCHIQ_AUDIO_PACKET_SIZE); + }else if (count > VCHIQ_AUDIO_PACKET_SIZE){ + count -= (count % VCHIQ_AUDIO_PACKET_SIZE); + }else if (size > count + readyptr) { + count = 0; + } BCM2835_AUDIO_UNLOCK(sc); - if (count < VCHIQ_AUDIO_PACKET_SIZE) + if (count % VCHIQ_AUDIO_PACKET_SIZE != 0) { + BCM2835_LOG_WARN(sc, "count: %u initial count: %u " + "size: %u readyptr: %u available: %u\n", count, + i_count,size,readyptr,available); + } + if (size_changed) + BCM2835_LOG_INFO(sc, "bsize changed to %u\n", size); + + if (count == 0) { + BCM2835_LOG_WARN(sc, + "not enough room for a packet: count %d," + " i_count %d, rptr %d, size %d\n", + count, i_count, readyptr, size); continue; + } buf = ch->buffer->buf + readyptr; bcm2835_audio_write_samples(ch, buf, count); BCM2835_AUDIO_LOCK(sc); ch->unsubmittedptr = (ch->unsubmittedptr + count) % ch->buffer->bufsize; ch->available_space -= count; ch->submitted_samples += count; + long sub = count; + long sub_total = ch->submitted_samples; + long retd = ch->retrieved_samples; KASSERT(ch->available_space >= 0, ("ch->available_space == %d\n", ch->available_space)); BCM2835_AUDIO_UNLOCK(sc); + + BCM2835_LOG_TRACE(sc, + "submitted %lu for a total of %lu having been acked %lu; " + "rptr %d, had %u available\n", sub, sub_total, retd, + readyptr, available); } BCM2835_AUDIO_LOCK(sc); sc->worker_state = WORKER_STOPPED; cv_signal(&sc->worker_cv); BCM2835_AUDIO_UNLOCK(sc); kproc_exit(0); } static void bcm2835_audio_create_worker(struct bcm2835_audio_info *sc) { struct proc *newp; sc->worker_state = WORKER_RUNNING; if (kproc_create(bcm2835_audio_worker, (void*)sc, &newp, 0, 0, "bcm2835_audio_worker") != 0) { BCM2835_LOG_ERROR(sc, "failed to create bcm2835_audio_worker\n"); } } /* -------------------------------------------------------------------- */ /* channel interface for VCHI audio */ static void * bcmchan_init(kobj_t obj, void *devinfo, struct snd_dbuf *b, struct pcm_channel *c, int dir) { struct bcm2835_audio_info *sc = devinfo; struct bcm2835_audio_chinfo *ch = &sc->pch; void *buffer; if (dir == PCMDIR_REC) return NULL; ch->parent = sc; ch->channel = c; ch->buffer = b; /* default values */ ch->spd = 44100; ch->fmt = SND_FORMAT(AFMT_S16_LE, 2, 0); ch->blksz = VCHIQ_AUDIO_PACKET_SIZE; buffer = malloc(sc->bufsz, M_DEVBUF, M_WAITOK | M_ZERO); if (sndbuf_setup(ch->buffer, buffer, sc->bufsz) != 0) { device_printf(sc->dev, "sndbuf_setup failed\n"); free(buffer, M_DEVBUF); return NULL; } + ch->log_vars = DEFAULT_LOG_VALUES; + BCM2835_AUDIO_LOCK(sc); bcm2835_worker_update_params(sc); BCM2835_AUDIO_UNLOCK(sc); return ch; } static int bcmchan_free(kobj_t obj, void *data) { struct bcm2835_audio_chinfo *ch = data; void *buffer; buffer = ch->buffer->buf; if (buffer) free(buffer, M_DEVBUF); return (0); } static int bcmchan_setformat(kobj_t obj, void *data, uint32_t format) { struct bcm2835_audio_chinfo *ch = data; struct bcm2835_audio_info *sc = ch->parent; BCM2835_AUDIO_LOCK(sc); ch->fmt = format; bcm2835_worker_update_params(sc); BCM2835_AUDIO_UNLOCK(sc); return 0; } static uint32_t bcmchan_setspeed(kobj_t obj, void *data, uint32_t speed) { struct bcm2835_audio_chinfo *ch = data; struct bcm2835_audio_info *sc = ch->parent; BCM2835_AUDIO_LOCK(sc); ch->spd = speed; bcm2835_worker_update_params(sc); BCM2835_AUDIO_UNLOCK(sc); return ch->spd; } static uint32_t bcmchan_setblocksize(kobj_t obj, void *data, uint32_t blocksize) { struct bcm2835_audio_chinfo *ch = data; return ch->blksz; } static int bcmchan_trigger(kobj_t obj, void *data, int go) { struct bcm2835_audio_chinfo *ch = data; struct bcm2835_audio_info *sc = ch->parent; if (!PCMTRIG_COMMON(go)) return (0); switch (go) { case PCMTRIG_START: /* kickstart data flow */ chn_intr(sc->pch.channel); ch->submitted_samples = 0; ch->retrieved_samples = 0; bcm2835_worker_play_start(sc); break; case PCMTRIG_STOP: case PCMTRIG_ABORT: bcm2835_worker_play_stop(sc); break; default: break; } return 0; } static uint32_t bcmchan_getptr(kobj_t obj, void *data) { struct bcm2835_audio_chinfo *ch = data; struct bcm2835_audio_info *sc = ch->parent; uint32_t ret; BCM2835_AUDIO_LOCK(sc); ret = ch->unsubmittedptr; BCM2835_AUDIO_UNLOCK(sc); return ret; } static struct pcmchan_caps * bcmchan_getcaps(kobj_t obj, void *data) { return &bcm2835_audio_playcaps; } static kobj_method_t bcmchan_methods[] = { KOBJMETHOD(channel_init, bcmchan_init), KOBJMETHOD(channel_free, bcmchan_free), KOBJMETHOD(channel_setformat, bcmchan_setformat), KOBJMETHOD(channel_setspeed, bcmchan_setspeed), KOBJMETHOD(channel_setblocksize, bcmchan_setblocksize), KOBJMETHOD(channel_trigger, bcmchan_trigger), KOBJMETHOD(channel_getptr, bcmchan_getptr), KOBJMETHOD(channel_getcaps, bcmchan_getcaps), KOBJMETHOD_END }; CHANNEL_DECLARE(bcmchan); /************************************************************/ static int bcmmix_init(struct snd_mixer *m) { mix_setdevs(m, SOUND_MASK_VOLUME); return (0); } static int bcmmix_set(struct snd_mixer *m, unsigned dev, unsigned left, unsigned right) { struct bcm2835_audio_info *sc = mix_getdevinfo(m); switch (dev) { case SOUND_MIXER_VOLUME: BCM2835_AUDIO_LOCK(sc); sc->volume = left; bcm2835_worker_update_params(sc); BCM2835_AUDIO_UNLOCK(sc); break; default: break; } return left | (left << 8); } static kobj_method_t bcmmixer_methods[] = { KOBJMETHOD(mixer_init, bcmmix_init), KOBJMETHOD(mixer_set, bcmmix_set), KOBJMETHOD_END }; MIXER_DECLARE(bcmmixer); static int sysctl_bcm2835_audio_dest(SYSCTL_HANDLER_ARGS) { struct bcm2835_audio_info *sc = arg1; int val; int err; val = sc->dest; err = sysctl_handle_int(oidp, &val, 0, req); if (err || !req->newptr) /* error || read request */ return (err); if ((val < 0) || (val > 2)) return (EINVAL); BCM2835_AUDIO_LOCK(sc); sc->dest = val; bcm2835_worker_update_params(sc); BCM2835_AUDIO_UNLOCK(sc); if (bootverbose) device_printf(sc->dev, "destination set to %s\n", dest_description(val)); return (0); } static void vchi_audio_sysctl_init(struct bcm2835_audio_info *sc) { struct sysctl_ctx_list *ctx; struct sysctl_oid *tree_node; struct sysctl_oid_list *tree; /* * Add system sysctl tree/handlers. */ ctx = device_get_sysctl_ctx(sc->dev); tree_node = device_get_sysctl_tree(sc->dev); tree = SYSCTL_CHILDREN(tree_node); SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "dest", CTLFLAG_RW | CTLTYPE_UINT | CTLFLAG_NEEDGIANT, sc, sizeof(*sc), sysctl_bcm2835_audio_dest, "IU", "audio destination, " "0 - auto, 1 - headphones, 2 - HDMI"); SYSCTL_ADD_UQUAD(ctx, tree, OID_AUTO, "callbacks", CTLFLAG_RD, &sc->pch.callbacks, "callbacks total"); SYSCTL_ADD_UQUAD(ctx, tree, OID_AUTO, "submitted", CTLFLAG_RD, &sc->pch.submitted_samples, "last play submitted samples"); SYSCTL_ADD_UQUAD(ctx, tree, OID_AUTO, "retrieved", CTLFLAG_RD, &sc->pch.retrieved_samples, "last play retrieved samples"); SYSCTL_ADD_UQUAD(ctx, tree, OID_AUTO, "underruns", CTLFLAG_RD, &sc->pch.underruns, "callback underruns"); SYSCTL_ADD_INT(ctx, tree, OID_AUTO, "freebuffer", CTLFLAG_RD, &sc->pch.available_space, sc->pch.available_space, "callbacks total"); SYSCTL_ADD_INT(ctx, tree, OID_AUTO, "starved", CTLFLAG_RD, &sc->pch.starved, sc->pch.starved, "number of starved conditions"); SYSCTL_ADD_INT(ctx, tree, OID_AUTO, "trace", CTLFLAG_RW, &sc->verbose_trace, sc->verbose_trace, "enable tracing of transfers"); } static void bcm2835_audio_identify(driver_t *driver, device_t parent) { BUS_ADD_CHILD(parent, 0, "pcm", 0); } static int bcm2835_audio_probe(device_t dev) { device_set_desc(dev, "VCHIQ audio"); return (BUS_PROBE_DEFAULT); } static void bcm2835_audio_delayed_init(void *xsc) { struct bcm2835_audio_info *sc; char status[SND_STATUSLEN]; sc = xsc; config_intrhook_disestablish(&sc->intr_hook); bcm2835_audio_init(sc); bcm2835_audio_open(sc); sc->volume = 75; sc->dest = DEST_AUTO; sc->verbose_trace = 0; if (mixer_init(sc->dev, &bcmmixer_class, sc)) { device_printf(sc->dev, "mixer_init failed\n"); goto no; } pcm_init(sc->dev, sc); pcm_addchan(sc->dev, PCMDIR_PLAY, &bcmchan_class, sc); snprintf(status, SND_STATUSLEN, "at VCHIQ"); if (pcm_register(sc->dev, status)) { device_printf(sc->dev, "pcm_register failed\n"); goto no; } bcm2835_audio_reset_channel(&sc->pch); bcm2835_audio_create_worker(sc); vchi_audio_sysctl_init(sc); no: ; } static int bcm2835_audio_attach(device_t dev) { struct bcm2835_audio_info *sc; sc = malloc(sizeof(*sc), M_DEVBUF, M_WAITOK | M_ZERO); sc->dev = dev; sc->bufsz = VCHIQ_AUDIO_BUFFER_SIZE; mtx_init(&sc->lock, device_get_nameunit(dev), "bcm_audio_lock", MTX_DEF); cv_init(&sc->worker_cv, "worker_cv"); sc->vchi_handle = VCHIQ_SERVICE_HANDLE_INVALID; /* * We need interrupts enabled for VCHI to work properly, * so delay initialization until it happens. */ sc->intr_hook.ich_func = bcm2835_audio_delayed_init; sc->intr_hook.ich_arg = sc; if (config_intrhook_establish(&sc->intr_hook) != 0) goto no; return 0; no: return ENXIO; } static int bcm2835_audio_detach(device_t dev) { int r; struct bcm2835_audio_info *sc; sc = pcm_getdevinfo(dev); /* Stop worker thread */ BCM2835_AUDIO_LOCK(sc); sc->worker_state = WORKER_STOPPING; cv_signal(&sc->worker_cv); /* Wait for thread to exit */ while (sc->worker_state != WORKER_STOPPED) cv_wait_sig(&sc->worker_cv, &sc->lock); BCM2835_AUDIO_UNLOCK(sc); r = pcm_unregister(dev); if (r) return r; mtx_destroy(&sc->lock); cv_destroy(&sc->worker_cv); bcm2835_audio_release(sc); free(sc, M_DEVBUF); return 0; } static device_method_t bcm2835_audio_methods[] = { /* Device interface */ DEVMETHOD(device_identify, bcm2835_audio_identify), DEVMETHOD(device_probe, bcm2835_audio_probe), DEVMETHOD(device_attach, bcm2835_audio_attach), DEVMETHOD(device_detach, bcm2835_audio_detach), { 0, 0 } }; static driver_t bcm2835_audio_driver = { "pcm", bcm2835_audio_methods, PCM_SOFTC_SIZE, }; DRIVER_MODULE(bcm2835_audio, vchiq, bcm2835_audio_driver, 0, 0); MODULE_DEPEND(bcm2835_audio, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER); MODULE_DEPEND(bcm2835_audio, vchiq, 1, 1, 1); MODULE_VERSION(bcm2835_audio, 1); diff --git a/sys/arm/broadcom/bcm2835/vc_vchi_audioserv_defs.h b/sys/arm/broadcom/bcm2835/vc_vchi_audioserv_defs.h index 896e706ff492..ea972ff2d001 100644 --- a/sys/arm/broadcom/bcm2835/vc_vchi_audioserv_defs.h +++ b/sys/arm/broadcom/bcm2835/vc_vchi_audioserv_defs.h @@ -1,154 +1,154 @@ /* * Copyright (c) 2012, Broadcom Europe Ltd * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _VC_AUDIO_DEFS_H_ #define _VC_AUDIO_DEFS_H_ #define VC_AUDIOSERV_MIN_VER 1 #define VC_AUDIOSERV_VER 2 /* FourCC code used for VCHI connection */ #define VC_AUDIO_SERVER_NAME MAKE_FOURCC("AUDS") /* Maximum message length */ #define VC_AUDIO_MAX_MSG_LEN (sizeof( VC_AUDIO_MSG_T )) /* * List of screens that are currently supported * All message types supported for HOST->VC direction */ typedef enum { VC_AUDIO_MSG_TYPE_RESULT, /* Generic result */ VC_AUDIO_MSG_TYPE_COMPLETE, /* playback of samples complete */ VC_AUDIO_MSG_TYPE_CONFIG, /* Configure */ VC_AUDIO_MSG_TYPE_CONTROL, /* control */ VC_AUDIO_MSG_TYPE_OPEN, /* open */ VC_AUDIO_MSG_TYPE_CLOSE, /* close/shutdown */ VC_AUDIO_MSG_TYPE_START, /* start output (i.e. resume) */ VC_AUDIO_MSG_TYPE_STOP, /* stop output (i.e. pause) */ VC_AUDIO_MSG_TYPE_WRITE, /* write samples */ VC_AUDIO_MSG_TYPE_MAX } VC_AUDIO_MSG_TYPE; static const char *vc_audio_msg_type_names[] = { "VC_AUDIO_MSG_TYPE_RESULT", "VC_AUDIO_MSG_TYPE_COMPLETE", "VC_AUDIO_MSG_TYPE_CONFIG", "VC_AUDIO_MSG_TYPE_CONTROL", "VC_AUDIO_MSG_TYPE_OPEN", "VC_AUDIO_MSG_TYPE_CLOSE", "VC_AUDIO_MSG_TYPE_START", "VC_AUDIO_MSG_TYPE_STOP", "VC_AUDIO_MSG_TYPE_WRITE", "VC_AUDIO_MSG_TYPE_MAX" }; /* configure the audio */ typedef struct { uint32_t channels; uint32_t samplerate; uint32_t bps; } VC_AUDIO_CONFIG_T; typedef struct { uint32_t volume; uint32_t dest; } VC_AUDIO_CONTROL_T; typedef struct { uint32_t dummy; } VC_AUDIO_OPEN_T; typedef struct { uint32_t dummy; } VC_AUDIO_CLOSE_T; typedef struct { uint32_t dummy; } VC_AUDIO_START_T; typedef struct { uint32_t draining; } VC_AUDIO_STOP_T; typedef struct { uint32_t count; /* in bytes */ - void *callback; - void *cookie; + uint32_t callback; + uint32_t cookie; uint16_t silence; uint16_t max_packet; } VC_AUDIO_WRITE_T; /* Generic result for a request (VC->HOST) */ typedef struct { int32_t success; /* Success value */ } VC_AUDIO_RESULT_T; /* Generic result for a request (VC->HOST) */ typedef struct { int32_t count; /* Success value */ - void *callback; - void *cookie; + uint32_t callback; + uint32_t cookie; } VC_AUDIO_COMPLETE_T; /* Message header for all messages in HOST->VC direction */ typedef struct { int32_t type; /* Message type (VC_AUDIO_MSG_TYPE) */ union { VC_AUDIO_CONFIG_T config; VC_AUDIO_CONTROL_T control; VC_AUDIO_OPEN_T open; VC_AUDIO_CLOSE_T close; VC_AUDIO_START_T start; VC_AUDIO_STOP_T stop; VC_AUDIO_WRITE_T write; VC_AUDIO_RESULT_T result; VC_AUDIO_COMPLETE_T complete; } u; } VC_AUDIO_MSG_T; #endif /* _VC_AUDIO_DEFS_H_ */ diff --git a/sys/arm64/conf/std.broadcom b/sys/arm64/conf/std.broadcom index 3332aaac0826..65bee16e315d 100644 --- a/sys/arm64/conf/std.broadcom +++ b/sys/arm64/conf/std.broadcom @@ -1,37 +1,40 @@ # # Broadcom SoC support # # SoC support options SOC_BRCM_BCM2837 options SOC_BRCM_BCM2838 options SOC_BRCM_NS2 # I2C device bcm2835_bsc # Broadcom BCM283x I2C bus # SPI device bcm2835_spi # Broadcom BCM283x SPI bus # Serial (COM) ports device uart_mu # RPI3 aux port device pl011 # Ethernet NICs device genet # Broadcom on RPi4 # USB support device dwcotg # USB ethernet support device muge device smsc # MMC/SD/SDIO Card slot support device sdhci options FDT device acpi +# Sound support +device vchiq + # DTBs makeoptions MODULES_EXTRA+="dtb/rpi" diff --git a/sys/contrib/vchiq/interface/compat/vchi_bsd.c b/sys/contrib/vchiq/interface/compat/vchi_bsd.c index 8f47b3dc02d6..08f2f66dfc54 100644 --- a/sys/contrib/vchiq/interface/compat/vchi_bsd.c +++ b/sys/contrib/vchiq/interface/compat/vchi_bsd.c @@ -1,530 +1,526 @@ /*- * Copyright (c) 2010 Max Khon * All rights reserved. * * This software was developed by Max Khon under sponsorship from * the FreeBSD Foundation and Ethon Technologies GmbH. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $Id: bsd-compat.c 9253 2010-09-02 10:12:09Z fjoe $ */ #include #include #include #include #include #include #include #include #include #include #include #include "mbox_if.h" #include MALLOC_DEFINE(M_VCHI, "VCHI", "VCHI"); /* * Timer API */ static void run_timer(void *arg) { struct timer_list *t = (struct timer_list *) arg; void (*function)(unsigned long); mtx_lock_spin(&t->mtx); if (callout_pending(&t->callout)) { /* callout was reset */ mtx_unlock_spin(&t->mtx); return; } if (!callout_active(&t->callout)) { /* callout was stopped */ mtx_unlock_spin(&t->mtx); return; } callout_deactivate(&t->callout); function = t->function; mtx_unlock_spin(&t->mtx); function(t->data); } void vchiq_init_timer(struct timer_list *t) { mtx_init(&t->mtx, "dahdi timer lock", NULL, MTX_SPIN); callout_init(&t->callout, 1); t->expires = 0; /* * function and data are not initialized intentionally: * they are not initialized by Linux implementation too */ } void vchiq_setup_timer(struct timer_list *t, void (*function)(unsigned long), unsigned long data) { t->function = function; t->data = data; vchiq_init_timer(t); } void vchiq_mod_timer(struct timer_list *t, unsigned long expires) { mtx_lock_spin(&t->mtx); callout_reset(&t->callout, expires - jiffies, run_timer, t); mtx_unlock_spin(&t->mtx); } void vchiq_add_timer(struct timer_list *t) { vchiq_mod_timer(t, t->expires); } int vchiq_del_timer_sync(struct timer_list *t) { mtx_lock_spin(&t->mtx); callout_stop(&t->callout); mtx_unlock_spin(&t->mtx); mtx_destroy(&t->mtx); return 0; } int vchiq_del_timer(struct timer_list *t) { vchiq_del_timer_sync(t); return 0; } /* * Completion API */ void init_completion(struct completion *c) { cv_init(&c->cv, "VCHI completion cv"); mtx_init(&c->lock, "VCHI completion lock", "condvar", MTX_DEF); c->done = 0; } void destroy_completion(struct completion *c) { cv_destroy(&c->cv); mtx_destroy(&c->lock); } void complete(struct completion *c) { mtx_lock(&c->lock); if (c->done >= 0) { KASSERT(c->done < INT_MAX, ("c->done overflow")); /* XXX check */ c->done++; cv_signal(&c->cv); } else { KASSERT(c->done == -1, ("Invalid value of c->done: %d", c->done)); } mtx_unlock(&c->lock); } void complete_all(struct completion *c) { mtx_lock(&c->lock); if (c->done >= 0) { KASSERT(c->done < INT_MAX, ("c->done overflow")); /* XXX check */ c->done = -1; cv_broadcast(&c->cv); } else { KASSERT(c->done == -1, ("Invalid value of c->done: %d", c->done)); } mtx_unlock(&c->lock); } void INIT_COMPLETION_locked(struct completion *c) { mtx_lock(&c->lock); c->done = 0; mtx_unlock(&c->lock); } static void _completion_claim(struct completion *c) { KASSERT(mtx_owned(&c->lock), ("_completion_claim should be called with acquired lock")); KASSERT(c->done != 0, ("_completion_claim on non-waited completion")); if (c->done > 0) c->done--; else KASSERT(c->done == -1, ("Invalid value of c->done: %d", c->done)); } void wait_for_completion(struct completion *c) { mtx_lock(&c->lock); if (!c->done) cv_wait(&c->cv, &c->lock); c->done--; mtx_unlock(&c->lock); } int try_wait_for_completion(struct completion *c) { int res = 0; mtx_lock(&c->lock); if (!c->done) res = 1; else c->done--; mtx_unlock(&c->lock); return res == 0; } int wait_for_completion_interruptible_timeout(struct completion *c, unsigned long timeout) { int res = 0; unsigned long start, now; start = jiffies; mtx_lock(&c->lock); while (c->done == 0) { res = cv_timedwait_sig(&c->cv, &c->lock, timeout); if (res) goto out; now = jiffies; if (timeout < (now - start)) { res = EWOULDBLOCK; goto out; } timeout -= (now - start); start = now; } _completion_claim(c); res = 0; out: mtx_unlock(&c->lock); if (res == EWOULDBLOCK) { return 0; } else if ((res == EINTR) || (res == ERESTART)) { return -ERESTART; } else { KASSERT((res == 0), ("res = %d", res)); return timeout; } } int wait_for_completion_interruptible(struct completion *c) { int res = 0; mtx_lock(&c->lock); while (c->done == 0) { res = cv_wait_sig(&c->cv, &c->lock); if (res) goto out; } _completion_claim(c); out: mtx_unlock(&c->lock); if ((res == EINTR) || (res == ERESTART)) res = -ERESTART; return res; } int wait_for_completion_killable(struct completion *c) { return wait_for_completion_interruptible(c); } /* * Semaphore API */ void sema_sysinit(void *arg) { struct semaphore *s = arg; _sema_init(s, 1); } void _sema_init(struct semaphore *s, int value) { bzero(s, sizeof(*s)); mtx_init(&s->mtx, "sema lock", "VCHIQ sepmaphore backing lock", MTX_DEF | MTX_NOWITNESS | MTX_QUIET); cv_init(&s->cv, "sema cv"); s->value = value; } void _sema_destroy(struct semaphore *s) { mtx_destroy(&s->mtx); cv_destroy(&s->cv); } void down(struct semaphore *s) { mtx_lock(&s->mtx); while (s->value == 0) { s->waiters++; cv_wait(&s->cv, &s->mtx); s->waiters--; } s->value--; mtx_unlock(&s->mtx); } int down_interruptible(struct semaphore *s) { int ret ; ret = 0; - mtx_lock(&s->mtx); while (s->value == 0) { s->waiters++; ret = cv_wait_sig(&s->cv, &s->mtx); s->waiters--; - if (ret == EINTR) { + /* XXXMDC As per its semaphore.c, linux can only return EINTR */ + if (ret) { mtx_unlock(&s->mtx); - return (-EINTR); + return -EINTR; } - - if (ret == ERESTART) - continue; } s->value--; mtx_unlock(&s->mtx); return (0); } int down_trylock(struct semaphore *s) { int ret; ret = 0; mtx_lock(&s->mtx); if (s->value > 0) { /* Success. */ s->value--; ret = 0; } else { ret = -EAGAIN; } mtx_unlock(&s->mtx); return (ret); } void up(struct semaphore *s) { mtx_lock(&s->mtx); s->value++; if (s->waiters && s->value > 0) cv_signal(&s->cv); mtx_unlock(&s->mtx); } /* * Logging API */ void rlprintf(int pps, const char *fmt, ...) { va_list ap; static struct timeval last_printf; static int count; if (ppsratecheck(&last_printf, &count, pps)) { va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); } } void device_rlprintf(int pps, device_t dev, const char *fmt, ...) { va_list ap; static struct timeval last_printf; static int count; if (ppsratecheck(&last_printf, &count, pps)) { va_start(ap, fmt); device_print_prettyname(dev); vprintf(fmt, ap); va_end(ap); } } /* * Signals API */ void flush_signals(VCHIQ_THREAD_T thr) { printf("Implement ME: %s\n", __func__); } int fatal_signal_pending(VCHIQ_THREAD_T thr) { - printf("Implement ME: %s\n", __func__); - return (0); + return (curproc_sigkilled()); } /* * kthread API */ /* * This is a hack to avoid memory leak */ #define MAX_THREAD_DATA_SLOTS 32 static int thread_data_slot = 0; struct thread_data { void *data; int (*threadfn)(void *); }; static struct thread_data thread_slots[MAX_THREAD_DATA_SLOTS]; static void kthread_wrapper(void *data) { struct thread_data *slot; slot = data; slot->threadfn(slot->data); } VCHIQ_THREAD_T vchiq_thread_create(int (*threadfn)(void *data), void *data, const char namefmt[], ...) { VCHIQ_THREAD_T newp; va_list ap; char name[MAXCOMLEN+1]; struct thread_data *slot; if (thread_data_slot >= MAX_THREAD_DATA_SLOTS) { printf("kthread_create: out of thread data slots\n"); return (NULL); } slot = &thread_slots[thread_data_slot]; slot->data = data; slot->threadfn = threadfn; va_start(ap, namefmt); vsnprintf(name, sizeof(name), namefmt, ap); va_end(ap); newp = NULL; if (kproc_create(kthread_wrapper, (void*)slot, &newp, 0, 0, "%s", name) != 0) { /* Just to be sure */ newp = NULL; } else thread_data_slot++; return newp; } void set_user_nice(VCHIQ_THREAD_T thr, int nice) { /* NOOP */ } void wake_up_process(VCHIQ_THREAD_T thr) { /* NOOP */ } void bcm_mbox_write(int channel, uint32_t data) { device_t mbox; mbox = devclass_get_device(devclass_find("mbox"), 0); if (mbox) MBOX_WRITE(mbox, channel, data); } diff --git a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_2835_arm.c b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_2835_arm.c index 185e81e71bdc..7e105a6b3b77 100644 --- a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_2835_arm.c +++ b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_2835_arm.c @@ -1,607 +1,712 @@ /** * Copyright (c) 2010-2012 Broadcom. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the above-listed copyright holders may not be used * to endorse or promote products derived from this software without * specific prior written permission. * * ALTERNATIVELY, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2, as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include MALLOC_DEFINE(M_VCPAGELIST, "vcpagelist", "VideoCore pagelist memory"); #define TOTAL_SLOTS (VCHIQ_SLOT_ZERO_SLOTS + 2 * 32) #define VCHIQ_DOORBELL_IRQ IRQ_ARM_DOORBELL_0 #define VCHIQ_ARM_ADDRESS(x) ((void *)PHYS_TO_VCBUS(pmap_kextract((vm_offset_t)(x)))) #include "vchiq_arm.h" #include "vchiq_2835.h" #include "vchiq_connected.h" #include "vchiq_killable.h" #define MAX_FRAGMENTS (VCHIQ_NUM_CURRENT_BULKS * 2) +/* + * XXXMDC + * Do this less ad-hoc-y -- e.g. + * https://github.com/raspberrypi/linux/commit/c683db8860a80562a2bb5b451d77b3e471d24f36 + */ +#if defined(__aarch64__) +int g_cache_line_size = 64; +#else int g_cache_line_size = 32; +#endif static int g_fragment_size; +unsigned int g_long_bulk_space = 0; +#define VM_PAGE_TO_VC_BULK_PAGE(x) (\ + g_long_bulk_space ? VM_PAGE_TO_PHYS(x)\ + : PHYS_TO_VCBUS(VM_PAGE_TO_PHYS(x))\ +) + typedef struct vchiq_2835_state_struct { int inited; VCHIQ_ARM_STATE_T arm_state; } VCHIQ_2835_ARM_STATE_T; static char *g_slot_mem; static int g_slot_mem_size; vm_paddr_t g_slot_phys; /* BSD DMA */ bus_dma_tag_t bcm_slots_dma_tag; bus_dmamap_t bcm_slots_dma_map; static char *g_fragments_base; static char *g_free_fragments; struct semaphore g_free_fragments_sema; static DEFINE_SEMAPHORE(g_free_fragments_mutex); typedef struct bulkinfo_struct { PAGELIST_T *pagelist; bus_dma_tag_t pagelist_dma_tag; bus_dmamap_t pagelist_dma_map; void *buf; size_t size; } BULKINFO_T; static int create_pagelist(char __user *buf, size_t count, unsigned short type, struct proc *p, BULKINFO_T *bi); static void free_pagelist(BULKINFO_T *bi, int actual); static void vchiq_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int err) { bus_addr_t *addr; if (err) return; addr = (bus_addr_t*)arg; *addr = PHYS_TO_VCBUS(segs[0].ds_addr); } +#if defined(__aarch64__) /* See comment in free_pagelist */ +static int +invalidate_cachelines_in_range_of_ppage( + vm_page_t p, + size_t offset, + size_t count +) +{ + if(offset + count > PAGE_SIZE){ return EINVAL; } + uint8_t *dst = (uint8_t*)pmap_quick_enter_page(p); + if (!dst){ + return ENOMEM; + } + cpu_dcache_inv_range((void *)((vm_offset_t)dst + offset), count); + pmap_quick_remove_page((vm_offset_t)dst); + return 0; +} + +/* XXXMDC bulk instead of loading and invalidating single pages? */ +static void +invalidate_cachelines_in_range_of_ppage_seq(vm_page_t *p, size_t start, + size_t count) +{ + if (start >= PAGE_SIZE) + goto invalid_input; + +#define _NEXT_AT(x,_m) (((x)+((_m)-1)) & ~((_m)-1)) /* for power of two m */ + size_t offset = _NEXT_AT(start,g_cache_line_size); +#undef _NEXT_AT + count = (offset < start + count) ? count - (offset - start) : 0; + offset = offset & (PAGE_SIZE - 1); + for (size_t done = 0; count > done; + p++, done += PAGE_SIZE - offset, offset = 0) { + size_t in_page = PAGE_SIZE - offset; + size_t todo = (count-done > in_page) ? in_page : count-done; + int e = invalidate_cachelines_in_range_of_ppage(*p, offset, todo); + if (e != 0) + goto problem_in_loop; + } + return; + +problem_in_loop: +invalid_input: + WARN_ON(1); + return; +} +#endif + static int copyout_page(vm_page_t p, size_t offset, void *kaddr, size_t size) { uint8_t *dst; dst = (uint8_t*)pmap_quick_enter_page(p); if (!dst) return ENOMEM; memcpy(dst + offset, kaddr, size); pmap_quick_remove_page((vm_offset_t)dst); return 0; } int __init vchiq_platform_init(VCHIQ_STATE_T *state) { VCHIQ_SLOT_ZERO_T *vchiq_slot_zero; int frag_mem_size; int err; int i; /* Allocate space for the channels in coherent memory */ g_slot_mem_size = PAGE_ALIGN(TOTAL_SLOTS * VCHIQ_SLOT_SIZE); g_fragment_size = 2*g_cache_line_size; frag_mem_size = PAGE_ALIGN(g_fragment_size * MAX_FRAGMENTS); err = bus_dma_tag_create( NULL, PAGE_SIZE, 0, /* alignment, boundary */ BUS_SPACE_MAXADDR_32BIT, /* lowaddr */ BUS_SPACE_MAXADDR, /* highaddr */ NULL, NULL, /* filter, filterarg */ g_slot_mem_size + frag_mem_size, 1, /* maxsize, nsegments */ g_slot_mem_size + frag_mem_size, 0, /* maxsegsize, flags */ NULL, NULL, /* lockfunc, lockarg */ &bcm_slots_dma_tag); err = bus_dmamem_alloc(bcm_slots_dma_tag, (void **)&g_slot_mem, BUS_DMA_COHERENT | BUS_DMA_WAITOK, &bcm_slots_dma_map); if (err) { vchiq_log_error(vchiq_core_log_level, "Unable to allocate channel memory"); err = -ENOMEM; goto failed_alloc; } err = bus_dmamap_load(bcm_slots_dma_tag, bcm_slots_dma_map, g_slot_mem, g_slot_mem_size + frag_mem_size, vchiq_dmamap_cb, &g_slot_phys, 0); if (err) { vchiq_log_error(vchiq_core_log_level, "cannot load DMA map"); err = -ENOMEM; goto failed_load; } - WARN_ON(((int)g_slot_mem & (PAGE_SIZE - 1)) != 0); + WARN_ON(((size_t)g_slot_mem & (PAGE_SIZE - 1)) != 0); vchiq_slot_zero = vchiq_init_slots(g_slot_mem, g_slot_mem_size); if (!vchiq_slot_zero) { err = -EINVAL; goto failed_init_slots; } vchiq_slot_zero->platform_data[VCHIQ_PLATFORM_FRAGMENTS_OFFSET_IDX] = (int)g_slot_phys + g_slot_mem_size; vchiq_slot_zero->platform_data[VCHIQ_PLATFORM_FRAGMENTS_COUNT_IDX] = MAX_FRAGMENTS; g_fragments_base = (char *)(g_slot_mem + g_slot_mem_size); g_slot_mem_size += frag_mem_size; g_free_fragments = g_fragments_base; for (i = 0; i < (MAX_FRAGMENTS - 1); i++) { *(char **)&g_fragments_base[i*g_fragment_size] = &g_fragments_base[(i + 1)*g_fragment_size]; } *(char **)&g_fragments_base[i*g_fragment_size] = NULL; _sema_init(&g_free_fragments_sema, MAX_FRAGMENTS); if (vchiq_init_state(state, vchiq_slot_zero, 0/*slave*/) != VCHIQ_SUCCESS) { err = -EINVAL; goto failed_vchiq_init; } bcm_mbox_write(BCM2835_MBOX_CHAN_VCHIQ, (unsigned int)g_slot_phys); vchiq_log_info(vchiq_arm_log_level, "vchiq_init - done (slots %zx, phys %zx)", (size_t)vchiq_slot_zero, g_slot_phys); vchiq_call_connected_callbacks(); return 0; failed_vchiq_init: failed_init_slots: bus_dmamap_unload(bcm_slots_dma_tag, bcm_slots_dma_map); failed_load: bus_dmamem_free(bcm_slots_dma_tag, g_slot_mem, bcm_slots_dma_map); failed_alloc: bus_dma_tag_destroy(bcm_slots_dma_tag); return err; } void __exit vchiq_platform_exit(VCHIQ_STATE_T *state) { bus_dmamap_unload(bcm_slots_dma_tag, bcm_slots_dma_map); bus_dmamem_free(bcm_slots_dma_tag, g_slot_mem, bcm_slots_dma_map); bus_dma_tag_destroy(bcm_slots_dma_tag); } VCHIQ_STATUS_T vchiq_platform_init_state(VCHIQ_STATE_T *state) { VCHIQ_STATUS_T status = VCHIQ_SUCCESS; state->platform_state = kzalloc(sizeof(VCHIQ_2835_ARM_STATE_T), GFP_KERNEL); ((VCHIQ_2835_ARM_STATE_T*)state->platform_state)->inited = 1; status = vchiq_arm_init_state(state, &((VCHIQ_2835_ARM_STATE_T*)state->platform_state)->arm_state); if(status != VCHIQ_SUCCESS) { ((VCHIQ_2835_ARM_STATE_T*)state->platform_state)->inited = 0; } return status; } VCHIQ_ARM_STATE_T* vchiq_platform_get_arm_state(VCHIQ_STATE_T *state) { if(!((VCHIQ_2835_ARM_STATE_T*)state->platform_state)->inited) { BUG(); } return &((VCHIQ_2835_ARM_STATE_T*)state->platform_state)->arm_state; } int vchiq_copy_from_user(void *dst, const void *src, int size) { if (((vm_offset_t)(src)) < VM_MIN_KERNEL_ADDRESS) { int error = copyin(src, dst, size); return error ? VCHIQ_ERROR : VCHIQ_SUCCESS; } else bcopy(src, dst, size); return 0; } VCHIQ_STATUS_T vchiq_prepare_bulk_data(VCHIQ_BULK_T *bulk, VCHI_MEM_HANDLE_T memhandle, void *offset, int size, int dir) { BULKINFO_T *bi; int ret; WARN_ON(memhandle != VCHI_MEM_HANDLE_INVALID); bi = malloc(sizeof(*bi), M_VCPAGELIST, M_WAITOK | M_ZERO); ret = create_pagelist((char __user *)offset, size, (dir == VCHIQ_BULK_RECEIVE) ? PAGELIST_READ : PAGELIST_WRITE, current, bi); if (ret != 0) return VCHIQ_ERROR; bulk->handle = memhandle; bulk->data = VCHIQ_ARM_ADDRESS(bi->pagelist); /* Store the pagelist address in remote_data, which isn't used by the slave. */ bulk->remote_data = bi; return VCHIQ_SUCCESS; } void vchiq_complete_bulk(VCHIQ_BULK_T *bulk) { if (bulk && bulk->remote_data && bulk->actual) free_pagelist((BULKINFO_T *)bulk->remote_data, bulk->actual); } void vchiq_transfer_bulk(VCHIQ_BULK_T *bulk) { /* * This should only be called on the master (VideoCore) side, but * provide an implementation to avoid the need for ifdefery. */ BUG(); } void vchiq_dump_platform_state(void *dump_context) { char buf[80]; int len; len = snprintf(buf, sizeof(buf), " Platform: 2835 (VC master)"); vchiq_dump(dump_context, buf, len + 1); } VCHIQ_STATUS_T vchiq_platform_suspend(VCHIQ_STATE_T *state) { return VCHIQ_ERROR; } VCHIQ_STATUS_T vchiq_platform_resume(VCHIQ_STATE_T *state) { return VCHIQ_SUCCESS; } void vchiq_platform_paused(VCHIQ_STATE_T *state) { } void vchiq_platform_resumed(VCHIQ_STATE_T *state) { } int vchiq_platform_videocore_wanted(VCHIQ_STATE_T* state) { return 1; // autosuspend not supported - videocore always wanted } int vchiq_platform_use_suspend_timer(void) { return 0; } void vchiq_dump_platform_use_state(VCHIQ_STATE_T *state) { vchiq_log_info(vchiq_arm_log_level, "Suspend timer not in use"); } void vchiq_platform_handle_timeout(VCHIQ_STATE_T *state) { (void)state; } /* * Local functions */ static void pagelist_page_free(vm_page_t pp) { vm_page_unwire(pp, PQ_INACTIVE); } /* There is a potential problem with partial cache lines (pages?) ** at the ends of the block when reading. If the CPU accessed anything in ** the same line (page?) then it may have pulled old data into the cache, ** obscuring the new data underneath. We can solve this by transferring the ** partial cache lines separately, and allowing the ARM to copy into the ** cached area. ** N.B. This implementation plays slightly fast and loose with the Linux ** driver programming rules, e.g. its use of __virt_to_bus instead of ** dma_map_single, but it isn't a multi-platform driver and it benefits ** from increased speed as a result. */ + static int create_pagelist(char __user *buf, size_t count, unsigned short type, struct proc *p, BULKINFO_T *bi) { PAGELIST_T *pagelist; vm_page_t* pages; - unsigned long *addrs; + uint32_t *addrs; unsigned int num_pages, i; vm_offset_t offset; int pagelist_size; char *addr, *base_addr, *next_addr; int run, addridx, actual_pages; int err; vm_paddr_t pagelist_phys; vm_paddr_t pa; offset = (vm_offset_t)buf & (PAGE_SIZE - 1); num_pages = (count + offset + PAGE_SIZE - 1) / PAGE_SIZE; bi->pagelist = NULL; bi->buf = buf; bi->size = count; /* Allocate enough storage to hold the page pointers and the page ** list */ pagelist_size = sizeof(PAGELIST_T) + (num_pages * sizeof(unsigned long)) + (num_pages * sizeof(pages[0])); err = bus_dma_tag_create( NULL, PAGE_SIZE, 0, /* alignment, boundary */ BUS_SPACE_MAXADDR_32BIT, /* lowaddr */ BUS_SPACE_MAXADDR, /* highaddr */ NULL, NULL, /* filter, filterarg */ pagelist_size, 1, /* maxsize, nsegments */ pagelist_size, 0, /* maxsegsize, flags */ NULL, NULL, /* lockfunc, lockarg */ &bi->pagelist_dma_tag); err = bus_dmamem_alloc(bi->pagelist_dma_tag, (void **)&pagelist, BUS_DMA_COHERENT | BUS_DMA_WAITOK, &bi->pagelist_dma_map); - if (err) { + if (err || !pagelist) { vchiq_log_error(vchiq_core_log_level, "Unable to allocate pagelist memory"); err = -ENOMEM; goto failed_alloc; } err = bus_dmamap_load(bi->pagelist_dma_tag, bi->pagelist_dma_map, pagelist, pagelist_size, vchiq_dmamap_cb, &pagelist_phys, 0); if (err) { vchiq_log_error(vchiq_core_log_level, "cannot load DMA map for pagelist memory"); err = -ENOMEM; + bi->pagelist = pagelist; goto failed_load; } vchiq_log_trace(vchiq_arm_log_level, "create_pagelist - %zx (%zu bytes @%p)", (size_t)pagelist, count, buf); addrs = pagelist->addrs; pages = (vm_page_t*)(addrs + num_pages); actual_pages = vm_fault_quick_hold_pages(&p->p_vmspace->vm_map, (vm_offset_t)buf, count, (type == PAGELIST_READ ? VM_PROT_WRITE : 0 ) | VM_PROT_READ, pages, num_pages); if (actual_pages != num_pages) { if (actual_pages > 0) vm_page_unhold_pages(pages, actual_pages); - free(pagelist, M_VCPAGELIST); - return (-ENOMEM); + err = -ENOMEM; + bi->pagelist = pagelist; + goto failed_hold; } pagelist->length = count; pagelist->type = type; pagelist->offset = offset; /* Group the pages into runs of contiguous pages */ - base_addr = (void *)PHYS_TO_VCBUS(VM_PAGE_TO_PHYS(pages[0])); + size_t run_ceil = g_long_bulk_space ? 0x100 : PAGE_SIZE; + unsigned int pg_addr_rshift = g_long_bulk_space ? 4 : 0; + base_addr = (void *) VM_PAGE_TO_VC_BULK_PAGE(pages[0]); next_addr = base_addr + PAGE_SIZE; addridx = 0; run = 0; - +#define _PG_BLOCK(base,run) \ + ((((size_t) (base)) >> pg_addr_rshift) & ~(run_ceil-1)) + (run) for (i = 1; i < num_pages; i++) { - addr = (void *)PHYS_TO_VCBUS(VM_PAGE_TO_PHYS(pages[i])); - if ((addr == next_addr) && (run < (PAGE_SIZE - 1))) { + addr = (void *)VM_PAGE_TO_VC_BULK_PAGE(pages[i]); + if ((addr == next_addr) && (run < run_ceil - 1)) { next_addr += PAGE_SIZE; run++; } else { - addrs[addridx] = (unsigned long)base_addr + run; - addridx++; + addrs[addridx++] = (uint32_t) _PG_BLOCK(base_addr,run); base_addr = addr; next_addr = addr + PAGE_SIZE; run = 0; } } - - addrs[addridx] = (unsigned long)base_addr + run; - addridx++; + addrs[addridx++] = _PG_BLOCK(base_addr, run); +#undef _PG_BLOCK /* Partial cache lines (fragments) require special measures */ if ((type == PAGELIST_READ) && ((pagelist->offset & (g_cache_line_size - 1)) || ((pagelist->offset + pagelist->length) & (g_cache_line_size - 1)))) { char *fragments; if (down_interruptible(&g_free_fragments_sema) != 0) { free(pagelist, M_VCPAGELIST); return -EINTR; } WARN_ON(g_free_fragments == NULL); down(&g_free_fragments_mutex); fragments = g_free_fragments; WARN_ON(fragments == NULL); g_free_fragments = *(char **) g_free_fragments; up(&g_free_fragments_mutex); - pagelist->type = - PAGELIST_READ_WITH_FRAGMENTS + - (fragments - g_fragments_base)/g_fragment_size; + pagelist->type = PAGELIST_READ_WITH_FRAGMENTS + + (fragments - g_fragments_base)/g_fragment_size; +#if defined(__aarch64__) + bus_dmamap_sync(bcm_slots_dma_tag, bcm_slots_dma_map, + BUS_DMASYNC_PREREAD); +#endif } +#if defined(__aarch64__) + if(type == PAGELIST_READ) { + cpu_dcache_wbinv_range(buf, count); + } else { + cpu_dcache_wb_range(buf, count); + } + dsb(sy); +#else pa = pmap_extract(PCPU_GET(curpmap), (vm_offset_t)buf); dcache_wbinv_poc((vm_offset_t)buf, pa, count); +#endif - bus_dmamap_sync(bi->pagelist_dma_tag, bi->pagelist_dma_map, BUS_DMASYNC_PREWRITE); + bus_dmamap_sync(bi->pagelist_dma_tag, bi->pagelist_dma_map, + BUS_DMASYNC_PREWRITE); bi->pagelist = pagelist; return 0; +failed_hold: + bus_dmamap_unload(bi->pagelist_dma_tag,bi->pagelist_dma_map); failed_load: bus_dmamem_free(bi->pagelist_dma_tag, bi->pagelist, bi->pagelist_dma_map); failed_alloc: bus_dma_tag_destroy(bi->pagelist_dma_tag); return err; } static void free_pagelist(BULKINFO_T *bi, int actual) { vm_page_t*pages; unsigned int num_pages, i; PAGELIST_T *pagelist; pagelist = bi->pagelist; vchiq_log_trace(vchiq_arm_log_level, "free_pagelist - %zx, %d (%lu bytes @%p)", (size_t)pagelist, (int)actual, (unsigned long)pagelist->length, bi->buf); num_pages = (pagelist->length + pagelist->offset + PAGE_SIZE - 1) / PAGE_SIZE; pages = (vm_page_t*)(pagelist->addrs + num_pages); +#if defined(__aarch64__) + /* + * On arm64, even if the user keeps their end of the bargain + * -- do NOT touch the buffers sent to VC -- but reads around the + * pagelist after the invalidation above, the arm might preemptively + * load (and validate) cache lines for areas inside the page list, + * so we must invalidate them again. + * + * The functional test does it and without this it doesn't pass. + * + * XXXMDC might it be enough to invalidate a couple of pages at + * the ends of the page list? + */ + if(pagelist->type >= PAGELIST_READ && actual > 0) + invalidate_cachelines_in_range_of_ppage_seq(pages, + pagelist->offset, actual); +#endif + /* Deal with any partial cache lines (fragments) */ if (pagelist->type >= PAGELIST_READ_WITH_FRAGMENTS) { char *fragments = g_fragments_base + (pagelist->type - PAGELIST_READ_WITH_FRAGMENTS)*g_fragment_size; int head_bytes, tail_bytes; head_bytes = (g_cache_line_size - pagelist->offset) & (g_cache_line_size - 1); tail_bytes = (pagelist->offset + actual) & (g_cache_line_size - 1); if ((actual >= 0) && (head_bytes != 0)) { if (head_bytes > actual) head_bytes = actual; copyout_page(pages[0], pagelist->offset, fragments, head_bytes); } if ((actual >= 0) && (head_bytes < actual) && (tail_bytes != 0)) { copyout_page(pages[num_pages-1], (((vm_offset_t)bi->buf + actual) % PAGE_SIZE) - tail_bytes, fragments + g_cache_line_size, tail_bytes); } down(&g_free_fragments_mutex); *(char **) fragments = g_free_fragments; g_free_fragments = fragments; up(&g_free_fragments_mutex); up(&g_free_fragments_sema); } - for (i = 0; i < num_pages; i++) { - if (pagelist->type != PAGELIST_WRITE) { + if (pagelist->type != PAGELIST_WRITE) { + for (i = 0; i < num_pages; i++) { vm_page_dirty(pages[i]); pagelist_page_free(pages[i]); } } +#if defined(__aarch64__) + /* XXXMDC necessary? */ + dsb(sy); +#endif + bus_dmamap_unload(bi->pagelist_dma_tag, bi->pagelist_dma_map); bus_dmamem_free(bi->pagelist_dma_tag, bi->pagelist, bi->pagelist_dma_map); bus_dma_tag_destroy(bi->pagelist_dma_tag); free(bi, M_VCPAGELIST); } diff --git a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_arm.c b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_arm.c index e25c4d738922..36f9d0e3410d 100644 --- a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_arm.c +++ b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_arm.c @@ -1,2926 +1,2931 @@ /** * Copyright (c) 2014 Raspberry Pi (Trading) Ltd. All rights reserved. * Copyright (c) 2010-2012 Broadcom. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the above-listed copyright holders may not be used * to endorse or promote products derived from this software without * specific prior written permission. * * ALTERNATIVELY, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2, as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "vchiq_core.h" #include "vchiq_ioctl.h" #include "vchiq_arm.h" #define DEVICE_NAME "vchiq" /* Override the default prefix, which would be vchiq_arm (from the filename) */ #undef MODULE_PARAM_PREFIX #define MODULE_PARAM_PREFIX DEVICE_NAME "." #define VCHIQ_MINOR 0 /* Some per-instance constants */ #define MAX_COMPLETIONS 128 #define MAX_SERVICES 64 #define MAX_ELEMENTS 8 #define MSG_QUEUE_SIZE 128 #define KEEPALIVE_VER 1 #define KEEPALIVE_VER_MIN KEEPALIVE_VER /* Run time control of log level, based on KERN_XXX level. */ int vchiq_arm_log_level = VCHIQ_LOG_DEFAULT; int vchiq_susp_log_level = VCHIQ_LOG_ERROR; #define SUSPEND_TIMER_TIMEOUT_MS 100 #define SUSPEND_RETRY_TIMER_TIMEOUT_MS 1000 #define VC_SUSPEND_NUM_OFFSET 3 /* number of values before idle which are -ve */ static const char *const suspend_state_names[] = { "VC_SUSPEND_FORCE_CANCELED", "VC_SUSPEND_REJECTED", "VC_SUSPEND_FAILED", "VC_SUSPEND_IDLE", "VC_SUSPEND_REQUESTED", "VC_SUSPEND_IN_PROGRESS", "VC_SUSPEND_SUSPENDED" }; #define VC_RESUME_NUM_OFFSET 1 /* number of values before idle which are -ve */ static const char *const resume_state_names[] = { "VC_RESUME_FAILED", "VC_RESUME_IDLE", "VC_RESUME_REQUESTED", "VC_RESUME_IN_PROGRESS", "VC_RESUME_RESUMED" }; /* The number of times we allow force suspend to timeout before actually ** _forcing_ suspend. This is to cater for SW which fails to release vchiq ** correctly - we don't want to prevent ARM suspend indefinitely in this case. */ #define FORCE_SUSPEND_FAIL_MAX 8 /* The time in ms allowed for videocore to go idle when force suspend has been * requested */ #define FORCE_SUSPEND_TIMEOUT_MS 200 static void suspend_timer_callback(unsigned long context); #ifdef notyet static int vchiq_proc_add_instance(VCHIQ_INSTANCE_T instance); static void vchiq_proc_remove_instance(VCHIQ_INSTANCE_T instance); #endif typedef struct user_service_struct { VCHIQ_SERVICE_T *service; void *userdata; VCHIQ_INSTANCE_T instance; char is_vchi; char dequeue_pending; char close_pending; int message_available_pos; int msg_insert; int msg_remove; struct semaphore insert_event; struct semaphore remove_event; struct semaphore close_event; VCHIQ_HEADER_T * msg_queue[MSG_QUEUE_SIZE]; } USER_SERVICE_T; struct bulk_waiter_node { struct bulk_waiter bulk_waiter; int pid; struct list_head list; }; struct vchiq_instance_struct { VCHIQ_STATE_T *state; VCHIQ_COMPLETION_DATA_T completions[MAX_COMPLETIONS]; int completion_insert; int completion_remove; struct semaphore insert_event; struct semaphore remove_event; struct mutex completion_mutex; int connected; int closing; int pid; int mark; int use_close_delivered; int trace; struct list_head bulk_waiter_list; struct mutex bulk_waiter_list_mutex; #ifdef notyet VCHIQ_DEBUGFS_NODE_T proc_entry; #endif }; typedef struct dump_context_struct { char __user *buf; size_t actual; size_t space; loff_t offset; } DUMP_CONTEXT_T; static struct cdev * vchiq_cdev; VCHIQ_STATE_T g_state; static DEFINE_SPINLOCK(msg_queue_spinlock); static const char *const ioctl_names[] = { "CONNECT", "SHUTDOWN", "CREATE_SERVICE", "REMOVE_SERVICE", "QUEUE_MESSAGE", "QUEUE_BULK_TRANSMIT", "QUEUE_BULK_RECEIVE", "AWAIT_COMPLETION", "DEQUEUE_MESSAGE", "GET_CLIENT_ID", "GET_CONFIG", "CLOSE_SERVICE", "USE_SERVICE", "RELEASE_SERVICE", "SET_SERVICE_OPTION", "DUMP_PHYS_MEM", "LIB_VERSION", "CLOSE_DELIVERED" }; vchiq_static_assert((sizeof(ioctl_names)/sizeof(ioctl_names[0])) == (VCHIQ_IOC_MAX + 1)); static d_open_t vchiq_open; static d_close_t vchiq_close; static d_ioctl_t vchiq_ioctl; static struct cdevsw vchiq_cdevsw = { .d_version = D_VERSION, .d_ioctl = vchiq_ioctl, .d_open = vchiq_open, .d_close = vchiq_close, .d_name = DEVICE_NAME, }; #if 0 static void dump_phys_mem(void *virt_addr, uint32_t num_bytes); #endif /**************************************************************************** * * add_completion * ***************************************************************************/ static VCHIQ_STATUS_T add_completion(VCHIQ_INSTANCE_T instance, VCHIQ_REASON_T reason, VCHIQ_HEADER_T *header, USER_SERVICE_T *user_service, void *bulk_userdata) { VCHIQ_COMPLETION_DATA_T *completion; int insert; DEBUG_INITIALISE(g_state.local) insert = instance->completion_insert; while ((insert - instance->completion_remove) >= MAX_COMPLETIONS) { /* Out of space - wait for the client */ DEBUG_TRACE(SERVICE_CALLBACK_LINE); vchiq_log_trace(vchiq_arm_log_level, "add_completion - completion queue full"); DEBUG_COUNT(COMPLETION_QUEUE_FULL_COUNT); if (down_interruptible(&instance->remove_event) != 0) { vchiq_log_info(vchiq_arm_log_level, "service_callback interrupted"); return VCHIQ_RETRY; } if (instance->closing) { vchiq_log_info(vchiq_arm_log_level, "service_callback closing"); return VCHIQ_SUCCESS; } DEBUG_TRACE(SERVICE_CALLBACK_LINE); } completion = &instance->completions[insert & (MAX_COMPLETIONS - 1)]; completion->header = header; completion->reason = reason; /* N.B. service_userdata is updated while processing AWAIT_COMPLETION */ completion->service_userdata = user_service->service; completion->bulk_userdata = bulk_userdata; if (reason == VCHIQ_SERVICE_CLOSED) { /* Take an extra reference, to be held until this CLOSED notification is delivered. */ lock_service(user_service->service); if (instance->use_close_delivered) user_service->close_pending = 1; } /* A write barrier is needed here to ensure that the entire completion record is written out before the insert point. */ wmb(); if (reason == VCHIQ_MESSAGE_AVAILABLE) user_service->message_available_pos = insert; instance->completion_insert = ++insert; up(&instance->insert_event); return VCHIQ_SUCCESS; } /**************************************************************************** * * service_callback * ***************************************************************************/ static VCHIQ_STATUS_T service_callback(VCHIQ_REASON_T reason, VCHIQ_HEADER_T *header, VCHIQ_SERVICE_HANDLE_T handle, void *bulk_userdata) { /* How do we ensure the callback goes to the right client? ** The service_user data points to a USER_SERVICE_T record containing ** the original callback and the user state structure, which contains a ** circular buffer for completion records. */ USER_SERVICE_T *user_service; VCHIQ_SERVICE_T *service; VCHIQ_INSTANCE_T instance; int skip_completion = 0; DEBUG_INITIALISE(g_state.local) DEBUG_TRACE(SERVICE_CALLBACK_LINE); service = handle_to_service(handle); BUG_ON(!service); user_service = (USER_SERVICE_T *)service->base.userdata; instance = user_service->instance; if (!instance || instance->closing) return VCHIQ_SUCCESS; vchiq_log_trace(vchiq_arm_log_level, "service_callback - service %lx(%d,%p), reason %d, header %lx, " "instance %lx, bulk_userdata %lx", (unsigned long)user_service, service->localport, user_service->userdata, reason, (unsigned long)header, (unsigned long)instance, (unsigned long)bulk_userdata); if (header && user_service->is_vchi) { spin_lock(&msg_queue_spinlock); while (user_service->msg_insert == (user_service->msg_remove + MSG_QUEUE_SIZE)) { spin_unlock(&msg_queue_spinlock); DEBUG_TRACE(SERVICE_CALLBACK_LINE); DEBUG_COUNT(MSG_QUEUE_FULL_COUNT); vchiq_log_trace(vchiq_arm_log_level, "service_callback - msg queue full"); /* If there is no MESSAGE_AVAILABLE in the completion ** queue, add one */ if ((user_service->message_available_pos - instance->completion_remove) < 0) { VCHIQ_STATUS_T status; vchiq_log_info(vchiq_arm_log_level, "Inserting extra MESSAGE_AVAILABLE"); DEBUG_TRACE(SERVICE_CALLBACK_LINE); status = add_completion(instance, reason, NULL, user_service, bulk_userdata); if (status != VCHIQ_SUCCESS) { DEBUG_TRACE(SERVICE_CALLBACK_LINE); return status; } } DEBUG_TRACE(SERVICE_CALLBACK_LINE); if (down_interruptible(&user_service->remove_event) != 0) { vchiq_log_info(vchiq_arm_log_level, "service_callback interrupted"); DEBUG_TRACE(SERVICE_CALLBACK_LINE); return VCHIQ_RETRY; } else if (instance->closing) { vchiq_log_info(vchiq_arm_log_level, "service_callback closing"); DEBUG_TRACE(SERVICE_CALLBACK_LINE); return VCHIQ_ERROR; } DEBUG_TRACE(SERVICE_CALLBACK_LINE); spin_lock(&msg_queue_spinlock); } user_service->msg_queue[user_service->msg_insert & (MSG_QUEUE_SIZE - 1)] = header; user_service->msg_insert++; /* If there is a thread waiting in DEQUEUE_MESSAGE, or if ** there is a MESSAGE_AVAILABLE in the completion queue then ** bypass the completion queue. */ if (((user_service->message_available_pos - instance->completion_remove) >= 0) || user_service->dequeue_pending) { user_service->dequeue_pending = 0; skip_completion = 1; } spin_unlock(&msg_queue_spinlock); up(&user_service->insert_event); header = NULL; } if (skip_completion) { DEBUG_TRACE(SERVICE_CALLBACK_LINE); return VCHIQ_SUCCESS; } DEBUG_TRACE(SERVICE_CALLBACK_LINE); return add_completion(instance, reason, header, user_service, bulk_userdata); } /**************************************************************************** * * user_service_free * ***************************************************************************/ static void user_service_free(void *userdata) { USER_SERVICE_T *user_service = userdata; - + _sema_destroy(&user_service->insert_event); _sema_destroy(&user_service->remove_event); kfree(user_service); } /**************************************************************************** * * close_delivered * ***************************************************************************/ static void close_delivered(USER_SERVICE_T *user_service) { vchiq_log_info(vchiq_arm_log_level, "close_delivered(handle=%x)", user_service->service->handle); if (user_service->close_pending) { /* Allow the underlying service to be culled */ unlock_service(user_service->service); /* Wake the user-thread blocked in close_ or remove_service */ up(&user_service->close_event); - + user_service->close_pending = 0; } } /**************************************************************************** * * vchiq_ioctl * ***************************************************************************/ static int vchiq_ioctl(struct cdev *cdev, u_long cmd, caddr_t arg, int fflag, struct thread *td) { VCHIQ_INSTANCE_T instance; VCHIQ_STATUS_T status = VCHIQ_SUCCESS; VCHIQ_SERVICE_T *service = NULL; int ret = 0; int i, rc; DEBUG_INITIALISE(g_state.local) if ((ret = devfs_get_cdevpriv((void**)&instance))) { printf("vchiq_ioctl: devfs_get_cdevpriv failed: error %d\n", ret); return (ret); } /* XXXBSD: HACK! */ #define _IOC_NR(x) ((x) & 0xff) #define _IOC_TYPE(x) IOCGROUP(x) vchiq_log_trace(vchiq_arm_log_level, "vchiq_ioctl - instance %zx, cmd %s, arg %p", (size_t)instance, ((_IOC_TYPE(cmd) == VCHIQ_IOC_MAGIC) && (_IOC_NR(cmd) <= VCHIQ_IOC_MAX)) ? ioctl_names[_IOC_NR(cmd)] : "", arg); switch (cmd) { case VCHIQ_IOC_SHUTDOWN: if (!instance->connected) break; /* Remove all services */ i = 0; while ((service = next_service_by_instance(instance->state, instance, &i)) != NULL) { status = vchiq_remove_service(service->handle); unlock_service(service); if (status != VCHIQ_SUCCESS) break; } service = NULL; if (status == VCHIQ_SUCCESS) { /* Wake the completion thread and ask it to exit */ instance->closing = 1; up(&instance->insert_event); } break; case VCHIQ_IOC_CONNECT: if (instance->connected) { ret = -EINVAL; break; } rc = lmutex_lock_interruptible(&instance->state->mutex); if (rc != 0) { vchiq_log_error(vchiq_arm_log_level, "vchiq: connect: could not lock mutex for " "state %d: %d", instance->state->id, rc); ret = -EINTR; break; } status = vchiq_connect_internal(instance->state, instance); lmutex_unlock(&instance->state->mutex); if (status == VCHIQ_SUCCESS) instance->connected = 1; else vchiq_log_error(vchiq_arm_log_level, "vchiq: could not connect: %d", status); break; case VCHIQ_IOC_CREATE_SERVICE: { VCHIQ_CREATE_SERVICE_T args; USER_SERVICE_T *user_service = NULL; void *userdata; int srvstate; memcpy(&args, (const void*)arg, sizeof(args)); user_service = kmalloc(sizeof(USER_SERVICE_T), GFP_KERNEL); if (!user_service) { ret = -ENOMEM; break; } if (args.is_open) { if (!instance->connected) { ret = -ENOTCONN; kfree(user_service); break; } srvstate = VCHIQ_SRVSTATE_OPENING; } else { srvstate = instance->connected ? VCHIQ_SRVSTATE_LISTENING : VCHIQ_SRVSTATE_HIDDEN; } userdata = args.params.userdata; args.params.callback = service_callback; args.params.userdata = user_service; service = vchiq_add_service_internal( instance->state, &args.params, srvstate, instance, user_service_free); if (service != NULL) { user_service->service = service; user_service->userdata = userdata; user_service->instance = instance; user_service->is_vchi = (args.is_vchi != 0); user_service->dequeue_pending = 0; user_service->close_pending = 0; user_service->message_available_pos = instance->completion_remove - 1; user_service->msg_insert = 0; user_service->msg_remove = 0; _sema_init(&user_service->insert_event, 0); _sema_init(&user_service->remove_event, 0); _sema_init(&user_service->close_event, 0); if (args.is_open) { status = vchiq_open_service_internal (service, instance->pid); if (status != VCHIQ_SUCCESS) { vchiq_remove_service(service->handle); service = NULL; ret = (status == VCHIQ_RETRY) ? -EINTR : -EIO; break; } } #ifdef VCHIQ_IOCTL_DEBUG printf("%s: [CREATE SERVICE] handle = %08x\n", __func__, service->handle); #endif memcpy((void *) &(((VCHIQ_CREATE_SERVICE_T*) arg)->handle), (const void *)&service->handle, sizeof(service->handle)); service = NULL; } else { ret = -EEXIST; kfree(user_service); } } break; case VCHIQ_IOC_CLOSE_SERVICE: { VCHIQ_SERVICE_HANDLE_T handle; memcpy(&handle, (const void*)arg, sizeof(handle)); #ifdef VCHIQ_IOCTL_DEBUG printf("%s: [CLOSE SERVICE] handle = %08x\n", __func__, handle); #endif service = find_service_for_instance(instance, handle); if (service != NULL) { USER_SERVICE_T *user_service = (USER_SERVICE_T *)service->base.userdata; /* close_pending is false on first entry, and when the wait in vchiq_close_service has been interrupted. */ if (!user_service->close_pending) { status = vchiq_close_service(service->handle); if (status != VCHIQ_SUCCESS) break; } /* close_pending is true once the underlying service has been closed until the client library calls the CLOSE_DELIVERED ioctl, signalling close_event. */ if (user_service->close_pending && down_interruptible(&user_service->close_event)) status = VCHIQ_RETRY; } else ret = -EINVAL; } break; case VCHIQ_IOC_REMOVE_SERVICE: { VCHIQ_SERVICE_HANDLE_T handle; memcpy(&handle, (const void*)arg, sizeof(handle)); #ifdef VCHIQ_IOCTL_DEBUG printf("%s: [REMOVE SERVICE] handle = %08x\n", __func__, handle); #endif service = find_service_for_instance(instance, handle); if (service != NULL) { USER_SERVICE_T *user_service = (USER_SERVICE_T *)service->base.userdata; /* close_pending is false on first entry, and when the wait in vchiq_close_service has been interrupted. */ if (!user_service->close_pending) { status = vchiq_remove_service(service->handle); if (status != VCHIQ_SUCCESS) break; } /* close_pending is true once the underlying service has been closed until the client library calls the CLOSE_DELIVERED ioctl, signalling close_event. */ if (user_service->close_pending && down_interruptible(&user_service->close_event)) status = VCHIQ_RETRY; } else ret = -EINVAL; } break; case VCHIQ_IOC_USE_SERVICE: case VCHIQ_IOC_RELEASE_SERVICE: { VCHIQ_SERVICE_HANDLE_T handle; memcpy(&handle, (const void*)arg, sizeof(handle)); #ifdef VCHIQ_IOCTL_DEBUG printf("%s: [%s SERVICE] handle = %08x\n", __func__, cmd == VCHIQ_IOC_USE_SERVICE ? "USE" : "RELEASE", handle); #endif service = find_service_for_instance(instance, handle); if (service != NULL) { status = (cmd == VCHIQ_IOC_USE_SERVICE) ? vchiq_use_service_internal(service) : vchiq_release_service_internal(service); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s: cmd %s returned error %d for " "service %c%c%c%c:%8x", __func__, (cmd == VCHIQ_IOC_USE_SERVICE) ? "VCHIQ_IOC_USE_SERVICE" : "VCHIQ_IOC_RELEASE_SERVICE", status, VCHIQ_FOURCC_AS_4CHARS( service->base.fourcc), service->client_id); ret = -EINVAL; } } else ret = -EINVAL; } break; case VCHIQ_IOC_QUEUE_MESSAGE: { VCHIQ_QUEUE_MESSAGE_T args; memcpy(&args, (const void*)arg, sizeof(args)); #ifdef VCHIQ_IOCTL_DEBUG printf("%s: [QUEUE MESSAGE] handle = %08x\n", __func__, args.handle); #endif service = find_service_for_instance(instance, args.handle); if ((service != NULL) && (args.count <= MAX_ELEMENTS)) { /* Copy elements into kernel space */ VCHIQ_ELEMENT_T elements[MAX_ELEMENTS]; if (copy_from_user(elements, args.elements, args.count * sizeof(VCHIQ_ELEMENT_T)) == 0) status = vchiq_queue_message (args.handle, elements, args.count); else ret = -EFAULT; } else { ret = -EINVAL; } } break; case VCHIQ_IOC_QUEUE_BULK_TRANSMIT: case VCHIQ_IOC_QUEUE_BULK_RECEIVE: { VCHIQ_QUEUE_BULK_TRANSFER_T args; struct bulk_waiter_node *waiter = NULL; VCHIQ_BULK_DIR_T dir = (cmd == VCHIQ_IOC_QUEUE_BULK_TRANSMIT) ? VCHIQ_BULK_TRANSMIT : VCHIQ_BULK_RECEIVE; memcpy(&args, (const void*)arg, sizeof(args)); service = find_service_for_instance(instance, args.handle); if (!service) { ret = -EINVAL; break; } if (args.mode == VCHIQ_BULK_MODE_BLOCKING) { waiter = kzalloc(sizeof(struct bulk_waiter_node), GFP_KERNEL); if (!waiter) { ret = -ENOMEM; break; } args.userdata = &waiter->bulk_waiter; } else if (args.mode == VCHIQ_BULK_MODE_WAITING) { struct list_head *pos; lmutex_lock(&instance->bulk_waiter_list_mutex); list_for_each(pos, &instance->bulk_waiter_list) { if (list_entry(pos, struct bulk_waiter_node, list)->pid == current->p_pid) { waiter = list_entry(pos, struct bulk_waiter_node, list); list_del(pos); break; } } lmutex_unlock(&instance->bulk_waiter_list_mutex); if (!waiter) { vchiq_log_error(vchiq_arm_log_level, "no bulk_waiter found for pid %d", current->p_pid); ret = -ESRCH; break; } vchiq_log_info(vchiq_arm_log_level, "found bulk_waiter %zx for pid %d", (size_t)waiter, current->p_pid); args.userdata = &waiter->bulk_waiter; } + status = vchiq_bulk_transfer (args.handle, VCHI_MEM_HANDLE_INVALID, args.data, args.size, args.userdata, args.mode, dir); if (!waiter) break; if ((status != VCHIQ_RETRY) || fatal_signal_pending(current) || !waiter->bulk_waiter.bulk) { if (waiter->bulk_waiter.bulk) { /* Cancel the signal when the transfer ** completes. */ spin_lock(&bulk_waiter_spinlock); waiter->bulk_waiter.bulk->userdata = NULL; spin_unlock(&bulk_waiter_spinlock); } _sema_destroy(&waiter->bulk_waiter.event); kfree(waiter); } else { const VCHIQ_BULK_MODE_T mode_waiting = VCHIQ_BULK_MODE_WAITING; waiter->pid = current->p_pid; lmutex_lock(&instance->bulk_waiter_list_mutex); list_add(&waiter->list, &instance->bulk_waiter_list); lmutex_unlock(&instance->bulk_waiter_list_mutex); vchiq_log_info(vchiq_arm_log_level, "saved bulk_waiter %zx for pid %d", (size_t)waiter, current->p_pid); memcpy((void *) &(((VCHIQ_QUEUE_BULK_TRANSFER_T *) arg)->mode), (const void *)&mode_waiting, sizeof(mode_waiting)); } } break; case VCHIQ_IOC_AWAIT_COMPLETION: { VCHIQ_AWAIT_COMPLETION_T args; int count = 0; DEBUG_TRACE(AWAIT_COMPLETION_LINE); if (!instance->connected) { ret = -ENOTCONN; break; } memcpy(&args, (const void*)arg, sizeof(args)); lmutex_lock(&instance->completion_mutex); DEBUG_TRACE(AWAIT_COMPLETION_LINE); while ((instance->completion_remove == instance->completion_insert) && !instance->closing) { DEBUG_TRACE(AWAIT_COMPLETION_LINE); lmutex_unlock(&instance->completion_mutex); rc = down_interruptible(&instance->insert_event); lmutex_lock(&instance->completion_mutex); if (rc != 0) { DEBUG_TRACE(AWAIT_COMPLETION_LINE); vchiq_log_info(vchiq_arm_log_level, "AWAIT_COMPLETION interrupted"); ret = -EINTR; break; } } DEBUG_TRACE(AWAIT_COMPLETION_LINE); if (ret == 0) { int msgbufcount = args.msgbufcount; int remove; remove = instance->completion_remove; for (count = 0; count < args.count; count++) { VCHIQ_COMPLETION_DATA_T *completion; VCHIQ_SERVICE_T *service1; USER_SERVICE_T *user_service; VCHIQ_HEADER_T *header; if (remove == instance->completion_insert) break; completion = &instance->completions[ remove & (MAX_COMPLETIONS - 1)]; /* A read memory barrier is needed to prevent ** the prefetch of a stale completion record */ rmb(); service1 = completion->service_userdata; user_service = service1->base.userdata; completion->service_userdata = user_service->userdata; header = completion->header; if (header) { void __user *msgbuf; int msglen; msglen = header->size + sizeof(VCHIQ_HEADER_T); /* This must be a VCHIQ-style service */ if (args.msgbufsize < msglen) { vchiq_log_error( vchiq_arm_log_level, "header %zx: msgbufsize" " %x < msglen %x", (size_t)header, args.msgbufsize, msglen); WARN(1, "invalid message " "size\n"); if (count == 0) ret = -EMSGSIZE; break; } if (msgbufcount <= 0) /* Stall here for lack of a ** buffer for the message. */ break; /* Get the pointer from user space */ msgbufcount--; if (copy_from_user(&msgbuf, (const void __user *) &args.msgbufs[msgbufcount], sizeof(msgbuf)) != 0) { if (count == 0) ret = -EFAULT; break; } /* Copy the message to user space */ if (copy_to_user(msgbuf, header, msglen) != 0) { if (count == 0) ret = -EFAULT; break; } /* Now it has been copied, the message ** can be released. */ vchiq_release_message(service1->handle, header); /* The completion must point to the ** msgbuf. */ completion->header = msgbuf; } if ((completion->reason == VCHIQ_SERVICE_CLOSED) && !instance->use_close_delivered) unlock_service(service1); if (copy_to_user((void __user *)( (size_t)args.buf + count * sizeof(VCHIQ_COMPLETION_DATA_T)), completion, sizeof(VCHIQ_COMPLETION_DATA_T)) != 0) { if (ret == 0) ret = -EFAULT; break; } /* Ensure that the above copy has completed ** before advancing the remove pointer. */ mb(); instance->completion_remove = ++remove; } if (msgbufcount != args.msgbufcount) { memcpy((void __user *) &((VCHIQ_AWAIT_COMPLETION_T *)arg)-> msgbufcount, &msgbufcount, sizeof(msgbufcount)); } if (count != args.count) { memcpy((void __user *) &((VCHIQ_AWAIT_COMPLETION_T *)arg)->count, &count, sizeof(count)); } } if (count != 0) up(&instance->remove_event); if ((ret == 0) && instance->closing) ret = -ENOTCONN; /* * XXXBSD: ioctl return codes are not negative as in linux, so * we can not indicate success with positive number of passed * messages */ if (ret > 0) ret = 0; lmutex_unlock(&instance->completion_mutex); DEBUG_TRACE(AWAIT_COMPLETION_LINE); } break; case VCHIQ_IOC_DEQUEUE_MESSAGE: { VCHIQ_DEQUEUE_MESSAGE_T args; USER_SERVICE_T *user_service; VCHIQ_HEADER_T *header; DEBUG_TRACE(DEQUEUE_MESSAGE_LINE); memcpy(&args, (const void*)arg, sizeof(args)); service = find_service_for_instance(instance, args.handle); if (!service) { ret = -EINVAL; break; } user_service = (USER_SERVICE_T *)service->base.userdata; if (user_service->is_vchi == 0) { ret = -EINVAL; break; } spin_lock(&msg_queue_spinlock); if (user_service->msg_remove == user_service->msg_insert) { if (!args.blocking) { spin_unlock(&msg_queue_spinlock); DEBUG_TRACE(DEQUEUE_MESSAGE_LINE); ret = -EWOULDBLOCK; break; } user_service->dequeue_pending = 1; do { spin_unlock(&msg_queue_spinlock); DEBUG_TRACE(DEQUEUE_MESSAGE_LINE); if (down_interruptible( &user_service->insert_event) != 0) { vchiq_log_info(vchiq_arm_log_level, "DEQUEUE_MESSAGE interrupted"); ret = -EINTR; break; } spin_lock(&msg_queue_spinlock); } while (user_service->msg_remove == user_service->msg_insert); if (ret) break; } BUG_ON((int)(user_service->msg_insert - user_service->msg_remove) < 0); header = user_service->msg_queue[user_service->msg_remove & (MSG_QUEUE_SIZE - 1)]; user_service->msg_remove++; spin_unlock(&msg_queue_spinlock); up(&user_service->remove_event); if (header == NULL) ret = -ENOTCONN; else if (header->size <= args.bufsize) { /* Copy to user space if msgbuf is not NULL */ if ((args.buf == NULL) || (copy_to_user((void __user *)args.buf, header->data, header->size) == 0)) { args.bufsize = header->size; memcpy((void *)arg, &args, sizeof(args)); vchiq_release_message( service->handle, header); } else ret = -EFAULT; } else { vchiq_log_error(vchiq_arm_log_level, "header %zx: bufsize %x < size %x", (size_t)header, args.bufsize, header->size); WARN(1, "invalid size\n"); ret = -EMSGSIZE; } DEBUG_TRACE(DEQUEUE_MESSAGE_LINE); } break; case VCHIQ_IOC_GET_CLIENT_ID: { VCHIQ_SERVICE_HANDLE_T handle; memcpy(&handle, (const void*)arg, sizeof(handle)); ret = vchiq_get_client_id(handle); } break; case VCHIQ_IOC_GET_CONFIG: { VCHIQ_GET_CONFIG_T args; VCHIQ_CONFIG_T config; memcpy(&args, (const void*)arg, sizeof(args)); if (args.config_size > sizeof(config)) { ret = -EINVAL; break; } status = vchiq_get_config(instance, args.config_size, &config); if (status == VCHIQ_SUCCESS) { if (copy_to_user((void __user *)args.pconfig, &config, args.config_size) != 0) { ret = -EFAULT; break; } } } break; case VCHIQ_IOC_SET_SERVICE_OPTION: { VCHIQ_SET_SERVICE_OPTION_T args; memcpy(&args, (const void*)arg, sizeof(args)); service = find_service_for_instance(instance, args.handle); if (!service) { ret = -EINVAL; break; } status = vchiq_set_service_option( args.handle, args.option, args.value); } break; case VCHIQ_IOC_DUMP_PHYS_MEM: { VCHIQ_DUMP_MEM_T args; memcpy(&args, (const void*)arg, sizeof(args)); printf("IMPLEMENT ME: %s:%d\n", __FILE__, __LINE__); #if 0 dump_phys_mem(args.virt_addr, args.num_bytes); #endif } break; case VCHIQ_IOC_LIB_VERSION: { - unsigned int lib_version = (unsigned int)arg; + size_t lib_version = (size_t)arg; if (lib_version < VCHIQ_VERSION_MIN) ret = -EINVAL; else if (lib_version >= VCHIQ_VERSION_CLOSE_DELIVERED) instance->use_close_delivered = 1; } break; case VCHIQ_IOC_CLOSE_DELIVERED: { VCHIQ_SERVICE_HANDLE_T handle; memcpy(&handle, (const void*)arg, sizeof(handle)); service = find_closed_service_for_instance(instance, handle); if (service != NULL) { USER_SERVICE_T *user_service = (USER_SERVICE_T *)service->base.userdata; close_delivered(user_service); } else ret = -EINVAL; } break; default: ret = -ENOTTY; break; } if (service) unlock_service(service); if (ret == 0) { if (status == VCHIQ_ERROR) ret = -EIO; else if (status == VCHIQ_RETRY) ret = -EINTR; } if ((status == VCHIQ_SUCCESS) && (ret < 0) && (ret != -EINTR) && (ret != -EWOULDBLOCK)) vchiq_log_info(vchiq_arm_log_level, " ioctl instance %lx, cmd %s -> status %d, %d", (unsigned long)instance, (_IOC_NR(cmd) <= VCHIQ_IOC_MAX) ? ioctl_names[_IOC_NR(cmd)] : "", status, ret); else vchiq_log_trace(vchiq_arm_log_level, " ioctl instance %lx, cmd %s -> status %d, %d", (unsigned long)instance, (_IOC_NR(cmd) <= VCHIQ_IOC_MAX) ? ioctl_names[_IOC_NR(cmd)] : "", status, ret); /* XXXBSD: report BSD-style error to userland */ if (ret < 0) ret = -ret; return ret; } -static void -instance_dtr(void *data) -{ - kfree(data); -} /**************************************************************************** * * vchiq_open * ***************************************************************************/ +static void instance_dtr(void *data); static int vchiq_open(struct cdev *dev, int flags, int fmt __unused, struct thread *td) { vchiq_log_info(vchiq_arm_log_level, "vchiq_open"); /* XXXBSD: do we really need this check? */ if (1) { VCHIQ_STATE_T *state = vchiq_get_state(); VCHIQ_INSTANCE_T instance; if (!state) { vchiq_log_error(vchiq_arm_log_level, "vchiq has no connection to VideoCore"); return -ENOTCONN; } instance = kmalloc(sizeof(*instance), GFP_KERNEL); if (!instance) return -ENOMEM; instance->state = state; /* XXXBSD: PID or thread ID? */ instance->pid = td->td_proc->p_pid; #ifdef notyet ret = vchiq_proc_add_instance(instance); if (ret != 0) { kfree(instance); return ret; } #endif _sema_init(&instance->insert_event, 0); _sema_init(&instance->remove_event, 0); lmutex_init(&instance->completion_mutex); lmutex_init(&instance->bulk_waiter_list_mutex); INIT_LIST_HEAD(&instance->bulk_waiter_list); devfs_set_cdevpriv(instance, instance_dtr); - } + } else { vchiq_log_error(vchiq_arm_log_level, "Unknown minor device"); return -ENXIO; } return 0; } /**************************************************************************** * * vchiq_release * ***************************************************************************/ + static int -vchiq_close(struct cdev *dev, int flags __unused, int fmt __unused, - struct thread *td) +_vchiq_close_instance(VCHIQ_INSTANCE_T instance) { int ret = 0; - if (1) { - VCHIQ_INSTANCE_T instance; - VCHIQ_STATE_T *state = vchiq_get_state(); - VCHIQ_SERVICE_T *service; - int i; - - if ((ret = devfs_get_cdevpriv((void**)&instance))) { - printf("devfs_get_cdevpriv failed: error %d\n", ret); - return (ret); - } - - vchiq_log_info(vchiq_arm_log_level, - "vchiq_release: instance=%lx", - (unsigned long)instance); - - if (!state) { - ret = -EPERM; - goto out; - } + VCHIQ_STATE_T *state = vchiq_get_state(); + VCHIQ_SERVICE_T *service; + int i; - /* Ensure videocore is awake to allow termination. */ - vchiq_use_internal(instance->state, NULL, - USE_TYPE_VCHIQ); + vchiq_log_info(vchiq_arm_log_level, + "vchiq_release: instance=%lx", + (unsigned long)instance); - lmutex_lock(&instance->completion_mutex); + if (!state) { + ret = -EPERM; + goto out; + } - /* Wake the completion thread and ask it to exit */ - instance->closing = 1; - up(&instance->insert_event); + /* Ensure videocore is awake to allow termination. */ + vchiq_use_internal(instance->state, NULL, + USE_TYPE_VCHIQ); - lmutex_unlock(&instance->completion_mutex); + lmutex_lock(&instance->completion_mutex); - /* Wake the slot handler if the completion queue is full. */ - up(&instance->remove_event); + /* Wake the completion thread and ask it to exit */ + instance->closing = 1; + up(&instance->insert_event); - /* Mark all services for termination... */ - i = 0; - while ((service = next_service_by_instance(state, instance, - &i)) != NULL) { - USER_SERVICE_T *user_service = service->base.userdata; + lmutex_unlock(&instance->completion_mutex); - /* Wake the slot handler if the msg queue is full. */ - up(&user_service->remove_event); + /* Wake the slot handler if the completion queue is full. */ + up(&instance->remove_event); - vchiq_terminate_service_internal(service); - unlock_service(service); - } + /* Mark all services for termination... */ + i = 0; + while ((service = next_service_by_instance(state, instance, + &i)) != NULL) { + USER_SERVICE_T *user_service = service->base.userdata; - /* ...and wait for them to die */ - i = 0; - while ((service = next_service_by_instance(state, instance, &i)) - != NULL) { - USER_SERVICE_T *user_service = service->base.userdata; + /* Wake the slot handler if the msg queue is full. */ + up(&user_service->remove_event); - down(&service->remove_event); + vchiq_terminate_service_internal(service); + unlock_service(service); + } - BUG_ON(service->srvstate != VCHIQ_SRVSTATE_FREE); + /* ...and wait for them to die */ + i = 0; + while ((service = next_service_by_instance(state, instance, &i)) + != NULL) { + USER_SERVICE_T *user_service = service->base.userdata; - spin_lock(&msg_queue_spinlock); + down(&service->remove_event); - while (user_service->msg_remove != - user_service->msg_insert) { - VCHIQ_HEADER_T *header = user_service-> - msg_queue[user_service->msg_remove & - (MSG_QUEUE_SIZE - 1)]; - user_service->msg_remove++; - spin_unlock(&msg_queue_spinlock); + BUG_ON(service->srvstate != VCHIQ_SRVSTATE_FREE); - if (header) - vchiq_release_message( - service->handle, - header); - spin_lock(&msg_queue_spinlock); - } + spin_lock(&msg_queue_spinlock); + while (user_service->msg_remove != + user_service->msg_insert) { + VCHIQ_HEADER_T *header = user_service-> + msg_queue[user_service->msg_remove & + (MSG_QUEUE_SIZE - 1)]; + user_service->msg_remove++; spin_unlock(&msg_queue_spinlock); - unlock_service(service); + if (header) + vchiq_release_message( + service->handle, + header); + spin_lock(&msg_queue_spinlock); } - /* Release any closed services */ - while (instance->completion_remove != - instance->completion_insert) { - VCHIQ_COMPLETION_DATA_T *completion; - VCHIQ_SERVICE_T *service1; - completion = &instance->completions[ - instance->completion_remove & - (MAX_COMPLETIONS - 1)]; - service1 = completion->service_userdata; - if (completion->reason == VCHIQ_SERVICE_CLOSED) - { - USER_SERVICE_T *user_service = - service->base.userdata; - - /* Wake any blocked user-thread */ - if (instance->use_close_delivered) - up(&user_service->close_event); - unlock_service(service1); - } - instance->completion_remove++; - } + spin_unlock(&msg_queue_spinlock); - /* Release the PEER service count. */ - vchiq_release_internal(instance->state, NULL); + unlock_service(service); + } + /* Release any closed services */ + while (instance->completion_remove != + instance->completion_insert) { + VCHIQ_COMPLETION_DATA_T *completion; + VCHIQ_SERVICE_T *service; + completion = &instance->completions[ + instance->completion_remove & + (MAX_COMPLETIONS - 1)]; + service = completion->service_userdata; + if (completion->reason == VCHIQ_SERVICE_CLOSED) { - struct list_head *pos, *next; - list_for_each_safe(pos, next, - &instance->bulk_waiter_list) { - struct bulk_waiter_node *waiter; - waiter = list_entry(pos, - struct bulk_waiter_node, - list); - list_del(pos); - vchiq_log_info(vchiq_arm_log_level, - "bulk_waiter - cleaned up %x " - "for pid %d", - (unsigned int)waiter, waiter->pid); - _sema_destroy(&waiter->bulk_waiter.event); - kfree(waiter); - } - } + USER_SERVICE_T *user_service = + service->base.userdata; + /* Wake any blocked user-thread */ + if (instance->use_close_delivered) + up(&user_service->close_event); + + unlock_service(service); + } + instance->completion_remove++; } - else { - vchiq_log_error(vchiq_arm_log_level, - "Unknown minor device"); - ret = -ENXIO; + + /* Release the PEER service count. */ + vchiq_release_internal(instance->state, NULL); + + { + struct list_head *pos, *next; + list_for_each_safe(pos, next, + &instance->bulk_waiter_list) { + struct bulk_waiter_node *waiter; + waiter = list_entry(pos, + struct bulk_waiter_node, + list); + list_del(pos); + vchiq_log_info(vchiq_arm_log_level, + "bulk_waiter - cleaned up %zx " + "for pid %d", + (size_t)waiter, waiter->pid); + _sema_destroy(&waiter->bulk_waiter.event); + kfree(waiter); + } } out: return ret; + +} + +static void +instance_dtr(void *data) +{ + VCHIQ_INSTANCE_T instance = data; + _vchiq_close_instance(instance); + kfree(data); +} + +static int +vchiq_close(struct cdev *dev, int flags __unused, int fmt __unused, + struct thread *td) +{ + + /* XXXMDC it's privdata that tracks opens */ + /* XXXMDC only get closes when there are no more open fds on a vnode */ + + return(0); + } /**************************************************************************** * * vchiq_dump * ***************************************************************************/ void vchiq_dump(void *dump_context, const char *str, int len) { DUMP_CONTEXT_T *context = (DUMP_CONTEXT_T *)dump_context; if (context->actual < context->space) { int copy_bytes; if (context->offset > 0) { int skip_bytes = min(len, (int)context->offset); str += skip_bytes; len -= skip_bytes; context->offset -= skip_bytes; if (context->offset > 0) return; } copy_bytes = min(len, (int)(context->space - context->actual)); if (copy_bytes == 0) return; memcpy(context->buf + context->actual, str, copy_bytes); context->actual += copy_bytes; len -= copy_bytes; /* If tne terminating NUL is included in the length, then it ** marks the end of a line and should be replaced with a ** carriage return. */ if ((len == 0) && (str[copy_bytes - 1] == '\0')) { char cr = '\n'; memcpy(context->buf + context->actual - 1, &cr, 1); } } } /**************************************************************************** * * vchiq_dump_platform_instance_state * ***************************************************************************/ void vchiq_dump_platform_instances(void *dump_context) { VCHIQ_STATE_T *state = vchiq_get_state(); char buf[80]; int len; int i; /* There is no list of instances, so instead scan all services, marking those that have been dumped. */ for (i = 0; i < state->unused_service; i++) { VCHIQ_SERVICE_T *service = state->services[i]; VCHIQ_INSTANCE_T instance; if (service && (service->base.callback == service_callback)) { instance = service->instance; if (instance) instance->mark = 0; } } for (i = 0; i < state->unused_service; i++) { VCHIQ_SERVICE_T *service = state->services[i]; VCHIQ_INSTANCE_T instance; if (service && (service->base.callback == service_callback)) { instance = service->instance; if (instance && !instance->mark) { len = snprintf(buf, sizeof(buf), "Instance %zx: pid %d,%s completions " "%d/%d", (size_t)instance, instance->pid, instance->connected ? " connected, " : "", instance->completion_insert - instance->completion_remove, MAX_COMPLETIONS); vchiq_dump(dump_context, buf, len + 1); instance->mark = 1; } } } } /**************************************************************************** * * vchiq_dump_platform_service_state * ***************************************************************************/ void vchiq_dump_platform_service_state(void *dump_context, VCHIQ_SERVICE_T *service) { USER_SERVICE_T *user_service = (USER_SERVICE_T *)service->base.userdata; char buf[80]; int len; len = snprintf(buf, sizeof(buf), " instance %zx", (size_t)service->instance); if ((service->base.callback == service_callback) && user_service->is_vchi) { len += snprintf(buf + len, sizeof(buf) - len, ", %d/%d messages", user_service->msg_insert - user_service->msg_remove, MSG_QUEUE_SIZE); if (user_service->dequeue_pending) len += snprintf(buf + len, sizeof(buf) - len, " (dequeue pending)"); } vchiq_dump(dump_context, buf, len + 1); } #ifdef notyet /**************************************************************************** * * dump_user_mem * ***************************************************************************/ static void dump_phys_mem(void *virt_addr, uint32_t num_bytes) { int rc; uint8_t *end_virt_addr = virt_addr + num_bytes; int num_pages; int offset; int end_offset; int page_idx; int prev_idx; struct page *page; struct page **pages; uint8_t *kmapped_virt_ptr; /* Align virtAddr and endVirtAddr to 16 byte boundaries. */ virt_addr = (void *)((unsigned long)virt_addr & ~0x0fuL); end_virt_addr = (void *)(((unsigned long)end_virt_addr + 15uL) & ~0x0fuL); offset = (int)(long)virt_addr & (PAGE_SIZE - 1); end_offset = (int)(long)end_virt_addr & (PAGE_SIZE - 1); num_pages = (offset + num_bytes + PAGE_SIZE - 1) / PAGE_SIZE; pages = kmalloc(sizeof(struct page *) * num_pages, GFP_KERNEL); if (pages == NULL) { vchiq_log_error(vchiq_arm_log_level, "Unable to allocation memory for %d pages\n", num_pages); return; } down_read(¤t->mm->mmap_sem); rc = get_user_pages(current, /* task */ current->mm, /* mm */ (unsigned long)virt_addr, /* start */ num_pages, /* len */ 0, /* write */ 0, /* force */ pages, /* pages (array of page pointers) */ NULL); /* vmas */ up_read(¤t->mm->mmap_sem); prev_idx = -1; page = NULL; while (offset < end_offset) { int page_offset = offset % PAGE_SIZE; page_idx = offset / PAGE_SIZE; if (page_idx != prev_idx) { if (page != NULL) kunmap(page); page = pages[page_idx]; kmapped_virt_ptr = kmap(page); prev_idx = page_idx; } if (vchiq_arm_log_level >= VCHIQ_LOG_TRACE) vchiq_log_dump_mem("ph", (uint32_t)(unsigned long)&kmapped_virt_ptr[ page_offset], &kmapped_virt_ptr[page_offset], 16); offset += 16; } if (page != NULL) kunmap(page); for (page_idx = 0; page_idx < num_pages; page_idx++) page_cache_release(pages[page_idx]); kfree(pages); } /**************************************************************************** * * vchiq_read * ***************************************************************************/ static ssize_t vchiq_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { DUMP_CONTEXT_T context; context.buf = buf; context.actual = 0; context.space = count; context.offset = *ppos; vchiq_dump_state(&context, &g_state); *ppos += context.actual; return context.actual; } #endif VCHIQ_STATE_T * vchiq_get_state(void) { if (g_state.remote == NULL) printk(KERN_ERR "%s: g_state.remote == NULL\n", __func__); else if (g_state.remote->initialised != 1) printk(KERN_NOTICE "%s: g_state.remote->initialised != 1 (%d)\n", __func__, g_state.remote->initialised); return ((g_state.remote != NULL) && (g_state.remote->initialised == 1)) ? &g_state : NULL; } /* * Autosuspend related functionality */ int vchiq_videocore_wanted(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); if (!arm_state) /* autosuspend not supported - always return wanted */ return 1; else if (arm_state->blocked_count) return 1; else if (!arm_state->videocore_use_count) /* usage count zero - check for override unless we're forcing */ if (arm_state->resume_blocked) return 0; else return vchiq_platform_videocore_wanted(state); else /* non-zero usage count - videocore still required */ return 1; } static VCHIQ_STATUS_T vchiq_keepalive_vchiq_callback(VCHIQ_REASON_T reason, VCHIQ_HEADER_T *header, VCHIQ_SERVICE_HANDLE_T service_user, void *bulk_user) { vchiq_log_error(vchiq_susp_log_level, "%s callback reason %d", __func__, reason); return 0; } static int vchiq_keepalive_thread_func(void *v) { VCHIQ_STATE_T *state = (VCHIQ_STATE_T *) v; VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); VCHIQ_STATUS_T status; VCHIQ_INSTANCE_T instance; VCHIQ_SERVICE_HANDLE_T ka_handle; VCHIQ_SERVICE_PARAMS_T params = { .fourcc = VCHIQ_MAKE_FOURCC('K', 'E', 'E', 'P'), .callback = vchiq_keepalive_vchiq_callback, .version = KEEPALIVE_VER, .version_min = KEEPALIVE_VER_MIN }; status = vchiq_initialise(&instance); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s vchiq_initialise failed %d", __func__, status); goto exit; } status = vchiq_connect(instance); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s vchiq_connect failed %d", __func__, status); goto shutdown; } status = vchiq_add_service(instance, ¶ms, &ka_handle); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s vchiq_open_service failed %d", __func__, status); goto shutdown; } while (1) { long rc = 0, uc = 0; if (wait_for_completion_interruptible(&arm_state->ka_evt) != 0) { vchiq_log_error(vchiq_susp_log_level, "%s interrupted", __func__); flush_signals(current); continue; } /* read and clear counters. Do release_count then use_count to * prevent getting more releases than uses */ rc = atomic_xchg(&arm_state->ka_release_count, 0); uc = atomic_xchg(&arm_state->ka_use_count, 0); /* Call use/release service the requisite number of times. * Process use before release so use counts don't go negative */ while (uc--) { atomic_inc(&arm_state->ka_use_ack_count); status = vchiq_use_service(ka_handle); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s vchiq_use_service error %d", __func__, status); } } while (rc--) { status = vchiq_release_service(ka_handle); if (status != VCHIQ_SUCCESS) { vchiq_log_error(vchiq_susp_log_level, "%s vchiq_release_service error %d", __func__, status); } } } shutdown: vchiq_shutdown(instance); exit: return 0; } VCHIQ_STATUS_T vchiq_arm_init_state(VCHIQ_STATE_T *state, VCHIQ_ARM_STATE_T *arm_state) { VCHIQ_STATUS_T status = VCHIQ_SUCCESS; if (arm_state) { rwlock_init(&arm_state->susp_res_lock); init_completion(&arm_state->ka_evt); atomic_set(&arm_state->ka_use_count, 0); atomic_set(&arm_state->ka_use_ack_count, 0); atomic_set(&arm_state->ka_release_count, 0); init_completion(&arm_state->vc_suspend_complete); init_completion(&arm_state->vc_resume_complete); /* Initialise to 'done' state. We only want to block on resume * completion while videocore is suspended. */ set_resume_state(arm_state, VC_RESUME_RESUMED); init_completion(&arm_state->resume_blocker); /* Initialise to 'done' state. We only want to block on this * completion while resume is blocked */ complete_all(&arm_state->resume_blocker); init_completion(&arm_state->blocked_blocker); /* Initialise to 'done' state. We only want to block on this * completion while things are waiting on the resume blocker */ complete_all(&arm_state->blocked_blocker); arm_state->suspend_timer_timeout = SUSPEND_TIMER_TIMEOUT_MS; arm_state->suspend_timer_running = 0; vchiq_init_timer(&arm_state->suspend_timer); arm_state->suspend_timer.data = (unsigned long)(state); arm_state->suspend_timer.function = suspend_timer_callback; arm_state->first_connect = 0; } return status; } /* ** Functions to modify the state variables; ** set_suspend_state ** set_resume_state ** ** There are more state variables than we might like, so ensure they remain in ** step. Suspend and resume state are maintained separately, since most of ** these state machines can operate independently. However, there are a few ** states where state transitions in one state machine cause a reset to the ** other state machine. In addition, there are some completion events which ** need to occur on state machine reset and end-state(s), so these are also ** dealt with in these functions. ** ** In all states we set the state variable according to the input, but in some ** cases we perform additional steps outlined below; ** ** VC_SUSPEND_IDLE - Initialise the suspend completion at the same time. ** The suspend completion is completed after any suspend ** attempt. When we reset the state machine we also reset ** the completion. This reset occurs when videocore is ** resumed, and also if we initiate suspend after a suspend ** failure. ** ** VC_SUSPEND_IN_PROGRESS - This state is considered the point of no return for ** suspend - ie from this point on we must try to suspend ** before resuming can occur. We therefore also reset the ** resume state machine to VC_RESUME_IDLE in this state. ** ** VC_SUSPEND_SUSPENDED - Suspend has completed successfully. Also call ** complete_all on the suspend completion to notify ** anything waiting for suspend to happen. ** ** VC_SUSPEND_REJECTED - Videocore rejected suspend. Videocore will also ** initiate resume, so no need to alter resume state. ** We call complete_all on the suspend completion to notify ** of suspend rejection. ** ** VC_SUSPEND_FAILED - We failed to initiate videocore suspend. We notify the ** suspend completion and reset the resume state machine. ** ** VC_RESUME_IDLE - Initialise the resume completion at the same time. The ** resume completion is in its 'done' state whenever ** videcore is running. Therfore, the VC_RESUME_IDLE state ** implies that videocore is suspended. ** Hence, any thread which needs to wait until videocore is ** running can wait on this completion - it will only block ** if videocore is suspended. ** ** VC_RESUME_RESUMED - Resume has completed successfully. Videocore is running. ** Call complete_all on the resume completion to unblock ** any threads waiting for resume. Also reset the suspend ** state machine to it's idle state. ** ** VC_RESUME_FAILED - Currently unused - no mechanism to fail resume exists. */ void set_suspend_state(VCHIQ_ARM_STATE_T *arm_state, enum vc_suspend_status new_state) { /* set the state in all cases */ arm_state->vc_suspend_state = new_state; /* state specific additional actions */ switch (new_state) { case VC_SUSPEND_FORCE_CANCELED: complete_all(&arm_state->vc_suspend_complete); break; case VC_SUSPEND_REJECTED: complete_all(&arm_state->vc_suspend_complete); break; case VC_SUSPEND_FAILED: complete_all(&arm_state->vc_suspend_complete); arm_state->vc_resume_state = VC_RESUME_RESUMED; complete_all(&arm_state->vc_resume_complete); break; case VC_SUSPEND_IDLE: /* TODO: reinit_completion */ INIT_COMPLETION(arm_state->vc_suspend_complete); break; case VC_SUSPEND_REQUESTED: break; case VC_SUSPEND_IN_PROGRESS: set_resume_state(arm_state, VC_RESUME_IDLE); break; case VC_SUSPEND_SUSPENDED: complete_all(&arm_state->vc_suspend_complete); break; default: BUG(); break; } } void set_resume_state(VCHIQ_ARM_STATE_T *arm_state, enum vc_resume_status new_state) { /* set the state in all cases */ arm_state->vc_resume_state = new_state; /* state specific additional actions */ switch (new_state) { case VC_RESUME_FAILED: break; case VC_RESUME_IDLE: /* TODO: reinit_completion */ INIT_COMPLETION(arm_state->vc_resume_complete); break; case VC_RESUME_REQUESTED: break; case VC_RESUME_IN_PROGRESS: break; case VC_RESUME_RESUMED: complete_all(&arm_state->vc_resume_complete); set_suspend_state(arm_state, VC_SUSPEND_IDLE); break; default: BUG(); break; } } /* should be called with the write lock held */ inline void start_suspend_timer(VCHIQ_ARM_STATE_T *arm_state) { vchiq_del_timer(&arm_state->suspend_timer); arm_state->suspend_timer.expires = jiffies + msecs_to_jiffies(arm_state-> suspend_timer_timeout); vchiq_add_timer(&arm_state->suspend_timer); arm_state->suspend_timer_running = 1; } /* should be called with the write lock held */ static inline void stop_suspend_timer(VCHIQ_ARM_STATE_T *arm_state) { if (arm_state->suspend_timer_running) { vchiq_del_timer(&arm_state->suspend_timer); arm_state->suspend_timer_running = 0; } } static inline int need_resume(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); return (arm_state->vc_suspend_state > VC_SUSPEND_IDLE) && (arm_state->vc_resume_state < VC_RESUME_REQUESTED) && vchiq_videocore_wanted(state); } static int block_resume(VCHIQ_ARM_STATE_T *arm_state) { int status = VCHIQ_SUCCESS; const unsigned long timeout_val = msecs_to_jiffies(FORCE_SUSPEND_TIMEOUT_MS); int resume_count = 0; /* Allow any threads which were blocked by the last force suspend to * complete if they haven't already. Only give this one shot; if * blocked_count is incremented after blocked_blocker is completed * (which only happens when blocked_count hits 0) then those threads * will have to wait until next time around */ if (arm_state->blocked_count) { /* TODO: reinit_completion */ INIT_COMPLETION(arm_state->blocked_blocker); write_unlock_bh(&arm_state->susp_res_lock); vchiq_log_info(vchiq_susp_log_level, "%s wait for previously " "blocked clients", __func__); if (wait_for_completion_interruptible_timeout( &arm_state->blocked_blocker, timeout_val) <= 0) { vchiq_log_error(vchiq_susp_log_level, "%s wait for " "previously blocked clients failed" , __func__); status = VCHIQ_ERROR; write_lock_bh(&arm_state->susp_res_lock); goto out; } vchiq_log_info(vchiq_susp_log_level, "%s previously blocked " "clients resumed", __func__); write_lock_bh(&arm_state->susp_res_lock); } /* We need to wait for resume to complete if it's in process */ while (arm_state->vc_resume_state != VC_RESUME_RESUMED && arm_state->vc_resume_state > VC_RESUME_IDLE) { if (resume_count > 1) { status = VCHIQ_ERROR; vchiq_log_error(vchiq_susp_log_level, "%s waited too " "many times for resume" , __func__); goto out; } write_unlock_bh(&arm_state->susp_res_lock); vchiq_log_info(vchiq_susp_log_level, "%s wait for resume", __func__); if (wait_for_completion_interruptible_timeout( &arm_state->vc_resume_complete, timeout_val) <= 0) { vchiq_log_error(vchiq_susp_log_level, "%s wait for " "resume failed (%s)", __func__, resume_state_names[arm_state->vc_resume_state + VC_RESUME_NUM_OFFSET]); status = VCHIQ_ERROR; write_lock_bh(&arm_state->susp_res_lock); goto out; } vchiq_log_info(vchiq_susp_log_level, "%s resumed", __func__); write_lock_bh(&arm_state->susp_res_lock); resume_count++; } /* TODO: reinit_completion */ INIT_COMPLETION(arm_state->resume_blocker); arm_state->resume_blocked = 1; out: return status; } static inline void unblock_resume(VCHIQ_ARM_STATE_T *arm_state) { complete_all(&arm_state->resume_blocker); arm_state->resume_blocked = 0; } /* Initiate suspend via slot handler. Should be called with the write lock * held */ VCHIQ_STATUS_T vchiq_arm_vcsuspend(VCHIQ_STATE_T *state) { VCHIQ_STATUS_T status = VCHIQ_ERROR; VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); if (!arm_state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); status = VCHIQ_SUCCESS; switch (arm_state->vc_suspend_state) { case VC_SUSPEND_REQUESTED: vchiq_log_info(vchiq_susp_log_level, "%s: suspend already " "requested", __func__); break; case VC_SUSPEND_IN_PROGRESS: vchiq_log_info(vchiq_susp_log_level, "%s: suspend already in " "progress", __func__); break; default: /* We don't expect to be in other states, so log but continue * anyway */ vchiq_log_error(vchiq_susp_log_level, "%s unexpected suspend state %s", __func__, suspend_state_names[arm_state->vc_suspend_state + VC_SUSPEND_NUM_OFFSET]); /* fall through */ case VC_SUSPEND_REJECTED: case VC_SUSPEND_FAILED: /* Ensure any idle state actions have been run */ set_suspend_state(arm_state, VC_SUSPEND_IDLE); /* fall through */ case VC_SUSPEND_IDLE: vchiq_log_info(vchiq_susp_log_level, "%s: suspending", __func__); set_suspend_state(arm_state, VC_SUSPEND_REQUESTED); /* kick the slot handler thread to initiate suspend */ request_poll(state, NULL, 0); break; } out: vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, status); return status; } void vchiq_platform_check_suspend(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); int susp = 0; if (!arm_state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); write_lock_bh(&arm_state->susp_res_lock); if (arm_state->vc_suspend_state == VC_SUSPEND_REQUESTED && arm_state->vc_resume_state == VC_RESUME_RESUMED) { set_suspend_state(arm_state, VC_SUSPEND_IN_PROGRESS); susp = 1; } write_unlock_bh(&arm_state->susp_res_lock); if (susp) vchiq_platform_suspend(state); out: vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__); return; } static void output_timeout_error(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); char service_err[50] = ""; int vc_use_count = arm_state->videocore_use_count; int active_services = state->unused_service; int i; if (!arm_state->videocore_use_count) { snprintf(service_err, 50, " Videocore usecount is 0"); goto output_msg; } for (i = 0; i < active_services; i++) { VCHIQ_SERVICE_T *service_ptr = state->services[i]; if (service_ptr && service_ptr->service_use_count && (service_ptr->srvstate != VCHIQ_SRVSTATE_FREE)) { snprintf(service_err, 50, " %c%c%c%c(%8x) service has " "use count %d%s", VCHIQ_FOURCC_AS_4CHARS( service_ptr->base.fourcc), service_ptr->client_id, service_ptr->service_use_count, service_ptr->service_use_count == vc_use_count ? "" : " (+ more)"); break; } } output_msg: vchiq_log_error(vchiq_susp_log_level, "timed out waiting for vc suspend (%d).%s", arm_state->autosuspend_override, service_err); } /* Try to get videocore into suspended state, regardless of autosuspend state. ** We don't actually force suspend, since videocore may get into a bad state ** if we force suspend at a bad time. Instead, we wait for autosuspend to ** determine a good point to suspend. If this doesn't happen within 100ms we ** report failure. ** ** Returns VCHIQ_SUCCESS if videocore suspended successfully, VCHIQ_RETRY if ** videocore failed to suspend in time or VCHIQ_ERROR if interrupted. */ VCHIQ_STATUS_T vchiq_arm_force_suspend(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); VCHIQ_STATUS_T status = VCHIQ_ERROR; long rc = 0; int repeat = -1; if (!arm_state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); write_lock_bh(&arm_state->susp_res_lock); status = block_resume(arm_state); if (status != VCHIQ_SUCCESS) goto unlock; if (arm_state->vc_suspend_state == VC_SUSPEND_SUSPENDED) { /* Already suspended - just block resume and exit */ vchiq_log_info(vchiq_susp_log_level, "%s already suspended", __func__); status = VCHIQ_SUCCESS; goto unlock; } else if (arm_state->vc_suspend_state <= VC_SUSPEND_IDLE) { /* initiate suspend immediately in the case that we're waiting * for the timeout */ stop_suspend_timer(arm_state); if (!vchiq_videocore_wanted(state)) { vchiq_log_info(vchiq_susp_log_level, "%s videocore " "idle, initiating suspend", __func__); status = vchiq_arm_vcsuspend(state); } else if (arm_state->autosuspend_override < FORCE_SUSPEND_FAIL_MAX) { vchiq_log_info(vchiq_susp_log_level, "%s letting " "videocore go idle", __func__); status = VCHIQ_SUCCESS; } else { vchiq_log_warning(vchiq_susp_log_level, "%s failed too " "many times - attempting suspend", __func__); status = vchiq_arm_vcsuspend(state); } } else { vchiq_log_info(vchiq_susp_log_level, "%s videocore suspend " "in progress - wait for completion", __func__); status = VCHIQ_SUCCESS; } /* Wait for suspend to happen due to system idle (not forced..) */ if (status != VCHIQ_SUCCESS) goto unblock_resume; do { write_unlock_bh(&arm_state->susp_res_lock); rc = wait_for_completion_interruptible_timeout( &arm_state->vc_suspend_complete, msecs_to_jiffies(FORCE_SUSPEND_TIMEOUT_MS)); write_lock_bh(&arm_state->susp_res_lock); if (rc < 0) { vchiq_log_warning(vchiq_susp_log_level, "%s " "interrupted waiting for suspend", __func__); status = VCHIQ_ERROR; goto unblock_resume; } else if (rc == 0) { if (arm_state->vc_suspend_state > VC_SUSPEND_IDLE) { /* Repeat timeout once if in progress */ if (repeat < 0) { repeat = 1; continue; } } arm_state->autosuspend_override++; output_timeout_error(state); status = VCHIQ_RETRY; goto unblock_resume; } } while (0 < (repeat--)); /* Check and report state in case we need to abort ARM suspend */ if (arm_state->vc_suspend_state != VC_SUSPEND_SUSPENDED) { status = VCHIQ_RETRY; vchiq_log_error(vchiq_susp_log_level, "%s videocore suspend failed (state %s)", __func__, suspend_state_names[arm_state->vc_suspend_state + VC_SUSPEND_NUM_OFFSET]); /* Reset the state only if it's still in an error state. * Something could have already initiated another suspend. */ if (arm_state->vc_suspend_state < VC_SUSPEND_IDLE) set_suspend_state(arm_state, VC_SUSPEND_IDLE); goto unblock_resume; } /* successfully suspended - unlock and exit */ goto unlock; unblock_resume: /* all error states need to unblock resume before exit */ unblock_resume(arm_state); unlock: write_unlock_bh(&arm_state->susp_res_lock); out: vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, status); return status; } void vchiq_check_suspend(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); if (!arm_state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); write_lock_bh(&arm_state->susp_res_lock); if (arm_state->vc_suspend_state != VC_SUSPEND_SUSPENDED && arm_state->first_connect && !vchiq_videocore_wanted(state)) { vchiq_arm_vcsuspend(state); } write_unlock_bh(&arm_state->susp_res_lock); out: vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__); return; } int vchiq_arm_allow_resume(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); int resume = 0; int ret = -1; if (!arm_state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); write_lock_bh(&arm_state->susp_res_lock); unblock_resume(arm_state); resume = vchiq_check_resume(state); write_unlock_bh(&arm_state->susp_res_lock); if (resume) { if (wait_for_completion_interruptible( &arm_state->vc_resume_complete) < 0) { vchiq_log_error(vchiq_susp_log_level, "%s interrupted", __func__); /* failed, cannot accurately derive suspend * state, so exit early. */ goto out; } } read_lock_bh(&arm_state->susp_res_lock); if (arm_state->vc_suspend_state == VC_SUSPEND_SUSPENDED) { vchiq_log_info(vchiq_susp_log_level, "%s: Videocore remains suspended", __func__); } else { vchiq_log_info(vchiq_susp_log_level, "%s: Videocore resumed", __func__); ret = 0; } read_unlock_bh(&arm_state->susp_res_lock); out: vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret); return ret; } /* This function should be called with the write lock held */ int vchiq_check_resume(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); int resume = 0; if (!arm_state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); if (need_resume(state)) { set_resume_state(arm_state, VC_RESUME_REQUESTED); request_poll(state, NULL, 0); resume = 1; } out: vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__); return resume; } #ifdef notyet void vchiq_platform_check_resume(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); int res = 0; if (!arm_state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); write_lock_bh(&arm_state->susp_res_lock); if (arm_state->wake_address == 0) { vchiq_log_info(vchiq_susp_log_level, "%s: already awake", __func__); goto unlock; } if (arm_state->vc_resume_state == VC_RESUME_IN_PROGRESS) { vchiq_log_info(vchiq_susp_log_level, "%s: already resuming", __func__); goto unlock; } if (arm_state->vc_resume_state == VC_RESUME_REQUESTED) { set_resume_state(arm_state, VC_RESUME_IN_PROGRESS); res = 1; } else vchiq_log_trace(vchiq_susp_log_level, "%s: not resuming (resume state %s)", __func__, resume_state_names[arm_state->vc_resume_state + VC_RESUME_NUM_OFFSET]); unlock: write_unlock_bh(&arm_state->susp_res_lock); if (res) vchiq_platform_resume(state); out: vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__); return; } #endif VCHIQ_STATUS_T vchiq_use_internal(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service, enum USE_TYPE_E use_type) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); VCHIQ_STATUS_T ret = VCHIQ_SUCCESS; char entity[16]; int *entity_uc; int local_uc, local_entity_uc; if (!arm_state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); if (use_type == USE_TYPE_VCHIQ) { snprintf(entity, sizeof(entity), "VCHIQ: "); entity_uc = &arm_state->peer_use_count; } else if (service) { snprintf(entity, sizeof(entity), "%c%c%c%c:%8x", VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc), service->client_id); entity_uc = &service->service_use_count; } else { vchiq_log_error(vchiq_susp_log_level, "%s null service " "ptr", __func__); ret = VCHIQ_ERROR; goto out; } write_lock_bh(&arm_state->susp_res_lock); while (arm_state->resume_blocked) { /* If we call 'use' while force suspend is waiting for suspend, * then we're about to block the thread which the force is * waiting to complete, so we're bound to just time out. In this * case, set the suspend state such that the wait will be * canceled, so we can complete as quickly as possible. */ if (arm_state->resume_blocked && arm_state->vc_suspend_state == VC_SUSPEND_IDLE) { set_suspend_state(arm_state, VC_SUSPEND_FORCE_CANCELED); break; } /* If suspend is already in progress then we need to block */ if (!try_wait_for_completion(&arm_state->resume_blocker)) { /* Indicate that there are threads waiting on the resume * blocker. These need to be allowed to complete before * a _second_ call to force suspend can complete, * otherwise low priority threads might never actually * continue */ arm_state->blocked_count++; write_unlock_bh(&arm_state->susp_res_lock); vchiq_log_info(vchiq_susp_log_level, "%s %s resume " "blocked - waiting...", __func__, entity); if (wait_for_completion_killable( &arm_state->resume_blocker) != 0) { vchiq_log_error(vchiq_susp_log_level, "%s %s " "wait for resume blocker interrupted", __func__, entity); ret = VCHIQ_ERROR; write_lock_bh(&arm_state->susp_res_lock); arm_state->blocked_count--; write_unlock_bh(&arm_state->susp_res_lock); goto out; } vchiq_log_info(vchiq_susp_log_level, "%s %s resume " "unblocked", __func__, entity); write_lock_bh(&arm_state->susp_res_lock); if (--arm_state->blocked_count == 0) complete_all(&arm_state->blocked_blocker); } } stop_suspend_timer(arm_state); local_uc = ++arm_state->videocore_use_count; local_entity_uc = ++(*entity_uc); /* If there's a pending request which hasn't yet been serviced then * just clear it. If we're past VC_SUSPEND_REQUESTED state then * vc_resume_complete will block until we either resume or fail to * suspend */ if (arm_state->vc_suspend_state <= VC_SUSPEND_REQUESTED) set_suspend_state(arm_state, VC_SUSPEND_IDLE); if ((use_type != USE_TYPE_SERVICE_NO_RESUME) && need_resume(state)) { set_resume_state(arm_state, VC_RESUME_REQUESTED); vchiq_log_info(vchiq_susp_log_level, "%s %s count %d, state count %d", __func__, entity, local_entity_uc, local_uc); request_poll(state, NULL, 0); } else vchiq_log_trace(vchiq_susp_log_level, "%s %s count %d, state count %d", __func__, entity, *entity_uc, local_uc); write_unlock_bh(&arm_state->susp_res_lock); /* Completion is in a done state when we're not suspended, so this won't * block for the non-suspended case. */ if (!try_wait_for_completion(&arm_state->vc_resume_complete)) { vchiq_log_info(vchiq_susp_log_level, "%s %s wait for resume", __func__, entity); if (wait_for_completion_killable( &arm_state->vc_resume_complete) != 0) { vchiq_log_error(vchiq_susp_log_level, "%s %s wait for " "resume interrupted", __func__, entity); ret = VCHIQ_ERROR; goto out; } vchiq_log_info(vchiq_susp_log_level, "%s %s resumed", __func__, entity); } if (ret == VCHIQ_SUCCESS) { VCHIQ_STATUS_T status = VCHIQ_SUCCESS; long ack_cnt = atomic_xchg(&arm_state->ka_use_ack_count, 0); while (ack_cnt && (status == VCHIQ_SUCCESS)) { /* Send the use notify to videocore */ status = vchiq_send_remote_use_active(state); if (status == VCHIQ_SUCCESS) ack_cnt--; else atomic_add(ack_cnt, &arm_state->ka_use_ack_count); } } out: vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret); return ret; } VCHIQ_STATUS_T vchiq_release_internal(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); VCHIQ_STATUS_T ret = VCHIQ_SUCCESS; char entity[16]; int *entity_uc; if (!arm_state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); if (service) { snprintf(entity, sizeof(entity), "%c%c%c%c:%8x", VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc), service->client_id); entity_uc = &service->service_use_count; } else { snprintf(entity, sizeof(entity), "PEER: "); entity_uc = &arm_state->peer_use_count; } write_lock_bh(&arm_state->susp_res_lock); if (!arm_state->videocore_use_count || !(*entity_uc)) { /* Don't use BUG_ON - don't allow user thread to crash kernel */ WARN_ON(!arm_state->videocore_use_count); WARN_ON(!(*entity_uc)); ret = VCHIQ_ERROR; goto unlock; } --arm_state->videocore_use_count; --(*entity_uc); if (!vchiq_videocore_wanted(state)) { if (vchiq_platform_use_suspend_timer() && !arm_state->resume_blocked) { /* Only use the timer if we're not trying to force * suspend (=> resume_blocked) */ start_suspend_timer(arm_state); } else { vchiq_log_info(vchiq_susp_log_level, "%s %s count %d, state count %d - suspending", __func__, entity, *entity_uc, arm_state->videocore_use_count); vchiq_arm_vcsuspend(state); } } else vchiq_log_trace(vchiq_susp_log_level, "%s %s count %d, state count %d", __func__, entity, *entity_uc, arm_state->videocore_use_count); unlock: write_unlock_bh(&arm_state->susp_res_lock); out: vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret); return ret; } void vchiq_on_remote_use(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); atomic_inc(&arm_state->ka_use_count); complete(&arm_state->ka_evt); } void vchiq_on_remote_release(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); atomic_inc(&arm_state->ka_release_count); complete(&arm_state->ka_evt); } VCHIQ_STATUS_T vchiq_use_service_internal(VCHIQ_SERVICE_T *service) { return vchiq_use_internal(service->state, service, USE_TYPE_SERVICE); } VCHIQ_STATUS_T vchiq_release_service_internal(VCHIQ_SERVICE_T *service) { return vchiq_release_internal(service->state, service); } static void suspend_timer_callback(unsigned long context) { VCHIQ_STATE_T *state = (VCHIQ_STATE_T *)context; VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); if (!arm_state) goto out; vchiq_log_info(vchiq_susp_log_level, "%s - suspend timer expired - check suspend", __func__); vchiq_check_suspend(state); out: return; } VCHIQ_STATUS_T vchiq_use_service_no_resume(VCHIQ_SERVICE_HANDLE_T handle) { VCHIQ_STATUS_T ret = VCHIQ_ERROR; VCHIQ_SERVICE_T *service = find_service_by_handle(handle); if (service) { ret = vchiq_use_internal(service->state, service, USE_TYPE_SERVICE_NO_RESUME); unlock_service(service); } return ret; } VCHIQ_STATUS_T vchiq_use_service(VCHIQ_SERVICE_HANDLE_T handle) { VCHIQ_STATUS_T ret = VCHIQ_ERROR; VCHIQ_SERVICE_T *service = find_service_by_handle(handle); if (service) { ret = vchiq_use_internal(service->state, service, USE_TYPE_SERVICE); unlock_service(service); } return ret; } VCHIQ_STATUS_T vchiq_release_service(VCHIQ_SERVICE_HANDLE_T handle) { VCHIQ_STATUS_T ret = VCHIQ_ERROR; VCHIQ_SERVICE_T *service = find_service_by_handle(handle); if (service) { ret = vchiq_release_internal(service->state, service); unlock_service(service); } return ret; } void vchiq_dump_service_use_state(VCHIQ_STATE_T *state) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); int i, j = 0; /* Only dump 64 services */ static const int local_max_services = 64; /* If there's more than 64 services, only dump ones with * non-zero counts */ int only_nonzero = 0; static const char *nz = "<-- preventing suspend"; enum vc_suspend_status vc_suspend_state; enum vc_resume_status vc_resume_state; int peer_count; int vc_use_count; int active_services; struct service_data_struct { int fourcc; int clientid; int use_count; } service_data[local_max_services]; if (!arm_state) return; read_lock_bh(&arm_state->susp_res_lock); vc_suspend_state = arm_state->vc_suspend_state; vc_resume_state = arm_state->vc_resume_state; peer_count = arm_state->peer_use_count; vc_use_count = arm_state->videocore_use_count; active_services = state->unused_service; if (active_services > local_max_services) only_nonzero = 1; for (i = 0; (i < active_services) && (j < local_max_services); i++) { VCHIQ_SERVICE_T *service_ptr = state->services[i]; if (!service_ptr) continue; if (only_nonzero && !service_ptr->service_use_count) continue; if (service_ptr->srvstate != VCHIQ_SRVSTATE_FREE) { service_data[j].fourcc = service_ptr->base.fourcc; service_data[j].clientid = service_ptr->client_id; service_data[j++].use_count = service_ptr-> service_use_count; } } read_unlock_bh(&arm_state->susp_res_lock); vchiq_log_warning(vchiq_susp_log_level, "-- Videcore suspend state: %s --", suspend_state_names[vc_suspend_state + VC_SUSPEND_NUM_OFFSET]); vchiq_log_warning(vchiq_susp_log_level, "-- Videcore resume state: %s --", resume_state_names[vc_resume_state + VC_RESUME_NUM_OFFSET]); if (only_nonzero) vchiq_log_warning(vchiq_susp_log_level, "Too many active " "services (%d). Only dumping up to first %d services " "with non-zero use-count", active_services, local_max_services); for (i = 0; i < j; i++) { vchiq_log_warning(vchiq_susp_log_level, "----- %c%c%c%c:%d service count %d %s", VCHIQ_FOURCC_AS_4CHARS(service_data[i].fourcc), service_data[i].clientid, service_data[i].use_count, service_data[i].use_count ? nz : ""); } vchiq_log_warning(vchiq_susp_log_level, "----- VCHIQ use count count %d", peer_count); vchiq_log_warning(vchiq_susp_log_level, "--- Overall vchiq instance use count %d", vc_use_count); vchiq_dump_platform_use_state(state); } VCHIQ_STATUS_T vchiq_check_service(VCHIQ_SERVICE_T *service) { VCHIQ_ARM_STATE_T *arm_state; VCHIQ_STATUS_T ret = VCHIQ_ERROR; if (!service || !service->state) goto out; vchiq_log_trace(vchiq_susp_log_level, "%s", __func__); arm_state = vchiq_platform_get_arm_state(service->state); read_lock_bh(&arm_state->susp_res_lock); if (service->service_use_count) ret = VCHIQ_SUCCESS; read_unlock_bh(&arm_state->susp_res_lock); if (ret == VCHIQ_ERROR) { vchiq_log_error(vchiq_susp_log_level, "%s ERROR - %c%c%c%c:%8x service count %d, " "state count %d, videocore suspend state %s", __func__, VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc), service->client_id, service->service_use_count, arm_state->videocore_use_count, suspend_state_names[arm_state->vc_suspend_state + VC_SUSPEND_NUM_OFFSET]); vchiq_dump_service_use_state(service->state); } out: return ret; } /* stub functions */ void vchiq_on_remote_use_active(VCHIQ_STATE_T *state) { (void)state; } void vchiq_platform_conn_state_changed(VCHIQ_STATE_T *state, VCHIQ_CONNSTATE_T oldstate, VCHIQ_CONNSTATE_T newstate) { VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state); vchiq_log_info(vchiq_susp_log_level, "%d: %s->%s", state->id, get_conn_state_name(oldstate), get_conn_state_name(newstate)); if (state->conn_state == VCHIQ_CONNSTATE_CONNECTED) { write_lock_bh(&arm_state->susp_res_lock); if (!arm_state->first_connect) { char threadname[10]; arm_state->first_connect = 1; write_unlock_bh(&arm_state->susp_res_lock); snprintf(threadname, sizeof(threadname), "VCHIQka-%d", state->id); arm_state->ka_thread = vchiq_thread_create( &vchiq_keepalive_thread_func, (void *)state, threadname); if (arm_state->ka_thread == NULL) { vchiq_log_error(vchiq_susp_log_level, "vchiq: FATAL: couldn't create thread %s", threadname); } else { wake_up_process(arm_state->ka_thread); } } else write_unlock_bh(&arm_state->susp_res_lock); } } /**************************************************************************** * * vchiq_init - called when the module is loaded. * ***************************************************************************/ int __init vchiq_init(void); int __init vchiq_init(void) { int err; #ifdef notyet /* create proc entries */ err = vchiq_proc_init(); if (err != 0) goto failed_proc_init; #endif vchiq_cdev = make_dev(&vchiq_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "vchiq"); if (!vchiq_cdev) { printf("Failed to create /dev/vchiq"); return (-ENXIO); } spin_lock_init(&msg_queue_spinlock); err = vchiq_platform_init(&g_state); if (err != 0) goto failed_platform_init; vchiq_log_info(vchiq_arm_log_level, "vchiq: initialised - version %d (min %d)", VCHIQ_VERSION, VCHIQ_VERSION_MIN); return 0; failed_platform_init: if (vchiq_cdev) { destroy_dev(vchiq_cdev); vchiq_cdev = NULL; } vchiq_log_warning(vchiq_arm_log_level, "could not load vchiq"); return err; } #ifdef notyet static int vchiq_instance_get_use_count(VCHIQ_INSTANCE_T instance) { VCHIQ_SERVICE_T *service; int use_count = 0, i; i = 0; while ((service = next_service_by_instance(instance->state, instance, &i)) != NULL) { use_count += service->service_use_count; unlock_service(service); } return use_count; } /* read the per-process use-count */ static int proc_read_use_count(char *page, char **start, off_t off, int count, int *eof, void *data) { VCHIQ_INSTANCE_T instance = data; int len, use_count; use_count = vchiq_instance_get_use_count(instance); len = snprintf(page+off, count, "%d\n", use_count); return len; } /* add an instance (process) to the proc entries */ static int vchiq_proc_add_instance(VCHIQ_INSTANCE_T instance) { char pidstr[32]; struct proc_dir_entry *top, *use_count; struct proc_dir_entry *clients = vchiq_clients_top(); int pid = instance->pid; snprintf(pidstr, sizeof(pidstr), "%d", pid); top = proc_mkdir(pidstr, clients); if (!top) goto fail_top; use_count = create_proc_read_entry("use_count", 0444, top, proc_read_use_count, instance); if (!use_count) goto fail_use_count; instance->proc_entry = top; return 0; fail_use_count: remove_proc_entry(top->name, clients); fail_top: return -ENOMEM; } static void vchiq_proc_remove_instance(VCHIQ_INSTANCE_T instance) { struct proc_dir_entry *clients = vchiq_clients_top(); remove_proc_entry("use_count", instance->proc_entry); remove_proc_entry(instance->proc_entry->name, clients); } #endif /**************************************************************************** * * vchiq_exit - called when the module is unloaded. * ***************************************************************************/ void vchiq_exit(void); void vchiq_exit(void) { vchiq_platform_exit(&g_state); if (vchiq_cdev) { destroy_dev(vchiq_cdev); vchiq_cdev = NULL; } } diff --git a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_core.c b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_core.c index e7459a5553e4..923cf56f10ee 100644 --- a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_core.c +++ b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_core.c @@ -1,3952 +1,3971 @@ /** * Copyright (c) 2010-2012 Broadcom. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the above-listed copyright holders may not be used * to endorse or promote products derived from this software without * specific prior written permission. * * ALTERNATIVELY, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2, as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "vchiq_core.h" #include "vchiq_killable.h" #define VCHIQ_SLOT_HANDLER_STACK 8192 #define HANDLE_STATE_SHIFT 12 #define SLOT_INFO_FROM_INDEX(state, index) (state->slot_info + (index)) #define SLOT_DATA_FROM_INDEX(state, index) (state->slot_data + (index)) #define SLOT_INDEX_FROM_DATA(state, data) \ (((unsigned int)((char *)data - (char *)state->slot_data)) / \ VCHIQ_SLOT_SIZE) #define SLOT_INDEX_FROM_INFO(state, info) \ ((unsigned int)(info - state->slot_info)) #define SLOT_QUEUE_INDEX_FROM_POS(pos) \ ((int)((unsigned int)(pos) / VCHIQ_SLOT_SIZE)) #define BULK_INDEX(x) (x & (VCHIQ_NUM_SERVICE_BULKS - 1)) #define SRVTRACE_LEVEL(srv) \ (((srv) && (srv)->trace) ? VCHIQ_LOG_TRACE : vchiq_core_msg_log_level) #define SRVTRACE_ENABLED(srv, lev) \ (((srv) && (srv)->trace) || (vchiq_core_msg_log_level >= (lev))) struct vchiq_open_payload { int fourcc; int client_id; short version; short version_min; }; struct vchiq_openack_payload { short version; }; enum { QMFLAGS_IS_BLOCKING = (1 << 0), QMFLAGS_NO_MUTEX_LOCK = (1 << 1), QMFLAGS_NO_MUTEX_UNLOCK = (1 << 2) }; /* we require this for consistency between endpoints */ vchiq_static_assert(sizeof(VCHIQ_HEADER_T) == 8); vchiq_static_assert(IS_POW2(sizeof(VCHIQ_HEADER_T))); vchiq_static_assert(IS_POW2(VCHIQ_NUM_CURRENT_BULKS)); vchiq_static_assert(IS_POW2(VCHIQ_NUM_SERVICE_BULKS)); vchiq_static_assert(IS_POW2(VCHIQ_MAX_SERVICES)); vchiq_static_assert(VCHIQ_VERSION >= VCHIQ_VERSION_MIN); /* Run time control of log level, based on KERN_XXX level. */ int vchiq_core_log_level = VCHIQ_LOG_DEFAULT; int vchiq_core_msg_log_level = VCHIQ_LOG_DEFAULT; int vchiq_sync_log_level = VCHIQ_LOG_DEFAULT; static atomic_t pause_bulks_count = ATOMIC_INIT(0); static DEFINE_SPINLOCK(service_spinlock); DEFINE_SPINLOCK(bulk_waiter_spinlock); DEFINE_SPINLOCK(quota_spinlock); void vchiq_core_initialize(void) { spin_lock_init(&service_spinlock); spin_lock_init(&bulk_waiter_spinlock); spin_lock_init("a_spinlock); } VCHIQ_STATE_T *vchiq_states[VCHIQ_MAX_STATES]; static unsigned int handle_seq; static const char *const srvstate_names[] = { "FREE", "HIDDEN", "LISTENING", "OPENING", "OPEN", "OPENSYNC", "CLOSESENT", "CLOSERECVD", "CLOSEWAIT", "CLOSED" }; static const char *const reason_names[] = { "SERVICE_OPENED", "SERVICE_CLOSED", "MESSAGE_AVAILABLE", "BULK_TRANSMIT_DONE", "BULK_RECEIVE_DONE", "BULK_TRANSMIT_ABORTED", "BULK_RECEIVE_ABORTED" }; static const char *const conn_state_names[] = { "DISCONNECTED", "CONNECTING", "CONNECTED", "PAUSING", "PAUSE_SENT", "PAUSED", "RESUMING", "PAUSE_TIMEOUT", "RESUME_TIMEOUT" }; static void release_message_sync(VCHIQ_STATE_T *state, VCHIQ_HEADER_T *header); static const char *msg_type_str(unsigned int msg_type) { switch (msg_type) { case VCHIQ_MSG_PADDING: return "PADDING"; case VCHIQ_MSG_CONNECT: return "CONNECT"; case VCHIQ_MSG_OPEN: return "OPEN"; case VCHIQ_MSG_OPENACK: return "OPENACK"; case VCHIQ_MSG_CLOSE: return "CLOSE"; case VCHIQ_MSG_DATA: return "DATA"; case VCHIQ_MSG_BULK_RX: return "BULK_RX"; case VCHIQ_MSG_BULK_TX: return "BULK_TX"; case VCHIQ_MSG_BULK_RX_DONE: return "BULK_RX_DONE"; case VCHIQ_MSG_BULK_TX_DONE: return "BULK_TX_DONE"; case VCHIQ_MSG_PAUSE: return "PAUSE"; case VCHIQ_MSG_RESUME: return "RESUME"; case VCHIQ_MSG_REMOTE_USE: return "REMOTE_USE"; case VCHIQ_MSG_REMOTE_RELEASE: return "REMOTE_RELEASE"; case VCHIQ_MSG_REMOTE_USE_ACTIVE: return "REMOTE_USE_ACTIVE"; } return "???"; } static inline void vchiq_set_service_state(VCHIQ_SERVICE_T *service, int newstate) { vchiq_log_info(vchiq_core_log_level, "%d: srv:%d %s->%s", service->state->id, service->localport, srvstate_names[service->srvstate], srvstate_names[newstate]); service->srvstate = newstate; } VCHIQ_SERVICE_T * find_service_by_handle(VCHIQ_SERVICE_HANDLE_T handle) { VCHIQ_SERVICE_T *service; spin_lock(&service_spinlock); service = handle_to_service(handle); if (service && (service->srvstate != VCHIQ_SRVSTATE_FREE) && (service->handle == handle)) { BUG_ON(service->ref_count == 0); service->ref_count++; } else service = NULL; spin_unlock(&service_spinlock); if (!service) vchiq_log_info(vchiq_core_log_level, "Invalid service handle 0x%x", handle); return service; } VCHIQ_SERVICE_T * find_service_by_port(VCHIQ_STATE_T *state, int localport) { VCHIQ_SERVICE_T *service = NULL; if ((unsigned int)localport <= VCHIQ_PORT_MAX) { spin_lock(&service_spinlock); service = state->services[localport]; if (service && (service->srvstate != VCHIQ_SRVSTATE_FREE)) { BUG_ON(service->ref_count == 0); service->ref_count++; } else service = NULL; spin_unlock(&service_spinlock); } if (!service) vchiq_log_info(vchiq_core_log_level, "Invalid port %d", localport); return service; } VCHIQ_SERVICE_T * find_service_for_instance(VCHIQ_INSTANCE_T instance, VCHIQ_SERVICE_HANDLE_T handle) { VCHIQ_SERVICE_T *service; spin_lock(&service_spinlock); service = handle_to_service(handle); if (service && (service->srvstate != VCHIQ_SRVSTATE_FREE) && (service->handle == handle) && (service->instance == instance)) { BUG_ON(service->ref_count == 0); service->ref_count++; } else service = NULL; spin_unlock(&service_spinlock); if (!service) vchiq_log_info(vchiq_core_log_level, "Invalid service handle 0x%x", handle); return service; } VCHIQ_SERVICE_T * find_closed_service_for_instance(VCHIQ_INSTANCE_T instance, VCHIQ_SERVICE_HANDLE_T handle) { VCHIQ_SERVICE_T *service; spin_lock(&service_spinlock); service = handle_to_service(handle); if (service && ((service->srvstate == VCHIQ_SRVSTATE_FREE) || (service->srvstate == VCHIQ_SRVSTATE_CLOSED)) && (service->handle == handle) && (service->instance == instance)) { BUG_ON(service->ref_count == 0); service->ref_count++; } else service = NULL; spin_unlock(&service_spinlock); if (!service) vchiq_log_info(vchiq_core_log_level, "Invalid service handle 0x%x", handle); return service; } VCHIQ_SERVICE_T * next_service_by_instance(VCHIQ_STATE_T *state, VCHIQ_INSTANCE_T instance, int *pidx) { VCHIQ_SERVICE_T *service = NULL; int idx = *pidx; spin_lock(&service_spinlock); while (idx < state->unused_service) { VCHIQ_SERVICE_T *srv = state->services[idx++]; if (srv && (srv->srvstate != VCHIQ_SRVSTATE_FREE) && (srv->instance == instance)) { service = srv; BUG_ON(service->ref_count == 0); service->ref_count++; break; } } spin_unlock(&service_spinlock); *pidx = idx; return service; } void lock_service(VCHIQ_SERVICE_T *service) { spin_lock(&service_spinlock); BUG_ON(!service || (service->ref_count == 0)); if (service) service->ref_count++; spin_unlock(&service_spinlock); } void unlock_service(VCHIQ_SERVICE_T *service) { VCHIQ_STATE_T *state = service->state; spin_lock(&service_spinlock); BUG_ON(!service || (service->ref_count == 0)); if (service && service->ref_count) { service->ref_count--; if (!service->ref_count) { BUG_ON(service->srvstate != VCHIQ_SRVSTATE_FREE); state->services[service->localport] = NULL; _sema_destroy(&service->remove_event); _sema_destroy(&service->bulk_remove_event); lmutex_destroy(&service->bulk_mutex); } else service = NULL; } spin_unlock(&service_spinlock); if (service && service->userdata_term) service->userdata_term(service->base.userdata); kfree(service); } int vchiq_get_client_id(VCHIQ_SERVICE_HANDLE_T handle) { VCHIQ_SERVICE_T *service = find_service_by_handle(handle); int id; id = service ? service->client_id : 0; if (service) unlock_service(service); return id; } void * vchiq_get_service_userdata(VCHIQ_SERVICE_HANDLE_T handle) { VCHIQ_SERVICE_T *service = handle_to_service(handle); return service ? service->base.userdata : NULL; } int vchiq_get_service_fourcc(VCHIQ_SERVICE_HANDLE_T handle) { VCHIQ_SERVICE_T *service = handle_to_service(handle); return service ? service->base.fourcc : 0; } static void mark_service_closing_internal(VCHIQ_SERVICE_T *service, int sh_thread) { VCHIQ_STATE_T *state = service->state; VCHIQ_SERVICE_QUOTA_T *service_quota; service->closing = 1; /* Synchronise with other threads. */ lmutex_lock(&state->recycle_mutex); lmutex_unlock(&state->recycle_mutex); if (!sh_thread || (state->conn_state != VCHIQ_CONNSTATE_PAUSE_SENT)) { /* If we're pausing then the slot_mutex is held until resume * by the slot handler. Therefore don't try to acquire this * mutex if we're the slot handler and in the pause sent state. * We don't need to in this case anyway. */ lmutex_lock(&state->slot_mutex); lmutex_unlock(&state->slot_mutex); } /* Unblock any sending thread. */ service_quota = &state->service_quotas[service->localport]; up(&service_quota->quota_event); } static void mark_service_closing(VCHIQ_SERVICE_T *service) { mark_service_closing_internal(service, 0); } static inline VCHIQ_STATUS_T make_service_callback(VCHIQ_SERVICE_T *service, VCHIQ_REASON_T reason, VCHIQ_HEADER_T *header, void *bulk_userdata) { VCHIQ_STATUS_T status; vchiq_log_trace(vchiq_core_log_level, "%d: callback:%d (%s, %p, %p)", service->state->id, service->localport, reason_names[reason], header, bulk_userdata); status = service->base.callback(reason, header, service->handle, bulk_userdata); if (status == VCHIQ_ERROR) { vchiq_log_warning(vchiq_core_log_level, "%d: ignoring ERROR from callback to service %x", service->state->id, service->handle); status = VCHIQ_SUCCESS; } return status; } inline void vchiq_set_conn_state(VCHIQ_STATE_T *state, VCHIQ_CONNSTATE_T newstate) { VCHIQ_CONNSTATE_T oldstate = state->conn_state; vchiq_log_info(vchiq_core_log_level, "%d: %s->%s", state->id, conn_state_names[oldstate], conn_state_names[newstate]); state->conn_state = newstate; vchiq_platform_conn_state_changed(state, oldstate, newstate); } +#define ACTUAL_EVENT_SEM_ADDR(ref,offset)\ + ((struct semaphore *)(((size_t) ref) + ((size_t) offset))) static inline void -remote_event_create(REMOTE_EVENT_T *event) +remote_event_create(VCHIQ_STATE_T *ref, REMOTE_EVENT_T *event) { event->armed = 0; /* Don't clear the 'fired' flag because it may already have been set ** by the other side. */ - _sema_init(event->event, 0); + _sema_init(ACTUAL_EVENT_SEM_ADDR(ref,event->event), 0); } __unused static inline void remote_event_destroy(REMOTE_EVENT_T *event) { (void)event; } static inline int -remote_event_wait(REMOTE_EVENT_T *event) +remote_event_wait(VCHIQ_STATE_T *ref, REMOTE_EVENT_T *event) { if (!event->fired) { event->armed = 1; +#if defined(__aarch64__) + dsb(sy); +#else dsb(); +#endif + if (!event->fired) { - if (down_interruptible(event->event) != 0) { + if (down_interruptible(ACTUAL_EVENT_SEM_ADDR(ref,event->event)) != 0) { event->armed = 0; return 0; } } event->armed = 0; wmb(); } event->fired = 0; return 1; } static inline void -remote_event_signal_local(REMOTE_EVENT_T *event) +remote_event_signal_local(VCHIQ_STATE_T *ref, REMOTE_EVENT_T *event) { +/* + * Mirror + * https://github.com/raspberrypi/linux/commit/a50c4c9a65779ca835746b5fd79d3d5278afbdbe + * for extra safety + */ + event->fired = 1; event->armed = 0; - up(event->event); + up(ACTUAL_EVENT_SEM_ADDR(ref,event->event)); } static inline void -remote_event_poll(REMOTE_EVENT_T *event) +remote_event_poll(VCHIQ_STATE_T *ref, REMOTE_EVENT_T *event) { if (event->fired && event->armed) - remote_event_signal_local(event); + remote_event_signal_local(ref,event); } void remote_event_pollall(VCHIQ_STATE_T *state) { - remote_event_poll(&state->local->sync_trigger); - remote_event_poll(&state->local->sync_release); - remote_event_poll(&state->local->trigger); - remote_event_poll(&state->local->recycle); + remote_event_poll(state , &state->local->sync_trigger); + remote_event_poll(state , &state->local->sync_release); + remote_event_poll(state , &state->local->trigger); + remote_event_poll(state , &state->local->recycle); } /* Round up message sizes so that any space at the end of a slot is always big ** enough for a header. This relies on header size being a power of two, which ** has been verified earlier by a static assertion. */ static inline unsigned int calc_stride(unsigned int size) { /* Allow room for the header */ size += sizeof(VCHIQ_HEADER_T); /* Round up */ return (size + sizeof(VCHIQ_HEADER_T) - 1) & ~(sizeof(VCHIQ_HEADER_T) - 1); } /* Called by the slot handler thread */ static VCHIQ_SERVICE_T * get_listening_service(VCHIQ_STATE_T *state, int fourcc) { int i; WARN_ON(fourcc == VCHIQ_FOURCC_INVALID); for (i = 0; i < state->unused_service; i++) { VCHIQ_SERVICE_T *service = state->services[i]; if (service && (service->public_fourcc == fourcc) && ((service->srvstate == VCHIQ_SRVSTATE_LISTENING) || ((service->srvstate == VCHIQ_SRVSTATE_OPEN) && (service->remoteport == VCHIQ_PORT_FREE)))) { lock_service(service); return service; } } return NULL; } /* Called by the slot handler thread */ static VCHIQ_SERVICE_T * get_connected_service(VCHIQ_STATE_T *state, unsigned int port) { int i; for (i = 0; i < state->unused_service; i++) { VCHIQ_SERVICE_T *service = state->services[i]; if (service && (service->srvstate == VCHIQ_SRVSTATE_OPEN) && (service->remoteport == port)) { lock_service(service); return service; } } return NULL; } inline void request_poll(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service, int poll_type) { uint32_t value; if (service) { do { value = atomic_read(&service->poll_flags); } while (atomic_cmpxchg(&service->poll_flags, value, value | (1 << poll_type)) != value); do { value = atomic_read(&state->poll_services[ service->localport>>5]); } while (atomic_cmpxchg( &state->poll_services[service->localport>>5], value, value | (1 << (service->localport & 0x1f))) != value); } state->poll_needed = 1; wmb(); /* ... and ensure the slot handler runs. */ - remote_event_signal_local(&state->local->trigger); + remote_event_signal_local(state, &state->local->trigger); } /* Called from queue_message, by the slot handler and application threads, ** with slot_mutex held */ static VCHIQ_HEADER_T * reserve_space(VCHIQ_STATE_T *state, int space, int is_blocking) { VCHIQ_SHARED_STATE_T *local = state->local; int tx_pos = state->local_tx_pos; int slot_space = VCHIQ_SLOT_SIZE - (tx_pos & VCHIQ_SLOT_MASK); if (space > slot_space) { VCHIQ_HEADER_T *header; /* Fill the remaining space with padding */ WARN_ON(state->tx_data == NULL); header = (VCHIQ_HEADER_T *) (state->tx_data + (tx_pos & VCHIQ_SLOT_MASK)); header->msgid = VCHIQ_MSGID_PADDING; header->size = slot_space - sizeof(VCHIQ_HEADER_T); tx_pos += slot_space; } /* If necessary, get the next slot. */ if ((tx_pos & VCHIQ_SLOT_MASK) == 0) { int slot_index; /* If there is no free slot... */ if (down_trylock(&state->slot_available_event) != 0) { /* ...wait for one. */ VCHIQ_STATS_INC(state, slot_stalls); /* But first, flush through the last slot. */ state->local_tx_pos = tx_pos; local->tx_pos = tx_pos; remote_event_signal(&state->remote->trigger); if (!is_blocking || (down_interruptible( &state->slot_available_event) != 0)) return NULL; /* No space available */ } BUG_ON(tx_pos == (state->slot_queue_available * VCHIQ_SLOT_SIZE)); slot_index = local->slot_queue[ SLOT_QUEUE_INDEX_FROM_POS(tx_pos) & VCHIQ_SLOT_QUEUE_MASK]; state->tx_data = (char *)SLOT_DATA_FROM_INDEX(state, slot_index); } state->local_tx_pos = tx_pos + space; return (VCHIQ_HEADER_T *)(state->tx_data + (tx_pos & VCHIQ_SLOT_MASK)); } /* Called by the recycle thread. */ static void process_free_queue(VCHIQ_STATE_T *state) { VCHIQ_SHARED_STATE_T *local = state->local; VCHI_BITSET_T service_found[VCHI_BITSET_SIZE(VCHIQ_MAX_SERVICES)]; int slot_queue_available; /* Find slots which have been freed by the other side, and return them ** to the available queue. */ slot_queue_available = state->slot_queue_available; /* Use a memory barrier to ensure that any state that may have been ** modified by another thread is not masked by stale prefetched ** values. */ mb(); while (slot_queue_available != local->slot_queue_recycle) { unsigned int pos; int slot_index = local->slot_queue[slot_queue_available++ & VCHIQ_SLOT_QUEUE_MASK]; char *data = (char *)SLOT_DATA_FROM_INDEX(state, slot_index); int data_found = 0; rmb(); vchiq_log_trace(vchiq_core_log_level, "%d: pfq %d=%p %x %x", state->id, slot_index, data, local->slot_queue_recycle, slot_queue_available); /* Initialise the bitmask for services which have used this ** slot */ VCHI_BITSET_ZERO(service_found); pos = 0; while (pos < VCHIQ_SLOT_SIZE) { VCHIQ_HEADER_T *header = (VCHIQ_HEADER_T *)(data + pos); int msgid = header->msgid; if (VCHIQ_MSG_TYPE(msgid) == VCHIQ_MSG_DATA) { int port = VCHIQ_MSG_SRCPORT(msgid); VCHIQ_SERVICE_QUOTA_T *service_quota = &state->service_quotas[port]; int count; spin_lock("a_spinlock); count = service_quota->message_use_count; if (count > 0) service_quota->message_use_count = count - 1; spin_unlock("a_spinlock); if (count == service_quota->message_quota) /* Signal the service that it ** has dropped below its quota */ up(&service_quota->quota_event); else if (count == 0) { vchiq_log_error(vchiq_core_log_level, "service %d " "message_use_count=%d " "(header %p, msgid %x, " "header->msgid %x, " "header->size %x)", port, service_quota-> message_use_count, header, msgid, header->msgid, header->size); WARN(1, "invalid message use count\n"); } if (!VCHI_BITSET_IS_SET(service_found, port)) { /* Set the found bit for this service */ VCHI_BITSET_SET(service_found, port); spin_lock("a_spinlock); count = service_quota->slot_use_count; if (count > 0) service_quota->slot_use_count = count - 1; spin_unlock("a_spinlock); if (count > 0) { /* Signal the service in case ** it has dropped below its ** quota */ up(&service_quota->quota_event); vchiq_log_trace( vchiq_core_log_level, "%d: pfq:%d %x@%p - " "slot_use->%d", state->id, port, header->size, header, count - 1); } else { vchiq_log_error( vchiq_core_log_level, "service %d " "slot_use_count" "=%d (header %p" ", msgid %x, " "header->msgid" " %x, header->" "size %x)", port, count, header, msgid, header->msgid, header->size); WARN(1, "bad slot use count\n"); } } data_found = 1; } pos += calc_stride(header->size); if (pos > VCHIQ_SLOT_SIZE) { vchiq_log_error(vchiq_core_log_level, "pfq - pos %x: header %p, msgid %x, " "header->msgid %x, header->size %x", pos, header, msgid, header->msgid, header->size); WARN(1, "invalid slot position\n"); } } if (data_found) { int count; spin_lock("a_spinlock); count = state->data_use_count; if (count > 0) state->data_use_count = count - 1; spin_unlock("a_spinlock); if (count == state->data_quota) up(&state->data_quota_event); } mb(); state->slot_queue_available = slot_queue_available; up(&state->slot_available_event); } } /* Called by the slot handler and application threads */ static VCHIQ_STATUS_T queue_message(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service, int msgid, const VCHIQ_ELEMENT_T *elements, int count, int size, int flags) { VCHIQ_SHARED_STATE_T *local; VCHIQ_SERVICE_QUOTA_T *service_quota = NULL; VCHIQ_HEADER_T *header; int type = VCHIQ_MSG_TYPE(msgid); unsigned int stride; local = state->local; stride = calc_stride(size); WARN_ON(!(stride <= VCHIQ_SLOT_SIZE)); if (!(flags & QMFLAGS_NO_MUTEX_LOCK) && (lmutex_lock_interruptible(&state->slot_mutex) != 0)) return VCHIQ_RETRY; if (type == VCHIQ_MSG_DATA) { int tx_end_index; BUG_ON(!service); BUG_ON((flags & (QMFLAGS_NO_MUTEX_LOCK | QMFLAGS_NO_MUTEX_UNLOCK)) != 0); if (service->closing) { /* The service has been closed */ lmutex_unlock(&state->slot_mutex); return VCHIQ_ERROR; } service_quota = &state->service_quotas[service->localport]; spin_lock("a_spinlock); /* Ensure this service doesn't use more than its quota of ** messages or slots */ tx_end_index = SLOT_QUEUE_INDEX_FROM_POS( state->local_tx_pos + stride - 1); /* Ensure data messages don't use more than their quota of ** slots */ while ((tx_end_index != state->previous_data_index) && (state->data_use_count == state->data_quota)) { VCHIQ_STATS_INC(state, data_stalls); spin_unlock("a_spinlock); lmutex_unlock(&state->slot_mutex); if (down_interruptible(&state->data_quota_event) != 0) return VCHIQ_RETRY; lmutex_lock(&state->slot_mutex); spin_lock("a_spinlock); tx_end_index = SLOT_QUEUE_INDEX_FROM_POS( state->local_tx_pos + stride - 1); if ((tx_end_index == state->previous_data_index) || (state->data_use_count < state->data_quota)) { /* Pass the signal on to other waiters */ up(&state->data_quota_event); break; } } while ((service_quota->message_use_count == service_quota->message_quota) || ((tx_end_index != service_quota->previous_tx_index) && (service_quota->slot_use_count == service_quota->slot_quota))) { spin_unlock("a_spinlock); vchiq_log_trace(vchiq_core_log_level, "%d: qm:%d %s,%x - quota stall " "(msg %d, slot %d)", state->id, service->localport, msg_type_str(type), size, service_quota->message_use_count, service_quota->slot_use_count); VCHIQ_SERVICE_STATS_INC(service, quota_stalls); lmutex_unlock(&state->slot_mutex); if (down_interruptible(&service_quota->quota_event) != 0) return VCHIQ_RETRY; if (service->closing) return VCHIQ_ERROR; if (lmutex_lock_interruptible(&state->slot_mutex) != 0) return VCHIQ_RETRY; if (service->srvstate != VCHIQ_SRVSTATE_OPEN) { /* The service has been closed */ lmutex_unlock(&state->slot_mutex); return VCHIQ_ERROR; } spin_lock("a_spinlock); tx_end_index = SLOT_QUEUE_INDEX_FROM_POS( state->local_tx_pos + stride - 1); } spin_unlock("a_spinlock); } header = reserve_space(state, stride, flags & QMFLAGS_IS_BLOCKING); if (!header) { if (service) VCHIQ_SERVICE_STATS_INC(service, slot_stalls); /* In the event of a failure, return the mutex to the state it was in */ if (!(flags & QMFLAGS_NO_MUTEX_LOCK)) lmutex_unlock(&state->slot_mutex); return VCHIQ_RETRY; } if (type == VCHIQ_MSG_DATA) { int i, pos; int tx_end_index; int slot_use_count; vchiq_log_info(vchiq_core_log_level, "%d: qm %s@%p,%x (%d->%d)", state->id, msg_type_str(VCHIQ_MSG_TYPE(msgid)), header, size, VCHIQ_MSG_SRCPORT(msgid), VCHIQ_MSG_DSTPORT(msgid)); BUG_ON(!service); BUG_ON((flags & (QMFLAGS_NO_MUTEX_LOCK | QMFLAGS_NO_MUTEX_UNLOCK)) != 0); for (i = 0, pos = 0; i < (unsigned int)count; pos += elements[i++].size) if (elements[i].size) { if (vchiq_copy_from_user (header->data + pos, elements[i].data, (size_t) elements[i].size) != VCHIQ_SUCCESS) { lmutex_unlock(&state->slot_mutex); VCHIQ_SERVICE_STATS_INC(service, error_count); return VCHIQ_ERROR; } } if (SRVTRACE_ENABLED(service, VCHIQ_LOG_INFO)) vchiq_log_dump_mem("Sent", 0, header->data, min(16, pos)); spin_lock("a_spinlock); service_quota->message_use_count++; tx_end_index = SLOT_QUEUE_INDEX_FROM_POS(state->local_tx_pos - 1); /* If this transmission can't fit in the last slot used by any ** service, the data_use_count must be increased. */ if (tx_end_index != state->previous_data_index) { state->previous_data_index = tx_end_index; state->data_use_count++; } /* If this isn't the same slot last used by this service, ** the service's slot_use_count must be increased. */ if (tx_end_index != service_quota->previous_tx_index) { service_quota->previous_tx_index = tx_end_index; slot_use_count = ++service_quota->slot_use_count; } else { slot_use_count = 0; } spin_unlock("a_spinlock); if (slot_use_count) vchiq_log_trace(vchiq_core_log_level, "%d: qm:%d %s,%x - slot_use->%d (hdr %p)", state->id, service->localport, msg_type_str(VCHIQ_MSG_TYPE(msgid)), size, slot_use_count, header); VCHIQ_SERVICE_STATS_INC(service, ctrl_tx_count); VCHIQ_SERVICE_STATS_ADD(service, ctrl_tx_bytes, size); } else { vchiq_log_info(vchiq_core_log_level, "%d: qm %s@%p,%x (%d->%d)", state->id, msg_type_str(VCHIQ_MSG_TYPE(msgid)), header, size, VCHIQ_MSG_SRCPORT(msgid), VCHIQ_MSG_DSTPORT(msgid)); if (size != 0) { WARN_ON(!((count == 1) && (size == elements[0].size))); memcpy(header->data, elements[0].data, elements[0].size); } VCHIQ_STATS_INC(state, ctrl_tx_count); } header->msgid = msgid; header->size = size; { int svc_fourcc; svc_fourcc = service ? service->base.fourcc : VCHIQ_MAKE_FOURCC('?', '?', '?', '?'); vchiq_log_info(SRVTRACE_LEVEL(service), "Sent Msg %s(%u) to %c%c%c%c s:%u d:%d len:%d", msg_type_str(VCHIQ_MSG_TYPE(msgid)), VCHIQ_MSG_TYPE(msgid), VCHIQ_FOURCC_AS_4CHARS(svc_fourcc), VCHIQ_MSG_SRCPORT(msgid), VCHIQ_MSG_DSTPORT(msgid), size); } /* Make sure the new header is visible to the peer. */ wmb(); /* Make the new tx_pos visible to the peer. */ local->tx_pos = state->local_tx_pos; wmb(); if (service && (type == VCHIQ_MSG_CLOSE)) vchiq_set_service_state(service, VCHIQ_SRVSTATE_CLOSESENT); if (!(flags & QMFLAGS_NO_MUTEX_UNLOCK)) lmutex_unlock(&state->slot_mutex); remote_event_signal(&state->remote->trigger); return VCHIQ_SUCCESS; } /* Called by the slot handler and application threads */ static VCHIQ_STATUS_T queue_message_sync(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service, int msgid, const VCHIQ_ELEMENT_T *elements, int count, int size, int is_blocking) { VCHIQ_SHARED_STATE_T *local; VCHIQ_HEADER_T *header; local = state->local; if ((VCHIQ_MSG_TYPE(msgid) != VCHIQ_MSG_RESUME) && (lmutex_lock_interruptible(&state->sync_mutex) != 0)) return VCHIQ_RETRY; - remote_event_wait(&local->sync_release); + remote_event_wait(state, &local->sync_release); rmb(); header = (VCHIQ_HEADER_T *)SLOT_DATA_FROM_INDEX(state, local->slot_sync); { int oldmsgid = header->msgid; if (oldmsgid != VCHIQ_MSGID_PADDING) vchiq_log_error(vchiq_core_log_level, "%d: qms - msgid %x, not PADDING", state->id, oldmsgid); } if (service) { int i, pos; vchiq_log_info(vchiq_sync_log_level, "%d: qms %s@%p,%x (%d->%d)", state->id, msg_type_str(VCHIQ_MSG_TYPE(msgid)), header, size, VCHIQ_MSG_SRCPORT(msgid), VCHIQ_MSG_DSTPORT(msgid)); for (i = 0, pos = 0; i < (unsigned int)count; pos += elements[i++].size) if (elements[i].size) { if (vchiq_copy_from_user (header->data + pos, elements[i].data, (size_t) elements[i].size) != VCHIQ_SUCCESS) { lmutex_unlock(&state->sync_mutex); VCHIQ_SERVICE_STATS_INC(service, error_count); return VCHIQ_ERROR; } } if (vchiq_sync_log_level >= VCHIQ_LOG_TRACE) vchiq_log_dump_mem("Sent Sync", 0, header->data, min(16, pos)); VCHIQ_SERVICE_STATS_INC(service, ctrl_tx_count); VCHIQ_SERVICE_STATS_ADD(service, ctrl_tx_bytes, size); } else { vchiq_log_info(vchiq_sync_log_level, "%d: qms %s@%p,%x (%d->%d)", state->id, msg_type_str(VCHIQ_MSG_TYPE(msgid)), header, size, VCHIQ_MSG_SRCPORT(msgid), VCHIQ_MSG_DSTPORT(msgid)); if (size != 0) { WARN_ON(!((count == 1) && (size == elements[0].size))); memcpy(header->data, elements[0].data, elements[0].size); } VCHIQ_STATS_INC(state, ctrl_tx_count); } header->size = size; header->msgid = msgid; if (vchiq_sync_log_level >= VCHIQ_LOG_TRACE) { int svc_fourcc; svc_fourcc = service ? service->base.fourcc : VCHIQ_MAKE_FOURCC('?', '?', '?', '?'); vchiq_log_trace(vchiq_sync_log_level, "Sent Sync Msg %s(%u) to %c%c%c%c s:%u d:%d len:%d", msg_type_str(VCHIQ_MSG_TYPE(msgid)), VCHIQ_MSG_TYPE(msgid), VCHIQ_FOURCC_AS_4CHARS(svc_fourcc), VCHIQ_MSG_SRCPORT(msgid), VCHIQ_MSG_DSTPORT(msgid), size); } - /* Make sure the new header is visible to the peer. */ - wmb(); - remote_event_signal(&state->remote->sync_trigger); if (VCHIQ_MSG_TYPE(msgid) != VCHIQ_MSG_PAUSE) lmutex_unlock(&state->sync_mutex); return VCHIQ_SUCCESS; } static inline void claim_slot(VCHIQ_SLOT_INFO_T *slot) { slot->use_count++; } static void release_slot(VCHIQ_STATE_T *state, VCHIQ_SLOT_INFO_T *slot_info, VCHIQ_HEADER_T *header, VCHIQ_SERVICE_T *service) { int release_count; lmutex_lock(&state->recycle_mutex); if (header) { int msgid = header->msgid; if (((msgid & VCHIQ_MSGID_CLAIMED) == 0) || (service && service->closing)) { lmutex_unlock(&state->recycle_mutex); return; } /* Rewrite the message header to prevent a double ** release */ header->msgid = msgid & ~VCHIQ_MSGID_CLAIMED; } release_count = slot_info->release_count; slot_info->release_count = ++release_count; if (release_count == slot_info->use_count) { int slot_queue_recycle; /* Add to the freed queue */ /* A read barrier is necessary here to prevent speculative ** fetches of remote->slot_queue_recycle from overtaking the ** mutex. */ rmb(); slot_queue_recycle = state->remote->slot_queue_recycle; state->remote->slot_queue[slot_queue_recycle & VCHIQ_SLOT_QUEUE_MASK] = SLOT_INDEX_FROM_INFO(state, slot_info); state->remote->slot_queue_recycle = slot_queue_recycle + 1; vchiq_log_info(vchiq_core_log_level, "%d: release_slot %d - recycle->%x", state->id, SLOT_INDEX_FROM_INFO(state, slot_info), state->remote->slot_queue_recycle); /* A write barrier is necessary, but remote_event_signal ** contains one. */ remote_event_signal(&state->remote->recycle); } lmutex_unlock(&state->recycle_mutex); } /* Called by the slot handler - don't hold the bulk mutex */ static VCHIQ_STATUS_T notify_bulks(VCHIQ_SERVICE_T *service, VCHIQ_BULK_QUEUE_T *queue, int retry_poll) { VCHIQ_STATUS_T status = VCHIQ_SUCCESS; vchiq_log_trace(vchiq_core_log_level, "%d: nb:%d %cx - p=%x rn=%x r=%x", service->state->id, service->localport, (queue == &service->bulk_tx) ? 't' : 'r', queue->process, queue->remote_notify, queue->remove); if (service->state->is_master) { while (queue->remote_notify != queue->process) { VCHIQ_BULK_T *bulk = &queue->bulks[BULK_INDEX(queue->remote_notify)]; int msgtype = (bulk->dir == VCHIQ_BULK_TRANSMIT) ? VCHIQ_MSG_BULK_RX_DONE : VCHIQ_MSG_BULK_TX_DONE; int msgid = VCHIQ_MAKE_MSG(msgtype, service->localport, service->remoteport); VCHIQ_ELEMENT_T element = { &bulk->actual, 4 }; /* Only reply to non-dummy bulk requests */ if (bulk->remote_data) { status = queue_message(service->state, NULL, msgid, &element, 1, 4, 0); if (status != VCHIQ_SUCCESS) break; } queue->remote_notify++; } } else { queue->remote_notify = queue->process; } if (status == VCHIQ_SUCCESS) { while (queue->remove != queue->remote_notify) { VCHIQ_BULK_T *bulk = &queue->bulks[BULK_INDEX(queue->remove)]; /* Only generate callbacks for non-dummy bulk ** requests, and non-terminated services */ if (bulk->data && service->instance) { if (bulk->actual != VCHIQ_BULK_ACTUAL_ABORTED) { if (bulk->dir == VCHIQ_BULK_TRANSMIT) { VCHIQ_SERVICE_STATS_INC(service, bulk_tx_count); VCHIQ_SERVICE_STATS_ADD(service, bulk_tx_bytes, bulk->actual); } else { VCHIQ_SERVICE_STATS_INC(service, bulk_rx_count); VCHIQ_SERVICE_STATS_ADD(service, bulk_rx_bytes, bulk->actual); } } else { VCHIQ_SERVICE_STATS_INC(service, bulk_aborted_count); } if (bulk->mode == VCHIQ_BULK_MODE_BLOCKING) { struct bulk_waiter *waiter; spin_lock(&bulk_waiter_spinlock); waiter = bulk->userdata; if (waiter) { waiter->actual = bulk->actual; up(&waiter->event); } spin_unlock(&bulk_waiter_spinlock); } else if (bulk->mode == VCHIQ_BULK_MODE_CALLBACK) { VCHIQ_REASON_T reason = (bulk->dir == VCHIQ_BULK_TRANSMIT) ? ((bulk->actual == VCHIQ_BULK_ACTUAL_ABORTED) ? VCHIQ_BULK_TRANSMIT_ABORTED : VCHIQ_BULK_TRANSMIT_DONE) : ((bulk->actual == VCHIQ_BULK_ACTUAL_ABORTED) ? VCHIQ_BULK_RECEIVE_ABORTED : VCHIQ_BULK_RECEIVE_DONE); status = make_service_callback(service, reason, NULL, bulk->userdata); if (status == VCHIQ_RETRY) break; } } queue->remove++; up(&service->bulk_remove_event); } if (!retry_poll) status = VCHIQ_SUCCESS; } if (status == VCHIQ_RETRY) request_poll(service->state, service, (queue == &service->bulk_tx) ? VCHIQ_POLL_TXNOTIFY : VCHIQ_POLL_RXNOTIFY); return status; } /* Called by the slot handler thread */ static void poll_services(VCHIQ_STATE_T *state) { int group, i; for (group = 0; group < VCHI_BITSET_SIZE(state->unused_service); group++) { uint32_t flags; flags = atomic_xchg(&state->poll_services[group], 0); for (i = 0; flags; i++) { if (flags & (1 << i)) { VCHIQ_SERVICE_T *service = find_service_by_port(state, (group<<5) + i); uint32_t service_flags; flags &= ~(1 << i); if (!service) continue; service_flags = atomic_xchg(&service->poll_flags, 0); if (service_flags & (1 << VCHIQ_POLL_REMOVE)) { vchiq_log_info(vchiq_core_log_level, "%d: ps - remove %d<->%d", state->id, service->localport, service->remoteport); /* Make it look like a client, because it must be removed and not left in the LISTENING state. */ service->public_fourcc = VCHIQ_FOURCC_INVALID; if (vchiq_close_service_internal( service, 0/*!close_recvd*/) != VCHIQ_SUCCESS) request_poll(state, service, VCHIQ_POLL_REMOVE); } else if (service_flags & (1 << VCHIQ_POLL_TERMINATE)) { vchiq_log_info(vchiq_core_log_level, "%d: ps - terminate %d<->%d", state->id, service->localport, service->remoteport); if (vchiq_close_service_internal( service, 0/*!close_recvd*/) != VCHIQ_SUCCESS) request_poll(state, service, VCHIQ_POLL_TERMINATE); } if (service_flags & (1 << VCHIQ_POLL_TXNOTIFY)) notify_bulks(service, &service->bulk_tx, 1/*retry_poll*/); if (service_flags & (1 << VCHIQ_POLL_RXNOTIFY)) notify_bulks(service, &service->bulk_rx, 1/*retry_poll*/); unlock_service(service); } } } } /* Called by the slot handler or application threads, holding the bulk mutex. */ static int resolve_bulks(VCHIQ_SERVICE_T *service, VCHIQ_BULK_QUEUE_T *queue) { VCHIQ_STATE_T *state = service->state; int resolved = 0; int rc; while ((queue->process != queue->local_insert) && (queue->process != queue->remote_insert)) { VCHIQ_BULK_T *bulk = &queue->bulks[BULK_INDEX(queue->process)]; vchiq_log_trace(vchiq_core_log_level, "%d: rb:%d %cx - li=%x ri=%x p=%x", state->id, service->localport, (queue == &service->bulk_tx) ? 't' : 'r', queue->local_insert, queue->remote_insert, queue->process); WARN_ON(!((int)(queue->local_insert - queue->process) > 0)); WARN_ON(!((int)(queue->remote_insert - queue->process) > 0)); rc = lmutex_lock_interruptible(&state->bulk_transfer_mutex); if (rc != 0) break; vchiq_transfer_bulk(bulk); lmutex_unlock(&state->bulk_transfer_mutex); if (SRVTRACE_ENABLED(service, VCHIQ_LOG_INFO)) { const char *header = (queue == &service->bulk_tx) ? "Send Bulk to" : "Recv Bulk from"; if (bulk->actual != VCHIQ_BULK_ACTUAL_ABORTED) vchiq_log_info(SRVTRACE_LEVEL(service), "%s %c%c%c%c d:%d len:%d %p<->%p", header, VCHIQ_FOURCC_AS_4CHARS( service->base.fourcc), service->remoteport, bulk->size, bulk->data, bulk->remote_data); else vchiq_log_info(SRVTRACE_LEVEL(service), "%s %c%c%c%c d:%d ABORTED - tx len:%d," " rx len:%d %p<->%p", header, VCHIQ_FOURCC_AS_4CHARS( service->base.fourcc), service->remoteport, bulk->size, bulk->remote_size, bulk->data, bulk->remote_data); } vchiq_complete_bulk(bulk); queue->process++; resolved++; } return resolved; } /* Called with the bulk_mutex held */ static void abort_outstanding_bulks(VCHIQ_SERVICE_T *service, VCHIQ_BULK_QUEUE_T *queue) { int is_tx = (queue == &service->bulk_tx); vchiq_log_trace(vchiq_core_log_level, "%d: aob:%d %cx - li=%x ri=%x p=%x", service->state->id, service->localport, is_tx ? 't' : 'r', queue->local_insert, queue->remote_insert, queue->process); WARN_ON(!((int)(queue->local_insert - queue->process) >= 0)); WARN_ON(!((int)(queue->remote_insert - queue->process) >= 0)); while ((queue->process != queue->local_insert) || (queue->process != queue->remote_insert)) { VCHIQ_BULK_T *bulk = &queue->bulks[BULK_INDEX(queue->process)]; if (queue->process == queue->remote_insert) { /* fabricate a matching dummy bulk */ bulk->remote_data = NULL; bulk->remote_size = 0; queue->remote_insert++; } if (queue->process != queue->local_insert) { vchiq_complete_bulk(bulk); vchiq_log_info(SRVTRACE_LEVEL(service), "%s %c%c%c%c d:%d ABORTED - tx len:%d, " "rx len:%d", is_tx ? "Send Bulk to" : "Recv Bulk from", VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc), service->remoteport, bulk->size, bulk->remote_size); } else { /* fabricate a matching dummy bulk */ bulk->data = NULL; bulk->size = 0; bulk->actual = VCHIQ_BULK_ACTUAL_ABORTED; bulk->dir = is_tx ? VCHIQ_BULK_TRANSMIT : VCHIQ_BULK_RECEIVE; queue->local_insert++; } queue->process++; } } /* Called from the slot handler thread */ static void pause_bulks(VCHIQ_STATE_T *state) { if (unlikely(atomic_inc_return(&pause_bulks_count) != 1)) { WARN_ON_ONCE(1); atomic_set(&pause_bulks_count, 1); return; } /* Block bulk transfers from all services */ lmutex_lock(&state->bulk_transfer_mutex); } /* Called from the slot handler thread */ static void resume_bulks(VCHIQ_STATE_T *state) { int i; if (unlikely(atomic_dec_return(&pause_bulks_count) != 0)) { WARN_ON_ONCE(1); atomic_set(&pause_bulks_count, 0); return; } /* Allow bulk transfers from all services */ lmutex_unlock(&state->bulk_transfer_mutex); if (state->deferred_bulks == 0) return; /* Deal with any bulks which had to be deferred due to being in * paused state. Don't try to match up to number of deferred bulks * in case we've had something come and close the service in the * interim - just process all bulk queues for all services */ vchiq_log_info(vchiq_core_log_level, "%s: processing %d deferred bulks", __func__, state->deferred_bulks); for (i = 0; i < state->unused_service; i++) { VCHIQ_SERVICE_T *service = state->services[i]; int resolved_rx = 0; int resolved_tx = 0; if (!service || (service->srvstate != VCHIQ_SRVSTATE_OPEN)) continue; lmutex_lock(&service->bulk_mutex); resolved_rx = resolve_bulks(service, &service->bulk_rx); resolved_tx = resolve_bulks(service, &service->bulk_tx); lmutex_unlock(&service->bulk_mutex); if (resolved_rx) notify_bulks(service, &service->bulk_rx, 1); if (resolved_tx) notify_bulks(service, &service->bulk_tx, 1); } state->deferred_bulks = 0; } static int parse_open(VCHIQ_STATE_T *state, VCHIQ_HEADER_T *header) { VCHIQ_SERVICE_T *service = NULL; int msgid, size; unsigned int localport, remoteport; msgid = header->msgid; size = header->size; //int type = VCHIQ_MSG_TYPE(msgid); localport = VCHIQ_MSG_DSTPORT(msgid); remoteport = VCHIQ_MSG_SRCPORT(msgid); if (size >= sizeof(struct vchiq_open_payload)) { const struct vchiq_open_payload *payload = (struct vchiq_open_payload *)header->data; unsigned int fourcc; fourcc = payload->fourcc; vchiq_log_info(vchiq_core_log_level, "%d: prs OPEN@%p (%d->'%c%c%c%c')", state->id, header, localport, VCHIQ_FOURCC_AS_4CHARS(fourcc)); service = get_listening_service(state, fourcc); if (service) { /* A matching service exists */ short version = payload->version; short version_min = payload->version_min; if ((service->version < version_min) || (version < service->version_min)) { /* Version mismatch */ vchiq_loud_error_header(); vchiq_loud_error("%d: service %d (%c%c%c%c) " "version mismatch - local (%d, min %d)" " vs. remote (%d, min %d)", state->id, service->localport, VCHIQ_FOURCC_AS_4CHARS(fourcc), service->version, service->version_min, version, version_min); vchiq_loud_error_footer(); unlock_service(service); service = NULL; goto fail_open; } service->peer_version = version; if (service->srvstate == VCHIQ_SRVSTATE_LISTENING) { struct vchiq_openack_payload ack_payload = { service->version }; VCHIQ_ELEMENT_T body = { &ack_payload, sizeof(ack_payload) }; if (state->version_common < VCHIQ_VERSION_SYNCHRONOUS_MODE) service->sync = 0; /* Acknowledge the OPEN */ if (service->sync && (state->version_common >= VCHIQ_VERSION_SYNCHRONOUS_MODE)) { if (queue_message_sync(state, NULL, VCHIQ_MAKE_MSG( VCHIQ_MSG_OPENACK, service->localport, remoteport), &body, 1, sizeof(ack_payload), 0) == VCHIQ_RETRY) goto bail_not_ready; } else { if (queue_message(state, NULL, VCHIQ_MAKE_MSG( VCHIQ_MSG_OPENACK, service->localport, remoteport), &body, 1, sizeof(ack_payload), 0) == VCHIQ_RETRY) goto bail_not_ready; } /* The service is now open */ vchiq_set_service_state(service, service->sync ? VCHIQ_SRVSTATE_OPENSYNC : VCHIQ_SRVSTATE_OPEN); } service->remoteport = remoteport; service->client_id = ((int *)header->data)[1]; if (make_service_callback(service, VCHIQ_SERVICE_OPENED, NULL, NULL) == VCHIQ_RETRY) { /* Bail out if not ready */ service->remoteport = VCHIQ_PORT_FREE; goto bail_not_ready; } /* Success - the message has been dealt with */ unlock_service(service); return 1; } } fail_open: /* No available service, or an invalid request - send a CLOSE */ if (queue_message(state, NULL, VCHIQ_MAKE_MSG(VCHIQ_MSG_CLOSE, 0, VCHIQ_MSG_SRCPORT(msgid)), NULL, 0, 0, 0) == VCHIQ_RETRY) goto bail_not_ready; return 1; bail_not_ready: if (service) unlock_service(service); return 0; } /* Called by the slot handler thread */ static void parse_rx_slots(VCHIQ_STATE_T *state) { VCHIQ_SHARED_STATE_T *remote = state->remote; VCHIQ_SERVICE_T *service = NULL; int tx_pos; DEBUG_INITIALISE(state->local) tx_pos = remote->tx_pos; while (state->rx_pos != tx_pos) { VCHIQ_HEADER_T *header; int msgid, size; int type; unsigned int localport, remoteport; DEBUG_TRACE(PARSE_LINE); if (!state->rx_data) { int rx_index; WARN_ON(!((state->rx_pos & VCHIQ_SLOT_MASK) == 0)); rx_index = remote->slot_queue[ SLOT_QUEUE_INDEX_FROM_POS(state->rx_pos) & VCHIQ_SLOT_QUEUE_MASK]; state->rx_data = (char *)SLOT_DATA_FROM_INDEX(state, rx_index); state->rx_info = SLOT_INFO_FROM_INDEX(state, rx_index); /* Initialise use_count to one, and increment ** release_count at the end of the slot to avoid ** releasing the slot prematurely. */ state->rx_info->use_count = 1; state->rx_info->release_count = 0; } header = (VCHIQ_HEADER_T *)(state->rx_data + (state->rx_pos & VCHIQ_SLOT_MASK)); DEBUG_VALUE(PARSE_HEADER, (size_t)header); msgid = header->msgid; DEBUG_VALUE(PARSE_MSGID, msgid); size = header->size; type = VCHIQ_MSG_TYPE(msgid); localport = VCHIQ_MSG_DSTPORT(msgid); remoteport = VCHIQ_MSG_SRCPORT(msgid); if (type != VCHIQ_MSG_DATA) VCHIQ_STATS_INC(state, ctrl_rx_count); switch (type) { case VCHIQ_MSG_OPENACK: case VCHIQ_MSG_CLOSE: case VCHIQ_MSG_DATA: case VCHIQ_MSG_BULK_RX: case VCHIQ_MSG_BULK_TX: case VCHIQ_MSG_BULK_RX_DONE: case VCHIQ_MSG_BULK_TX_DONE: service = find_service_by_port(state, localport); if ((!service || ((service->remoteport != remoteport) && (service->remoteport != VCHIQ_PORT_FREE))) && (localport == 0) && (type == VCHIQ_MSG_CLOSE)) { /* This could be a CLOSE from a client which hadn't yet received the OPENACK - look for the connected service */ if (service) unlock_service(service); service = get_connected_service(state, remoteport); if (service) vchiq_log_warning(vchiq_core_log_level, "%d: prs %s@%p (%d->%d) - " "found connected service %d", state->id, msg_type_str(type), header, remoteport, localport, service->localport); } if (!service) { vchiq_log_error(vchiq_core_log_level, "%d: prs %s@%p (%d->%d) - " /* XXX */ "invalid/closed service %d", state->id, msg_type_str(type), header, remoteport, localport, localport); goto skip_message; } break; default: break; } if (SRVTRACE_ENABLED(service, VCHIQ_LOG_INFO)) { int svc_fourcc; svc_fourcc = service ? service->base.fourcc : VCHIQ_MAKE_FOURCC('?', '?', '?', '?'); vchiq_log_info(SRVTRACE_LEVEL(service), "Rcvd Msg %s(%u) from %c%c%c%c s:%d d:%d " "len:%d", msg_type_str(type), type, VCHIQ_FOURCC_AS_4CHARS(svc_fourcc), remoteport, localport, size); if (size > 0) vchiq_log_dump_mem("Rcvd", 0, header->data, min(16, size)); } if (((size_t)header & VCHIQ_SLOT_MASK) + calc_stride(size) > VCHIQ_SLOT_SIZE) { vchiq_log_error(vchiq_core_log_level, "header %p (msgid %x) - size %x too big for " "slot", header, (unsigned int)msgid, (unsigned int)size); WARN(1, "oversized for slot\n"); } switch (type) { case VCHIQ_MSG_OPEN: WARN_ON(!(VCHIQ_MSG_DSTPORT(msgid) == 0)); if (!parse_open(state, header)) goto bail_not_ready; break; case VCHIQ_MSG_OPENACK: if (size >= sizeof(struct vchiq_openack_payload)) { const struct vchiq_openack_payload *payload = (struct vchiq_openack_payload *) header->data; service->peer_version = payload->version; } vchiq_log_info(vchiq_core_log_level, "%d: prs OPENACK@%p,%x (%d->%d) v:%d", state->id, header, size, remoteport, localport, service->peer_version); if (service->srvstate == VCHIQ_SRVSTATE_OPENING) { service->remoteport = remoteport; vchiq_set_service_state(service, VCHIQ_SRVSTATE_OPEN); up(&service->remove_event); } else vchiq_log_error(vchiq_core_log_level, "OPENACK received in state %s", srvstate_names[service->srvstate]); break; case VCHIQ_MSG_CLOSE: WARN_ON(size != 0); /* There should be no data */ vchiq_log_info(vchiq_core_log_level, "%d: prs CLOSE@%p (%d->%d)", state->id, header, remoteport, localport); mark_service_closing_internal(service, 1); if (vchiq_close_service_internal(service, 1/*close_recvd*/) == VCHIQ_RETRY) goto bail_not_ready; vchiq_log_info(vchiq_core_log_level, "Close Service %c%c%c%c s:%u d:%d", VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc), service->localport, service->remoteport); break; case VCHIQ_MSG_DATA: vchiq_log_info(vchiq_core_log_level, "%d: prs DATA@%p,%x (%d->%d)", state->id, header, size, remoteport, localport); if ((service->remoteport == remoteport) && (service->srvstate == VCHIQ_SRVSTATE_OPEN)) { header->msgid = msgid | VCHIQ_MSGID_CLAIMED; claim_slot(state->rx_info); DEBUG_TRACE(PARSE_LINE); if (make_service_callback(service, VCHIQ_MESSAGE_AVAILABLE, header, NULL) == VCHIQ_RETRY) { DEBUG_TRACE(PARSE_LINE); goto bail_not_ready; } VCHIQ_SERVICE_STATS_INC(service, ctrl_rx_count); VCHIQ_SERVICE_STATS_ADD(service, ctrl_rx_bytes, size); } else { VCHIQ_STATS_INC(state, error_count); } break; case VCHIQ_MSG_CONNECT: vchiq_log_info(vchiq_core_log_level, "%d: prs CONNECT@%p", state->id, header); state->version_common = ((VCHIQ_SLOT_ZERO_T *) state->slot_data)->version; up(&state->connect); break; +/* + * XXXMDC Apparently nothing uses this + * https://github.com/raspberrypi/linux/commit/14f4d72fb799a9b3170a45ab80d4a3ddad541960 + * but taking out the master bits is a whole new job + */ case VCHIQ_MSG_BULK_RX: - case VCHIQ_MSG_BULK_TX: { + case VCHIQ_MSG_BULK_TX: + WARN_ON(1); + break; +#if 0 + { VCHIQ_BULK_QUEUE_T *queue; WARN_ON(!state->is_master); queue = (type == VCHIQ_MSG_BULK_RX) ? &service->bulk_tx : &service->bulk_rx; if ((service->remoteport == remoteport) && (service->srvstate == VCHIQ_SRVSTATE_OPEN)) { VCHIQ_BULK_T *bulk; int resolved = 0; DEBUG_TRACE(PARSE_LINE); if (lmutex_lock_interruptible( &service->bulk_mutex) != 0) { DEBUG_TRACE(PARSE_LINE); goto bail_not_ready; } WARN_ON(!(queue->remote_insert < queue->remove + VCHIQ_NUM_SERVICE_BULKS)); bulk = &queue->bulks[ BULK_INDEX(queue->remote_insert)]; bulk->remote_data = (void *)((int *)header->data)[0]; bulk->remote_size = ((int *)header->data)[1]; wmb(); vchiq_log_info(vchiq_core_log_level, "%d: prs %s@%p (%d->%d) %x@%p", state->id, msg_type_str(type), header, remoteport, localport, bulk->remote_size, bulk->remote_data); queue->remote_insert++; if (atomic_read(&pause_bulks_count)) { state->deferred_bulks++; vchiq_log_info(vchiq_core_log_level, "%s: deferring bulk (%d)", __func__, state->deferred_bulks); if (state->conn_state != VCHIQ_CONNSTATE_PAUSE_SENT) vchiq_log_error( vchiq_core_log_level, "%s: bulks paused in " "unexpected state %s", __func__, conn_state_names[ state->conn_state]); } else if (state->conn_state == VCHIQ_CONNSTATE_CONNECTED) { DEBUG_TRACE(PARSE_LINE); resolved = resolve_bulks(service, queue); } lmutex_unlock(&service->bulk_mutex); if (resolved) notify_bulks(service, queue, - 1/*retry_poll*/); + 1//retry_poll + ); } - } break; + } +#endif case VCHIQ_MSG_BULK_RX_DONE: case VCHIQ_MSG_BULK_TX_DONE: WARN_ON(state->is_master); if ((service->remoteport == remoteport) && (service->srvstate != VCHIQ_SRVSTATE_FREE)) { VCHIQ_BULK_QUEUE_T *queue; VCHIQ_BULK_T *bulk; queue = (type == VCHIQ_MSG_BULK_RX_DONE) ? &service->bulk_rx : &service->bulk_tx; DEBUG_TRACE(PARSE_LINE); if (lmutex_lock_interruptible( &service->bulk_mutex) != 0) { DEBUG_TRACE(PARSE_LINE); goto bail_not_ready; } if ((int)(queue->remote_insert - queue->local_insert) >= 0) { vchiq_log_error(vchiq_core_log_level, "%d: prs %s@%p (%d->%d) " "unexpected (ri=%d,li=%d)", state->id, msg_type_str(type), header, remoteport, localport, queue->remote_insert, queue->local_insert); lmutex_unlock(&service->bulk_mutex); break; } BUG_ON(queue->process == queue->local_insert); BUG_ON(queue->process != queue->remote_insert); bulk = &queue->bulks[ BULK_INDEX(queue->remote_insert)]; bulk->actual = *(int *)header->data; queue->remote_insert++; vchiq_log_info(vchiq_core_log_level, "%d: prs %s@%p (%d->%d) %x@%p", state->id, msg_type_str(type), header, remoteport, localport, bulk->actual, bulk->data); vchiq_log_trace(vchiq_core_log_level, "%d: prs:%d %cx li=%x ri=%x p=%x", state->id, localport, (type == VCHIQ_MSG_BULK_RX_DONE) ? 'r' : 't', queue->local_insert, queue->remote_insert, queue->process); DEBUG_TRACE(PARSE_LINE); WARN_ON(queue->process == queue->local_insert); vchiq_complete_bulk(bulk); queue->process++; lmutex_unlock(&service->bulk_mutex); DEBUG_TRACE(PARSE_LINE); notify_bulks(service, queue, 1/*retry_poll*/); DEBUG_TRACE(PARSE_LINE); } break; case VCHIQ_MSG_PADDING: vchiq_log_trace(vchiq_core_log_level, "%d: prs PADDING@%p,%x", state->id, header, size); break; case VCHIQ_MSG_PAUSE: /* If initiated, signal the application thread */ vchiq_log_trace(vchiq_core_log_level, "%d: prs PAUSE@%p,%x", state->id, header, size); if (state->conn_state == VCHIQ_CONNSTATE_PAUSED) { vchiq_log_error(vchiq_core_log_level, "%d: PAUSE received in state PAUSED", state->id); break; } if (state->conn_state != VCHIQ_CONNSTATE_PAUSE_SENT) { /* Send a PAUSE in response */ if (queue_message(state, NULL, VCHIQ_MAKE_MSG(VCHIQ_MSG_PAUSE, 0, 0), NULL, 0, 0, QMFLAGS_NO_MUTEX_UNLOCK) == VCHIQ_RETRY) goto bail_not_ready; if (state->is_master) pause_bulks(state); } /* At this point slot_mutex is held */ vchiq_set_conn_state(state, VCHIQ_CONNSTATE_PAUSED); vchiq_platform_paused(state); break; case VCHIQ_MSG_RESUME: vchiq_log_trace(vchiq_core_log_level, "%d: prs RESUME@%p,%x", state->id, header, size); /* Release the slot mutex */ lmutex_unlock(&state->slot_mutex); if (state->is_master) resume_bulks(state); vchiq_set_conn_state(state, VCHIQ_CONNSTATE_CONNECTED); vchiq_platform_resumed(state); break; case VCHIQ_MSG_REMOTE_USE: vchiq_on_remote_use(state); break; case VCHIQ_MSG_REMOTE_RELEASE: vchiq_on_remote_release(state); break; case VCHIQ_MSG_REMOTE_USE_ACTIVE: vchiq_on_remote_use_active(state); break; default: vchiq_log_error(vchiq_core_log_level, "%d: prs invalid msgid %x@%p,%x", state->id, msgid, header, size); WARN(1, "invalid message\n"); break; } skip_message: if (service) { unlock_service(service); service = NULL; } state->rx_pos += calc_stride(size); DEBUG_TRACE(PARSE_LINE); /* Perform some housekeeping when the end of the slot is ** reached. */ if ((state->rx_pos & VCHIQ_SLOT_MASK) == 0) { /* Remove the extra reference count. */ release_slot(state, state->rx_info, NULL, NULL); state->rx_data = NULL; } } bail_not_ready: if (service) unlock_service(service); } /* Called by the slot handler thread */ int slot_handler_func(void *v); int slot_handler_func(void *v) { VCHIQ_STATE_T *state = (VCHIQ_STATE_T *) v; VCHIQ_SHARED_STATE_T *local = state->local; DEBUG_INITIALISE(local) while (1) { DEBUG_COUNT(SLOT_HANDLER_COUNT); DEBUG_TRACE(SLOT_HANDLER_LINE); - remote_event_wait(&local->trigger); + remote_event_wait(state, &local->trigger); rmb(); DEBUG_TRACE(SLOT_HANDLER_LINE); if (state->poll_needed) { /* Check if we need to suspend - may change our * conn_state */ vchiq_platform_check_suspend(state); state->poll_needed = 0; /* Handle service polling and other rare conditions here ** out of the mainline code */ switch (state->conn_state) { case VCHIQ_CONNSTATE_CONNECTED: /* Poll the services as requested */ poll_services(state); break; case VCHIQ_CONNSTATE_PAUSING: if (state->is_master) pause_bulks(state); if (queue_message(state, NULL, VCHIQ_MAKE_MSG(VCHIQ_MSG_PAUSE, 0, 0), NULL, 0, 0, QMFLAGS_NO_MUTEX_UNLOCK) != VCHIQ_RETRY) { vchiq_set_conn_state(state, VCHIQ_CONNSTATE_PAUSE_SENT); } else { if (state->is_master) resume_bulks(state); /* Retry later */ state->poll_needed = 1; } break; case VCHIQ_CONNSTATE_PAUSED: vchiq_platform_resume(state); break; case VCHIQ_CONNSTATE_RESUMING: if (queue_message(state, NULL, VCHIQ_MAKE_MSG(VCHIQ_MSG_RESUME, 0, 0), NULL, 0, 0, QMFLAGS_NO_MUTEX_LOCK) != VCHIQ_RETRY) { if (state->is_master) resume_bulks(state); vchiq_set_conn_state(state, VCHIQ_CONNSTATE_CONNECTED); vchiq_platform_resumed(state); } else { /* This should really be impossible, ** since the PAUSE should have flushed ** through outstanding messages. */ vchiq_log_error(vchiq_core_log_level, "Failed to send RESUME " "message"); BUG(); } break; case VCHIQ_CONNSTATE_PAUSE_TIMEOUT: case VCHIQ_CONNSTATE_RESUME_TIMEOUT: vchiq_platform_handle_timeout(state); break; default: break; } } DEBUG_TRACE(SLOT_HANDLER_LINE); parse_rx_slots(state); } return 0; } /* Called by the recycle thread */ int recycle_func(void *v); int recycle_func(void *v) { VCHIQ_STATE_T *state = (VCHIQ_STATE_T *) v; VCHIQ_SHARED_STATE_T *local = state->local; while (1) { - remote_event_wait(&local->recycle); - + remote_event_wait(state, &local->recycle); process_free_queue(state); } return 0; } /* Called by the sync thread */ int sync_func(void *v); int sync_func(void *v) { VCHIQ_STATE_T *state = (VCHIQ_STATE_T *) v; VCHIQ_SHARED_STATE_T *local = state->local; VCHIQ_HEADER_T *header = (VCHIQ_HEADER_T *)SLOT_DATA_FROM_INDEX(state, state->remote->slot_sync); while (1) { VCHIQ_SERVICE_T *service; int msgid, size; int type; unsigned int localport, remoteport; - remote_event_wait(&local->sync_trigger); + remote_event_wait(state, &local->sync_trigger); rmb(); msgid = header->msgid; size = header->size; type = VCHIQ_MSG_TYPE(msgid); localport = VCHIQ_MSG_DSTPORT(msgid); remoteport = VCHIQ_MSG_SRCPORT(msgid); service = find_service_by_port(state, localport); if (!service) { vchiq_log_error(vchiq_sync_log_level, "%d: sf %s@%p (%d->%d) - " "invalid/closed service %d", state->id, msg_type_str(type), header, remoteport, localport, localport); release_message_sync(state, header); continue; } if (vchiq_sync_log_level >= VCHIQ_LOG_TRACE) { int svc_fourcc; svc_fourcc = service ? service->base.fourcc : VCHIQ_MAKE_FOURCC('?', '?', '?', '?'); vchiq_log_trace(vchiq_sync_log_level, "Rcvd Msg %s from %c%c%c%c s:%d d:%d len:%d", msg_type_str(type), VCHIQ_FOURCC_AS_4CHARS(svc_fourcc), remoteport, localport, size); if (size > 0) vchiq_log_dump_mem("Rcvd", 0, header->data, min(16, size)); } switch (type) { case VCHIQ_MSG_OPENACK: if (size >= sizeof(struct vchiq_openack_payload)) { const struct vchiq_openack_payload *payload = (struct vchiq_openack_payload *) header->data; service->peer_version = payload->version; } vchiq_log_info(vchiq_sync_log_level, "%d: sf OPENACK@%p,%x (%d->%d) v:%d", state->id, header, size, remoteport, localport, service->peer_version); if (service->srvstate == VCHIQ_SRVSTATE_OPENING) { service->remoteport = remoteport; vchiq_set_service_state(service, VCHIQ_SRVSTATE_OPENSYNC); service->sync = 1; up(&service->remove_event); } release_message_sync(state, header); break; case VCHIQ_MSG_DATA: vchiq_log_trace(vchiq_sync_log_level, "%d: sf DATA@%p,%x (%d->%d)", state->id, header, size, remoteport, localport); if ((service->remoteport == remoteport) && (service->srvstate == VCHIQ_SRVSTATE_OPENSYNC)) { if (make_service_callback(service, VCHIQ_MESSAGE_AVAILABLE, header, NULL) == VCHIQ_RETRY) vchiq_log_error(vchiq_sync_log_level, "synchronous callback to " "service %d returns " "VCHIQ_RETRY", localport); } break; default: vchiq_log_error(vchiq_sync_log_level, "%d: sf unexpected msgid %x@%p,%x", state->id, msgid, header, size); release_message_sync(state, header); break; } unlock_service(service); } return 0; } static void init_bulk_queue(VCHIQ_BULK_QUEUE_T *queue) { queue->local_insert = 0; queue->remote_insert = 0; queue->process = 0; queue->remote_notify = 0; queue->remove = 0; } inline const char * get_conn_state_name(VCHIQ_CONNSTATE_T conn_state) { return conn_state_names[conn_state]; } VCHIQ_SLOT_ZERO_T * vchiq_init_slots(void *mem_base, int mem_size) { - int mem_align = (VCHIQ_SLOT_SIZE - (int)mem_base) & VCHIQ_SLOT_MASK; + int mem_align = (int)((VCHIQ_SLOT_SIZE - (long)mem_base) & VCHIQ_SLOT_MASK); VCHIQ_SLOT_ZERO_T *slot_zero = (VCHIQ_SLOT_ZERO_T *)((char *)mem_base + mem_align); int num_slots = (mem_size - mem_align)/VCHIQ_SLOT_SIZE; int first_data_slot = VCHIQ_SLOT_ZERO_SLOTS; /* Ensure there is enough memory to run an absolutely minimum system */ num_slots -= first_data_slot; if (num_slots < 4) { vchiq_log_error(vchiq_core_log_level, "vchiq_init_slots - insufficient memory %x bytes", mem_size); return NULL; } memset(slot_zero, 0, sizeof(VCHIQ_SLOT_ZERO_T)); slot_zero->magic = VCHIQ_MAGIC; slot_zero->version = VCHIQ_VERSION; slot_zero->version_min = VCHIQ_VERSION_MIN; slot_zero->slot_zero_size = sizeof(VCHIQ_SLOT_ZERO_T); slot_zero->slot_size = VCHIQ_SLOT_SIZE; slot_zero->max_slots = VCHIQ_MAX_SLOTS; slot_zero->max_slots_per_side = VCHIQ_MAX_SLOTS_PER_SIDE; slot_zero->master.slot_sync = first_data_slot; slot_zero->master.slot_first = first_data_slot + 1; slot_zero->master.slot_last = first_data_slot + (num_slots/2) - 1; slot_zero->slave.slot_sync = first_data_slot + (num_slots/2); slot_zero->slave.slot_first = first_data_slot + (num_slots/2) + 1; slot_zero->slave.slot_last = first_data_slot + num_slots - 1; return slot_zero; } VCHIQ_STATUS_T vchiq_init_state(VCHIQ_STATE_T *state, VCHIQ_SLOT_ZERO_T *slot_zero, int is_master) { VCHIQ_SHARED_STATE_T *local; VCHIQ_SHARED_STATE_T *remote; VCHIQ_STATUS_T status; char threadname[10]; static int id; int i; /* Check the input configuration */ if (slot_zero->magic != VCHIQ_MAGIC) { vchiq_loud_error_header(); vchiq_loud_error("Invalid VCHIQ magic value found."); vchiq_loud_error("slot_zero=%p: magic=%x (expected %x)", slot_zero, slot_zero->magic, VCHIQ_MAGIC); vchiq_loud_error_footer(); return VCHIQ_ERROR; } vchiq_log_warning(vchiq_core_log_level, "local ver %d (min %d), remote ver %d.", VCHIQ_VERSION, VCHIQ_VERSION_MIN, slot_zero->version); if (slot_zero->version < VCHIQ_VERSION_MIN) { vchiq_loud_error_header(); vchiq_loud_error("Incompatible VCHIQ versions found."); vchiq_loud_error("slot_zero=%p: VideoCore version=%d " "(minimum %d)", slot_zero, slot_zero->version, VCHIQ_VERSION_MIN); vchiq_loud_error("Restart with a newer VideoCore image."); vchiq_loud_error_footer(); return VCHIQ_ERROR; } if (VCHIQ_VERSION < slot_zero->version_min) { vchiq_loud_error_header(); vchiq_loud_error("Incompatible VCHIQ versions found."); vchiq_loud_error("slot_zero=%p: version=%d (VideoCore " "minimum %d)", slot_zero, VCHIQ_VERSION, slot_zero->version_min); vchiq_loud_error("Restart with a newer kernel."); vchiq_loud_error_footer(); return VCHIQ_ERROR; } if ((slot_zero->slot_zero_size != sizeof(VCHIQ_SLOT_ZERO_T)) || (slot_zero->slot_size != VCHIQ_SLOT_SIZE) || (slot_zero->max_slots != VCHIQ_MAX_SLOTS) || (slot_zero->max_slots_per_side != VCHIQ_MAX_SLOTS_PER_SIDE)) { vchiq_loud_error_header(); if (slot_zero->slot_zero_size != sizeof(VCHIQ_SLOT_ZERO_T)) vchiq_loud_error("slot_zero=%p: slot_zero_size=%x " "(expected %zx)", slot_zero, slot_zero->slot_zero_size, sizeof(VCHIQ_SLOT_ZERO_T)); if (slot_zero->slot_size != VCHIQ_SLOT_SIZE) vchiq_loud_error("slot_zero=%p: slot_size=%d " "(expected %d", slot_zero, slot_zero->slot_size, VCHIQ_SLOT_SIZE); if (slot_zero->max_slots != VCHIQ_MAX_SLOTS) vchiq_loud_error("slot_zero=%p: max_slots=%d " "(expected %d)", slot_zero, slot_zero->max_slots, VCHIQ_MAX_SLOTS); if (slot_zero->max_slots_per_side != VCHIQ_MAX_SLOTS_PER_SIDE) vchiq_loud_error("slot_zero=%p: max_slots_per_side=%d " "(expected %d)", slot_zero, slot_zero->max_slots_per_side, VCHIQ_MAX_SLOTS_PER_SIDE); vchiq_loud_error_footer(); return VCHIQ_ERROR; } if (VCHIQ_VERSION < slot_zero->version) slot_zero->version = VCHIQ_VERSION; if (is_master) { local = &slot_zero->master; remote = &slot_zero->slave; } else { local = &slot_zero->slave; remote = &slot_zero->master; } if (local->initialised) { vchiq_loud_error_header(); if (remote->initialised) vchiq_loud_error("local state has already been " "initialised"); else vchiq_loud_error("master/slave mismatch - two %ss", is_master ? "master" : "slave"); vchiq_loud_error_footer(); return VCHIQ_ERROR; } memset(state, 0, sizeof(VCHIQ_STATE_T)); state->id = id++; state->is_master = is_master; /* initialize shared state pointers */ state->local = local; state->remote = remote; state->slot_data = (VCHIQ_SLOT_T *)slot_zero; /* initialize events and mutexes */ _sema_init(&state->connect, 0); lmutex_init(&state->mutex); _sema_init(&state->trigger_event, 0); _sema_init(&state->recycle_event, 0); _sema_init(&state->sync_trigger_event, 0); _sema_init(&state->sync_release_event, 0); lmutex_init(&state->slot_mutex); lmutex_init(&state->recycle_mutex); lmutex_init(&state->sync_mutex); lmutex_init(&state->bulk_transfer_mutex); _sema_init(&state->slot_available_event, 0); _sema_init(&state->slot_remove_event, 0); _sema_init(&state->data_quota_event, 0); state->slot_queue_available = 0; for (i = 0; i < VCHIQ_MAX_SERVICES; i++) { VCHIQ_SERVICE_QUOTA_T *service_quota = &state->service_quotas[i]; _sema_init(&service_quota->quota_event, 0); } for (i = local->slot_first; i <= local->slot_last; i++) { local->slot_queue[state->slot_queue_available++] = i; up(&state->slot_available_event); } state->default_slot_quota = state->slot_queue_available/2; state->default_message_quota = min((unsigned short)(state->default_slot_quota * 256), (unsigned short)~0); state->previous_data_index = -1; state->data_use_count = 0; state->data_quota = state->slot_queue_available - 1; - local->trigger.event = &state->trigger_event; - remote_event_create(&local->trigger); + local->trigger.event = offsetof(VCHIQ_STATE_T, trigger_event); + remote_event_create(state, &local->trigger); local->tx_pos = 0; - local->recycle.event = &state->recycle_event; - remote_event_create(&local->recycle); + local->recycle.event = offsetof(VCHIQ_STATE_T, recycle_event); + remote_event_create(state, &local->recycle); local->slot_queue_recycle = state->slot_queue_available; - local->sync_trigger.event = &state->sync_trigger_event; - remote_event_create(&local->sync_trigger); + local->sync_trigger.event = offsetof(VCHIQ_STATE_T, sync_trigger_event); + remote_event_create(state, &local->sync_trigger); - local->sync_release.event = &state->sync_release_event; - remote_event_create(&local->sync_release); + local->sync_release.event = offsetof(VCHIQ_STATE_T, sync_release_event); + remote_event_create(state, &local->sync_release); /* At start-of-day, the slot is empty and available */ ((VCHIQ_HEADER_T *)SLOT_DATA_FROM_INDEX(state, local->slot_sync))->msgid = VCHIQ_MSGID_PADDING; - remote_event_signal_local(&local->sync_release); + remote_event_signal_local(state, &local->sync_release); local->debug[DEBUG_ENTRIES] = DEBUG_MAX; status = vchiq_platform_init_state(state); /* bring up slot handler thread */ snprintf(threadname, sizeof(threadname), "VCHIQ-%d", state->id); state->slot_handler_thread = vchiq_thread_create(&slot_handler_func, (void *)state, threadname); if (state->slot_handler_thread == NULL) { vchiq_loud_error_header(); vchiq_loud_error("couldn't create thread %s", threadname); vchiq_loud_error_footer(); return VCHIQ_ERROR; } set_user_nice(state->slot_handler_thread, -19); wake_up_process(state->slot_handler_thread); snprintf(threadname, sizeof(threadname), "VCHIQr-%d", state->id); state->recycle_thread = vchiq_thread_create(&recycle_func, (void *)state, threadname); if (state->recycle_thread == NULL) { vchiq_loud_error_header(); vchiq_loud_error("couldn't create thread %s", threadname); vchiq_loud_error_footer(); return VCHIQ_ERROR; } set_user_nice(state->recycle_thread, -19); wake_up_process(state->recycle_thread); snprintf(threadname, sizeof(threadname), "VCHIQs-%d", state->id); state->sync_thread = vchiq_thread_create(&sync_func, (void *)state, threadname); if (state->sync_thread == NULL) { vchiq_loud_error_header(); vchiq_loud_error("couldn't create thread %s", threadname); vchiq_loud_error_footer(); return VCHIQ_ERROR; } set_user_nice(state->sync_thread, -20); wake_up_process(state->sync_thread); BUG_ON(state->id >= VCHIQ_MAX_STATES); vchiq_states[state->id] = state; /* Indicate readiness to the other side */ local->initialised = 1; return status; } /* Called from application thread when a client or server service is created. */ VCHIQ_SERVICE_T * vchiq_add_service_internal(VCHIQ_STATE_T *state, const VCHIQ_SERVICE_PARAMS_T *params, int srvstate, VCHIQ_INSTANCE_T instance, VCHIQ_USERDATA_TERM_T userdata_term) { VCHIQ_SERVICE_T *service; service = kmalloc(sizeof(VCHIQ_SERVICE_T), GFP_KERNEL); if (service) { service->base.fourcc = params->fourcc; service->base.callback = params->callback; service->base.userdata = params->userdata; service->handle = VCHIQ_SERVICE_HANDLE_INVALID; service->ref_count = 1; service->srvstate = VCHIQ_SRVSTATE_FREE; service->userdata_term = userdata_term; service->localport = VCHIQ_PORT_FREE; service->remoteport = VCHIQ_PORT_FREE; service->public_fourcc = (srvstate == VCHIQ_SRVSTATE_OPENING) ? VCHIQ_FOURCC_INVALID : params->fourcc; service->client_id = 0; service->auto_close = 1; service->sync = 0; service->closing = 0; service->trace = 0; atomic_set(&service->poll_flags, 0); service->version = params->version; service->version_min = params->version_min; service->state = state; service->instance = instance; service->service_use_count = 0; init_bulk_queue(&service->bulk_tx); init_bulk_queue(&service->bulk_rx); _sema_init(&service->remove_event, 0); _sema_init(&service->bulk_remove_event, 0); lmutex_init(&service->bulk_mutex); memset(&service->stats, 0, sizeof(service->stats)); } else { vchiq_log_error(vchiq_core_log_level, "Out of memory"); } if (service) { VCHIQ_SERVICE_T **pservice = NULL; int i; /* Although it is perfectly possible to use service_spinlock ** to protect the creation of services, it is overkill as it ** disables interrupts while the array is searched. ** The only danger is of another thread trying to create a ** service - service deletion is safe. ** Therefore it is preferable to use state->mutex which, ** although slower to claim, doesn't block interrupts while ** it is held. */ lmutex_lock(&state->mutex); /* Prepare to use a previously unused service */ if (state->unused_service < VCHIQ_MAX_SERVICES) pservice = &state->services[state->unused_service]; if (srvstate == VCHIQ_SRVSTATE_OPENING) { for (i = 0; i < state->unused_service; i++) { VCHIQ_SERVICE_T *srv = state->services[i]; if (!srv) { pservice = &state->services[i]; break; } } } else { for (i = (state->unused_service - 1); i >= 0; i--) { VCHIQ_SERVICE_T *srv = state->services[i]; if (!srv) pservice = &state->services[i]; else if ((srv->public_fourcc == params->fourcc) && ((srv->instance != instance) || (srv->base.callback != params->callback))) { /* There is another server using this ** fourcc which doesn't match. */ pservice = NULL; break; } } } if (pservice) { service->localport = (pservice - state->services); if (!handle_seq) handle_seq = VCHIQ_MAX_STATES * VCHIQ_MAX_SERVICES; service->handle = handle_seq | (state->id * VCHIQ_MAX_SERVICES) | service->localport; handle_seq += VCHIQ_MAX_STATES * VCHIQ_MAX_SERVICES; *pservice = service; if (pservice == &state->services[state->unused_service]) state->unused_service++; } lmutex_unlock(&state->mutex); if (!pservice) { _sema_destroy(&service->remove_event); _sema_destroy(&service->bulk_remove_event); lmutex_destroy(&service->bulk_mutex); kfree(service); service = NULL; } } if (service) { VCHIQ_SERVICE_QUOTA_T *service_quota = &state->service_quotas[service->localport]; service_quota->slot_quota = state->default_slot_quota; service_quota->message_quota = state->default_message_quota; if (service_quota->slot_use_count == 0) service_quota->previous_tx_index = SLOT_QUEUE_INDEX_FROM_POS(state->local_tx_pos) - 1; /* Bring this service online */ vchiq_set_service_state(service, srvstate); vchiq_log_info(vchiq_core_msg_log_level, "%s Service %c%c%c%c SrcPort:%d", (srvstate == VCHIQ_SRVSTATE_OPENING) ? "Open" : "Add", VCHIQ_FOURCC_AS_4CHARS(params->fourcc), service->localport); } /* Don't unlock the service - leave it with a ref_count of 1. */ return service; } VCHIQ_STATUS_T vchiq_open_service_internal(VCHIQ_SERVICE_T *service, int client_id) { struct vchiq_open_payload payload = { service->base.fourcc, client_id, service->version, service->version_min }; VCHIQ_ELEMENT_T body = { &payload, sizeof(payload) }; VCHIQ_STATUS_T status = VCHIQ_SUCCESS; service->client_id = client_id; vchiq_use_service_internal(service); status = queue_message(service->state, NULL, VCHIQ_MAKE_MSG(VCHIQ_MSG_OPEN, service->localport, 0), &body, 1, sizeof(payload), QMFLAGS_IS_BLOCKING); if (status == VCHIQ_SUCCESS) { /* Wait for the ACK/NAK */ if (down_interruptible(&service->remove_event) != 0) { status = VCHIQ_RETRY; vchiq_release_service_internal(service); } else if ((service->srvstate != VCHIQ_SRVSTATE_OPEN) && (service->srvstate != VCHIQ_SRVSTATE_OPENSYNC)) { if (service->srvstate != VCHIQ_SRVSTATE_CLOSEWAIT) vchiq_log_error(vchiq_core_log_level, "%d: osi - srvstate = %s (ref %d)", service->state->id, srvstate_names[service->srvstate], service->ref_count); status = VCHIQ_ERROR; VCHIQ_SERVICE_STATS_INC(service, error_count); vchiq_release_service_internal(service); } } return status; } static void release_service_messages(VCHIQ_SERVICE_T *service) { VCHIQ_STATE_T *state = service->state; int slot_last = state->remote->slot_last; int i; /* Release any claimed messages aimed at this service */ if (service->sync) { VCHIQ_HEADER_T *header = (VCHIQ_HEADER_T *)SLOT_DATA_FROM_INDEX(state, state->remote->slot_sync); if (VCHIQ_MSG_DSTPORT(header->msgid) == service->localport) release_message_sync(state, header); return; } for (i = state->remote->slot_first; i <= slot_last; i++) { VCHIQ_SLOT_INFO_T *slot_info = SLOT_INFO_FROM_INDEX(state, i); if (slot_info->release_count != slot_info->use_count) { char *data = (char *)SLOT_DATA_FROM_INDEX(state, i); unsigned int pos, end; end = VCHIQ_SLOT_SIZE; if (data == state->rx_data) /* This buffer is still being read from - stop ** at the current read position */ end = state->rx_pos & VCHIQ_SLOT_MASK; pos = 0; while (pos < end) { VCHIQ_HEADER_T *header = (VCHIQ_HEADER_T *)(data + pos); int msgid = header->msgid; int port = VCHIQ_MSG_DSTPORT(msgid); if ((port == service->localport) && (msgid & VCHIQ_MSGID_CLAIMED)) { vchiq_log_info(vchiq_core_log_level, " fsi - hdr %p", header); release_slot(state, slot_info, header, NULL); } pos += calc_stride(header->size); if (pos > VCHIQ_SLOT_SIZE) { vchiq_log_error(vchiq_core_log_level, "fsi - pos %x: header %p, " "msgid %x, header->msgid %x, " "header->size %x", pos, header, msgid, header->msgid, header->size); WARN(1, "invalid slot position\n"); } } } } } static int do_abort_bulks(VCHIQ_SERVICE_T *service) { VCHIQ_STATUS_T status; /* Abort any outstanding bulk transfers */ if (lmutex_lock_interruptible(&service->bulk_mutex) != 0) return 0; abort_outstanding_bulks(service, &service->bulk_tx); abort_outstanding_bulks(service, &service->bulk_rx); lmutex_unlock(&service->bulk_mutex); status = notify_bulks(service, &service->bulk_tx, 0/*!retry_poll*/); if (status == VCHIQ_SUCCESS) status = notify_bulks(service, &service->bulk_rx, 0/*!retry_poll*/); return (status == VCHIQ_SUCCESS); } static VCHIQ_STATUS_T close_service_complete(VCHIQ_SERVICE_T *service, int failstate) { VCHIQ_STATUS_T status; int is_server = (service->public_fourcc != VCHIQ_FOURCC_INVALID); int newstate; switch (service->srvstate) { case VCHIQ_SRVSTATE_OPEN: case VCHIQ_SRVSTATE_CLOSESENT: case VCHIQ_SRVSTATE_CLOSERECVD: if (is_server) { if (service->auto_close) { service->client_id = 0; service->remoteport = VCHIQ_PORT_FREE; newstate = VCHIQ_SRVSTATE_LISTENING; } else newstate = VCHIQ_SRVSTATE_CLOSEWAIT; } else newstate = VCHIQ_SRVSTATE_CLOSED; vchiq_set_service_state(service, newstate); break; case VCHIQ_SRVSTATE_LISTENING: break; default: vchiq_log_error(vchiq_core_log_level, "close_service_complete(%x) called in state %s", service->handle, srvstate_names[service->srvstate]); WARN(1, "close_service_complete in unexpected state\n"); return VCHIQ_ERROR; } status = make_service_callback(service, VCHIQ_SERVICE_CLOSED, NULL, NULL); if (status != VCHIQ_RETRY) { int uc = service->service_use_count; int i; /* Complete the close process */ for (i = 0; i < uc; i++) /* cater for cases where close is forced and the ** client may not close all it's handles */ vchiq_release_service_internal(service); service->client_id = 0; service->remoteport = VCHIQ_PORT_FREE; if (service->srvstate == VCHIQ_SRVSTATE_CLOSED) vchiq_free_service_internal(service); else if (service->srvstate != VCHIQ_SRVSTATE_CLOSEWAIT) { if (is_server) service->closing = 0; up(&service->remove_event); } } else vchiq_set_service_state(service, failstate); return status; } /* Called by the slot handler */ VCHIQ_STATUS_T vchiq_close_service_internal(VCHIQ_SERVICE_T *service, int close_recvd) { VCHIQ_STATE_T *state = service->state; VCHIQ_STATUS_T status = VCHIQ_SUCCESS; int is_server = (service->public_fourcc != VCHIQ_FOURCC_INVALID); vchiq_log_info(vchiq_core_log_level, "%d: csi:%d,%d (%s)", service->state->id, service->localport, close_recvd, srvstate_names[service->srvstate]); switch (service->srvstate) { case VCHIQ_SRVSTATE_CLOSED: case VCHIQ_SRVSTATE_HIDDEN: case VCHIQ_SRVSTATE_LISTENING: case VCHIQ_SRVSTATE_CLOSEWAIT: if (close_recvd) vchiq_log_error(vchiq_core_log_level, "vchiq_close_service_internal(1) called " "in state %s", srvstate_names[service->srvstate]); else if (is_server) { if (service->srvstate == VCHIQ_SRVSTATE_LISTENING) { status = VCHIQ_ERROR; } else { service->client_id = 0; service->remoteport = VCHIQ_PORT_FREE; if (service->srvstate == VCHIQ_SRVSTATE_CLOSEWAIT) vchiq_set_service_state(service, VCHIQ_SRVSTATE_LISTENING); } up(&service->remove_event); } else vchiq_free_service_internal(service); break; case VCHIQ_SRVSTATE_OPENING: if (close_recvd) { /* The open was rejected - tell the user */ vchiq_set_service_state(service, VCHIQ_SRVSTATE_CLOSEWAIT); up(&service->remove_event); } else { /* Shutdown mid-open - let the other side know */ status = queue_message(state, service, VCHIQ_MAKE_MSG (VCHIQ_MSG_CLOSE, service->localport, VCHIQ_MSG_DSTPORT(service->remoteport)), NULL, 0, 0, 0); } break; case VCHIQ_SRVSTATE_OPENSYNC: lmutex_lock(&state->sync_mutex); /* Drop through */ case VCHIQ_SRVSTATE_OPEN: if (state->is_master || close_recvd) { if (!do_abort_bulks(service)) status = VCHIQ_RETRY; } release_service_messages(service); if (status == VCHIQ_SUCCESS) status = queue_message(state, service, VCHIQ_MAKE_MSG (VCHIQ_MSG_CLOSE, service->localport, VCHIQ_MSG_DSTPORT(service->remoteport)), NULL, 0, 0, QMFLAGS_NO_MUTEX_UNLOCK); if (status == VCHIQ_SUCCESS) { if (!close_recvd) { /* Change the state while the mutex is still held */ vchiq_set_service_state(service, VCHIQ_SRVSTATE_CLOSESENT); lmutex_unlock(&state->slot_mutex); if (service->sync) lmutex_unlock(&state->sync_mutex); break; } } else if (service->srvstate == VCHIQ_SRVSTATE_OPENSYNC) { lmutex_unlock(&state->sync_mutex); break; } else break; /* Change the state while the mutex is still held */ vchiq_set_service_state(service, VCHIQ_SRVSTATE_CLOSERECVD); lmutex_unlock(&state->slot_mutex); if (service->sync) lmutex_unlock(&state->sync_mutex); status = close_service_complete(service, VCHIQ_SRVSTATE_CLOSERECVD); break; case VCHIQ_SRVSTATE_CLOSESENT: if (!close_recvd) /* This happens when a process is killed mid-close */ break; if (!state->is_master) { if (!do_abort_bulks(service)) { status = VCHIQ_RETRY; break; } } if (status == VCHIQ_SUCCESS) status = close_service_complete(service, VCHIQ_SRVSTATE_CLOSERECVD); break; case VCHIQ_SRVSTATE_CLOSERECVD: if (!close_recvd && is_server) /* Force into LISTENING mode */ vchiq_set_service_state(service, VCHIQ_SRVSTATE_LISTENING); status = close_service_complete(service, VCHIQ_SRVSTATE_CLOSERECVD); break; default: vchiq_log_error(vchiq_core_log_level, "vchiq_close_service_internal(%d) called in state %s", close_recvd, srvstate_names[service->srvstate]); break; } return status; } /* Called from the application process upon process death */ void vchiq_terminate_service_internal(VCHIQ_SERVICE_T *service) { VCHIQ_STATE_T *state = service->state; vchiq_log_info(vchiq_core_log_level, "%d: tsi - (%d<->%d)", state->id, service->localport, service->remoteport); mark_service_closing(service); /* Mark the service for removal by the slot handler */ request_poll(state, service, VCHIQ_POLL_REMOVE); } /* Called from the slot handler */ void vchiq_free_service_internal(VCHIQ_SERVICE_T *service) { VCHIQ_STATE_T *state = service->state; vchiq_log_info(vchiq_core_log_level, "%d: fsi - (%d)", state->id, service->localport); switch (service->srvstate) { case VCHIQ_SRVSTATE_OPENING: case VCHIQ_SRVSTATE_CLOSED: case VCHIQ_SRVSTATE_HIDDEN: case VCHIQ_SRVSTATE_LISTENING: case VCHIQ_SRVSTATE_CLOSEWAIT: break; default: vchiq_log_error(vchiq_core_log_level, "%d: fsi - (%d) in state %s", state->id, service->localport, srvstate_names[service->srvstate]); return; } vchiq_set_service_state(service, VCHIQ_SRVSTATE_FREE); up(&service->remove_event); /* Release the initial lock */ unlock_service(service); } VCHIQ_STATUS_T vchiq_connect_internal(VCHIQ_STATE_T *state, VCHIQ_INSTANCE_T instance) { VCHIQ_SERVICE_T *service; int i; /* Find all services registered to this client and enable them. */ i = 0; while ((service = next_service_by_instance(state, instance, &i)) != NULL) { if (service->srvstate == VCHIQ_SRVSTATE_HIDDEN) vchiq_set_service_state(service, VCHIQ_SRVSTATE_LISTENING); unlock_service(service); } if (state->conn_state == VCHIQ_CONNSTATE_DISCONNECTED) { if (queue_message(state, NULL, VCHIQ_MAKE_MSG(VCHIQ_MSG_CONNECT, 0, 0), NULL, 0, 0, QMFLAGS_IS_BLOCKING) == VCHIQ_RETRY) return VCHIQ_RETRY; vchiq_set_conn_state(state, VCHIQ_CONNSTATE_CONNECTING); } if (state->conn_state == VCHIQ_CONNSTATE_CONNECTING) { if (down_interruptible(&state->connect) != 0) return VCHIQ_RETRY; vchiq_set_conn_state(state, VCHIQ_CONNSTATE_CONNECTED); up(&state->connect); } return VCHIQ_SUCCESS; } VCHIQ_STATUS_T vchiq_shutdown_internal(VCHIQ_STATE_T *state, VCHIQ_INSTANCE_T instance) { VCHIQ_SERVICE_T *service; int i; /* Find all services registered to this client and enable them. */ i = 0; while ((service = next_service_by_instance(state, instance, &i)) != NULL) { (void)vchiq_remove_service(service->handle); unlock_service(service); } return VCHIQ_SUCCESS; } VCHIQ_STATUS_T vchiq_pause_internal(VCHIQ_STATE_T *state) { VCHIQ_STATUS_T status = VCHIQ_SUCCESS; switch (state->conn_state) { case VCHIQ_CONNSTATE_CONNECTED: /* Request a pause */ vchiq_set_conn_state(state, VCHIQ_CONNSTATE_PAUSING); request_poll(state, NULL, 0); break; default: vchiq_log_error(vchiq_core_log_level, "vchiq_pause_internal in state %s\n", conn_state_names[state->conn_state]); status = VCHIQ_ERROR; VCHIQ_STATS_INC(state, error_count); break; } return status; } VCHIQ_STATUS_T vchiq_resume_internal(VCHIQ_STATE_T *state) { VCHIQ_STATUS_T status = VCHIQ_SUCCESS; if (state->conn_state == VCHIQ_CONNSTATE_PAUSED) { vchiq_set_conn_state(state, VCHIQ_CONNSTATE_RESUMING); request_poll(state, NULL, 0); } else { status = VCHIQ_ERROR; VCHIQ_STATS_INC(state, error_count); } return status; } VCHIQ_STATUS_T vchiq_close_service(VCHIQ_SERVICE_HANDLE_T handle) { /* Unregister the service */ VCHIQ_SERVICE_T *service = find_service_by_handle(handle); VCHIQ_STATUS_T status = VCHIQ_SUCCESS; if (!service) return VCHIQ_ERROR; vchiq_log_info(vchiq_core_log_level, "%d: close_service:%d", service->state->id, service->localport); if ((service->srvstate == VCHIQ_SRVSTATE_FREE) || (service->srvstate == VCHIQ_SRVSTATE_LISTENING) || (service->srvstate == VCHIQ_SRVSTATE_HIDDEN)) { unlock_service(service); return VCHIQ_ERROR; } mark_service_closing(service); if (current == service->state->slot_handler_thread) { status = vchiq_close_service_internal(service, 0/*!close_recvd*/); BUG_ON(status == VCHIQ_RETRY); } else { /* Mark the service for termination by the slot handler */ request_poll(service->state, service, VCHIQ_POLL_TERMINATE); } while (1) { if (down_interruptible(&service->remove_event) != 0) { status = VCHIQ_RETRY; break; } if ((service->srvstate == VCHIQ_SRVSTATE_FREE) || (service->srvstate == VCHIQ_SRVSTATE_LISTENING) || (service->srvstate == VCHIQ_SRVSTATE_OPEN)) break; vchiq_log_warning(vchiq_core_log_level, "%d: close_service:%d - waiting in state %s", service->state->id, service->localport, srvstate_names[service->srvstate]); } if ((status == VCHIQ_SUCCESS) && (service->srvstate != VCHIQ_SRVSTATE_FREE) && (service->srvstate != VCHIQ_SRVSTATE_LISTENING)) status = VCHIQ_ERROR; unlock_service(service); return status; } VCHIQ_STATUS_T vchiq_remove_service(VCHIQ_SERVICE_HANDLE_T handle) { /* Unregister the service */ VCHIQ_SERVICE_T *service = find_service_by_handle(handle); VCHIQ_STATUS_T status = VCHIQ_SUCCESS; if (!service) return VCHIQ_ERROR; vchiq_log_info(vchiq_core_log_level, "%d: remove_service:%d", service->state->id, service->localport); if (service->srvstate == VCHIQ_SRVSTATE_FREE) { unlock_service(service); return VCHIQ_ERROR; } mark_service_closing(service); if ((service->srvstate == VCHIQ_SRVSTATE_HIDDEN) || (current == service->state->slot_handler_thread)) { /* Make it look like a client, because it must be removed and not left in the LISTENING state. */ service->public_fourcc = VCHIQ_FOURCC_INVALID; status = vchiq_close_service_internal(service, 0/*!close_recvd*/); BUG_ON(status == VCHIQ_RETRY); } else { /* Mark the service for removal by the slot handler */ request_poll(service->state, service, VCHIQ_POLL_REMOVE); } while (1) { if (down_interruptible(&service->remove_event) != 0) { status = VCHIQ_RETRY; break; } if ((service->srvstate == VCHIQ_SRVSTATE_FREE) || (service->srvstate == VCHIQ_SRVSTATE_OPEN)) break; vchiq_log_warning(vchiq_core_log_level, "%d: remove_service:%d - waiting in state %s", service->state->id, service->localport, srvstate_names[service->srvstate]); } if ((status == VCHIQ_SUCCESS) && (service->srvstate != VCHIQ_SRVSTATE_FREE)) status = VCHIQ_ERROR; unlock_service(service); return status; } /* This function may be called by kernel threads or user threads. * User threads may receive VCHIQ_RETRY to indicate that a signal has been * received and the call should be retried after being returned to user * context. * When called in blocking mode, the userdata field points to a bulk_waiter * structure. */ VCHIQ_STATUS_T vchiq_bulk_transfer(VCHIQ_SERVICE_HANDLE_T handle, VCHI_MEM_HANDLE_T memhandle, void *offset, int size, void *userdata, VCHIQ_BULK_MODE_T mode, VCHIQ_BULK_DIR_T dir) { VCHIQ_SERVICE_T *service = find_service_by_handle(handle); VCHIQ_BULK_QUEUE_T *queue; VCHIQ_BULK_T *bulk; VCHIQ_STATE_T *state; struct bulk_waiter *bulk_waiter = NULL; const char dir_char = (dir == VCHIQ_BULK_TRANSMIT) ? 't' : 'r'; const int dir_msgtype = (dir == VCHIQ_BULK_TRANSMIT) ? VCHIQ_MSG_BULK_TX : VCHIQ_MSG_BULK_RX; VCHIQ_STATUS_T status = VCHIQ_ERROR; if (!service || (service->srvstate != VCHIQ_SRVSTATE_OPEN) || ((memhandle == VCHI_MEM_HANDLE_INVALID) && (offset == NULL)) || (vchiq_check_service(service) != VCHIQ_SUCCESS)) goto error_exit; switch (mode) { case VCHIQ_BULK_MODE_NOCALLBACK: case VCHIQ_BULK_MODE_CALLBACK: break; case VCHIQ_BULK_MODE_BLOCKING: bulk_waiter = (struct bulk_waiter *)userdata; _sema_init(&bulk_waiter->event, 0); bulk_waiter->actual = 0; bulk_waiter->bulk = NULL; break; case VCHIQ_BULK_MODE_WAITING: bulk_waiter = (struct bulk_waiter *)userdata; bulk = bulk_waiter->bulk; goto waiting; default: goto error_exit; } state = service->state; queue = (dir == VCHIQ_BULK_TRANSMIT) ? &service->bulk_tx : &service->bulk_rx; if (lmutex_lock_interruptible(&service->bulk_mutex) != 0) { status = VCHIQ_RETRY; goto error_exit; } if (queue->local_insert == queue->remove + VCHIQ_NUM_SERVICE_BULKS) { VCHIQ_SERVICE_STATS_INC(service, bulk_stalls); do { lmutex_unlock(&service->bulk_mutex); if (down_interruptible(&service->bulk_remove_event) != 0) { status = VCHIQ_RETRY; goto error_exit; } if (lmutex_lock_interruptible(&service->bulk_mutex) != 0) { status = VCHIQ_RETRY; goto error_exit; } } while (queue->local_insert == queue->remove + VCHIQ_NUM_SERVICE_BULKS); } bulk = &queue->bulks[BULK_INDEX(queue->local_insert)]; bulk->mode = mode; bulk->dir = dir; bulk->userdata = userdata; bulk->size = size; bulk->actual = VCHIQ_BULK_ACTUAL_ABORTED; if (vchiq_prepare_bulk_data(bulk, memhandle, offset, size, dir) != VCHIQ_SUCCESS) goto unlock_error_exit; wmb(); vchiq_log_info(vchiq_core_log_level, "%d: bt (%d->%d) %cx %x@%p %p", state->id, service->localport, service->remoteport, dir_char, size, bulk->data, userdata); /* The slot mutex must be held when the service is being closed, so claim it here to ensure that isn't happening */ if (lmutex_lock_interruptible(&state->slot_mutex) != 0) { status = VCHIQ_RETRY; goto cancel_bulk_error_exit; } if (service->srvstate != VCHIQ_SRVSTATE_OPEN) goto unlock_both_error_exit; if (state->is_master) { queue->local_insert++; if (resolve_bulks(service, queue)) request_poll(state, service, (dir == VCHIQ_BULK_TRANSMIT) ? VCHIQ_POLL_TXNOTIFY : VCHIQ_POLL_RXNOTIFY); } else { - int payload[2] = { (int)bulk->data, bulk->size }; + uint32_t payload[2] = { (uint32_t)(uintptr_t)bulk->data, bulk->size }; VCHIQ_ELEMENT_T element = { payload, sizeof(payload) }; status = queue_message(state, NULL, VCHIQ_MAKE_MSG(dir_msgtype, service->localport, service->remoteport), &element, 1, sizeof(payload), QMFLAGS_IS_BLOCKING | QMFLAGS_NO_MUTEX_LOCK | QMFLAGS_NO_MUTEX_UNLOCK); if (status != VCHIQ_SUCCESS) { goto unlock_both_error_exit; } queue->local_insert++; } lmutex_unlock(&state->slot_mutex); lmutex_unlock(&service->bulk_mutex); vchiq_log_trace(vchiq_core_log_level, "%d: bt:%d %cx li=%x ri=%x p=%x", state->id, service->localport, dir_char, queue->local_insert, queue->remote_insert, queue->process); waiting: unlock_service(service); status = VCHIQ_SUCCESS; if (bulk_waiter) { bulk_waiter->bulk = bulk; if (down_interruptible(&bulk_waiter->event) != 0) status = VCHIQ_RETRY; else if (bulk_waiter->actual == VCHIQ_BULK_ACTUAL_ABORTED) status = VCHIQ_ERROR; } return status; unlock_both_error_exit: lmutex_unlock(&state->slot_mutex); cancel_bulk_error_exit: vchiq_complete_bulk(bulk); unlock_error_exit: lmutex_unlock(&service->bulk_mutex); error_exit: if (service) unlock_service(service); return status; } VCHIQ_STATUS_T vchiq_queue_message(VCHIQ_SERVICE_HANDLE_T handle, const VCHIQ_ELEMENT_T *elements, unsigned int count) { VCHIQ_SERVICE_T *service = find_service_by_handle(handle); VCHIQ_STATUS_T status = VCHIQ_ERROR; unsigned int size = 0; unsigned int i; if (!service || (vchiq_check_service(service) != VCHIQ_SUCCESS)) goto error_exit; for (i = 0; i < (unsigned int)count; i++) { if (elements[i].size) { if (elements[i].data == NULL) { VCHIQ_SERVICE_STATS_INC(service, error_count); goto error_exit; } size += elements[i].size; } } if (size > VCHIQ_MAX_MSG_SIZE) { VCHIQ_SERVICE_STATS_INC(service, error_count); goto error_exit; } switch (service->srvstate) { case VCHIQ_SRVSTATE_OPEN: status = queue_message(service->state, service, VCHIQ_MAKE_MSG(VCHIQ_MSG_DATA, service->localport, service->remoteport), elements, count, size, 1); break; case VCHIQ_SRVSTATE_OPENSYNC: status = queue_message_sync(service->state, service, VCHIQ_MAKE_MSG(VCHIQ_MSG_DATA, service->localport, service->remoteport), elements, count, size, 1); break; default: status = VCHIQ_ERROR; break; } error_exit: if (service) unlock_service(service); return status; } void vchiq_release_message(VCHIQ_SERVICE_HANDLE_T handle, VCHIQ_HEADER_T *header) { VCHIQ_SERVICE_T *service = find_service_by_handle(handle); VCHIQ_SHARED_STATE_T *remote; VCHIQ_STATE_T *state; int slot_index; if (!service) return; state = service->state; remote = state->remote; slot_index = SLOT_INDEX_FROM_DATA(state, (void *)header); if ((slot_index >= remote->slot_first) && (slot_index <= remote->slot_last)) { int msgid = header->msgid; if (msgid & VCHIQ_MSGID_CLAIMED) { VCHIQ_SLOT_INFO_T *slot_info = SLOT_INFO_FROM_INDEX(state, slot_index); release_slot(state, slot_info, header, service); } } else if (slot_index == remote->slot_sync) release_message_sync(state, header); unlock_service(service); } static void release_message_sync(VCHIQ_STATE_T *state, VCHIQ_HEADER_T *header) { header->msgid = VCHIQ_MSGID_PADDING; - wmb(); remote_event_signal(&state->remote->sync_release); } VCHIQ_STATUS_T vchiq_get_peer_version(VCHIQ_SERVICE_HANDLE_T handle, short *peer_version) { VCHIQ_STATUS_T status = VCHIQ_ERROR; VCHIQ_SERVICE_T *service = find_service_by_handle(handle); if (!service || (vchiq_check_service(service) != VCHIQ_SUCCESS) || !peer_version) goto exit; *peer_version = service->peer_version; status = VCHIQ_SUCCESS; exit: if (service) unlock_service(service); return status; } VCHIQ_STATUS_T vchiq_get_config(VCHIQ_INSTANCE_T instance, int config_size, VCHIQ_CONFIG_T *pconfig) { VCHIQ_CONFIG_T config; (void)instance; config.max_msg_size = VCHIQ_MAX_MSG_SIZE; config.bulk_threshold = VCHIQ_MAX_MSG_SIZE; config.max_outstanding_bulks = VCHIQ_NUM_SERVICE_BULKS; config.max_services = VCHIQ_MAX_SERVICES; config.version = VCHIQ_VERSION; config.version_min = VCHIQ_VERSION_MIN; if (config_size > sizeof(VCHIQ_CONFIG_T)) return VCHIQ_ERROR; memcpy(pconfig, &config, min(config_size, (int)(sizeof(VCHIQ_CONFIG_T)))); return VCHIQ_SUCCESS; } VCHIQ_STATUS_T vchiq_set_service_option(VCHIQ_SERVICE_HANDLE_T handle, VCHIQ_SERVICE_OPTION_T option, int value) { VCHIQ_SERVICE_T *service = find_service_by_handle(handle); VCHIQ_STATUS_T status = VCHIQ_ERROR; if (service) { switch (option) { case VCHIQ_SERVICE_OPTION_AUTOCLOSE: service->auto_close = value; status = VCHIQ_SUCCESS; break; case VCHIQ_SERVICE_OPTION_SLOT_QUOTA: { VCHIQ_SERVICE_QUOTA_T *service_quota = &service->state->service_quotas[ service->localport]; if (value == 0) value = service->state->default_slot_quota; if ((value >= service_quota->slot_use_count) && (value < (unsigned short)~0)) { service_quota->slot_quota = value; if ((value >= service_quota->slot_use_count) && (service_quota->message_quota >= service_quota->message_use_count)) { /* Signal the service that it may have ** dropped below its quota */ up(&service_quota->quota_event); } status = VCHIQ_SUCCESS; } } break; case VCHIQ_SERVICE_OPTION_MESSAGE_QUOTA: { VCHIQ_SERVICE_QUOTA_T *service_quota = &service->state->service_quotas[ service->localport]; if (value == 0) value = service->state->default_message_quota; if ((value >= service_quota->message_use_count) && (value < (unsigned short)~0)) { service_quota->message_quota = value; if ((value >= service_quota->message_use_count) && (service_quota->slot_quota >= service_quota->slot_use_count)) /* Signal the service that it may have ** dropped below its quota */ up(&service_quota->quota_event); status = VCHIQ_SUCCESS; } } break; case VCHIQ_SERVICE_OPTION_SYNCHRONOUS: if ((service->srvstate == VCHIQ_SRVSTATE_HIDDEN) || (service->srvstate == VCHIQ_SRVSTATE_LISTENING)) { service->sync = value; status = VCHIQ_SUCCESS; } break; case VCHIQ_SERVICE_OPTION_TRACE: service->trace = value; status = VCHIQ_SUCCESS; break; default: break; } unlock_service(service); } return status; } static void vchiq_dump_shared_state(void *dump_context, VCHIQ_STATE_T *state, VCHIQ_SHARED_STATE_T *shared, const char *label) { static const char *const debug_names[] = { "", "SLOT_HANDLER_COUNT", "SLOT_HANDLER_LINE", "PARSE_LINE", "PARSE_HEADER", "PARSE_MSGID", "AWAIT_COMPLETION_LINE", "DEQUEUE_MESSAGE_LINE", "SERVICE_CALLBACK_LINE", "MSG_QUEUE_FULL_COUNT", "COMPLETION_QUEUE_FULL_COUNT" }; int i; char buf[80]; int len; len = snprintf(buf, sizeof(buf), " %s: slots %d-%d tx_pos=%x recycle=%x", label, shared->slot_first, shared->slot_last, shared->tx_pos, shared->slot_queue_recycle); vchiq_dump(dump_context, buf, len + 1); len = snprintf(buf, sizeof(buf), " Slots claimed:"); vchiq_dump(dump_context, buf, len + 1); for (i = shared->slot_first; i <= shared->slot_last; i++) { VCHIQ_SLOT_INFO_T slot_info = *SLOT_INFO_FROM_INDEX(state, i); if (slot_info.use_count != slot_info.release_count) { len = snprintf(buf, sizeof(buf), " %d: %d/%d", i, slot_info.use_count, slot_info.release_count); vchiq_dump(dump_context, buf, len + 1); } } for (i = 1; i < shared->debug[DEBUG_ENTRIES]; i++) { len = snprintf(buf, sizeof(buf), " DEBUG: %s = %d(%x)", debug_names[i], shared->debug[i], shared->debug[i]); vchiq_dump(dump_context, buf, len + 1); } } void vchiq_dump_state(void *dump_context, VCHIQ_STATE_T *state) { char buf[80]; int len; int i; len = snprintf(buf, sizeof(buf), "State %d: %s", state->id, conn_state_names[state->conn_state]); vchiq_dump(dump_context, buf, len + 1); len = snprintf(buf, sizeof(buf), " tx_pos=%x(@%p), rx_pos=%x(@%p)", state->local->tx_pos, state->tx_data + (state->local_tx_pos & VCHIQ_SLOT_MASK), state->rx_pos, state->rx_data + (state->rx_pos & VCHIQ_SLOT_MASK)); vchiq_dump(dump_context, buf, len + 1); len = snprintf(buf, sizeof(buf), " Version: %d (min %d)", VCHIQ_VERSION, VCHIQ_VERSION_MIN); vchiq_dump(dump_context, buf, len + 1); if (VCHIQ_ENABLE_STATS) { len = snprintf(buf, sizeof(buf), " Stats: ctrl_tx_count=%d, ctrl_rx_count=%d, " "error_count=%d", state->stats.ctrl_tx_count, state->stats.ctrl_rx_count, state->stats.error_count); vchiq_dump(dump_context, buf, len + 1); } len = snprintf(buf, sizeof(buf), " Slots: %d available (%d data), %d recyclable, %d stalls " "(%d data)", ((state->slot_queue_available * VCHIQ_SLOT_SIZE) - state->local_tx_pos) / VCHIQ_SLOT_SIZE, state->data_quota - state->data_use_count, state->local->slot_queue_recycle - state->slot_queue_available, state->stats.slot_stalls, state->stats.data_stalls); vchiq_dump(dump_context, buf, len + 1); vchiq_dump_platform_state(dump_context); vchiq_dump_shared_state(dump_context, state, state->local, "Local"); vchiq_dump_shared_state(dump_context, state, state->remote, "Remote"); vchiq_dump_platform_instances(dump_context); for (i = 0; i < state->unused_service; i++) { VCHIQ_SERVICE_T *service = find_service_by_port(state, i); if (service) { vchiq_dump_service_state(dump_context, service); unlock_service(service); } } } void vchiq_dump_service_state(void *dump_context, VCHIQ_SERVICE_T *service) { char buf[120]; int len; len = snprintf(buf, sizeof(buf), "Service %d: %s (ref %u)", service->localport, srvstate_names[service->srvstate], service->ref_count - 1); /*Don't include the lock just taken*/ if (service->srvstate != VCHIQ_SRVSTATE_FREE) { char remoteport[30]; VCHIQ_SERVICE_QUOTA_T *service_quota = &service->state->service_quotas[service->localport]; int fourcc = service->base.fourcc; int tx_pending, rx_pending; if (service->remoteport != VCHIQ_PORT_FREE) { int len2 = snprintf(remoteport, sizeof(remoteport), "%d", service->remoteport); if (service->public_fourcc != VCHIQ_FOURCC_INVALID) snprintf(remoteport + len2, sizeof(remoteport) - len2, " (client %8x)", service->client_id); } else strcpy(remoteport, "n/a"); len += snprintf(buf + len, sizeof(buf) - len, " '%c%c%c%c' remote %s (msg use %d/%d, slot use %d/%d)", VCHIQ_FOURCC_AS_4CHARS(fourcc), remoteport, service_quota->message_use_count, service_quota->message_quota, service_quota->slot_use_count, service_quota->slot_quota); vchiq_dump(dump_context, buf, len + 1); tx_pending = service->bulk_tx.local_insert - service->bulk_tx.remote_insert; rx_pending = service->bulk_rx.local_insert - service->bulk_rx.remote_insert; len = snprintf(buf, sizeof(buf), " Bulk: tx_pending=%d (size %d)," " rx_pending=%d (size %d)", tx_pending, tx_pending ? service->bulk_tx.bulks[ BULK_INDEX(service->bulk_tx.remove)].size : 0, rx_pending, rx_pending ? service->bulk_rx.bulks[ BULK_INDEX(service->bulk_rx.remove)].size : 0); if (VCHIQ_ENABLE_STATS) { vchiq_dump(dump_context, buf, len + 1); len = snprintf(buf, sizeof(buf), " Ctrl: tx_count=%d, tx_bytes=%ju, " "rx_count=%d, rx_bytes=%ju", service->stats.ctrl_tx_count, (uintmax_t) service->stats.ctrl_tx_bytes, service->stats.ctrl_rx_count, (uintmax_t) service->stats.ctrl_rx_bytes); vchiq_dump(dump_context, buf, len + 1); len = snprintf(buf, sizeof(buf), " Bulk: tx_count=%d, tx_bytes=%ju, " "rx_count=%d, rx_bytes=%ju", service->stats.bulk_tx_count, (uintmax_t) service->stats.bulk_tx_bytes, service->stats.bulk_rx_count, (uintmax_t) service->stats.bulk_rx_bytes); vchiq_dump(dump_context, buf, len + 1); len = snprintf(buf, sizeof(buf), " %d quota stalls, %d slot stalls, " "%d bulk stalls, %d aborted, %d errors", service->stats.quota_stalls, service->stats.slot_stalls, service->stats.bulk_stalls, service->stats.bulk_aborted_count, service->stats.error_count); } } vchiq_dump(dump_context, buf, len + 1); if (service->srvstate != VCHIQ_SRVSTATE_FREE) vchiq_dump_platform_service_state(dump_context, service); } void vchiq_loud_error_header(void) { vchiq_log_error(vchiq_core_log_level, "============================================================" "================"); vchiq_log_error(vchiq_core_log_level, "============================================================" "================"); vchiq_log_error(vchiq_core_log_level, "====="); } void vchiq_loud_error_footer(void) { vchiq_log_error(vchiq_core_log_level, "====="); vchiq_log_error(vchiq_core_log_level, "============================================================" "================"); vchiq_log_error(vchiq_core_log_level, "============================================================" "================"); } VCHIQ_STATUS_T vchiq_send_remote_use(VCHIQ_STATE_T *state) { VCHIQ_STATUS_T status = VCHIQ_RETRY; if (state->conn_state != VCHIQ_CONNSTATE_DISCONNECTED) status = queue_message(state, NULL, VCHIQ_MAKE_MSG(VCHIQ_MSG_REMOTE_USE, 0, 0), NULL, 0, 0, 0); return status; } VCHIQ_STATUS_T vchiq_send_remote_release(VCHIQ_STATE_T *state) { VCHIQ_STATUS_T status = VCHIQ_RETRY; if (state->conn_state != VCHIQ_CONNSTATE_DISCONNECTED) status = queue_message(state, NULL, VCHIQ_MAKE_MSG(VCHIQ_MSG_REMOTE_RELEASE, 0, 0), NULL, 0, 0, 0); return status; } VCHIQ_STATUS_T vchiq_send_remote_use_active(VCHIQ_STATE_T *state) { VCHIQ_STATUS_T status = VCHIQ_RETRY; if (state->conn_state != VCHIQ_CONNSTATE_DISCONNECTED) status = queue_message(state, NULL, VCHIQ_MAKE_MSG(VCHIQ_MSG_REMOTE_USE_ACTIVE, 0, 0), NULL, 0, 0, 0); return status; } void vchiq_log_dump_mem(const char *label, uint32_t addr, const void *voidMem, size_t numBytes) { const uint8_t *mem = (const uint8_t *)voidMem; size_t offset; char lineBuf[100]; char *s; while (numBytes > 0) { s = lineBuf; for (offset = 0; offset < 16; offset++) { if (offset < numBytes) s += snprintf(s, 4, "%02x ", mem[offset]); else s += snprintf(s, 4, " "); } for (offset = 0; offset < 16; offset++) { if (offset < numBytes) { uint8_t ch = mem[offset]; if ((ch < ' ') || (ch > '~')) ch = '.'; *s++ = (char)ch; } } *s++ = '\0'; if ((label != NULL) && (*label != '\0')) vchiq_log_trace(VCHIQ_LOG_TRACE, "%s: %08x: %s", label, addr, lineBuf); else vchiq_log_trace(VCHIQ_LOG_TRACE, "%08x: %s", addr, lineBuf); addr += 16; mem += 16; if (numBytes > 16) numBytes -= 16; else numBytes = 0; } } diff --git a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_core.h b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_core.h index 38ede407f4f4..4e3f41203bc4 100644 --- a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_core.h +++ b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_core.h @@ -1,716 +1,725 @@ /** * Copyright (c) 2010-2012 Broadcom. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the above-listed copyright holders may not be used * to endorse or promote products derived from this software without * specific prior written permission. * * ALTERNATIVELY, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2, as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef VCHIQ_CORE_H #define VCHIQ_CORE_H #include #include #include "vchiq_cfg.h" #include "vchiq.h" /* Run time control of log level, based on KERN_XXX level. */ #ifndef VCHIQ_LOG_DEFAULT #define VCHIQ_LOG_DEFAULT 4 #endif #define VCHIQ_LOG_ERROR 3 #define VCHIQ_LOG_WARNING 4 #define VCHIQ_LOG_INFO 6 #define VCHIQ_LOG_TRACE 7 #define VCHIQ_LOG_PREFIX "vchiq: " #ifndef vchiq_log_error #define vchiq_log_error(cat, fmt, ...) \ do { if (cat >= VCHIQ_LOG_ERROR) \ printf(VCHIQ_LOG_PREFIX fmt "\n", ##__VA_ARGS__); } while (0) #endif #ifndef vchiq_log_warning #define vchiq_log_warning(cat, fmt, ...) \ do { if (cat >= VCHIQ_LOG_WARNING) \ printf(VCHIQ_LOG_PREFIX fmt "\n", ##__VA_ARGS__); } while (0) #endif #ifndef vchiq_log_info #define vchiq_log_info(cat, fmt, ...) \ do { if (cat >= VCHIQ_LOG_INFO) \ printf(VCHIQ_LOG_PREFIX fmt "\n", ##__VA_ARGS__); } while (0) #endif #ifndef vchiq_log_trace #define vchiq_log_trace(cat, fmt, ...) \ do { if (cat >= VCHIQ_LOG_TRACE) \ printf(VCHIQ_LOG_PREFIX fmt "\n", ##__VA_ARGS__); } while (0) #endif #define vchiq_loud_error(...) \ vchiq_log_error(vchiq_core_log_level, "===== " __VA_ARGS__) #ifndef vchiq_static_assert #define vchiq_static_assert(cond) __attribute__((unused)) \ extern int vchiq_static_assert[(cond) ? 1 : -1] #endif #define IS_POW2(x) (x && ((x & (x - 1)) == 0)) /* Ensure that the slot size and maximum number of slots are powers of 2 */ vchiq_static_assert(IS_POW2(VCHIQ_SLOT_SIZE)); vchiq_static_assert(IS_POW2(VCHIQ_MAX_SLOTS)); vchiq_static_assert(IS_POW2(VCHIQ_MAX_SLOTS_PER_SIDE)); #define VCHIQ_SLOT_MASK (VCHIQ_SLOT_SIZE - 1) #define VCHIQ_SLOT_QUEUE_MASK (VCHIQ_MAX_SLOTS_PER_SIDE - 1) #define VCHIQ_SLOT_ZERO_SLOTS ((sizeof(VCHIQ_SLOT_ZERO_T) + \ VCHIQ_SLOT_SIZE - 1) / VCHIQ_SLOT_SIZE) #define VCHIQ_MSG_PADDING 0 /* - */ #define VCHIQ_MSG_CONNECT 1 /* - */ #define VCHIQ_MSG_OPEN 2 /* + (srcport, -), fourcc, client_id */ #define VCHIQ_MSG_OPENACK 3 /* + (srcport, dstport) */ #define VCHIQ_MSG_CLOSE 4 /* + (srcport, dstport) */ #define VCHIQ_MSG_DATA 5 /* + (srcport, dstport) */ #define VCHIQ_MSG_BULK_RX 6 /* + (srcport, dstport), data, size */ #define VCHIQ_MSG_BULK_TX 7 /* + (srcport, dstport), data, size */ #define VCHIQ_MSG_BULK_RX_DONE 8 /* + (srcport, dstport), actual */ #define VCHIQ_MSG_BULK_TX_DONE 9 /* + (srcport, dstport), actual */ #define VCHIQ_MSG_PAUSE 10 /* - */ #define VCHIQ_MSG_RESUME 11 /* - */ #define VCHIQ_MSG_REMOTE_USE 12 /* - */ #define VCHIQ_MSG_REMOTE_RELEASE 13 /* - */ #define VCHIQ_MSG_REMOTE_USE_ACTIVE 14 /* - */ #define VCHIQ_PORT_MAX (VCHIQ_MAX_SERVICES - 1) #define VCHIQ_PORT_FREE 0x1000 #define VCHIQ_PORT_IS_VALID(port) (port < VCHIQ_PORT_FREE) #define VCHIQ_MAKE_MSG(type, srcport, dstport) \ ((type<<24) | (srcport<<12) | (dstport<<0)) #define VCHIQ_MSG_TYPE(msgid) ((unsigned int)msgid >> 24) #define VCHIQ_MSG_SRCPORT(msgid) \ (unsigned short)(((unsigned int)msgid >> 12) & 0xfff) #define VCHIQ_MSG_DSTPORT(msgid) \ ((unsigned short)msgid & 0xfff) #define VCHIQ_FOURCC_AS_4CHARS(fourcc) \ ((fourcc) >> 24) & 0xff, \ ((fourcc) >> 16) & 0xff, \ ((fourcc) >> 8) & 0xff, \ (fourcc) & 0xff /* Ensure the fields are wide enough */ vchiq_static_assert(VCHIQ_MSG_SRCPORT(VCHIQ_MAKE_MSG(0, 0, VCHIQ_PORT_MAX)) == 0); vchiq_static_assert(VCHIQ_MSG_TYPE(VCHIQ_MAKE_MSG(0, VCHIQ_PORT_MAX, 0)) == 0); vchiq_static_assert((unsigned int)VCHIQ_PORT_MAX < (unsigned int)VCHIQ_PORT_FREE); #define VCHIQ_MSGID_PADDING VCHIQ_MAKE_MSG(VCHIQ_MSG_PADDING, 0, 0) #define VCHIQ_MSGID_CLAIMED 0x40000000 #define VCHIQ_FOURCC_INVALID 0x00000000 #define VCHIQ_FOURCC_IS_LEGAL(fourcc) (fourcc != VCHIQ_FOURCC_INVALID) #define VCHIQ_BULK_ACTUAL_ABORTED -1 typedef uint32_t VCHI_BITSET_T; vchiq_static_assert((sizeof(VCHI_BITSET_T) * 8) == 32); #define VCHI_BITSET_SIZE(b) ((b + 31) >> 5) #define VCHI_BITSET_WORD(b) (b >> 5) #define VCHI_BITSET_BIT(b) (1 << (b & 31)) #define VCHI_BITSET_ZERO(bs) memset(bs, 0, sizeof(bs)) #define VCHI_BITSET_IS_SET(bs, b) (bs[VCHI_BITSET_WORD(b)] & VCHI_BITSET_BIT(b)) #define VCHI_BITSET_SET(bs, b) (bs[VCHI_BITSET_WORD(b)] |= VCHI_BITSET_BIT(b)) #define VCHI_BITSET_CLR(bs, b) (bs[VCHI_BITSET_WORD(b)] &= ~VCHI_BITSET_BIT(b)) #if VCHIQ_ENABLE_STATS #define VCHIQ_STATS_INC(state, stat) (state->stats. stat++) #define VCHIQ_SERVICE_STATS_INC(service, stat) (service->stats. stat++) #define VCHIQ_SERVICE_STATS_ADD(service, stat, addend) \ (service->stats. stat += addend) #else #define VCHIQ_STATS_INC(state, stat) ((void)0) #define VCHIQ_SERVICE_STATS_INC(service, stat) ((void)0) #define VCHIQ_SERVICE_STATS_ADD(service, stat, addend) ((void)0) #endif enum { DEBUG_ENTRIES, #if VCHIQ_ENABLE_DEBUG DEBUG_SLOT_HANDLER_COUNT, DEBUG_SLOT_HANDLER_LINE, DEBUG_PARSE_LINE, DEBUG_PARSE_HEADER, DEBUG_PARSE_MSGID, DEBUG_AWAIT_COMPLETION_LINE, DEBUG_DEQUEUE_MESSAGE_LINE, DEBUG_SERVICE_CALLBACK_LINE, DEBUG_MSG_QUEUE_FULL_COUNT, DEBUG_COMPLETION_QUEUE_FULL_COUNT, #endif DEBUG_MAX }; #if VCHIQ_ENABLE_DEBUG #define DEBUG_INITIALISE(local) int *debug_ptr = (local)->debug; +#if defined(__aarch64__) +#define DEBUG_TRACE(d) \ + do { debug_ptr[DEBUG_ ## d] = __LINE__; dsb(sy); } while (0) +#define DEBUG_VALUE(d, v) \ + do { debug_ptr[DEBUG_ ## d] = (v); dsb(sy); } while (0) +#define DEBUG_COUNT(d) \ + do { debug_ptr[DEBUG_ ## d]++; dsb(sy); } while (0) +#else #define DEBUG_TRACE(d) \ do { debug_ptr[DEBUG_ ## d] = __LINE__; dsb(); } while (0) #define DEBUG_VALUE(d, v) \ do { debug_ptr[DEBUG_ ## d] = (v); dsb(); } while (0) #define DEBUG_COUNT(d) \ do { debug_ptr[DEBUG_ ## d]++; dsb(); } while (0) +#endif #else /* VCHIQ_ENABLE_DEBUG */ #define DEBUG_INITIALISE(local) #define DEBUG_TRACE(d) #define DEBUG_VALUE(d, v) #define DEBUG_COUNT(d) #endif /* VCHIQ_ENABLE_DEBUG */ typedef enum { VCHIQ_CONNSTATE_DISCONNECTED, VCHIQ_CONNSTATE_CONNECTING, VCHIQ_CONNSTATE_CONNECTED, VCHIQ_CONNSTATE_PAUSING, VCHIQ_CONNSTATE_PAUSE_SENT, VCHIQ_CONNSTATE_PAUSED, VCHIQ_CONNSTATE_RESUMING, VCHIQ_CONNSTATE_PAUSE_TIMEOUT, VCHIQ_CONNSTATE_RESUME_TIMEOUT } VCHIQ_CONNSTATE_T; enum { VCHIQ_SRVSTATE_FREE, VCHIQ_SRVSTATE_HIDDEN, VCHIQ_SRVSTATE_LISTENING, VCHIQ_SRVSTATE_OPENING, VCHIQ_SRVSTATE_OPEN, VCHIQ_SRVSTATE_OPENSYNC, VCHIQ_SRVSTATE_CLOSESENT, VCHIQ_SRVSTATE_CLOSERECVD, VCHIQ_SRVSTATE_CLOSEWAIT, VCHIQ_SRVSTATE_CLOSED }; enum { VCHIQ_POLL_TERMINATE, VCHIQ_POLL_REMOVE, VCHIQ_POLL_TXNOTIFY, VCHIQ_POLL_RXNOTIFY, VCHIQ_POLL_COUNT }; typedef enum { VCHIQ_BULK_TRANSMIT, VCHIQ_BULK_RECEIVE } VCHIQ_BULK_DIR_T; typedef void (*VCHIQ_USERDATA_TERM_T)(void *userdata); typedef struct vchiq_bulk_struct { short mode; short dir; void *userdata; VCHI_MEM_HANDLE_T handle; void *data; int size; void *remote_data; int remote_size; int actual; } VCHIQ_BULK_T; typedef struct vchiq_bulk_queue_struct { int local_insert; /* Where to insert the next local bulk */ int remote_insert; /* Where to insert the next remote bulk (master) */ int process; /* Bulk to transfer next */ int remote_notify; /* Bulk to notify the remote client of next (mstr) */ int remove; /* Bulk to notify the local client of, and remove, ** next */ VCHIQ_BULK_T bulks[VCHIQ_NUM_SERVICE_BULKS]; } VCHIQ_BULK_QUEUE_T; typedef struct remote_event_struct { int armed; int fired; - struct semaphore *event; + uint32_t event; } REMOTE_EVENT_T; typedef struct opaque_platform_state_t *VCHIQ_PLATFORM_STATE_T; typedef struct vchiq_state_struct VCHIQ_STATE_T; typedef struct vchiq_slot_struct { char data[VCHIQ_SLOT_SIZE]; } VCHIQ_SLOT_T; typedef struct vchiq_slot_info_struct { /* Use two counters rather than one to avoid the need for a mutex. */ short use_count; short release_count; } VCHIQ_SLOT_INFO_T; typedef struct vchiq_service_struct { VCHIQ_SERVICE_BASE_T base; VCHIQ_SERVICE_HANDLE_T handle; unsigned int ref_count; int srvstate; VCHIQ_USERDATA_TERM_T userdata_term; unsigned int localport; unsigned int remoteport; int public_fourcc; int client_id; char auto_close; char sync; char closing; char trace; atomic_t poll_flags; short version; short version_min; short peer_version; VCHIQ_STATE_T *state; VCHIQ_INSTANCE_T instance; int service_use_count; VCHIQ_BULK_QUEUE_T bulk_tx; VCHIQ_BULK_QUEUE_T bulk_rx; struct semaphore remove_event; struct semaphore bulk_remove_event; struct mutex bulk_mutex; struct service_stats_struct { int quota_stalls; int slot_stalls; int bulk_stalls; int error_count; int ctrl_tx_count; int ctrl_rx_count; int bulk_tx_count; int bulk_rx_count; int bulk_aborted_count; uint64_t ctrl_tx_bytes; uint64_t ctrl_rx_bytes; uint64_t bulk_tx_bytes; uint64_t bulk_rx_bytes; } stats; } VCHIQ_SERVICE_T; /* The quota information is outside VCHIQ_SERVICE_T so that it can be statically allocated, since for accounting reasons a service's slot usage is carried over between users of the same port number. */ typedef struct vchiq_service_quota_struct { unsigned short slot_quota; unsigned short slot_use_count; unsigned short message_quota; unsigned short message_use_count; struct semaphore quota_event; int previous_tx_index; } VCHIQ_SERVICE_QUOTA_T; typedef struct vchiq_shared_state_struct { /* A non-zero value here indicates that the content is valid. */ int initialised; /* The first and last (inclusive) slots allocated to the owner. */ int slot_first; int slot_last; /* The slot allocated to synchronous messages from the owner. */ int slot_sync; /* Signalling this event indicates that owner's slot handler thread ** should run. */ REMOTE_EVENT_T trigger; /* Indicates the byte position within the stream where the next message ** will be written. The least significant bits are an index into the ** slot. The next bits are the index of the slot in slot_queue. */ int tx_pos; /* This event should be signalled when a slot is recycled. */ REMOTE_EVENT_T recycle; /* The slot_queue index where the next recycled slot will be written. */ int slot_queue_recycle; /* This event should be signalled when a synchronous message is sent. */ REMOTE_EVENT_T sync_trigger; /* This event should be signalled when a synchronous message has been ** released. */ REMOTE_EVENT_T sync_release; /* A circular buffer of slot indexes. */ int slot_queue[VCHIQ_MAX_SLOTS_PER_SIDE]; /* Debugging state */ int debug[DEBUG_MAX]; } VCHIQ_SHARED_STATE_T; typedef struct vchiq_slot_zero_struct { int magic; short version; short version_min; int slot_zero_size; int slot_size; int max_slots; int max_slots_per_side; int platform_data[2]; VCHIQ_SHARED_STATE_T master; VCHIQ_SHARED_STATE_T slave; VCHIQ_SLOT_INFO_T slots[VCHIQ_MAX_SLOTS]; } VCHIQ_SLOT_ZERO_T; struct vchiq_state_struct { int id; int initialised; VCHIQ_CONNSTATE_T conn_state; int is_master; short version_common; VCHIQ_SHARED_STATE_T *local; VCHIQ_SHARED_STATE_T *remote; VCHIQ_SLOT_T *slot_data; unsigned short default_slot_quota; unsigned short default_message_quota; /* Event indicating connect message received */ struct semaphore connect; /* Mutex protecting services */ struct mutex mutex; VCHIQ_INSTANCE_T *instance; /* Processes incoming messages */ VCHIQ_THREAD_T slot_handler_thread; /* Processes recycled slots */ VCHIQ_THREAD_T recycle_thread; /* Processes synchronous messages */ VCHIQ_THREAD_T sync_thread; /* Local implementation of the trigger remote event */ struct semaphore trigger_event; /* Local implementation of the recycle remote event */ struct semaphore recycle_event; /* Local implementation of the sync trigger remote event */ struct semaphore sync_trigger_event; /* Local implementation of the sync release remote event */ struct semaphore sync_release_event; char *tx_data; char *rx_data; VCHIQ_SLOT_INFO_T *rx_info; struct mutex slot_mutex; struct mutex recycle_mutex; struct mutex sync_mutex; struct mutex bulk_transfer_mutex; /* Indicates the byte position within the stream from where the next ** message will be read. The least significant bits are an index into ** the slot.The next bits are the index of the slot in ** remote->slot_queue. */ int rx_pos; /* A cached copy of local->tx_pos. Only write to local->tx_pos, and read from remote->tx_pos. */ int local_tx_pos; /* The slot_queue index of the slot to become available next. */ int slot_queue_available; /* A flag to indicate if any poll has been requested */ int poll_needed; /* Ths index of the previous slot used for data messages. */ int previous_data_index; /* The number of slots occupied by data messages. */ unsigned short data_use_count; /* The maximum number of slots to be occupied by data messages. */ unsigned short data_quota; /* An array of bit sets indicating which services must be polled. */ atomic_t poll_services[VCHI_BITSET_SIZE(VCHIQ_MAX_SERVICES)]; /* The number of the first unused service */ int unused_service; /* Signalled when a free slot becomes available. */ struct semaphore slot_available_event; struct semaphore slot_remove_event; /* Signalled when a free data slot becomes available. */ struct semaphore data_quota_event; /* Incremented when there are bulk transfers which cannot be processed * whilst paused and must be processed on resume */ int deferred_bulks; struct state_stats_struct { int slot_stalls; int data_stalls; int ctrl_tx_count; int ctrl_rx_count; int error_count; } stats; VCHIQ_SERVICE_T * services[VCHIQ_MAX_SERVICES]; VCHIQ_SERVICE_QUOTA_T service_quotas[VCHIQ_MAX_SERVICES]; VCHIQ_SLOT_INFO_T slot_info[VCHIQ_MAX_SLOTS]; VCHIQ_PLATFORM_STATE_T platform_state; }; struct bulk_waiter { VCHIQ_BULK_T *bulk; struct semaphore event; int actual; }; extern spinlock_t bulk_waiter_spinlock; extern int vchiq_core_log_level; extern int vchiq_core_msg_log_level; extern int vchiq_sync_log_level; extern VCHIQ_STATE_T *vchiq_states[VCHIQ_MAX_STATES]; extern const char * get_conn_state_name(VCHIQ_CONNSTATE_T conn_state); extern VCHIQ_SLOT_ZERO_T * vchiq_init_slots(void *mem_base, int mem_size); extern VCHIQ_STATUS_T vchiq_init_state(VCHIQ_STATE_T *state, VCHIQ_SLOT_ZERO_T *slot_zero, int is_master); extern VCHIQ_STATUS_T vchiq_connect_internal(VCHIQ_STATE_T *state, VCHIQ_INSTANCE_T instance); extern VCHIQ_SERVICE_T * vchiq_add_service_internal(VCHIQ_STATE_T *state, const VCHIQ_SERVICE_PARAMS_T *params, int srvstate, VCHIQ_INSTANCE_T instance, VCHIQ_USERDATA_TERM_T userdata_term); extern VCHIQ_STATUS_T vchiq_open_service_internal(VCHIQ_SERVICE_T *service, int client_id); extern VCHIQ_STATUS_T vchiq_close_service_internal(VCHIQ_SERVICE_T *service, int close_recvd); extern void vchiq_terminate_service_internal(VCHIQ_SERVICE_T *service); extern void vchiq_free_service_internal(VCHIQ_SERVICE_T *service); extern VCHIQ_STATUS_T vchiq_shutdown_internal(VCHIQ_STATE_T *state, VCHIQ_INSTANCE_T instance); extern VCHIQ_STATUS_T vchiq_pause_internal(VCHIQ_STATE_T *state); extern VCHIQ_STATUS_T vchiq_resume_internal(VCHIQ_STATE_T *state); extern void remote_event_pollall(VCHIQ_STATE_T *state); extern VCHIQ_STATUS_T vchiq_bulk_transfer(VCHIQ_SERVICE_HANDLE_T handle, VCHI_MEM_HANDLE_T memhandle, void *offset, int size, void *userdata, VCHIQ_BULK_MODE_T mode, VCHIQ_BULK_DIR_T dir); extern void vchiq_dump_state(void *dump_context, VCHIQ_STATE_T *state); extern void vchiq_dump_service_state(void *dump_context, VCHIQ_SERVICE_T *service); extern void vchiq_loud_error_header(void); extern void vchiq_loud_error_footer(void); extern void request_poll(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service, int poll_type); static inline VCHIQ_SERVICE_T * handle_to_service(VCHIQ_SERVICE_HANDLE_T handle) { VCHIQ_STATE_T *state = vchiq_states[(handle / VCHIQ_MAX_SERVICES) & (VCHIQ_MAX_STATES - 1)]; if (!state) return NULL; return state->services[handle & (VCHIQ_MAX_SERVICES - 1)]; } extern VCHIQ_SERVICE_T * find_service_by_handle(VCHIQ_SERVICE_HANDLE_T handle); extern VCHIQ_SERVICE_T * find_service_by_port(VCHIQ_STATE_T *state, int localport); extern VCHIQ_SERVICE_T * find_service_for_instance(VCHIQ_INSTANCE_T instance, VCHIQ_SERVICE_HANDLE_T handle); extern VCHIQ_SERVICE_T * find_closed_service_for_instance(VCHIQ_INSTANCE_T instance, VCHIQ_SERVICE_HANDLE_T handle); extern VCHIQ_SERVICE_T * next_service_by_instance(VCHIQ_STATE_T *state, VCHIQ_INSTANCE_T instance, int *pidx); extern void lock_service(VCHIQ_SERVICE_T *service); extern void unlock_service(VCHIQ_SERVICE_T *service); /* The following functions are called from vchiq_core, and external ** implementations must be provided. */ extern VCHIQ_STATUS_T vchiq_prepare_bulk_data(VCHIQ_BULK_T *bulk, VCHI_MEM_HANDLE_T memhandle, void *offset, int size, int dir); extern void vchiq_transfer_bulk(VCHIQ_BULK_T *bulk); extern void vchiq_complete_bulk(VCHIQ_BULK_T *bulk); extern VCHIQ_STATUS_T vchiq_copy_from_user(void *dst, const void *src, int size); extern void remote_event_signal(REMOTE_EVENT_T *event); void vchiq_platform_check_suspend(VCHIQ_STATE_T *state); extern void vchiq_platform_paused(VCHIQ_STATE_T *state); extern VCHIQ_STATUS_T vchiq_platform_resume(VCHIQ_STATE_T *state); extern void vchiq_platform_resumed(VCHIQ_STATE_T *state); extern void vchiq_dump(void *dump_context, const char *str, int len); extern void vchiq_dump_platform_state(void *dump_context); extern void vchiq_dump_platform_instances(void *dump_context); extern void vchiq_dump_platform_service_state(void *dump_context, VCHIQ_SERVICE_T *service); extern VCHIQ_STATUS_T vchiq_use_service_internal(VCHIQ_SERVICE_T *service); extern VCHIQ_STATUS_T vchiq_release_service_internal(VCHIQ_SERVICE_T *service); extern void vchiq_on_remote_use(VCHIQ_STATE_T *state); extern void vchiq_on_remote_release(VCHIQ_STATE_T *state); extern VCHIQ_STATUS_T vchiq_platform_init_state(VCHIQ_STATE_T *state); extern VCHIQ_STATUS_T vchiq_check_service(VCHIQ_SERVICE_T *service); extern void vchiq_on_remote_use_active(VCHIQ_STATE_T *state); extern VCHIQ_STATUS_T vchiq_send_remote_use(VCHIQ_STATE_T *state); extern VCHIQ_STATUS_T vchiq_send_remote_release(VCHIQ_STATE_T *state); extern VCHIQ_STATUS_T vchiq_send_remote_use_active(VCHIQ_STATE_T *state); extern void vchiq_platform_conn_state_changed(VCHIQ_STATE_T *state, VCHIQ_CONNSTATE_T oldstate, VCHIQ_CONNSTATE_T newstate); extern void vchiq_platform_handle_timeout(VCHIQ_STATE_T *state); extern void vchiq_set_conn_state(VCHIQ_STATE_T *state, VCHIQ_CONNSTATE_T newstate); extern void vchiq_log_dump_mem(const char *label, uint32_t addr, const void *voidMem, size_t numBytes); extern void vchiq_core_initialize(void); #endif diff --git a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_kmod.c b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_kmod.c index 190b6d16781e..9fcc0e7c2051 100644 --- a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_kmod.c +++ b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_kmod.c @@ -1,239 +1,297 @@ /*- * Copyright (c) 2012-2015 Oleksandr Tymoshenko * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +/* XXXMDC Is this necessary at all? */ +#if defined(__aarch64__) +#else #include +#endif #include "vchiq_arm.h" #include "vchiq_2835.h" #define VCHIQ_LOCK do { \ mtx_lock(&bcm_vchiq_sc->lock); \ } while(0) #define VCHIQ_UNLOCK do { \ mtx_unlock(&bcm_vchiq_sc->lock); \ } while(0) #ifdef DEBUG #define dprintf(fmt, args...) printf(fmt, ##args) #else #define dprintf(fmt, args...) #endif struct bcm_vchiq_softc { struct mtx lock; struct resource * mem_res; struct resource * irq_res; void* intr_hl; bus_space_tag_t bst; bus_space_handle_t bsh; int regs_offset; }; static struct bcm_vchiq_softc *bcm_vchiq_sc = NULL; -#define BSD_DTB 1 -#define UPSTREAM_DTB 2 + +#define CONFIG_INVALID 0 +#define CONFIG_VALID 1 << 0 +#define BSD_REG_ADDRS 1 << 1 +#define LONG_BULK_SPACE 1 << 2 + +/* + * Also controls the use of the standard VC address offset for bulk data DMA + * (normal bulks use that offset; bulks for long address spaces use physical + * page addresses) + */ +extern unsigned int g_long_bulk_space; + + +/* + * XXXMDC + * The man page for ofw_bus_is_compatible describes ``features'' + * as ``can be used''. Here we use understand them as ``must be used'' + */ + static struct ofw_compat_data compat_data[] = { - {"broadcom,bcm2835-vchiq", BSD_DTB}, - {"brcm,bcm2835-vchiq", UPSTREAM_DTB}, - {"brcm,bcm2711-vchiq", UPSTREAM_DTB}, - {NULL, 0} + {"broadcom,bcm2835-vchiq", BSD_REG_ADDRS | CONFIG_VALID}, + {"brcm,bcm2835-vchiq", CONFIG_VALID}, + {"brcm,bcm2711-vchiq", LONG_BULK_SPACE | CONFIG_VALID}, + {NULL, CONFIG_INVALID} }; #define vchiq_read_4(reg) \ bus_space_read_4(bcm_vchiq_sc->bst, bcm_vchiq_sc->bsh, (reg) + \ bcm_vchiq_sc->regs_offset) #define vchiq_write_4(reg, val) \ bus_space_write_4(bcm_vchiq_sc->bst, bcm_vchiq_sc->bsh, (reg) + \ bcm_vchiq_sc->regs_offset, val) /* * Extern functions */ void vchiq_exit(void); int vchiq_init(void); extern VCHIQ_STATE_T g_state; extern int g_cache_line_size; static void bcm_vchiq_intr(void *arg) { VCHIQ_STATE_T *state = &g_state; unsigned int status; /* Read (and clear) the doorbell */ status = vchiq_read_4(0x40); if (status & 0x4) { /* Was the doorbell rung? */ remote_event_pollall(state); } } void remote_event_signal(REMOTE_EVENT_T *event) { - event->fired = 1; + wmb(); + + event->fired = 1; /* The test on the next line also ensures the write on the previous line has completed */ + /* UPDATE: not on arm64, it would seem... */ +#if defined(__aarch64__) + dsb(sy); +#endif if (event->armed) { /* trigger vc interrupt */ +#if defined(__aarch64__) + dsb(sy); +#else dsb(); +#endif vchiq_write_4(0x48, 0); } } static int bcm_vchiq_probe(device_t dev) { - if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 0) + if ((ofw_bus_search_compatible(dev, compat_data)->ocd_data & CONFIG_VALID) == 0) return (ENXIO); device_set_desc(dev, "BCM2835 VCHIQ"); return (BUS_PROBE_DEFAULT); } +/* debug_sysctl */ +extern int vchiq_core_log_level; +extern int vchiq_arm_log_level; + static int bcm_vchiq_attach(device_t dev) { struct bcm_vchiq_softc *sc = device_get_softc(dev); phandle_t node; pcell_t cell; int rid = 0; if (bcm_vchiq_sc != NULL) return (EINVAL); sc->mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE); if (sc->mem_res == NULL) { device_printf(dev, "could not allocate memory resource\n"); return (ENXIO); } sc->bst = rman_get_bustag(sc->mem_res); sc->bsh = rman_get_bushandle(sc->mem_res); rid = 0; sc->irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE); if (sc->irq_res == NULL) { device_printf(dev, "could not allocate interrupt resource\n"); return (ENXIO); } - if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == UPSTREAM_DTB) + uintptr_t dev_compat_d = ofw_bus_search_compatible(dev, compat_data)->ocd_data; + /* XXXMDC: shouldn't happen (checked for in probe)--but, for symmetry */ + if ((dev_compat_d & CONFIG_VALID) == 0){ + device_printf(dev, "attempting to attach using invalid config.\n"); + bus_release_resource(dev, SYS_RES_IRQ, rid, sc->irq_res); + return (EINVAL); + } + if ((dev_compat_d & BSD_REG_ADDRS) == 0) sc->regs_offset = -0x40; + if(dev_compat_d & LONG_BULK_SPACE) + g_long_bulk_space = 1; node = ofw_bus_get_node(dev); if ((OF_getencprop(node, "cache-line-size", &cell, sizeof(cell))) > 0) g_cache_line_size = cell; vchiq_core_initialize(); + + /* debug_sysctl */ + struct sysctl_ctx_list *ctx_l = device_get_sysctl_ctx(dev); + struct sysctl_oid *tree_node = device_get_sysctl_tree(dev); + struct sysctl_oid_list *tree = SYSCTL_CHILDREN(tree_node); + SYSCTL_ADD_INT( + ctx_l, tree, OID_AUTO, "log", CTLFLAG_RW, + &vchiq_core_log_level, vchiq_core_log_level, "log level" + ); + SYSCTL_ADD_INT( + ctx_l, tree, OID_AUTO, "arm_log", CTLFLAG_RW, + &vchiq_arm_log_level, vchiq_arm_log_level, "arm log level" + ); /* Setup and enable the timer */ if (bus_setup_intr(dev, sc->irq_res, INTR_TYPE_MISC | INTR_MPSAFE, NULL, bcm_vchiq_intr, sc, &sc->intr_hl) != 0) { bus_release_resource(dev, SYS_RES_IRQ, rid, sc->irq_res); device_printf(dev, "Unable to setup the clock irq handler.\n"); return (ENXIO); } mtx_init(&sc->lock, "vchiq", 0, MTX_DEF); bcm_vchiq_sc = sc; vchiq_init(); bus_identify_children(dev); bus_attach_children(dev); return (0); } static int bcm_vchiq_detach(device_t dev) { struct bcm_vchiq_softc *sc = device_get_softc(dev); vchiq_exit(); if (sc->intr_hl) bus_teardown_intr(dev, sc->irq_res, sc->intr_hl); bus_release_resource(dev, SYS_RES_IRQ, 0, sc->irq_res); bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->mem_res); mtx_destroy(&sc->lock); return (0); } static device_method_t bcm_vchiq_methods[] = { DEVMETHOD(device_probe, bcm_vchiq_probe), DEVMETHOD(device_attach, bcm_vchiq_attach), DEVMETHOD(device_detach, bcm_vchiq_detach), /* Bus interface */ DEVMETHOD(bus_add_child, bus_generic_add_child), { 0, 0 } }; static driver_t bcm_vchiq_driver = { "vchiq", bcm_vchiq_methods, sizeof(struct bcm_vchiq_softc), }; DRIVER_MODULE(vchiq, simplebus, bcm_vchiq_driver, 0, 0); MODULE_VERSION(vchiq, 1); diff --git a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_pagelist.h b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_pagelist.h index 72c362464cc2..d1cb9f1e1658 100644 --- a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_pagelist.h +++ b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_pagelist.h @@ -1,52 +1,52 @@ /** * Copyright (c) 2010-2012 Broadcom. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the above-listed copyright holders may not be used * to endorse or promote products derived from this software without * specific prior written permission. * * ALTERNATIVELY, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2, as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef VCHIQ_PAGELIST_H #define VCHIQ_PAGELIST_H #ifndef PAGE_SIZE #define PAGE_SIZE 4096 #endif #define PAGELIST_WRITE 0 #define PAGELIST_READ 1 #define PAGELIST_READ_WITH_FRAGMENTS 2 typedef struct pagelist_struct { - unsigned long length; - unsigned short type; - unsigned short offset; - unsigned long addrs[1]; /* N.B. 12 LSBs hold the number of following + uint32_t length; + uint16_t type; + uint16_t offset; + uint32_t addrs[1]; /* N.B. 12 LSBs hold the number of following pages at consecutive addresses. */ } PAGELIST_T; #endif /* VCHIQ_PAGELIST_H */ diff --git a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_shim.c b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_shim.c index cc8ef2e071f8..f33c545cea45 100644 --- a/sys/contrib/vchiq/interface/vchiq_arm/vchiq_shim.c +++ b/sys/contrib/vchiq/interface/vchiq_arm/vchiq_shim.c @@ -1,860 +1,860 @@ /** * Copyright (c) 2010-2012 Broadcom. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the above-listed copyright holders may not be used * to endorse or promote products derived from this software without * specific prior written permission. * * ALTERNATIVELY, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2, as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include "interface/vchi/vchi.h" #include "vchiq.h" #include "vchiq_core.h" #include "vchiq_util.h" #define vchiq_status_to_vchi(status) ((int32_t)status) typedef struct { VCHIQ_SERVICE_HANDLE_T handle; VCHIU_QUEUE_T queue; VCHI_CALLBACK_T callback; void *callback_param; } SHIM_SERVICE_T; /* ---------------------------------------------------------------------- * return pointer to the mphi message driver function table * -------------------------------------------------------------------- */ const VCHI_MESSAGE_DRIVER_T * vchi_mphi_message_driver_func_table(void) { return NULL; } /* ---------------------------------------------------------------------- * return a pointer to the 'single' connection driver fops * -------------------------------------------------------------------- */ const VCHI_CONNECTION_API_T * single_get_func_table(void) { return NULL; } VCHI_CONNECTION_T *vchi_create_connection( const VCHI_CONNECTION_API_T *function_table, const VCHI_MESSAGE_DRIVER_T *low_level) { (void)function_table; (void)low_level; return NULL; } /*********************************************************** * Name: vchi_msg_peek * * Arguments: const VCHI_SERVICE_HANDLE_T handle, * void **data, * uint32_t *msg_size, * VCHI_FLAGS_T flags * * Description: Routine to return a pointer to the current message (to allow in * place processing). The message can be removed using * vchi_msg_remove when you're finished * * Returns: int32_t - success == 0 * ***********************************************************/ int32_t vchi_msg_peek(VCHI_SERVICE_HANDLE_T handle, void **data, uint32_t *msg_size, VCHI_FLAGS_T flags) { SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; VCHIQ_HEADER_T *header; WARN_ON((flags != VCHI_FLAGS_NONE) && (flags != VCHI_FLAGS_BLOCK_UNTIL_OP_COMPLETE)); if (flags == VCHI_FLAGS_NONE) if (vchiu_queue_is_empty(&service->queue)) return -1; header = vchiu_queue_peek(&service->queue); *data = header->data; *msg_size = header->size; return 0; } EXPORT_SYMBOL(vchi_msg_peek); /*********************************************************** * Name: vchi_msg_remove * * Arguments: const VCHI_SERVICE_HANDLE_T handle, * * Description: Routine to remove a message (after it has been read with * vchi_msg_peek) * * Returns: int32_t - success == 0 * ***********************************************************/ int32_t vchi_msg_remove(VCHI_SERVICE_HANDLE_T handle) { SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; VCHIQ_HEADER_T *header; header = vchiu_queue_pop(&service->queue); vchiq_release_message(service->handle, header); return 0; } EXPORT_SYMBOL(vchi_msg_remove); /*********************************************************** * Name: vchi_msg_queue * * Arguments: VCHI_SERVICE_HANDLE_T handle, * const void *data, * uint32_t data_size, * VCHI_FLAGS_T flags, * void *msg_handle, * * Description: Thin wrapper to queue a message onto a connection * * Returns: int32_t - success == 0 * ***********************************************************/ int32_t vchi_msg_queue(VCHI_SERVICE_HANDLE_T handle, const void *data, uint32_t data_size, VCHI_FLAGS_T flags, void *msg_handle) { SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; VCHIQ_ELEMENT_T element = {data, data_size}; VCHIQ_STATUS_T status; (void)msg_handle; WARN_ON(flags != VCHI_FLAGS_BLOCK_UNTIL_QUEUED); status = vchiq_queue_message(service->handle, &element, 1); /* vchiq_queue_message() may return VCHIQ_RETRY, so we need to ** implement a retry mechanism since this function is supposed ** to block until queued */ while (status == VCHIQ_RETRY) { msleep(1); status = vchiq_queue_message(service->handle, &element, 1); } return vchiq_status_to_vchi(status); } EXPORT_SYMBOL(vchi_msg_queue); /*********************************************************** * Name: vchi_bulk_queue_receive * * Arguments: VCHI_BULK_HANDLE_T handle, * void *data_dst, * const uint32_t data_size, * VCHI_FLAGS_T flags * void *bulk_handle * * Description: Routine to setup a rcv buffer * * Returns: int32_t - success == 0 * ***********************************************************/ int32_t vchi_bulk_queue_receive(VCHI_SERVICE_HANDLE_T handle, void *data_dst, uint32_t data_size, VCHI_FLAGS_T flags, void *bulk_handle) { SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; VCHIQ_BULK_MODE_T mode; VCHIQ_STATUS_T status; switch ((int)flags) { case VCHI_FLAGS_CALLBACK_WHEN_OP_COMPLETE | VCHI_FLAGS_BLOCK_UNTIL_QUEUED: WARN_ON(!service->callback); mode = VCHIQ_BULK_MODE_CALLBACK; break; case VCHI_FLAGS_BLOCK_UNTIL_OP_COMPLETE: mode = VCHIQ_BULK_MODE_BLOCKING; break; case VCHI_FLAGS_BLOCK_UNTIL_QUEUED: case VCHI_FLAGS_NONE: mode = VCHIQ_BULK_MODE_NOCALLBACK; break; default: WARN(1, "unsupported message\n"); return vchiq_status_to_vchi(VCHIQ_ERROR); } status = vchiq_bulk_receive(service->handle, data_dst, data_size, bulk_handle, mode); /* vchiq_bulk_receive() may return VCHIQ_RETRY, so we need to ** implement a retry mechanism since this function is supposed ** to block until queued */ while (status == VCHIQ_RETRY) { msleep(1); status = vchiq_bulk_receive(service->handle, data_dst, data_size, bulk_handle, mode); } return vchiq_status_to_vchi(status); } EXPORT_SYMBOL(vchi_bulk_queue_receive); /*********************************************************** * Name: vchi_bulk_queue_transmit * * Arguments: VCHI_BULK_HANDLE_T handle, * void *data_src, * uint32_t data_size, * VCHI_FLAGS_T flags, * void *bulk_handle * * Description: Routine to transmit some data * * Returns: int32_t - success == 0 * ***********************************************************/ int32_t vchi_bulk_queue_transmit(VCHI_SERVICE_HANDLE_T handle, void *data_src, uint32_t data_size, VCHI_FLAGS_T flags, void *bulk_handle) { SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; VCHIQ_BULK_MODE_T mode; VCHIQ_STATUS_T status; switch ((int)flags) { case VCHI_FLAGS_CALLBACK_WHEN_OP_COMPLETE | VCHI_FLAGS_BLOCK_UNTIL_QUEUED: WARN_ON(!service->callback); mode = VCHIQ_BULK_MODE_CALLBACK; break; case VCHI_FLAGS_BLOCK_UNTIL_DATA_READ: case VCHI_FLAGS_BLOCK_UNTIL_OP_COMPLETE: mode = VCHIQ_BULK_MODE_BLOCKING; break; case VCHI_FLAGS_BLOCK_UNTIL_QUEUED: case VCHI_FLAGS_NONE: mode = VCHIQ_BULK_MODE_NOCALLBACK; break; default: WARN(1, "unsupported message\n"); return vchiq_status_to_vchi(VCHIQ_ERROR); } status = vchiq_bulk_transmit(service->handle, data_src, data_size, bulk_handle, mode); /* vchiq_bulk_transmit() may return VCHIQ_RETRY, so we need to ** implement a retry mechanism since this function is supposed ** to block until queued */ while (status == VCHIQ_RETRY) { msleep(1); status = vchiq_bulk_transmit(service->handle, data_src, data_size, bulk_handle, mode); } return vchiq_status_to_vchi(status); } EXPORT_SYMBOL(vchi_bulk_queue_transmit); /*********************************************************** * Name: vchi_msg_dequeue * * Arguments: VCHI_SERVICE_HANDLE_T handle, * void *data, * uint32_t max_data_size_to_read, * uint32_t *actual_msg_size * VCHI_FLAGS_T flags * * Description: Routine to dequeue a message into the supplied buffer * * Returns: int32_t - success == 0 * ***********************************************************/ int32_t vchi_msg_dequeue(VCHI_SERVICE_HANDLE_T handle, void *data, uint32_t max_data_size_to_read, uint32_t *actual_msg_size, VCHI_FLAGS_T flags) { SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; VCHIQ_HEADER_T *header; WARN_ON((flags != VCHI_FLAGS_NONE) && (flags != VCHI_FLAGS_BLOCK_UNTIL_OP_COMPLETE)); if (flags == VCHI_FLAGS_NONE) if (vchiu_queue_is_empty(&service->queue)) return -1; header = vchiu_queue_pop(&service->queue); memcpy(data, header->data, header->size < max_data_size_to_read ? header->size : max_data_size_to_read); *actual_msg_size = header->size; vchiq_release_message(service->handle, header); return 0; } EXPORT_SYMBOL(vchi_msg_dequeue); /*********************************************************** * Name: vchi_msg_queuev * * Arguments: VCHI_SERVICE_HANDLE_T handle, * VCHI_MSG_VECTOR_T *vector, * uint32_t count, * VCHI_FLAGS_T flags, * void *msg_handle * * Description: Thin wrapper to queue a message onto a connection * * Returns: int32_t - success == 0 * ***********************************************************/ vchiq_static_assert(sizeof(VCHI_MSG_VECTOR_T) == sizeof(VCHIQ_ELEMENT_T)); vchiq_static_assert(offsetof(VCHI_MSG_VECTOR_T, vec_base) == offsetof(VCHIQ_ELEMENT_T, data)); vchiq_static_assert(offsetof(VCHI_MSG_VECTOR_T, vec_len) == offsetof(VCHIQ_ELEMENT_T, size)); int32_t vchi_msg_queuev(VCHI_SERVICE_HANDLE_T handle, VCHI_MSG_VECTOR_T *vector, uint32_t count, VCHI_FLAGS_T flags, void *msg_handle) { SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; (void)msg_handle; WARN_ON(flags != VCHI_FLAGS_BLOCK_UNTIL_QUEUED); return vchiq_status_to_vchi(vchiq_queue_message(service->handle, (const VCHIQ_ELEMENT_T *)vector, count)); } EXPORT_SYMBOL(vchi_msg_queuev); /*********************************************************** * Name: vchi_held_msg_release * * Arguments: VCHI_HELD_MSG_T *message * * Description: Routine to release a held message (after it has been read with * vchi_msg_hold) * * Returns: int32_t - success == 0 * ***********************************************************/ int32_t vchi_held_msg_release(VCHI_HELD_MSG_T *message) { - vchiq_release_message((VCHIQ_SERVICE_HANDLE_T)message->service, + vchiq_release_message((VCHIQ_SERVICE_HANDLE_T)(size_t)message->service, (VCHIQ_HEADER_T *)message->message); return 0; } EXPORT_SYMBOL(vchi_held_msg_release); /*********************************************************** * Name: vchi_msg_hold * * Arguments: VCHI_SERVICE_HANDLE_T handle, * void **data, * uint32_t *msg_size, * VCHI_FLAGS_T flags, * VCHI_HELD_MSG_T *message_handle * * Description: Routine to return a pointer to the current message (to allow * in place processing). The message is dequeued - don't forget * to release the message using vchi_held_msg_release when you're * finished. * * Returns: int32_t - success == 0 * ***********************************************************/ int32_t vchi_msg_hold(VCHI_SERVICE_HANDLE_T handle, void **data, uint32_t *msg_size, VCHI_FLAGS_T flags, VCHI_HELD_MSG_T *message_handle) { SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; VCHIQ_HEADER_T *header; WARN_ON((flags != VCHI_FLAGS_NONE) && (flags != VCHI_FLAGS_BLOCK_UNTIL_OP_COMPLETE)); if (flags == VCHI_FLAGS_NONE) if (vchiu_queue_is_empty(&service->queue)) return -1; header = vchiu_queue_pop(&service->queue); *data = header->data; *msg_size = header->size; message_handle->service = - (struct opaque_vchi_service_t *)service->handle; + (struct opaque_vchi_service_t *)(unsigned long)service->handle; message_handle->message = header; return 0; } EXPORT_SYMBOL(vchi_msg_hold); /*********************************************************** * Name: vchi_initialise * * Arguments: VCHI_INSTANCE_T *instance_handle * * Description: Initialises the hardware but does not transmit anything * When run as a Host App this will be called twice hence the need * to malloc the state information * * Returns: 0 if successful, failure otherwise * ***********************************************************/ int32_t vchi_initialise(VCHI_INSTANCE_T *instance_handle) { VCHIQ_INSTANCE_T instance; VCHIQ_STATUS_T status; status = vchiq_initialise(&instance); *instance_handle = (VCHI_INSTANCE_T)instance; return vchiq_status_to_vchi(status); } EXPORT_SYMBOL(vchi_initialise); /*********************************************************** * Name: vchi_connect * * Arguments: VCHI_CONNECTION_T **connections * const uint32_t num_connections * VCHI_INSTANCE_T instance_handle) * * Description: Starts the command service on each connection, * causing INIT messages to be pinged back and forth * * Returns: 0 if successful, failure otherwise * ***********************************************************/ int32_t vchi_connect(VCHI_CONNECTION_T **connections, const uint32_t num_connections, VCHI_INSTANCE_T instance_handle) { VCHIQ_INSTANCE_T instance = (VCHIQ_INSTANCE_T)instance_handle; (void)connections; (void)num_connections; return vchiq_connect(instance); } EXPORT_SYMBOL(vchi_connect); /*********************************************************** * Name: vchi_disconnect * * Arguments: VCHI_INSTANCE_T instance_handle * * Description: Stops the command service on each connection, * causing DE-INIT messages to be pinged back and forth * * Returns: 0 if successful, failure otherwise * ***********************************************************/ int32_t vchi_disconnect(VCHI_INSTANCE_T instance_handle) { VCHIQ_INSTANCE_T instance = (VCHIQ_INSTANCE_T)instance_handle; return vchiq_status_to_vchi(vchiq_shutdown(instance)); } EXPORT_SYMBOL(vchi_disconnect); /*********************************************************** * Name: vchi_service_open * Name: vchi_service_create * * Arguments: VCHI_INSTANCE_T *instance_handle * SERVICE_CREATION_T *setup, * VCHI_SERVICE_HANDLE_T *handle * * Description: Routine to open a service * * Returns: int32_t - success == 0 * ***********************************************************/ static VCHIQ_STATUS_T shim_callback(VCHIQ_REASON_T reason, VCHIQ_HEADER_T *header, VCHIQ_SERVICE_HANDLE_T handle, void *bulk_user) { SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)VCHIQ_GET_SERVICE_USERDATA(handle); if (!service->callback) goto release; switch (reason) { case VCHIQ_MESSAGE_AVAILABLE: vchiu_queue_push(&service->queue, header); service->callback(service->callback_param, VCHI_CALLBACK_MSG_AVAILABLE, NULL); goto done; break; case VCHIQ_BULK_TRANSMIT_DONE: service->callback(service->callback_param, VCHI_CALLBACK_BULK_SENT, bulk_user); break; case VCHIQ_BULK_RECEIVE_DONE: service->callback(service->callback_param, VCHI_CALLBACK_BULK_RECEIVED, bulk_user); break; case VCHIQ_SERVICE_CLOSED: service->callback(service->callback_param, VCHI_CALLBACK_SERVICE_CLOSED, NULL); break; case VCHIQ_SERVICE_OPENED: /* No equivalent VCHI reason */ break; case VCHIQ_BULK_TRANSMIT_ABORTED: service->callback(service->callback_param, VCHI_CALLBACK_BULK_TRANSMIT_ABORTED, bulk_user); break; case VCHIQ_BULK_RECEIVE_ABORTED: service->callback(service->callback_param, VCHI_CALLBACK_BULK_RECEIVE_ABORTED, bulk_user); break; default: WARN(1, "not supported\n"); break; } release: vchiq_release_message(service->handle, header); done: return VCHIQ_SUCCESS; } static SHIM_SERVICE_T *service_alloc(VCHIQ_INSTANCE_T instance, SERVICE_CREATION_T *setup) { SHIM_SERVICE_T *service = kzalloc(sizeof(SHIM_SERVICE_T), GFP_KERNEL); (void)instance; if (service) { if (vchiu_queue_init(&service->queue, 64)) { service->callback = setup->callback; service->callback_param = setup->callback_param; } else { kfree(service); service = NULL; } } return service; } static void service_free(SHIM_SERVICE_T *service) { if (service) { vchiu_queue_delete(&service->queue); kfree(service); } } int32_t vchi_service_open(VCHI_INSTANCE_T instance_handle, SERVICE_CREATION_T *setup, VCHI_SERVICE_HANDLE_T *handle) { VCHIQ_INSTANCE_T instance = (VCHIQ_INSTANCE_T)instance_handle; SHIM_SERVICE_T *service = service_alloc(instance, setup); *handle = (VCHI_SERVICE_HANDLE_T)service; if (service) { VCHIQ_SERVICE_PARAMS_T params; VCHIQ_STATUS_T status; memset(¶ms, 0, sizeof(params)); params.fourcc = setup->service_id; params.callback = shim_callback; params.userdata = service; params.version = setup->version.version; params.version_min = setup->version.version_min; status = vchiq_open_service(instance, ¶ms, &service->handle); if (status != VCHIQ_SUCCESS) { service_free(service); service = NULL; *handle = NULL; } } return (service != NULL) ? 0 : -1; } EXPORT_SYMBOL(vchi_service_open); int32_t vchi_service_create(VCHI_INSTANCE_T instance_handle, SERVICE_CREATION_T *setup, VCHI_SERVICE_HANDLE_T *handle) { VCHIQ_INSTANCE_T instance = (VCHIQ_INSTANCE_T)instance_handle; SHIM_SERVICE_T *service = service_alloc(instance, setup); *handle = (VCHI_SERVICE_HANDLE_T)service; if (service) { VCHIQ_SERVICE_PARAMS_T params; VCHIQ_STATUS_T status; memset(¶ms, 0, sizeof(params)); params.fourcc = setup->service_id; params.callback = shim_callback; params.userdata = service; params.version = setup->version.version; params.version_min = setup->version.version_min; status = vchiq_add_service(instance, ¶ms, &service->handle); if (status != VCHIQ_SUCCESS) { service_free(service); service = NULL; *handle = NULL; } } return (service != NULL) ? 0 : -1; } EXPORT_SYMBOL(vchi_service_create); int32_t vchi_service_close(const VCHI_SERVICE_HANDLE_T handle) { int32_t ret = -1; SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; if (service) { VCHIQ_STATUS_T status = vchiq_close_service(service->handle); if (status == VCHIQ_SUCCESS) { service_free(service); service = NULL; } ret = vchiq_status_to_vchi(status); } return ret; } EXPORT_SYMBOL(vchi_service_close); int32_t vchi_service_destroy(const VCHI_SERVICE_HANDLE_T handle) { int32_t ret = -1; SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; if (service) { VCHIQ_STATUS_T status = vchiq_remove_service(service->handle); if (status == VCHIQ_SUCCESS) { service_free(service); service = NULL; } ret = vchiq_status_to_vchi(status); } return ret; } EXPORT_SYMBOL(vchi_service_destroy); int32_t vchi_service_set_option(const VCHI_SERVICE_HANDLE_T handle, VCHI_SERVICE_OPTION_T option, int value) { int32_t ret = -1; SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; VCHIQ_SERVICE_OPTION_T vchiq_option; switch (option) { case VCHI_SERVICE_OPTION_TRACE: vchiq_option = VCHIQ_SERVICE_OPTION_TRACE; break; case VCHI_SERVICE_OPTION_SYNCHRONOUS: vchiq_option = VCHIQ_SERVICE_OPTION_SYNCHRONOUS; break; default: service = NULL; break; } if (service) { VCHIQ_STATUS_T status = vchiq_set_service_option(service->handle, vchiq_option, value); ret = vchiq_status_to_vchi(status); } return ret; } EXPORT_SYMBOL(vchi_service_set_option); int32_t vchi_get_peer_version( const VCHI_SERVICE_HANDLE_T handle, short *peer_version ) { int32_t ret = -1; SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; if(service) { VCHIQ_STATUS_T status = vchiq_get_peer_version(service->handle, peer_version); ret = vchiq_status_to_vchi( status ); } return ret; } EXPORT_SYMBOL(vchi_get_peer_version); #ifdef notyet /* ---------------------------------------------------------------------- * read a uint32_t from buffer. * network format is defined to be little endian * -------------------------------------------------------------------- */ uint32_t vchi_readbuf_uint32(const void *_ptr) { const unsigned char *ptr = _ptr; return ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24); } /* ---------------------------------------------------------------------- * write a uint32_t to buffer. * network format is defined to be little endian * -------------------------------------------------------------------- */ void vchi_writebuf_uint32(void *_ptr, uint32_t value) { unsigned char *ptr = _ptr; ptr[0] = (unsigned char)((value >> 0) & 0xFF); ptr[1] = (unsigned char)((value >> 8) & 0xFF); ptr[2] = (unsigned char)((value >> 16) & 0xFF); ptr[3] = (unsigned char)((value >> 24) & 0xFF); } /* ---------------------------------------------------------------------- * read a uint16_t from buffer. * network format is defined to be little endian * -------------------------------------------------------------------- */ uint16_t vchi_readbuf_uint16(const void *_ptr) { const unsigned char *ptr = _ptr; return ptr[0] | (ptr[1] << 8); } /* ---------------------------------------------------------------------- * write a uint16_t into the buffer. * network format is defined to be little endian * -------------------------------------------------------------------- */ void vchi_writebuf_uint16(void *_ptr, uint16_t value) { unsigned char *ptr = _ptr; ptr[0] = (value >> 0) & 0xFF; ptr[1] = (value >> 8) & 0xFF; } #endif /*********************************************************** * Name: vchi_service_use * * Arguments: const VCHI_SERVICE_HANDLE_T handle * * Description: Routine to increment refcount on a service * * Returns: void * ***********************************************************/ int32_t vchi_service_use(const VCHI_SERVICE_HANDLE_T handle) { int32_t ret = -1; SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; if (service) ret = vchiq_status_to_vchi(vchiq_use_service(service->handle)); return ret; } EXPORT_SYMBOL(vchi_service_use); /*********************************************************** * Name: vchi_service_release * * Arguments: const VCHI_SERVICE_HANDLE_T handle * * Description: Routine to decrement refcount on a service * * Returns: void * ***********************************************************/ int32_t vchi_service_release(const VCHI_SERVICE_HANDLE_T handle) { int32_t ret = -1; SHIM_SERVICE_T *service = (SHIM_SERVICE_T *)handle; if (service) ret = vchiq_status_to_vchi( vchiq_release_service(service->handle)); return ret; } EXPORT_SYMBOL(vchi_service_release);