ff853273786c71a17a61ae7e01830e6206598052
[linux-2.6-microblaze.git] / drivers / staging / vc04_services / interface / vchiq_arm / vchiq_core.c
1 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2 /* Copyright (c) 2010-2012 Broadcom. All rights reserved. */
3
4 #include <linux/types.h>
5 #include <linux/completion.h>
6 #include <linux/mutex.h>
7 #include <linux/bitops.h>
8 #include <linux/kthread.h>
9 #include <linux/wait.h>
10 #include <linux/delay.h>
11 #include <linux/slab.h>
12 #include <linux/kref.h>
13 #include <linux/rcupdate.h>
14 #include <linux/sched/signal.h>
15
16 #include "vchiq_core.h"
17
18 #define VCHIQ_SLOT_HANDLER_STACK 8192
19
20 #define HANDLE_STATE_SHIFT 12
21
22 #define SLOT_INFO_FROM_INDEX(state, index) (state->slot_info + (index))
23 #define SLOT_DATA_FROM_INDEX(state, index) (state->slot_data + (index))
24 #define SLOT_INDEX_FROM_DATA(state, data) \
25         (((unsigned int)((char *)data - (char *)state->slot_data)) / \
26         VCHIQ_SLOT_SIZE)
27 #define SLOT_INDEX_FROM_INFO(state, info) \
28         ((unsigned int)(info - state->slot_info))
29 #define SLOT_QUEUE_INDEX_FROM_POS(pos) \
30         ((int)((unsigned int)(pos) / VCHIQ_SLOT_SIZE))
31 #define SLOT_QUEUE_INDEX_FROM_POS_MASKED(pos) \
32         (SLOT_QUEUE_INDEX_FROM_POS(pos) & VCHIQ_SLOT_QUEUE_MASK)
33
34 #define BULK_INDEX(x) (x & (VCHIQ_NUM_SERVICE_BULKS - 1))
35
36 #define SRVTRACE_LEVEL(srv) \
37         (((srv) && (srv)->trace) ? VCHIQ_LOG_TRACE : vchiq_core_msg_log_level)
38 #define SRVTRACE_ENABLED(srv, lev) \
39         (((srv) && (srv)->trace) || (vchiq_core_msg_log_level >= (lev)))
40
41 struct vchiq_open_payload {
42         int fourcc;
43         int client_id;
44         short version;
45         short version_min;
46 };
47
48 struct vchiq_openack_payload {
49         short version;
50 };
51
52 enum {
53         QMFLAGS_IS_BLOCKING     = BIT(0),
54         QMFLAGS_NO_MUTEX_LOCK   = BIT(1),
55         QMFLAGS_NO_MUTEX_UNLOCK = BIT(2)
56 };
57
58 /* we require this for consistency between endpoints */
59 vchiq_static_assert(sizeof(struct vchiq_header) == 8);
60 vchiq_static_assert(IS_POW2(sizeof(struct vchiq_header)));
61 vchiq_static_assert(IS_POW2(VCHIQ_NUM_CURRENT_BULKS));
62 vchiq_static_assert(IS_POW2(VCHIQ_NUM_SERVICE_BULKS));
63 vchiq_static_assert(IS_POW2(VCHIQ_MAX_SERVICES));
64 vchiq_static_assert(VCHIQ_VERSION >= VCHIQ_VERSION_MIN);
65
66 /* Run time control of log level, based on KERN_XXX level. */
67 int vchiq_core_log_level = VCHIQ_LOG_DEFAULT;
68 int vchiq_core_msg_log_level = VCHIQ_LOG_DEFAULT;
69 int vchiq_sync_log_level = VCHIQ_LOG_DEFAULT;
70
71 DEFINE_SPINLOCK(bulk_waiter_spinlock);
72 static DEFINE_SPINLOCK(quota_spinlock);
73
74 struct vchiq_state *vchiq_states[VCHIQ_MAX_STATES];
75 static unsigned int handle_seq;
76
77 static const char *const srvstate_names[] = {
78         "FREE",
79         "HIDDEN",
80         "LISTENING",
81         "OPENING",
82         "OPEN",
83         "OPENSYNC",
84         "CLOSESENT",
85         "CLOSERECVD",
86         "CLOSEWAIT",
87         "CLOSED"
88 };
89
90 static const char *const reason_names[] = {
91         "SERVICE_OPENED",
92         "SERVICE_CLOSED",
93         "MESSAGE_AVAILABLE",
94         "BULK_TRANSMIT_DONE",
95         "BULK_RECEIVE_DONE",
96         "BULK_TRANSMIT_ABORTED",
97         "BULK_RECEIVE_ABORTED"
98 };
99
100 static const char *const conn_state_names[] = {
101         "DISCONNECTED",
102         "CONNECTING",
103         "CONNECTED",
104         "PAUSING",
105         "PAUSE_SENT",
106         "PAUSED",
107         "RESUMING",
108         "PAUSE_TIMEOUT",
109         "RESUME_TIMEOUT"
110 };
111
112 static void
113 release_message_sync(struct vchiq_state *state, struct vchiq_header *header);
114
115 static const char *msg_type_str(unsigned int msg_type)
116 {
117         switch (msg_type) {
118         case VCHIQ_MSG_PADDING:       return "PADDING";
119         case VCHIQ_MSG_CONNECT:       return "CONNECT";
120         case VCHIQ_MSG_OPEN:          return "OPEN";
121         case VCHIQ_MSG_OPENACK:       return "OPENACK";
122         case VCHIQ_MSG_CLOSE:         return "CLOSE";
123         case VCHIQ_MSG_DATA:          return "DATA";
124         case VCHIQ_MSG_BULK_RX:       return "BULK_RX";
125         case VCHIQ_MSG_BULK_TX:       return "BULK_TX";
126         case VCHIQ_MSG_BULK_RX_DONE:  return "BULK_RX_DONE";
127         case VCHIQ_MSG_BULK_TX_DONE:  return "BULK_TX_DONE";
128         case VCHIQ_MSG_PAUSE:         return "PAUSE";
129         case VCHIQ_MSG_RESUME:        return "RESUME";
130         case VCHIQ_MSG_REMOTE_USE:    return "REMOTE_USE";
131         case VCHIQ_MSG_REMOTE_RELEASE:      return "REMOTE_RELEASE";
132         case VCHIQ_MSG_REMOTE_USE_ACTIVE:   return "REMOTE_USE_ACTIVE";
133         }
134         return "???";
135 }
136
137 static inline void
138 vchiq_set_service_state(struct vchiq_service *service, int newstate)
139 {
140         vchiq_log_info(vchiq_core_log_level, "%d: srv:%d %s->%s",
141                 service->state->id, service->localport,
142                 srvstate_names[service->srvstate],
143                 srvstate_names[newstate]);
144         service->srvstate = newstate;
145 }
146
147 struct vchiq_service *
148 find_service_by_handle(unsigned int handle)
149 {
150         struct vchiq_service *service;
151
152         rcu_read_lock();
153         service = handle_to_service(handle);
154         if (service && service->srvstate != VCHIQ_SRVSTATE_FREE &&
155             service->handle == handle &&
156             kref_get_unless_zero(&service->ref_count)) {
157                 service = rcu_pointer_handoff(service);
158                 rcu_read_unlock();
159                 return service;
160         }
161         rcu_read_unlock();
162         vchiq_log_info(vchiq_core_log_level,
163                        "Invalid service handle 0x%x", handle);
164         return NULL;
165 }
166
167 struct vchiq_service *
168 find_service_by_port(struct vchiq_state *state, int localport)
169 {
170
171         if ((unsigned int)localport <= VCHIQ_PORT_MAX) {
172                 struct vchiq_service *service;
173
174                 rcu_read_lock();
175                 service = rcu_dereference(state->services[localport]);
176                 if (service && service->srvstate != VCHIQ_SRVSTATE_FREE &&
177                     kref_get_unless_zero(&service->ref_count)) {
178                         service = rcu_pointer_handoff(service);
179                         rcu_read_unlock();
180                         return service;
181                 }
182                 rcu_read_unlock();
183         }
184         vchiq_log_info(vchiq_core_log_level,
185                        "Invalid port %d", localport);
186         return NULL;
187 }
188
189 struct vchiq_service *
190 find_service_for_instance(struct vchiq_instance *instance,
191         unsigned int handle)
192 {
193         struct vchiq_service *service;
194
195         rcu_read_lock();
196         service = handle_to_service(handle);
197         if (service && service->srvstate != VCHIQ_SRVSTATE_FREE &&
198             service->handle == handle &&
199             service->instance == instance &&
200             kref_get_unless_zero(&service->ref_count)) {
201                 service = rcu_pointer_handoff(service);
202                 rcu_read_unlock();
203                 return service;
204         }
205         rcu_read_unlock();
206         vchiq_log_info(vchiq_core_log_level,
207                        "Invalid service handle 0x%x", handle);
208         return NULL;
209 }
210
211 struct vchiq_service *
212 find_closed_service_for_instance(struct vchiq_instance *instance,
213         unsigned int handle)
214 {
215         struct vchiq_service *service;
216
217         rcu_read_lock();
218         service = handle_to_service(handle);
219         if (service &&
220             (service->srvstate == VCHIQ_SRVSTATE_FREE ||
221              service->srvstate == VCHIQ_SRVSTATE_CLOSED) &&
222             service->handle == handle &&
223             service->instance == instance &&
224             kref_get_unless_zero(&service->ref_count)) {
225                 service = rcu_pointer_handoff(service);
226                 rcu_read_unlock();
227                 return service;
228         }
229         rcu_read_unlock();
230         vchiq_log_info(vchiq_core_log_level,
231                        "Invalid service handle 0x%x", handle);
232         return service;
233 }
234
235 struct vchiq_service *
236 __next_service_by_instance(struct vchiq_state *state,
237                            struct vchiq_instance *instance,
238                            int *pidx)
239 {
240         struct vchiq_service *service = NULL;
241         int idx = *pidx;
242
243         while (idx < state->unused_service) {
244                 struct vchiq_service *srv;
245
246                 srv = rcu_dereference(state->services[idx++]);
247                 if (srv && srv->srvstate != VCHIQ_SRVSTATE_FREE &&
248                     srv->instance == instance) {
249                         service = srv;
250                         break;
251                 }
252         }
253
254         *pidx = idx;
255         return service;
256 }
257
258 struct vchiq_service *
259 next_service_by_instance(struct vchiq_state *state,
260                          struct vchiq_instance *instance,
261                          int *pidx)
262 {
263         struct vchiq_service *service;
264
265         rcu_read_lock();
266         while (1) {
267                 service = __next_service_by_instance(state, instance, pidx);
268                 if (!service)
269                         break;
270                 if (kref_get_unless_zero(&service->ref_count)) {
271                         service = rcu_pointer_handoff(service);
272                         break;
273                 }
274         }
275         rcu_read_unlock();
276         return service;
277 }
278
279 void
280 lock_service(struct vchiq_service *service)
281 {
282         if (!service) {
283                 WARN(1, "%s service is NULL\n", __func__);
284                 return;
285         }
286         kref_get(&service->ref_count);
287 }
288
289 static void service_release(struct kref *kref)
290 {
291         struct vchiq_service *service =
292                 container_of(kref, struct vchiq_service, ref_count);
293         struct vchiq_state *state = service->state;
294
295         WARN_ON(service->srvstate != VCHIQ_SRVSTATE_FREE);
296         rcu_assign_pointer(state->services[service->localport], NULL);
297         if (service->userdata_term)
298                 service->userdata_term(service->base.userdata);
299         kfree_rcu(service, rcu);
300 }
301
302 void
303 unlock_service(struct vchiq_service *service)
304 {
305         if (!service) {
306                 WARN(1, "%s: service is NULL\n", __func__);
307                 return;
308         }
309         kref_put(&service->ref_count, service_release);
310 }
311
312 int
313 vchiq_get_client_id(unsigned int handle)
314 {
315         struct vchiq_service *service;
316         int id;
317
318         rcu_read_lock();
319         service = handle_to_service(handle);
320         id = service ? service->client_id : 0;
321         rcu_read_unlock();
322         return id;
323 }
324
325 void *
326 vchiq_get_service_userdata(unsigned int handle)
327 {
328         void *userdata;
329         struct vchiq_service *service;
330
331         rcu_read_lock();
332         service = handle_to_service(handle);
333         userdata = service ? service->base.userdata : NULL;
334         rcu_read_unlock();
335         return userdata;
336 }
337 EXPORT_SYMBOL(vchiq_get_service_userdata);
338
339 static void
340 mark_service_closing_internal(struct vchiq_service *service, int sh_thread)
341 {
342         struct vchiq_state *state = service->state;
343         struct vchiq_service_quota *quota;
344
345         service->closing = 1;
346
347         /* Synchronise with other threads. */
348         mutex_lock(&state->recycle_mutex);
349         mutex_unlock(&state->recycle_mutex);
350         if (!sh_thread || (state->conn_state != VCHIQ_CONNSTATE_PAUSE_SENT)) {
351                 /*
352                  * If we're pausing then the slot_mutex is held until resume
353                  * by the slot handler.  Therefore don't try to acquire this
354                  * mutex if we're the slot handler and in the pause sent state.
355                  * We don't need to in this case anyway.
356                  */
357                 mutex_lock(&state->slot_mutex);
358                 mutex_unlock(&state->slot_mutex);
359         }
360
361         /* Unblock any sending thread. */
362         quota = &state->service_quotas[service->localport];
363         complete(&quota->quota_event);
364 }
365
366 static void
367 mark_service_closing(struct vchiq_service *service)
368 {
369         mark_service_closing_internal(service, 0);
370 }
371
372 static inline enum vchiq_status
373 make_service_callback(struct vchiq_service *service, enum vchiq_reason reason,
374                       struct vchiq_header *header, void *bulk_userdata)
375 {
376         enum vchiq_status status;
377
378         vchiq_log_trace(vchiq_core_log_level, "%d: callback:%d (%s, %pK, %pK)",
379                 service->state->id, service->localport, reason_names[reason],
380                 header, bulk_userdata);
381         status = service->base.callback(reason, header, service->handle,
382                 bulk_userdata);
383         if (status == VCHIQ_ERROR) {
384                 vchiq_log_warning(vchiq_core_log_level,
385                         "%d: ignoring ERROR from callback to service %x",
386                         service->state->id, service->handle);
387                 status = VCHIQ_SUCCESS;
388         }
389
390         if (reason != VCHIQ_MESSAGE_AVAILABLE)
391                 vchiq_release_message(service->handle, header);
392
393         return status;
394 }
395
396 inline void
397 vchiq_set_conn_state(struct vchiq_state *state, enum vchiq_connstate newstate)
398 {
399         enum vchiq_connstate oldstate = state->conn_state;
400
401         vchiq_log_info(vchiq_core_log_level, "%d: %s->%s", state->id,
402                 conn_state_names[oldstate],
403                 conn_state_names[newstate]);
404         state->conn_state = newstate;
405         vchiq_platform_conn_state_changed(state, oldstate, newstate);
406 }
407
408 static inline void
409 remote_event_create(wait_queue_head_t *wq, struct remote_event *event)
410 {
411         event->armed = 0;
412         /*
413          * Don't clear the 'fired' flag because it may already have been set
414          * by the other side.
415          */
416         init_waitqueue_head(wq);
417 }
418
419 /*
420  * All the event waiting routines in VCHIQ used a custom semaphore
421  * implementation that filtered most signals. This achieved a behaviour similar
422  * to the "killable" family of functions. While cleaning up this code all the
423  * routines where switched to the "interruptible" family of functions, as the
424  * former was deemed unjustified and the use "killable" set all VCHIQ's
425  * threads in D state.
426  */
427 static inline int
428 remote_event_wait(wait_queue_head_t *wq, struct remote_event *event)
429 {
430         if (!event->fired) {
431                 event->armed = 1;
432                 dsb(sy);
433                 if (wait_event_interruptible(*wq, event->fired)) {
434                         event->armed = 0;
435                         return 0;
436                 }
437                 event->armed = 0;
438                 wmb();
439         }
440
441         event->fired = 0;
442         return 1;
443 }
444
445 static inline void
446 remote_event_signal_local(wait_queue_head_t *wq, struct remote_event *event)
447 {
448         event->fired = 1;
449         event->armed = 0;
450         wake_up_all(wq);
451 }
452
453 static inline void
454 remote_event_poll(wait_queue_head_t *wq, struct remote_event *event)
455 {
456         if (event->fired && event->armed)
457                 remote_event_signal_local(wq, event);
458 }
459
460 void
461 remote_event_pollall(struct vchiq_state *state)
462 {
463         remote_event_poll(&state->sync_trigger_event, &state->local->sync_trigger);
464         remote_event_poll(&state->sync_release_event, &state->local->sync_release);
465         remote_event_poll(&state->trigger_event, &state->local->trigger);
466         remote_event_poll(&state->recycle_event, &state->local->recycle);
467 }
468
469 /*
470  * Round up message sizes so that any space at the end of a slot is always big
471  * enough for a header. This relies on header size being a power of two, which
472  * has been verified earlier by a static assertion.
473  */
474
475 static inline size_t
476 calc_stride(size_t size)
477 {
478         /* Allow room for the header */
479         size += sizeof(struct vchiq_header);
480
481         /* Round up */
482         return (size + sizeof(struct vchiq_header) - 1) &
483                 ~(sizeof(struct vchiq_header) - 1);
484 }
485
486 /* Called by the slot handler thread */
487 static struct vchiq_service *
488 get_listening_service(struct vchiq_state *state, int fourcc)
489 {
490         int i;
491
492         WARN_ON(fourcc == VCHIQ_FOURCC_INVALID);
493
494         rcu_read_lock();
495         for (i = 0; i < state->unused_service; i++) {
496                 struct vchiq_service *service;
497
498                 service = rcu_dereference(state->services[i]);
499                 if (service &&
500                     service->public_fourcc == fourcc &&
501                     (service->srvstate == VCHIQ_SRVSTATE_LISTENING ||
502                      (service->srvstate == VCHIQ_SRVSTATE_OPEN &&
503                       service->remoteport == VCHIQ_PORT_FREE)) &&
504                     kref_get_unless_zero(&service->ref_count)) {
505                         service = rcu_pointer_handoff(service);
506                         rcu_read_unlock();
507                         return service;
508                 }
509         }
510         rcu_read_unlock();
511         return NULL;
512 }
513
514 /* Called by the slot handler thread */
515 static struct vchiq_service *
516 get_connected_service(struct vchiq_state *state, unsigned int port)
517 {
518         int i;
519
520         rcu_read_lock();
521         for (i = 0; i < state->unused_service; i++) {
522                 struct vchiq_service *service =
523                         rcu_dereference(state->services[i]);
524
525                 if (service && service->srvstate == VCHIQ_SRVSTATE_OPEN &&
526                     service->remoteport == port &&
527                     kref_get_unless_zero(&service->ref_count)) {
528                         service = rcu_pointer_handoff(service);
529                         rcu_read_unlock();
530                         return service;
531                 }
532         }
533         rcu_read_unlock();
534         return NULL;
535 }
536
537 inline void
538 request_poll(struct vchiq_state *state, struct vchiq_service *service,
539              int poll_type)
540 {
541         u32 value;
542         int index;
543
544         if (!service)
545                 goto skip_service;
546
547         do {
548                 value = atomic_read(&service->poll_flags);
549         } while (atomic_cmpxchg(&service->poll_flags, value,
550                  value | BIT(poll_type)) != value);
551
552         index = BITSET_WORD(service->localport);
553         do {
554                 value = atomic_read(&state->poll_services[index]);
555         } while (atomic_cmpxchg(&state->poll_services[index],
556                  value, value | BIT(service->localport & 0x1f)) != value);
557
558 skip_service:
559         state->poll_needed = 1;
560         wmb();
561
562         /* ... and ensure the slot handler runs. */
563         remote_event_signal_local(&state->trigger_event, &state->local->trigger);
564 }
565
566 /*
567  * Called from queue_message, by the slot handler and application threads,
568  * with slot_mutex held
569  */
570 static struct vchiq_header *
571 reserve_space(struct vchiq_state *state, size_t space, int is_blocking)
572 {
573         struct vchiq_shared_state *local = state->local;
574         int tx_pos = state->local_tx_pos;
575         int slot_space = VCHIQ_SLOT_SIZE - (tx_pos & VCHIQ_SLOT_MASK);
576
577         if (space > slot_space) {
578                 struct vchiq_header *header;
579                 /* Fill the remaining space with padding */
580                 WARN_ON(!state->tx_data);
581                 header = (struct vchiq_header *)
582                         (state->tx_data + (tx_pos & VCHIQ_SLOT_MASK));
583                 header->msgid = VCHIQ_MSGID_PADDING;
584                 header->size = slot_space - sizeof(struct vchiq_header);
585
586                 tx_pos += slot_space;
587         }
588
589         /* If necessary, get the next slot. */
590         if ((tx_pos & VCHIQ_SLOT_MASK) == 0) {
591                 int slot_index;
592
593                 /* If there is no free slot... */
594
595                 if (!try_wait_for_completion(&state->slot_available_event)) {
596                         /* ...wait for one. */
597
598                         VCHIQ_STATS_INC(state, slot_stalls);
599
600                         /* But first, flush through the last slot. */
601                         state->local_tx_pos = tx_pos;
602                         local->tx_pos = tx_pos;
603                         remote_event_signal(&state->remote->trigger);
604
605                         if (!is_blocking ||
606                                 (wait_for_completion_interruptible(
607                                 &state->slot_available_event)))
608                                 return NULL; /* No space available */
609                 }
610
611                 if (tx_pos == (state->slot_queue_available * VCHIQ_SLOT_SIZE)) {
612                         complete(&state->slot_available_event);
613                         pr_warn("%s: invalid tx_pos: %d\n", __func__, tx_pos);
614                         return NULL;
615                 }
616
617                 slot_index = local->slot_queue[
618                         SLOT_QUEUE_INDEX_FROM_POS_MASKED(tx_pos)];
619                 state->tx_data =
620                         (char *)SLOT_DATA_FROM_INDEX(state, slot_index);
621         }
622
623         state->local_tx_pos = tx_pos + space;
624
625         return (struct vchiq_header *)(state->tx_data +
626                                                 (tx_pos & VCHIQ_SLOT_MASK));
627 }
628
629 /* Called by the recycle thread. */
630 static void
631 process_free_queue(struct vchiq_state *state, BITSET_T *service_found,
632                    size_t length)
633 {
634         struct vchiq_shared_state *local = state->local;
635         int slot_queue_available;
636
637         /*
638          * Find slots which have been freed by the other side, and return them
639          * to the available queue.
640          */
641         slot_queue_available = state->slot_queue_available;
642
643         /*
644          * Use a memory barrier to ensure that any state that may have been
645          * modified by another thread is not masked by stale prefetched
646          * values.
647          */
648         mb();
649
650         while (slot_queue_available != local->slot_queue_recycle) {
651                 unsigned int pos;
652                 int slot_index = local->slot_queue[slot_queue_available++ &
653                         VCHIQ_SLOT_QUEUE_MASK];
654                 char *data = (char *)SLOT_DATA_FROM_INDEX(state, slot_index);
655                 int data_found = 0;
656
657                 /*
658                  * Beware of the address dependency - data is calculated
659                  * using an index written by the other side.
660                  */
661                 rmb();
662
663                 vchiq_log_trace(vchiq_core_log_level, "%d: pfq %d=%pK %x %x",
664                         state->id, slot_index, data,
665                         local->slot_queue_recycle, slot_queue_available);
666
667                 /* Initialise the bitmask for services which have used this slot */
668                 memset(service_found, 0, length);
669
670                 pos = 0;
671
672                 while (pos < VCHIQ_SLOT_SIZE) {
673                         struct vchiq_header *header =
674                                 (struct vchiq_header *)(data + pos);
675                         int msgid = header->msgid;
676
677                         if (VCHIQ_MSG_TYPE(msgid) == VCHIQ_MSG_DATA) {
678                                 int port = VCHIQ_MSG_SRCPORT(msgid);
679                                 struct vchiq_service_quota *quota =
680                                         &state->service_quotas[port];
681                                 int count;
682
683                                 spin_lock(&quota_spinlock);
684                                 count = quota->message_use_count;
685                                 if (count > 0)
686                                         quota->message_use_count =
687                                                 count - 1;
688                                 spin_unlock(&quota_spinlock);
689
690                                 if (count == quota->message_quota)
691                                         /*
692                                          * Signal the service that it
693                                          * has dropped below its quota
694                                          */
695                                         complete(&quota->quota_event);
696                                 else if (count == 0) {
697                                         vchiq_log_error(vchiq_core_log_level,
698                                                 "service %d message_use_count=%d (header %pK, msgid %x, header->msgid %x, header->size %x)",
699                                                 port,
700                                                 quota->message_use_count,
701                                                 header, msgid, header->msgid,
702                                                 header->size);
703                                         WARN(1, "invalid message use count\n");
704                                 }
705                                 if (!BITSET_IS_SET(service_found, port)) {
706                                         /* Set the found bit for this service */
707                                         BITSET_SET(service_found, port);
708
709                                         spin_lock(&quota_spinlock);
710                                         count = quota->slot_use_count;
711                                         if (count > 0)
712                                                 quota->slot_use_count =
713                                                         count - 1;
714                                         spin_unlock(&quota_spinlock);
715
716                                         if (count > 0) {
717                                                 /*
718                                                  * Signal the service in case
719                                                  * it has dropped below its quota
720                                                  */
721                                                 complete(&quota->quota_event);
722                                                 vchiq_log_trace(
723                                                         vchiq_core_log_level,
724                                                         "%d: pfq:%d %x@%pK - slot_use->%d",
725                                                         state->id, port,
726                                                         header->size, header,
727                                                         count - 1);
728                                         } else {
729                                                 vchiq_log_error(
730                                                         vchiq_core_log_level,
731                                                                 "service %d slot_use_count=%d (header %pK, msgid %x, header->msgid %x, header->size %x)",
732                                                         port, count, header,
733                                                         msgid, header->msgid,
734                                                         header->size);
735                                                 WARN(1, "bad slot use count\n");
736                                         }
737                                 }
738
739                                 data_found = 1;
740                         }
741
742                         pos += calc_stride(header->size);
743                         if (pos > VCHIQ_SLOT_SIZE) {
744                                 vchiq_log_error(vchiq_core_log_level,
745                                         "pfq - pos %x: header %pK, msgid %x, header->msgid %x, header->size %x",
746                                         pos, header, msgid, header->msgid,
747                                         header->size);
748                                 WARN(1, "invalid slot position\n");
749                         }
750                 }
751
752                 if (data_found) {
753                         int count;
754
755                         spin_lock(&quota_spinlock);
756                         count = state->data_use_count;
757                         if (count > 0)
758                                 state->data_use_count =
759                                         count - 1;
760                         spin_unlock(&quota_spinlock);
761                         if (count == state->data_quota)
762                                 complete(&state->data_quota_event);
763                 }
764
765                 /*
766                  * Don't allow the slot to be reused until we are no
767                  * longer interested in it.
768                  */
769                 mb();
770
771                 state->slot_queue_available = slot_queue_available;
772                 complete(&state->slot_available_event);
773         }
774 }
775
776 static ssize_t
777 memcpy_copy_callback(
778         void *context, void *dest,
779         size_t offset, size_t maxsize)
780 {
781         memcpy(dest + offset, context + offset, maxsize);
782         return maxsize;
783 }
784
785 static ssize_t
786 copy_message_data(
787         ssize_t (*copy_callback)(void *context, void *dest,
788                                  size_t offset, size_t maxsize),
789         void *context,
790         void *dest,
791         size_t size)
792 {
793         size_t pos = 0;
794
795         while (pos < size) {
796                 ssize_t callback_result;
797                 size_t max_bytes = size - pos;
798
799                 callback_result =
800                         copy_callback(context, dest + pos,
801                                       pos, max_bytes);
802
803                 if (callback_result < 0)
804                         return callback_result;
805
806                 if (!callback_result)
807                         return -EIO;
808
809                 if (callback_result > max_bytes)
810                         return -EIO;
811
812                 pos += callback_result;
813         }
814
815         return size;
816 }
817
818 /* Called by the slot handler and application threads */
819 static enum vchiq_status
820 queue_message(struct vchiq_state *state, struct vchiq_service *service,
821               int msgid,
822               ssize_t (*copy_callback)(void *context, void *dest,
823                                        size_t offset, size_t maxsize),
824               void *context, size_t size, int flags)
825 {
826         struct vchiq_shared_state *local;
827         struct vchiq_service_quota *quota = NULL;
828         struct vchiq_header *header;
829         int type = VCHIQ_MSG_TYPE(msgid);
830
831         size_t stride;
832
833         local = state->local;
834
835         stride = calc_stride(size);
836
837         WARN_ON(!(stride <= VCHIQ_SLOT_SIZE));
838
839         if (!(flags & QMFLAGS_NO_MUTEX_LOCK) &&
840             mutex_lock_killable(&state->slot_mutex))
841                 return VCHIQ_RETRY;
842
843         if (type == VCHIQ_MSG_DATA) {
844                 int tx_end_index;
845
846                 if (!service) {
847                         WARN(1, "%s: service is NULL\n", __func__);
848                         mutex_unlock(&state->slot_mutex);
849                         return VCHIQ_ERROR;
850                 }
851
852                 WARN_ON(flags & (QMFLAGS_NO_MUTEX_LOCK |
853                                  QMFLAGS_NO_MUTEX_UNLOCK));
854
855                 if (service->closing) {
856                         /* The service has been closed */
857                         mutex_unlock(&state->slot_mutex);
858                         return VCHIQ_ERROR;
859                 }
860
861                 quota = &state->service_quotas[service->localport];
862
863                 spin_lock(&quota_spinlock);
864
865                 /*
866                  * Ensure this service doesn't use more than its quota of
867                  * messages or slots
868                  */
869                 tx_end_index = SLOT_QUEUE_INDEX_FROM_POS(
870                         state->local_tx_pos + stride - 1);
871
872                 /*
873                  * Ensure data messages don't use more than their quota of
874                  * slots
875                  */
876                 while ((tx_end_index != state->previous_data_index) &&
877                         (state->data_use_count == state->data_quota)) {
878                         VCHIQ_STATS_INC(state, data_stalls);
879                         spin_unlock(&quota_spinlock);
880                         mutex_unlock(&state->slot_mutex);
881
882                         if (wait_for_completion_interruptible(
883                                                 &state->data_quota_event))
884                                 return VCHIQ_RETRY;
885
886                         mutex_lock(&state->slot_mutex);
887                         spin_lock(&quota_spinlock);
888                         tx_end_index = SLOT_QUEUE_INDEX_FROM_POS(
889                                 state->local_tx_pos + stride - 1);
890                         if ((tx_end_index == state->previous_data_index) ||
891                                 (state->data_use_count < state->data_quota)) {
892                                 /* Pass the signal on to other waiters */
893                                 complete(&state->data_quota_event);
894                                 break;
895                         }
896                 }
897
898                 while ((quota->message_use_count == quota->message_quota) ||
899                         ((tx_end_index != quota->previous_tx_index) &&
900                         (quota->slot_use_count ==
901                                 quota->slot_quota))) {
902                         spin_unlock(&quota_spinlock);
903                         vchiq_log_trace(vchiq_core_log_level,
904                                 "%d: qm:%d %s,%zx - quota stall (msg %d, slot %d)",
905                                 state->id, service->localport,
906                                 msg_type_str(type), size,
907                                 quota->message_use_count,
908                                 quota->slot_use_count);
909                         VCHIQ_SERVICE_STATS_INC(service, quota_stalls);
910                         mutex_unlock(&state->slot_mutex);
911                         if (wait_for_completion_interruptible(
912                                                 &quota->quota_event))
913                                 return VCHIQ_RETRY;
914                         if (service->closing)
915                                 return VCHIQ_ERROR;
916                         if (mutex_lock_killable(&state->slot_mutex))
917                                 return VCHIQ_RETRY;
918                         if (service->srvstate != VCHIQ_SRVSTATE_OPEN) {
919                                 /* The service has been closed */
920                                 mutex_unlock(&state->slot_mutex);
921                                 return VCHIQ_ERROR;
922                         }
923                         spin_lock(&quota_spinlock);
924                         tx_end_index = SLOT_QUEUE_INDEX_FROM_POS(
925                                 state->local_tx_pos + stride - 1);
926                 }
927
928                 spin_unlock(&quota_spinlock);
929         }
930
931         header = reserve_space(state, stride, flags & QMFLAGS_IS_BLOCKING);
932
933         if (!header) {
934                 if (service)
935                         VCHIQ_SERVICE_STATS_INC(service, slot_stalls);
936                 /*
937                  * In the event of a failure, return the mutex to the
938                  * state it was in
939                  */
940                 if (!(flags & QMFLAGS_NO_MUTEX_LOCK))
941                         mutex_unlock(&state->slot_mutex);
942                 return VCHIQ_RETRY;
943         }
944
945         if (type == VCHIQ_MSG_DATA) {
946                 ssize_t callback_result;
947                 int tx_end_index;
948                 int slot_use_count;
949
950                 vchiq_log_info(vchiq_core_log_level,
951                         "%d: qm %s@%pK,%zx (%d->%d)",
952                         state->id, msg_type_str(VCHIQ_MSG_TYPE(msgid)),
953                         header, size, VCHIQ_MSG_SRCPORT(msgid),
954                         VCHIQ_MSG_DSTPORT(msgid));
955
956                 WARN_ON(flags & (QMFLAGS_NO_MUTEX_LOCK |
957                                  QMFLAGS_NO_MUTEX_UNLOCK));
958
959                 callback_result =
960                         copy_message_data(copy_callback, context,
961                                           header->data, size);
962
963                 if (callback_result < 0) {
964                         mutex_unlock(&state->slot_mutex);
965                         VCHIQ_SERVICE_STATS_INC(service,
966                                                 error_count);
967                         return VCHIQ_ERROR;
968                 }
969
970                 if (SRVTRACE_ENABLED(service,
971                                      VCHIQ_LOG_INFO))
972                         vchiq_log_dump_mem("Sent", 0,
973                                            header->data,
974                                            min((size_t)16,
975                                                (size_t)callback_result));
976
977                 spin_lock(&quota_spinlock);
978                 quota->message_use_count++;
979
980                 tx_end_index =
981                         SLOT_QUEUE_INDEX_FROM_POS(state->local_tx_pos - 1);
982
983                 /*
984                  * If this transmission can't fit in the last slot used by any
985                  * service, the data_use_count must be increased.
986                  */
987                 if (tx_end_index != state->previous_data_index) {
988                         state->previous_data_index = tx_end_index;
989                         state->data_use_count++;
990                 }
991
992                 /*
993                  * If this isn't the same slot last used by this service,
994                  * the service's slot_use_count must be increased.
995                  */
996                 if (tx_end_index != quota->previous_tx_index) {
997                         quota->previous_tx_index = tx_end_index;
998                         slot_use_count = ++quota->slot_use_count;
999                 } else {
1000                         slot_use_count = 0;
1001                 }
1002
1003                 spin_unlock(&quota_spinlock);
1004
1005                 if (slot_use_count)
1006                         vchiq_log_trace(vchiq_core_log_level,
1007                                 "%d: qm:%d %s,%zx - slot_use->%d (hdr %p)",
1008                                 state->id, service->localport,
1009                                 msg_type_str(VCHIQ_MSG_TYPE(msgid)), size,
1010                                 slot_use_count, header);
1011
1012                 VCHIQ_SERVICE_STATS_INC(service, ctrl_tx_count);
1013                 VCHIQ_SERVICE_STATS_ADD(service, ctrl_tx_bytes, size);
1014         } else {
1015                 vchiq_log_info(vchiq_core_log_level,
1016                         "%d: qm %s@%pK,%zx (%d->%d)", state->id,
1017                         msg_type_str(VCHIQ_MSG_TYPE(msgid)),
1018                         header, size, VCHIQ_MSG_SRCPORT(msgid),
1019                         VCHIQ_MSG_DSTPORT(msgid));
1020                 if (size != 0) {
1021                         /*
1022                          * It is assumed for now that this code path
1023                          * only happens from calls inside this file.
1024                          *
1025                          * External callers are through the vchiq_queue_message
1026                          * path which always sets the type to be VCHIQ_MSG_DATA
1027                          *
1028                          * At first glance this appears to be correct but
1029                          * more review is needed.
1030                          */
1031                         copy_message_data(copy_callback, context,
1032                                           header->data, size);
1033                 }
1034                 VCHIQ_STATS_INC(state, ctrl_tx_count);
1035         }
1036
1037         header->msgid = msgid;
1038         header->size = size;
1039
1040         {
1041                 int svc_fourcc;
1042
1043                 svc_fourcc = service
1044                         ? service->base.fourcc
1045                         : VCHIQ_MAKE_FOURCC('?', '?', '?', '?');
1046
1047                 vchiq_log_info(SRVTRACE_LEVEL(service),
1048                         "Sent Msg %s(%u) to %c%c%c%c s:%u d:%d len:%zu",
1049                         msg_type_str(VCHIQ_MSG_TYPE(msgid)),
1050                         VCHIQ_MSG_TYPE(msgid),
1051                         VCHIQ_FOURCC_AS_4CHARS(svc_fourcc),
1052                         VCHIQ_MSG_SRCPORT(msgid),
1053                         VCHIQ_MSG_DSTPORT(msgid),
1054                         size);
1055         }
1056
1057         /* Make sure the new header is visible to the peer. */
1058         wmb();
1059
1060         /* Make the new tx_pos visible to the peer. */
1061         local->tx_pos = state->local_tx_pos;
1062         wmb();
1063
1064         if (service && (type == VCHIQ_MSG_CLOSE))
1065                 vchiq_set_service_state(service, VCHIQ_SRVSTATE_CLOSESENT);
1066
1067         if (!(flags & QMFLAGS_NO_MUTEX_UNLOCK))
1068                 mutex_unlock(&state->slot_mutex);
1069
1070         remote_event_signal(&state->remote->trigger);
1071
1072         return VCHIQ_SUCCESS;
1073 }
1074
1075 /* Called by the slot handler and application threads */
1076 static enum vchiq_status
1077 queue_message_sync(struct vchiq_state *state, struct vchiq_service *service,
1078                    int msgid,
1079                    ssize_t (*copy_callback)(void *context, void *dest,
1080                                             size_t offset, size_t maxsize),
1081                    void *context, int size, int is_blocking)
1082 {
1083         struct vchiq_shared_state *local;
1084         struct vchiq_header *header;
1085         ssize_t callback_result;
1086
1087         local = state->local;
1088
1089         if (VCHIQ_MSG_TYPE(msgid) != VCHIQ_MSG_RESUME &&
1090             mutex_lock_killable(&state->sync_mutex))
1091                 return VCHIQ_RETRY;
1092
1093         remote_event_wait(&state->sync_release_event, &local->sync_release);
1094
1095         rmb();
1096
1097         header = (struct vchiq_header *)SLOT_DATA_FROM_INDEX(state,
1098                 local->slot_sync);
1099
1100         {
1101                 int oldmsgid = header->msgid;
1102
1103                 if (oldmsgid != VCHIQ_MSGID_PADDING)
1104                         vchiq_log_error(vchiq_core_log_level,
1105                                 "%d: qms - msgid %x, not PADDING",
1106                                 state->id, oldmsgid);
1107         }
1108
1109         vchiq_log_info(vchiq_sync_log_level,
1110                        "%d: qms %s@%pK,%x (%d->%d)", state->id,
1111                        msg_type_str(VCHIQ_MSG_TYPE(msgid)),
1112                        header, size, VCHIQ_MSG_SRCPORT(msgid),
1113                        VCHIQ_MSG_DSTPORT(msgid));
1114
1115         callback_result =
1116                 copy_message_data(copy_callback, context,
1117                                   header->data, size);
1118
1119         if (callback_result < 0) {
1120                 mutex_unlock(&state->slot_mutex);
1121                 VCHIQ_SERVICE_STATS_INC(service,
1122                                         error_count);
1123                 return VCHIQ_ERROR;
1124         }
1125
1126         if (service) {
1127                 if (SRVTRACE_ENABLED(service,
1128                                      VCHIQ_LOG_INFO))
1129                         vchiq_log_dump_mem("Sent", 0,
1130                                            header->data,
1131                                            min((size_t)16,
1132                                                (size_t)callback_result));
1133
1134                 VCHIQ_SERVICE_STATS_INC(service, ctrl_tx_count);
1135                 VCHIQ_SERVICE_STATS_ADD(service, ctrl_tx_bytes, size);
1136         } else {
1137                 VCHIQ_STATS_INC(state, ctrl_tx_count);
1138         }
1139
1140         header->size = size;
1141         header->msgid = msgid;
1142
1143         if (vchiq_sync_log_level >= VCHIQ_LOG_TRACE) {
1144                 int svc_fourcc;
1145
1146                 svc_fourcc = service
1147                         ? service->base.fourcc
1148                         : VCHIQ_MAKE_FOURCC('?', '?', '?', '?');
1149
1150                 vchiq_log_trace(vchiq_sync_log_level,
1151                         "Sent Sync Msg %s(%u) to %c%c%c%c s:%u d:%d len:%d",
1152                         msg_type_str(VCHIQ_MSG_TYPE(msgid)),
1153                         VCHIQ_MSG_TYPE(msgid),
1154                         VCHIQ_FOURCC_AS_4CHARS(svc_fourcc),
1155                         VCHIQ_MSG_SRCPORT(msgid),
1156                         VCHIQ_MSG_DSTPORT(msgid),
1157                         size);
1158         }
1159
1160         remote_event_signal(&state->remote->sync_trigger);
1161
1162         if (VCHIQ_MSG_TYPE(msgid) != VCHIQ_MSG_PAUSE)
1163                 mutex_unlock(&state->sync_mutex);
1164
1165         return VCHIQ_SUCCESS;
1166 }
1167
1168 static inline void
1169 claim_slot(struct vchiq_slot_info *slot)
1170 {
1171         slot->use_count++;
1172 }
1173
1174 static void
1175 release_slot(struct vchiq_state *state, struct vchiq_slot_info *slot_info,
1176              struct vchiq_header *header, struct vchiq_service *service)
1177 {
1178         int release_count;
1179
1180         mutex_lock(&state->recycle_mutex);
1181
1182         if (header) {
1183                 int msgid = header->msgid;
1184
1185                 if (((msgid & VCHIQ_MSGID_CLAIMED) == 0) ||
1186                         (service && service->closing)) {
1187                         mutex_unlock(&state->recycle_mutex);
1188                         return;
1189                 }
1190
1191                 /* Rewrite the message header to prevent a double release */
1192                 header->msgid = msgid & ~VCHIQ_MSGID_CLAIMED;
1193         }
1194
1195         release_count = slot_info->release_count;
1196         slot_info->release_count = ++release_count;
1197
1198         if (release_count == slot_info->use_count) {
1199                 int slot_queue_recycle;
1200                 /* Add to the freed queue */
1201
1202                 /*
1203                  * A read barrier is necessary here to prevent speculative
1204                  * fetches of remote->slot_queue_recycle from overtaking the
1205                  * mutex.
1206                  */
1207                 rmb();
1208
1209                 slot_queue_recycle = state->remote->slot_queue_recycle;
1210                 state->remote->slot_queue[slot_queue_recycle &
1211                         VCHIQ_SLOT_QUEUE_MASK] =
1212                         SLOT_INDEX_FROM_INFO(state, slot_info);
1213                 state->remote->slot_queue_recycle = slot_queue_recycle + 1;
1214                 vchiq_log_info(vchiq_core_log_level,
1215                         "%d: %s %d - recycle->%x", state->id, __func__,
1216                         SLOT_INDEX_FROM_INFO(state, slot_info),
1217                         state->remote->slot_queue_recycle);
1218
1219                 /*
1220                  * A write barrier is necessary, but remote_event_signal
1221                  * contains one.
1222                  */
1223                 remote_event_signal(&state->remote->recycle);
1224         }
1225
1226         mutex_unlock(&state->recycle_mutex);
1227 }
1228
1229 static inline enum vchiq_reason
1230 get_bulk_reason(struct vchiq_bulk *bulk)
1231 {
1232         if (bulk->dir == VCHIQ_BULK_TRANSMIT) {
1233                 if (bulk->actual == VCHIQ_BULK_ACTUAL_ABORTED)
1234                         return VCHIQ_BULK_TRANSMIT_ABORTED;
1235
1236                 return VCHIQ_BULK_TRANSMIT_DONE;
1237         }
1238
1239         if (bulk->actual == VCHIQ_BULK_ACTUAL_ABORTED)
1240                 return VCHIQ_BULK_RECEIVE_ABORTED;
1241
1242         return VCHIQ_BULK_RECEIVE_DONE;
1243 }
1244
1245 /* Called by the slot handler - don't hold the bulk mutex */
1246 static enum vchiq_status
1247 notify_bulks(struct vchiq_service *service, struct vchiq_bulk_queue *queue,
1248              int retry_poll)
1249 {
1250         enum vchiq_status status = VCHIQ_SUCCESS;
1251
1252         vchiq_log_trace(vchiq_core_log_level,
1253                 "%d: nb:%d %cx - p=%x rn=%x r=%x",
1254                 service->state->id, service->localport,
1255                 (queue == &service->bulk_tx) ? 't' : 'r',
1256                 queue->process, queue->remote_notify, queue->remove);
1257
1258         queue->remote_notify = queue->process;
1259
1260         while (queue->remove != queue->remote_notify) {
1261                 struct vchiq_bulk *bulk =
1262                         &queue->bulks[BULK_INDEX(queue->remove)];
1263
1264                 /*
1265                  * Only generate callbacks for non-dummy bulk
1266                  * requests, and non-terminated services
1267                  */
1268                 if (bulk->data && service->instance) {
1269                         if (bulk->actual != VCHIQ_BULK_ACTUAL_ABORTED) {
1270                                 if (bulk->dir == VCHIQ_BULK_TRANSMIT) {
1271                                         VCHIQ_SERVICE_STATS_INC(service,
1272                                                 bulk_tx_count);
1273                                         VCHIQ_SERVICE_STATS_ADD(service,
1274                                                 bulk_tx_bytes,
1275                                                 bulk->actual);
1276                                 } else {
1277                                         VCHIQ_SERVICE_STATS_INC(service,
1278                                                 bulk_rx_count);
1279                                         VCHIQ_SERVICE_STATS_ADD(service,
1280                                                 bulk_rx_bytes,
1281                                                 bulk->actual);
1282                                 }
1283                         } else {
1284                                 VCHIQ_SERVICE_STATS_INC(service,
1285                                         bulk_aborted_count);
1286                         }
1287                         if (bulk->mode == VCHIQ_BULK_MODE_BLOCKING) {
1288                                 struct bulk_waiter *waiter;
1289
1290                                 spin_lock(&bulk_waiter_spinlock);
1291                                 waiter = bulk->userdata;
1292                                 if (waiter) {
1293                                         waiter->actual = bulk->actual;
1294                                         complete(&waiter->event);
1295                                 }
1296                                 spin_unlock(&bulk_waiter_spinlock);
1297                         } else if (bulk->mode ==
1298                                 VCHIQ_BULK_MODE_CALLBACK) {
1299                                 enum vchiq_reason reason =
1300                                                 get_bulk_reason(bulk);
1301                                 status = make_service_callback(service,
1302                                         reason, NULL, bulk->userdata);
1303                                 if (status == VCHIQ_RETRY)
1304                                         break;
1305                         }
1306                 }
1307
1308                 queue->remove++;
1309                 complete(&service->bulk_remove_event);
1310         }
1311         if (!retry_poll)
1312                 status = VCHIQ_SUCCESS;
1313
1314         if (status == VCHIQ_RETRY)
1315                 request_poll(service->state, service,
1316                         (queue == &service->bulk_tx) ?
1317                         VCHIQ_POLL_TXNOTIFY : VCHIQ_POLL_RXNOTIFY);
1318
1319         return status;
1320 }
1321
1322 /* Called by the slot handler thread */
1323 static void
1324 poll_services(struct vchiq_state *state)
1325 {
1326         int group, i;
1327
1328         for (group = 0; group < BITSET_SIZE(state->unused_service); group++) {
1329                 u32 flags;
1330
1331                 flags = atomic_xchg(&state->poll_services[group], 0);
1332                 for (i = 0; flags; i++) {
1333                         if (flags & BIT(i)) {
1334                                 struct vchiq_service *service =
1335                                         find_service_by_port(state,
1336                                                 (group<<5) + i);
1337                                 u32 service_flags;
1338
1339                                 flags &= ~BIT(i);
1340                                 if (!service)
1341                                         continue;
1342                                 service_flags =
1343                                         atomic_xchg(&service->poll_flags, 0);
1344                                 if (service_flags &
1345                                         BIT(VCHIQ_POLL_REMOVE)) {
1346                                         vchiq_log_info(vchiq_core_log_level,
1347                                                 "%d: ps - remove %d<->%d",
1348                                                 state->id, service->localport,
1349                                                 service->remoteport);
1350
1351                                         /*
1352                                          * Make it look like a client, because
1353                                          * it must be removed and not left in
1354                                          * the LISTENING state.
1355                                          */
1356                                         service->public_fourcc =
1357                                                 VCHIQ_FOURCC_INVALID;
1358
1359                                         if (vchiq_close_service_internal(
1360                                                 service, 0/*!close_recvd*/) !=
1361                                                 VCHIQ_SUCCESS)
1362                                                 request_poll(state, service,
1363                                                         VCHIQ_POLL_REMOVE);
1364                                 } else if (service_flags &
1365                                         BIT(VCHIQ_POLL_TERMINATE)) {
1366                                         vchiq_log_info(vchiq_core_log_level,
1367                                                 "%d: ps - terminate %d<->%d",
1368                                                 state->id, service->localport,
1369                                                 service->remoteport);
1370                                         if (vchiq_close_service_internal(
1371                                                 service, 0/*!close_recvd*/) !=
1372                                                 VCHIQ_SUCCESS)
1373                                                 request_poll(state, service,
1374                                                         VCHIQ_POLL_TERMINATE);
1375                                 }
1376                                 if (service_flags & BIT(VCHIQ_POLL_TXNOTIFY))
1377                                         notify_bulks(service,
1378                                                 &service->bulk_tx,
1379                                                 1/*retry_poll*/);
1380                                 if (service_flags & BIT(VCHIQ_POLL_RXNOTIFY))
1381                                         notify_bulks(service,
1382                                                 &service->bulk_rx,
1383                                                 1/*retry_poll*/);
1384                                 unlock_service(service);
1385                         }
1386                 }
1387         }
1388 }
1389
1390 /* Called with the bulk_mutex held */
1391 static void
1392 abort_outstanding_bulks(struct vchiq_service *service,
1393                         struct vchiq_bulk_queue *queue)
1394 {
1395         int is_tx = (queue == &service->bulk_tx);
1396
1397         vchiq_log_trace(vchiq_core_log_level,
1398                 "%d: aob:%d %cx - li=%x ri=%x p=%x",
1399                 service->state->id, service->localport, is_tx ? 't' : 'r',
1400                 queue->local_insert, queue->remote_insert, queue->process);
1401
1402         WARN_ON(!((int)(queue->local_insert - queue->process) >= 0));
1403         WARN_ON(!((int)(queue->remote_insert - queue->process) >= 0));
1404
1405         while ((queue->process != queue->local_insert) ||
1406                 (queue->process != queue->remote_insert)) {
1407                 struct vchiq_bulk *bulk =
1408                                 &queue->bulks[BULK_INDEX(queue->process)];
1409
1410                 if (queue->process == queue->remote_insert) {
1411                         /* fabricate a matching dummy bulk */
1412                         bulk->remote_data = NULL;
1413                         bulk->remote_size = 0;
1414                         queue->remote_insert++;
1415                 }
1416
1417                 if (queue->process != queue->local_insert) {
1418                         vchiq_complete_bulk(bulk);
1419
1420                         vchiq_log_info(SRVTRACE_LEVEL(service),
1421                                 "%s %c%c%c%c d:%d ABORTED - tx len:%d, rx len:%d",
1422                                 is_tx ? "Send Bulk to" : "Recv Bulk from",
1423                                 VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc),
1424                                 service->remoteport,
1425                                 bulk->size,
1426                                 bulk->remote_size);
1427                 } else {
1428                         /* fabricate a matching dummy bulk */
1429                         bulk->data = 0;
1430                         bulk->size = 0;
1431                         bulk->actual = VCHIQ_BULK_ACTUAL_ABORTED;
1432                         bulk->dir = is_tx ? VCHIQ_BULK_TRANSMIT :
1433                                 VCHIQ_BULK_RECEIVE;
1434                         queue->local_insert++;
1435                 }
1436
1437                 queue->process++;
1438         }
1439 }
1440
1441 static int
1442 parse_open(struct vchiq_state *state, struct vchiq_header *header)
1443 {
1444         struct vchiq_service *service = NULL;
1445         int msgid, size;
1446         unsigned int localport, remoteport;
1447
1448         msgid = header->msgid;
1449         size = header->size;
1450         localport = VCHIQ_MSG_DSTPORT(msgid);
1451         remoteport = VCHIQ_MSG_SRCPORT(msgid);
1452         if (size >= sizeof(struct vchiq_open_payload)) {
1453                 const struct vchiq_open_payload *payload =
1454                         (struct vchiq_open_payload *)header->data;
1455                 unsigned int fourcc;
1456
1457                 fourcc = payload->fourcc;
1458                 vchiq_log_info(vchiq_core_log_level,
1459                         "%d: prs OPEN@%pK (%d->'%c%c%c%c')",
1460                         state->id, header, localport,
1461                         VCHIQ_FOURCC_AS_4CHARS(fourcc));
1462
1463                 service = get_listening_service(state, fourcc);
1464
1465                 if (service) {
1466                         /* A matching service exists */
1467                         short version = payload->version;
1468                         short version_min = payload->version_min;
1469
1470                         if ((service->version < version_min) ||
1471                                 (version < service->version_min)) {
1472                                 /* Version mismatch */
1473                                 vchiq_loud_error_header();
1474                                 vchiq_loud_error("%d: service %d (%c%c%c%c) "
1475                                         "version mismatch - local (%d, min %d)"
1476                                         " vs. remote (%d, min %d)",
1477                                         state->id, service->localport,
1478                                         VCHIQ_FOURCC_AS_4CHARS(fourcc),
1479                                         service->version, service->version_min,
1480                                         version, version_min);
1481                                 vchiq_loud_error_footer();
1482                                 unlock_service(service);
1483                                 service = NULL;
1484                                 goto fail_open;
1485                         }
1486                         service->peer_version = version;
1487
1488                         if (service->srvstate == VCHIQ_SRVSTATE_LISTENING) {
1489                                 struct vchiq_openack_payload ack_payload = {
1490                                         service->version
1491                                 };
1492
1493                                 if (state->version_common <
1494                                     VCHIQ_VERSION_SYNCHRONOUS_MODE)
1495                                         service->sync = 0;
1496
1497                                 /* Acknowledge the OPEN */
1498                                 if (service->sync) {
1499                                         if (queue_message_sync(
1500                                                 state,
1501                                                 NULL,
1502                                                 VCHIQ_MAKE_MSG(
1503                                                         VCHIQ_MSG_OPENACK,
1504                                                         service->localport,
1505                                                         remoteport),
1506                                                 memcpy_copy_callback,
1507                                                 &ack_payload,
1508                                                 sizeof(ack_payload),
1509                                                 0) == VCHIQ_RETRY)
1510                                                 goto bail_not_ready;
1511                                 } else {
1512                                         if (queue_message(state,
1513                                                         NULL,
1514                                                         VCHIQ_MAKE_MSG(
1515                                                         VCHIQ_MSG_OPENACK,
1516                                                         service->localport,
1517                                                         remoteport),
1518                                                 memcpy_copy_callback,
1519                                                 &ack_payload,
1520                                                 sizeof(ack_payload),
1521                                                 0) == VCHIQ_RETRY)
1522                                                 goto bail_not_ready;
1523                                 }
1524
1525                                 /* The service is now open */
1526                                 vchiq_set_service_state(service,
1527                                         service->sync ? VCHIQ_SRVSTATE_OPENSYNC
1528                                         : VCHIQ_SRVSTATE_OPEN);
1529                         }
1530
1531                         /* Success - the message has been dealt with */
1532                         unlock_service(service);
1533                         return 1;
1534                 }
1535         }
1536
1537 fail_open:
1538         /* No available service, or an invalid request - send a CLOSE */
1539         if (queue_message(state, NULL,
1540                 VCHIQ_MAKE_MSG(VCHIQ_MSG_CLOSE, 0, VCHIQ_MSG_SRCPORT(msgid)),
1541                 NULL, NULL, 0, 0) == VCHIQ_RETRY)
1542                 goto bail_not_ready;
1543
1544         return 1;
1545
1546 bail_not_ready:
1547         if (service)
1548                 unlock_service(service);
1549
1550         return 0;
1551 }
1552
1553 /* Called by the slot handler thread */
1554 static void
1555 parse_rx_slots(struct vchiq_state *state)
1556 {
1557         struct vchiq_shared_state *remote = state->remote;
1558         struct vchiq_service *service = NULL;
1559         int tx_pos;
1560
1561         DEBUG_INITIALISE(state->local)
1562
1563         tx_pos = remote->tx_pos;
1564
1565         while (state->rx_pos != tx_pos) {
1566                 struct vchiq_header *header;
1567                 int msgid, size;
1568                 int type;
1569                 unsigned int localport, remoteport;
1570
1571                 DEBUG_TRACE(PARSE_LINE);
1572                 if (!state->rx_data) {
1573                         int rx_index;
1574
1575                         WARN_ON(!((state->rx_pos & VCHIQ_SLOT_MASK) == 0));
1576                         rx_index = remote->slot_queue[
1577                                 SLOT_QUEUE_INDEX_FROM_POS_MASKED(state->rx_pos)];
1578                         state->rx_data = (char *)SLOT_DATA_FROM_INDEX(state,
1579                                 rx_index);
1580                         state->rx_info = SLOT_INFO_FROM_INDEX(state, rx_index);
1581
1582                         /*
1583                          * Initialise use_count to one, and increment
1584                          * release_count at the end of the slot to avoid
1585                          * releasing the slot prematurely.
1586                          */
1587                         state->rx_info->use_count = 1;
1588                         state->rx_info->release_count = 0;
1589                 }
1590
1591                 header = (struct vchiq_header *)(state->rx_data +
1592                         (state->rx_pos & VCHIQ_SLOT_MASK));
1593                 DEBUG_VALUE(PARSE_HEADER, (int)(long)header);
1594                 msgid = header->msgid;
1595                 DEBUG_VALUE(PARSE_MSGID, msgid);
1596                 size = header->size;
1597                 type = VCHIQ_MSG_TYPE(msgid);
1598                 localport = VCHIQ_MSG_DSTPORT(msgid);
1599                 remoteport = VCHIQ_MSG_SRCPORT(msgid);
1600
1601                 if (type != VCHIQ_MSG_DATA)
1602                         VCHIQ_STATS_INC(state, ctrl_rx_count);
1603
1604                 switch (type) {
1605                 case VCHIQ_MSG_OPENACK:
1606                 case VCHIQ_MSG_CLOSE:
1607                 case VCHIQ_MSG_DATA:
1608                 case VCHIQ_MSG_BULK_RX:
1609                 case VCHIQ_MSG_BULK_TX:
1610                 case VCHIQ_MSG_BULK_RX_DONE:
1611                 case VCHIQ_MSG_BULK_TX_DONE:
1612                         service = find_service_by_port(state, localport);
1613                         if ((!service ||
1614                              ((service->remoteport != remoteport) &&
1615                               (service->remoteport != VCHIQ_PORT_FREE))) &&
1616                             (localport == 0) &&
1617                             (type == VCHIQ_MSG_CLOSE)) {
1618                                 /*
1619                                  * This could be a CLOSE from a client which
1620                                  * hadn't yet received the OPENACK - look for
1621                                  * the connected service
1622                                  */
1623                                 if (service)
1624                                         unlock_service(service);
1625                                 service = get_connected_service(state,
1626                                         remoteport);
1627                                 if (service)
1628                                         vchiq_log_warning(vchiq_core_log_level,
1629                                                 "%d: prs %s@%pK (%d->%d) - found connected service %d",
1630                                                 state->id, msg_type_str(type),
1631                                                 header, remoteport, localport,
1632                                                 service->localport);
1633                         }
1634
1635                         if (!service) {
1636                                 vchiq_log_error(vchiq_core_log_level,
1637                                         "%d: prs %s@%pK (%d->%d) - invalid/closed service %d",
1638                                         state->id, msg_type_str(type),
1639                                         header, remoteport, localport,
1640                                         localport);
1641                                 goto skip_message;
1642                         }
1643                         break;
1644                 default:
1645                         break;
1646                 }
1647
1648                 if (SRVTRACE_ENABLED(service, VCHIQ_LOG_INFO)) {
1649                         int svc_fourcc;
1650
1651                         svc_fourcc = service
1652                                 ? service->base.fourcc
1653                                 : VCHIQ_MAKE_FOURCC('?', '?', '?', '?');
1654                         vchiq_log_info(SRVTRACE_LEVEL(service),
1655                                 "Rcvd Msg %s(%u) from %c%c%c%c s:%d d:%d len:%d",
1656                                 msg_type_str(type), type,
1657                                 VCHIQ_FOURCC_AS_4CHARS(svc_fourcc),
1658                                 remoteport, localport, size);
1659                         if (size > 0)
1660                                 vchiq_log_dump_mem("Rcvd", 0, header->data,
1661                                         min(16, size));
1662                 }
1663
1664                 if (((unsigned long)header & VCHIQ_SLOT_MASK) +
1665                     calc_stride(size) > VCHIQ_SLOT_SIZE) {
1666                         vchiq_log_error(vchiq_core_log_level,
1667                                 "header %pK (msgid %x) - size %x too big for slot",
1668                                 header, (unsigned int)msgid,
1669                                 (unsigned int)size);
1670                         WARN(1, "oversized for slot\n");
1671                 }
1672
1673                 switch (type) {
1674                 case VCHIQ_MSG_OPEN:
1675                         WARN_ON(!(VCHIQ_MSG_DSTPORT(msgid) == 0));
1676                         if (!parse_open(state, header))
1677                                 goto bail_not_ready;
1678                         break;
1679                 case VCHIQ_MSG_OPENACK:
1680                         if (size >= sizeof(struct vchiq_openack_payload)) {
1681                                 const struct vchiq_openack_payload *payload =
1682                                         (struct vchiq_openack_payload *)
1683                                         header->data;
1684                                 service->peer_version = payload->version;
1685                         }
1686                         vchiq_log_info(vchiq_core_log_level,
1687                                 "%d: prs OPENACK@%pK,%x (%d->%d) v:%d",
1688                                 state->id, header, size, remoteport, localport,
1689                                 service->peer_version);
1690                         if (service->srvstate == VCHIQ_SRVSTATE_OPENING) {
1691                                 service->remoteport = remoteport;
1692                                 vchiq_set_service_state(service,
1693                                         VCHIQ_SRVSTATE_OPEN);
1694                                 complete(&service->remove_event);
1695                         } else
1696                                 vchiq_log_error(vchiq_core_log_level,
1697                                         "OPENACK received in state %s",
1698                                         srvstate_names[service->srvstate]);
1699                         break;
1700                 case VCHIQ_MSG_CLOSE:
1701                         WARN_ON(size != 0); /* There should be no data */
1702
1703                         vchiq_log_info(vchiq_core_log_level,
1704                                 "%d: prs CLOSE@%pK (%d->%d)",
1705                                 state->id, header, remoteport, localport);
1706
1707                         mark_service_closing_internal(service, 1);
1708
1709                         if (vchiq_close_service_internal(service,
1710                                 1/*close_recvd*/) == VCHIQ_RETRY)
1711                                 goto bail_not_ready;
1712
1713                         vchiq_log_info(vchiq_core_log_level,
1714                                 "Close Service %c%c%c%c s:%u d:%d",
1715                                 VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc),
1716                                 service->localport,
1717                                 service->remoteport);
1718                         break;
1719                 case VCHIQ_MSG_DATA:
1720                         vchiq_log_info(vchiq_core_log_level,
1721                                 "%d: prs DATA@%pK,%x (%d->%d)",
1722                                 state->id, header, size, remoteport, localport);
1723
1724                         if ((service->remoteport == remoteport) &&
1725                             (service->srvstate == VCHIQ_SRVSTATE_OPEN)) {
1726                                 header->msgid = msgid | VCHIQ_MSGID_CLAIMED;
1727                                 claim_slot(state->rx_info);
1728                                 DEBUG_TRACE(PARSE_LINE);
1729                                 if (make_service_callback(service,
1730                                         VCHIQ_MESSAGE_AVAILABLE, header,
1731                                         NULL) == VCHIQ_RETRY) {
1732                                         DEBUG_TRACE(PARSE_LINE);
1733                                         goto bail_not_ready;
1734                                 }
1735                                 VCHIQ_SERVICE_STATS_INC(service, ctrl_rx_count);
1736                                 VCHIQ_SERVICE_STATS_ADD(service, ctrl_rx_bytes,
1737                                         size);
1738                         } else {
1739                                 VCHIQ_STATS_INC(state, error_count);
1740                         }
1741                         break;
1742                 case VCHIQ_MSG_CONNECT:
1743                         vchiq_log_info(vchiq_core_log_level,
1744                                 "%d: prs CONNECT@%pK", state->id, header);
1745                         state->version_common = ((struct vchiq_slot_zero *)
1746                                                  state->slot_data)->version;
1747                         complete(&state->connect);
1748                         break;
1749                 case VCHIQ_MSG_BULK_RX:
1750                 case VCHIQ_MSG_BULK_TX:
1751                         /*
1752                          * We should never receive a bulk request from the
1753                          * other side since we're not setup to perform as the
1754                          * master.
1755                          */
1756                         WARN_ON(1);
1757                         break;
1758                 case VCHIQ_MSG_BULK_RX_DONE:
1759                 case VCHIQ_MSG_BULK_TX_DONE:
1760                         if ((service->remoteport == remoteport) &&
1761                             (service->srvstate != VCHIQ_SRVSTATE_FREE)) {
1762                                 struct vchiq_bulk_queue *queue;
1763                                 struct vchiq_bulk *bulk;
1764
1765                                 queue = (type == VCHIQ_MSG_BULK_RX_DONE) ?
1766                                         &service->bulk_rx : &service->bulk_tx;
1767
1768                                 DEBUG_TRACE(PARSE_LINE);
1769                                 if (mutex_lock_killable(&service->bulk_mutex)) {
1770                                         DEBUG_TRACE(PARSE_LINE);
1771                                         goto bail_not_ready;
1772                                 }
1773                                 if ((int)(queue->remote_insert -
1774                                         queue->local_insert) >= 0) {
1775                                         vchiq_log_error(vchiq_core_log_level,
1776                                                 "%d: prs %s@%pK (%d->%d) unexpected (ri=%d,li=%d)",
1777                                                 state->id, msg_type_str(type),
1778                                                 header, remoteport, localport,
1779                                                 queue->remote_insert,
1780                                                 queue->local_insert);
1781                                         mutex_unlock(&service->bulk_mutex);
1782                                         break;
1783                                 }
1784                                 if (queue->process != queue->remote_insert) {
1785                                         pr_err("%s: p %x != ri %x\n",
1786                                                __func__,
1787                                                queue->process,
1788                                                queue->remote_insert);
1789                                         mutex_unlock(&service->bulk_mutex);
1790                                         goto bail_not_ready;
1791                                 }
1792
1793                                 bulk = &queue->bulks[
1794                                         BULK_INDEX(queue->remote_insert)];
1795                                 bulk->actual = *(int *)header->data;
1796                                 queue->remote_insert++;
1797
1798                                 vchiq_log_info(vchiq_core_log_level,
1799                                         "%d: prs %s@%pK (%d->%d) %x@%pad",
1800                                         state->id, msg_type_str(type),
1801                                         header, remoteport, localport,
1802                                         bulk->actual, &bulk->data);
1803
1804                                 vchiq_log_trace(vchiq_core_log_level,
1805                                         "%d: prs:%d %cx li=%x ri=%x p=%x",
1806                                         state->id, localport,
1807                                         (type == VCHIQ_MSG_BULK_RX_DONE) ?
1808                                                 'r' : 't',
1809                                         queue->local_insert,
1810                                         queue->remote_insert, queue->process);
1811
1812                                 DEBUG_TRACE(PARSE_LINE);
1813                                 WARN_ON(queue->process == queue->local_insert);
1814                                 vchiq_complete_bulk(bulk);
1815                                 queue->process++;
1816                                 mutex_unlock(&service->bulk_mutex);
1817                                 DEBUG_TRACE(PARSE_LINE);
1818                                 notify_bulks(service, queue, 1/*retry_poll*/);
1819                                 DEBUG_TRACE(PARSE_LINE);
1820                         }
1821                         break;
1822                 case VCHIQ_MSG_PADDING:
1823                         vchiq_log_trace(vchiq_core_log_level,
1824                                 "%d: prs PADDING@%pK,%x",
1825                                 state->id, header, size);
1826                         break;
1827                 case VCHIQ_MSG_PAUSE:
1828                         /* If initiated, signal the application thread */
1829                         vchiq_log_trace(vchiq_core_log_level,
1830                                 "%d: prs PAUSE@%pK,%x",
1831                                 state->id, header, size);
1832                         if (state->conn_state == VCHIQ_CONNSTATE_PAUSED) {
1833                                 vchiq_log_error(vchiq_core_log_level,
1834                                         "%d: PAUSE received in state PAUSED",
1835                                         state->id);
1836                                 break;
1837                         }
1838                         if (state->conn_state != VCHIQ_CONNSTATE_PAUSE_SENT) {
1839                                 /* Send a PAUSE in response */
1840                                 if (queue_message(state, NULL,
1841                                         VCHIQ_MAKE_MSG(VCHIQ_MSG_PAUSE, 0, 0),
1842                                         NULL, NULL, 0, QMFLAGS_NO_MUTEX_UNLOCK)
1843                                     == VCHIQ_RETRY)
1844                                         goto bail_not_ready;
1845                         }
1846                         /* At this point slot_mutex is held */
1847                         vchiq_set_conn_state(state, VCHIQ_CONNSTATE_PAUSED);
1848                         break;
1849                 case VCHIQ_MSG_RESUME:
1850                         vchiq_log_trace(vchiq_core_log_level,
1851                                 "%d: prs RESUME@%pK,%x",
1852                                 state->id, header, size);
1853                         /* Release the slot mutex */
1854                         mutex_unlock(&state->slot_mutex);
1855                         vchiq_set_conn_state(state, VCHIQ_CONNSTATE_CONNECTED);
1856                         break;
1857
1858                 case VCHIQ_MSG_REMOTE_USE:
1859                         vchiq_on_remote_use(state);
1860                         break;
1861                 case VCHIQ_MSG_REMOTE_RELEASE:
1862                         vchiq_on_remote_release(state);
1863                         break;
1864                 case VCHIQ_MSG_REMOTE_USE_ACTIVE:
1865                         break;
1866
1867                 default:
1868                         vchiq_log_error(vchiq_core_log_level,
1869                                 "%d: prs invalid msgid %x@%pK,%x",
1870                                 state->id, msgid, header, size);
1871                         WARN(1, "invalid message\n");
1872                         break;
1873                 }
1874
1875 skip_message:
1876                 if (service) {
1877                         unlock_service(service);
1878                         service = NULL;
1879                 }
1880
1881                 state->rx_pos += calc_stride(size);
1882
1883                 DEBUG_TRACE(PARSE_LINE);
1884                 /*
1885                  * Perform some housekeeping when the end of the slot is
1886                  * reached.
1887                  */
1888                 if ((state->rx_pos & VCHIQ_SLOT_MASK) == 0) {
1889                         /* Remove the extra reference count. */
1890                         release_slot(state, state->rx_info, NULL, NULL);
1891                         state->rx_data = NULL;
1892                 }
1893         }
1894
1895 bail_not_ready:
1896         if (service)
1897                 unlock_service(service);
1898 }
1899
1900 /* Called by the slot handler thread */
1901 static int
1902 slot_handler_func(void *v)
1903 {
1904         struct vchiq_state *state = v;
1905         struct vchiq_shared_state *local = state->local;
1906
1907         DEBUG_INITIALISE(local)
1908
1909         while (1) {
1910                 DEBUG_COUNT(SLOT_HANDLER_COUNT);
1911                 DEBUG_TRACE(SLOT_HANDLER_LINE);
1912                 remote_event_wait(&state->trigger_event, &local->trigger);
1913
1914                 rmb();
1915
1916                 DEBUG_TRACE(SLOT_HANDLER_LINE);
1917                 if (state->poll_needed) {
1918
1919                         state->poll_needed = 0;
1920
1921                         /*
1922                          * Handle service polling and other rare conditions here
1923                          * out of the mainline code
1924                          */
1925                         switch (state->conn_state) {
1926                         case VCHIQ_CONNSTATE_CONNECTED:
1927                                 /* Poll the services as requested */
1928                                 poll_services(state);
1929                                 break;
1930
1931                         case VCHIQ_CONNSTATE_PAUSING:
1932                                 if (queue_message(state, NULL,
1933                                         VCHIQ_MAKE_MSG(VCHIQ_MSG_PAUSE, 0, 0),
1934                                         NULL, NULL, 0,
1935                                         QMFLAGS_NO_MUTEX_UNLOCK)
1936                                     != VCHIQ_RETRY) {
1937                                         vchiq_set_conn_state(state,
1938                                                 VCHIQ_CONNSTATE_PAUSE_SENT);
1939                                 } else {
1940                                         /* Retry later */
1941                                         state->poll_needed = 1;
1942                                 }
1943                                 break;
1944
1945                         case VCHIQ_CONNSTATE_RESUMING:
1946                                 if (queue_message(state, NULL,
1947                                         VCHIQ_MAKE_MSG(VCHIQ_MSG_RESUME, 0, 0),
1948                                         NULL, NULL, 0, QMFLAGS_NO_MUTEX_LOCK)
1949                                         != VCHIQ_RETRY) {
1950                                         vchiq_set_conn_state(state,
1951                                                 VCHIQ_CONNSTATE_CONNECTED);
1952                                 } else {
1953                                         /*
1954                                          * This should really be impossible,
1955                                          * since the PAUSE should have flushed
1956                                          * through outstanding messages.
1957                                          */
1958                                         vchiq_log_error(vchiq_core_log_level,
1959                                                 "Failed to send RESUME message");
1960                                 }
1961                                 break;
1962                         default:
1963                                 break;
1964                         }
1965
1966                 }
1967
1968                 DEBUG_TRACE(SLOT_HANDLER_LINE);
1969                 parse_rx_slots(state);
1970         }
1971         return 0;
1972 }
1973
1974 /* Called by the recycle thread */
1975 static int
1976 recycle_func(void *v)
1977 {
1978         struct vchiq_state *state = v;
1979         struct vchiq_shared_state *local = state->local;
1980         BITSET_T *found;
1981         size_t length;
1982
1983         length = sizeof(*found) * BITSET_SIZE(VCHIQ_MAX_SERVICES);
1984
1985         found = kmalloc_array(BITSET_SIZE(VCHIQ_MAX_SERVICES), sizeof(*found),
1986                               GFP_KERNEL);
1987         if (!found)
1988                 return -ENOMEM;
1989
1990         while (1) {
1991                 remote_event_wait(&state->recycle_event, &local->recycle);
1992
1993                 process_free_queue(state, found, length);
1994         }
1995         return 0;
1996 }
1997
1998 /* Called by the sync thread */
1999 static int
2000 sync_func(void *v)
2001 {
2002         struct vchiq_state *state = v;
2003         struct vchiq_shared_state *local = state->local;
2004         struct vchiq_header *header =
2005                 (struct vchiq_header *)SLOT_DATA_FROM_INDEX(state,
2006                         state->remote->slot_sync);
2007
2008         while (1) {
2009                 struct vchiq_service *service;
2010                 int msgid, size;
2011                 int type;
2012                 unsigned int localport, remoteport;
2013
2014                 remote_event_wait(&state->sync_trigger_event, &local->sync_trigger);
2015
2016                 rmb();
2017
2018                 msgid = header->msgid;
2019                 size = header->size;
2020                 type = VCHIQ_MSG_TYPE(msgid);
2021                 localport = VCHIQ_MSG_DSTPORT(msgid);
2022                 remoteport = VCHIQ_MSG_SRCPORT(msgid);
2023
2024                 service = find_service_by_port(state, localport);
2025
2026                 if (!service) {
2027                         vchiq_log_error(vchiq_sync_log_level,
2028                                 "%d: sf %s@%pK (%d->%d) - invalid/closed service %d",
2029                                 state->id, msg_type_str(type),
2030                                 header, remoteport, localport, localport);
2031                         release_message_sync(state, header);
2032                         continue;
2033                 }
2034
2035                 if (vchiq_sync_log_level >= VCHIQ_LOG_TRACE) {
2036                         int svc_fourcc;
2037
2038                         svc_fourcc = service
2039                                 ? service->base.fourcc
2040                                 : VCHIQ_MAKE_FOURCC('?', '?', '?', '?');
2041                         vchiq_log_trace(vchiq_sync_log_level,
2042                                 "Rcvd Msg %s from %c%c%c%c s:%d d:%d len:%d",
2043                                 msg_type_str(type),
2044                                 VCHIQ_FOURCC_AS_4CHARS(svc_fourcc),
2045                                 remoteport, localport, size);
2046                         if (size > 0)
2047                                 vchiq_log_dump_mem("Rcvd", 0, header->data,
2048                                         min(16, size));
2049                 }
2050
2051                 switch (type) {
2052                 case VCHIQ_MSG_OPENACK:
2053                         if (size >= sizeof(struct vchiq_openack_payload)) {
2054                                 const struct vchiq_openack_payload *payload =
2055                                         (struct vchiq_openack_payload *)
2056                                         header->data;
2057                                 service->peer_version = payload->version;
2058                         }
2059                         vchiq_log_info(vchiq_sync_log_level,
2060                                 "%d: sf OPENACK@%pK,%x (%d->%d) v:%d",
2061                                 state->id, header, size, remoteport, localport,
2062                                 service->peer_version);
2063                         if (service->srvstate == VCHIQ_SRVSTATE_OPENING) {
2064                                 service->remoteport = remoteport;
2065                                 vchiq_set_service_state(service,
2066                                         VCHIQ_SRVSTATE_OPENSYNC);
2067                                 service->sync = 1;
2068                                 complete(&service->remove_event);
2069                         }
2070                         release_message_sync(state, header);
2071                         break;
2072
2073                 case VCHIQ_MSG_DATA:
2074                         vchiq_log_trace(vchiq_sync_log_level,
2075                                 "%d: sf DATA@%pK,%x (%d->%d)",
2076                                 state->id, header, size, remoteport, localport);
2077
2078                         if ((service->remoteport == remoteport) &&
2079                                 (service->srvstate ==
2080                                 VCHIQ_SRVSTATE_OPENSYNC)) {
2081                                 if (make_service_callback(service,
2082                                         VCHIQ_MESSAGE_AVAILABLE, header,
2083                                         NULL) == VCHIQ_RETRY)
2084                                         vchiq_log_error(vchiq_sync_log_level,
2085                                                 "synchronous callback to service %d returns VCHIQ_RETRY",
2086                                                 localport);
2087                         }
2088                         break;
2089
2090                 default:
2091                         vchiq_log_error(vchiq_sync_log_level,
2092                                 "%d: sf unexpected msgid %x@%pK,%x",
2093                                 state->id, msgid, header, size);
2094                         release_message_sync(state, header);
2095                         break;
2096                 }
2097
2098                 unlock_service(service);
2099         }
2100
2101         return 0;
2102 }
2103
2104 static void
2105 init_bulk_queue(struct vchiq_bulk_queue *queue)
2106 {
2107         queue->local_insert = 0;
2108         queue->remote_insert = 0;
2109         queue->process = 0;
2110         queue->remote_notify = 0;
2111         queue->remove = 0;
2112 }
2113
2114 inline const char *
2115 get_conn_state_name(enum vchiq_connstate conn_state)
2116 {
2117         return conn_state_names[conn_state];
2118 }
2119
2120 struct vchiq_slot_zero *
2121 vchiq_init_slots(void *mem_base, int mem_size)
2122 {
2123         int mem_align =
2124                 (int)((VCHIQ_SLOT_SIZE - (long)mem_base) & VCHIQ_SLOT_MASK);
2125         struct vchiq_slot_zero *slot_zero =
2126                 (struct vchiq_slot_zero *)(mem_base + mem_align);
2127         int num_slots = (mem_size - mem_align)/VCHIQ_SLOT_SIZE;
2128         int first_data_slot = VCHIQ_SLOT_ZERO_SLOTS;
2129
2130         /* Ensure there is enough memory to run an absolutely minimum system */
2131         num_slots -= first_data_slot;
2132
2133         if (num_slots < 4) {
2134                 vchiq_log_error(vchiq_core_log_level,
2135                         "%s - insufficient memory %x bytes",
2136                         __func__, mem_size);
2137                 return NULL;
2138         }
2139
2140         memset(slot_zero, 0, sizeof(struct vchiq_slot_zero));
2141
2142         slot_zero->magic = VCHIQ_MAGIC;
2143         slot_zero->version = VCHIQ_VERSION;
2144         slot_zero->version_min = VCHIQ_VERSION_MIN;
2145         slot_zero->slot_zero_size = sizeof(struct vchiq_slot_zero);
2146         slot_zero->slot_size = VCHIQ_SLOT_SIZE;
2147         slot_zero->max_slots = VCHIQ_MAX_SLOTS;
2148         slot_zero->max_slots_per_side = VCHIQ_MAX_SLOTS_PER_SIDE;
2149
2150         slot_zero->master.slot_sync = first_data_slot;
2151         slot_zero->master.slot_first = first_data_slot + 1;
2152         slot_zero->master.slot_last = first_data_slot + (num_slots/2) - 1;
2153         slot_zero->slave.slot_sync = first_data_slot + (num_slots/2);
2154         slot_zero->slave.slot_first = first_data_slot + (num_slots/2) + 1;
2155         slot_zero->slave.slot_last = first_data_slot + num_slots - 1;
2156
2157         return slot_zero;
2158 }
2159
2160 enum vchiq_status
2161 vchiq_init_state(struct vchiq_state *state, struct vchiq_slot_zero *slot_zero)
2162 {
2163         struct vchiq_shared_state *local;
2164         struct vchiq_shared_state *remote;
2165         char threadname[16];
2166         int i, ret;
2167
2168         if (vchiq_states[0]) {
2169                 pr_err("%s: VCHIQ state already initialized\n", __func__);
2170                 return -EINVAL;
2171         }
2172
2173         local = &slot_zero->slave;
2174         remote = &slot_zero->master;
2175
2176         if (local->initialised) {
2177                 vchiq_loud_error_header();
2178                 if (remote->initialised)
2179                         vchiq_loud_error("local state has already been initialised");
2180                 else
2181                         vchiq_loud_error("master/slave mismatch two slaves");
2182                 vchiq_loud_error_footer();
2183                 return -EINVAL;
2184         }
2185
2186         memset(state, 0, sizeof(struct vchiq_state));
2187
2188         /*
2189          * initialize shared state pointers
2190          */
2191
2192         state->local = local;
2193         state->remote = remote;
2194         state->slot_data = (struct vchiq_slot *)slot_zero;
2195
2196         /*
2197          * initialize events and mutexes
2198          */
2199
2200         init_completion(&state->connect);
2201         mutex_init(&state->mutex);
2202         mutex_init(&state->slot_mutex);
2203         mutex_init(&state->recycle_mutex);
2204         mutex_init(&state->sync_mutex);
2205         mutex_init(&state->bulk_transfer_mutex);
2206
2207         init_completion(&state->slot_available_event);
2208         init_completion(&state->slot_remove_event);
2209         init_completion(&state->data_quota_event);
2210
2211         state->slot_queue_available = 0;
2212
2213         for (i = 0; i < VCHIQ_MAX_SERVICES; i++) {
2214                 struct vchiq_service_quota *quota =
2215                         &state->service_quotas[i];
2216                 init_completion(&quota->quota_event);
2217         }
2218
2219         for (i = local->slot_first; i <= local->slot_last; i++) {
2220                 local->slot_queue[state->slot_queue_available++] = i;
2221                 complete(&state->slot_available_event);
2222         }
2223
2224         state->default_slot_quota = state->slot_queue_available/2;
2225         state->default_message_quota =
2226                 min((unsigned short)(state->default_slot_quota * 256),
2227                 (unsigned short)~0);
2228
2229         state->previous_data_index = -1;
2230         state->data_use_count = 0;
2231         state->data_quota = state->slot_queue_available - 1;
2232
2233         remote_event_create(&state->trigger_event, &local->trigger);
2234         local->tx_pos = 0;
2235         remote_event_create(&state->recycle_event, &local->recycle);
2236         local->slot_queue_recycle = state->slot_queue_available;
2237         remote_event_create(&state->sync_trigger_event, &local->sync_trigger);
2238         remote_event_create(&state->sync_release_event, &local->sync_release);
2239
2240         /* At start-of-day, the slot is empty and available */
2241         ((struct vchiq_header *)
2242                 SLOT_DATA_FROM_INDEX(state, local->slot_sync))->msgid =
2243                                                         VCHIQ_MSGID_PADDING;
2244         remote_event_signal_local(&state->sync_release_event, &local->sync_release);
2245
2246         local->debug[DEBUG_ENTRIES] = DEBUG_MAX;
2247
2248         ret = vchiq_platform_init_state(state);
2249         if (ret)
2250                 return ret;
2251
2252         /*
2253          * bring up slot handler thread
2254          */
2255         snprintf(threadname, sizeof(threadname), "vchiq-slot/%d", state->id);
2256         state->slot_handler_thread = kthread_create(&slot_handler_func,
2257                 (void *)state,
2258                 threadname);
2259
2260         if (IS_ERR(state->slot_handler_thread)) {
2261                 vchiq_loud_error_header();
2262                 vchiq_loud_error("couldn't create thread %s", threadname);
2263                 vchiq_loud_error_footer();
2264                 return PTR_ERR(state->slot_handler_thread);
2265         }
2266         set_user_nice(state->slot_handler_thread, -19);
2267
2268         snprintf(threadname, sizeof(threadname), "vchiq-recy/%d", state->id);
2269         state->recycle_thread = kthread_create(&recycle_func,
2270                 (void *)state,
2271                 threadname);
2272         if (IS_ERR(state->recycle_thread)) {
2273                 vchiq_loud_error_header();
2274                 vchiq_loud_error("couldn't create thread %s", threadname);
2275                 vchiq_loud_error_footer();
2276                 ret = PTR_ERR(state->recycle_thread);
2277                 goto fail_free_handler_thread;
2278         }
2279         set_user_nice(state->recycle_thread, -19);
2280
2281         snprintf(threadname, sizeof(threadname), "vchiq-sync/%d", state->id);
2282         state->sync_thread = kthread_create(&sync_func,
2283                 (void *)state,
2284                 threadname);
2285         if (IS_ERR(state->sync_thread)) {
2286                 vchiq_loud_error_header();
2287                 vchiq_loud_error("couldn't create thread %s", threadname);
2288                 vchiq_loud_error_footer();
2289                 ret = PTR_ERR(state->sync_thread);
2290                 goto fail_free_recycle_thread;
2291         }
2292         set_user_nice(state->sync_thread, -20);
2293
2294         wake_up_process(state->slot_handler_thread);
2295         wake_up_process(state->recycle_thread);
2296         wake_up_process(state->sync_thread);
2297
2298         vchiq_states[0] = state;
2299
2300         /* Indicate readiness to the other side */
2301         local->initialised = 1;
2302
2303         return 0;
2304
2305 fail_free_recycle_thread:
2306         kthread_stop(state->recycle_thread);
2307 fail_free_handler_thread:
2308         kthread_stop(state->slot_handler_thread);
2309
2310         return ret;
2311 }
2312
2313 void vchiq_msg_queue_push(unsigned int handle, struct vchiq_header *header)
2314 {
2315         struct vchiq_service *service = find_service_by_handle(handle);
2316         int pos;
2317
2318         while (service->msg_queue_write == service->msg_queue_read +
2319                 VCHIQ_MAX_SLOTS) {
2320                 if (wait_for_completion_interruptible(&service->msg_queue_pop))
2321                         flush_signals(current);
2322         }
2323
2324         pos = service->msg_queue_write++ & (VCHIQ_MAX_SLOTS - 1);
2325         service->msg_queue[pos] = header;
2326
2327         complete(&service->msg_queue_push);
2328 }
2329 EXPORT_SYMBOL(vchiq_msg_queue_push);
2330
2331 struct vchiq_header *vchiq_msg_hold(unsigned int handle)
2332 {
2333         struct vchiq_service *service = find_service_by_handle(handle);
2334         struct vchiq_header *header;
2335         int pos;
2336
2337         if (service->msg_queue_write == service->msg_queue_read)
2338                 return NULL;
2339
2340         while (service->msg_queue_write == service->msg_queue_read) {
2341                 if (wait_for_completion_interruptible(&service->msg_queue_push))
2342                         flush_signals(current);
2343         }
2344
2345         pos = service->msg_queue_read++ & (VCHIQ_MAX_SLOTS - 1);
2346         header = service->msg_queue[pos];
2347
2348         complete(&service->msg_queue_pop);
2349
2350         return header;
2351 }
2352 EXPORT_SYMBOL(vchiq_msg_hold);
2353
2354 static int vchiq_validate_params(const struct vchiq_service_params_kernel *params)
2355 {
2356         if (!params->callback || !params->fourcc) {
2357                 vchiq_loud_error("Can't add service, invalid params\n");
2358                 return -EINVAL;
2359         }
2360
2361         return 0;
2362 }
2363
2364 /* Called from application thread when a client or server service is created. */
2365 struct vchiq_service *
2366 vchiq_add_service_internal(struct vchiq_state *state,
2367                            const struct vchiq_service_params_kernel *params,
2368                            int srvstate, struct vchiq_instance *instance,
2369                            vchiq_userdata_term userdata_term)
2370 {
2371         struct vchiq_service *service;
2372         struct vchiq_service __rcu **pservice = NULL;
2373         struct vchiq_service_quota *quota;
2374         int ret;
2375         int i;
2376
2377         ret = vchiq_validate_params(params);
2378         if (ret)
2379                 return NULL;
2380
2381         service = kmalloc(sizeof(*service), GFP_KERNEL);
2382         if (!service)
2383                 return service;
2384
2385         service->base.fourcc   = params->fourcc;
2386         service->base.callback = params->callback;
2387         service->base.userdata = params->userdata;
2388         service->handle        = VCHIQ_SERVICE_HANDLE_INVALID;
2389         kref_init(&service->ref_count);
2390         service->srvstate      = VCHIQ_SRVSTATE_FREE;
2391         service->userdata_term = userdata_term;
2392         service->localport     = VCHIQ_PORT_FREE;
2393         service->remoteport    = VCHIQ_PORT_FREE;
2394
2395         service->public_fourcc = (srvstate == VCHIQ_SRVSTATE_OPENING) ?
2396                 VCHIQ_FOURCC_INVALID : params->fourcc;
2397         service->client_id     = 0;
2398         service->auto_close    = 1;
2399         service->sync          = 0;
2400         service->closing       = 0;
2401         service->trace         = 0;
2402         atomic_set(&service->poll_flags, 0);
2403         service->version       = params->version;
2404         service->version_min   = params->version_min;
2405         service->state         = state;
2406         service->instance      = instance;
2407         service->service_use_count = 0;
2408         service->msg_queue_read = 0;
2409         service->msg_queue_write = 0;
2410         init_bulk_queue(&service->bulk_tx);
2411         init_bulk_queue(&service->bulk_rx);
2412         init_completion(&service->remove_event);
2413         init_completion(&service->bulk_remove_event);
2414         init_completion(&service->msg_queue_pop);
2415         init_completion(&service->msg_queue_push);
2416         mutex_init(&service->bulk_mutex);
2417         memset(&service->stats, 0, sizeof(service->stats));
2418         memset(&service->msg_queue, 0, sizeof(service->msg_queue));
2419
2420         /*
2421          * Although it is perfectly possible to use a spinlock
2422          * to protect the creation of services, it is overkill as it
2423          * disables interrupts while the array is searched.
2424          * The only danger is of another thread trying to create a
2425          * service - service deletion is safe.
2426          * Therefore it is preferable to use state->mutex which,
2427          * although slower to claim, doesn't block interrupts while
2428          * it is held.
2429          */
2430
2431         mutex_lock(&state->mutex);
2432
2433         /* Prepare to use a previously unused service */
2434         if (state->unused_service < VCHIQ_MAX_SERVICES)
2435                 pservice = &state->services[state->unused_service];
2436
2437         if (srvstate == VCHIQ_SRVSTATE_OPENING) {
2438                 for (i = 0; i < state->unused_service; i++) {
2439                         if (!rcu_access_pointer(state->services[i])) {
2440                                 pservice = &state->services[i];
2441                                 break;
2442                         }
2443                 }
2444         } else {
2445                 rcu_read_lock();
2446                 for (i = (state->unused_service - 1); i >= 0; i--) {
2447                         struct vchiq_service *srv;
2448
2449                         srv = rcu_dereference(state->services[i]);
2450                         if (!srv)
2451                                 pservice = &state->services[i];
2452                         else if ((srv->public_fourcc == params->fourcc) &&
2453                                  ((srv->instance != instance) ||
2454                                   (srv->base.callback != params->callback))) {
2455                                 /*
2456                                  * There is another server using this
2457                                  * fourcc which doesn't match.
2458                                  */
2459                                 pservice = NULL;
2460                                 break;
2461                         }
2462                 }
2463                 rcu_read_unlock();
2464         }
2465
2466         if (pservice) {
2467                 service->localport = (pservice - state->services);
2468                 if (!handle_seq)
2469                         handle_seq = VCHIQ_MAX_STATES *
2470                                  VCHIQ_MAX_SERVICES;
2471                 service->handle = handle_seq |
2472                         (state->id * VCHIQ_MAX_SERVICES) |
2473                         service->localport;
2474                 handle_seq += VCHIQ_MAX_STATES * VCHIQ_MAX_SERVICES;
2475                 rcu_assign_pointer(*pservice, service);
2476                 if (pservice == &state->services[state->unused_service])
2477                         state->unused_service++;
2478         }
2479
2480         mutex_unlock(&state->mutex);
2481
2482         if (!pservice) {
2483                 kfree(service);
2484                 return NULL;
2485         }
2486
2487         quota = &state->service_quotas[service->localport];
2488         quota->slot_quota = state->default_slot_quota;
2489         quota->message_quota = state->default_message_quota;
2490         if (quota->slot_use_count == 0)
2491                 quota->previous_tx_index =
2492                         SLOT_QUEUE_INDEX_FROM_POS(state->local_tx_pos)
2493                         - 1;
2494
2495         /* Bring this service online */
2496         vchiq_set_service_state(service, srvstate);
2497
2498         vchiq_log_info(vchiq_core_msg_log_level,
2499                 "%s Service %c%c%c%c SrcPort:%d",
2500                 (srvstate == VCHIQ_SRVSTATE_OPENING)
2501                 ? "Open" : "Add",
2502                 VCHIQ_FOURCC_AS_4CHARS(params->fourcc),
2503                 service->localport);
2504
2505         /* Don't unlock the service - leave it with a ref_count of 1. */
2506
2507         return service;
2508 }
2509
2510 enum vchiq_status
2511 vchiq_open_service_internal(struct vchiq_service *service, int client_id)
2512 {
2513         struct vchiq_open_payload payload = {
2514                 service->base.fourcc,
2515                 client_id,
2516                 service->version,
2517                 service->version_min
2518         };
2519         enum vchiq_status status = VCHIQ_SUCCESS;
2520
2521         service->client_id = client_id;
2522         vchiq_use_service_internal(service);
2523         status = queue_message(service->state,
2524                                NULL,
2525                                VCHIQ_MAKE_MSG(VCHIQ_MSG_OPEN,
2526                                               service->localport,
2527                                               0),
2528                                memcpy_copy_callback,
2529                                &payload,
2530                                sizeof(payload),
2531                                QMFLAGS_IS_BLOCKING);
2532
2533         if (status != VCHIQ_SUCCESS)
2534                 return status;
2535
2536         /* Wait for the ACK/NAK */
2537         if (wait_for_completion_interruptible(&service->remove_event)) {
2538                 status = VCHIQ_RETRY;
2539                 vchiq_release_service_internal(service);
2540         } else if ((service->srvstate != VCHIQ_SRVSTATE_OPEN) &&
2541                    (service->srvstate != VCHIQ_SRVSTATE_OPENSYNC)) {
2542                 if (service->srvstate != VCHIQ_SRVSTATE_CLOSEWAIT)
2543                         vchiq_log_error(vchiq_core_log_level,
2544                                         "%d: osi - srvstate = %s (ref %u)",
2545                                         service->state->id,
2546                                         srvstate_names[service->srvstate],
2547                                         kref_read(&service->ref_count));
2548                 status = VCHIQ_ERROR;
2549                 VCHIQ_SERVICE_STATS_INC(service, error_count);
2550                 vchiq_release_service_internal(service);
2551         }
2552
2553         return status;
2554 }
2555
2556 static void
2557 release_service_messages(struct vchiq_service *service)
2558 {
2559         struct vchiq_state *state = service->state;
2560         int slot_last = state->remote->slot_last;
2561         int i;
2562
2563         /* Release any claimed messages aimed at this service */
2564
2565         if (service->sync) {
2566                 struct vchiq_header *header =
2567                         (struct vchiq_header *)SLOT_DATA_FROM_INDEX(state,
2568                                                 state->remote->slot_sync);
2569                 if (VCHIQ_MSG_DSTPORT(header->msgid) == service->localport)
2570                         release_message_sync(state, header);
2571
2572                 return;
2573         }
2574
2575         for (i = state->remote->slot_first; i <= slot_last; i++) {
2576                 struct vchiq_slot_info *slot_info =
2577                         SLOT_INFO_FROM_INDEX(state, i);
2578                 if (slot_info->release_count != slot_info->use_count) {
2579                         char *data =
2580                                 (char *)SLOT_DATA_FROM_INDEX(state, i);
2581                         unsigned int pos, end;
2582
2583                         end = VCHIQ_SLOT_SIZE;
2584                         if (data == state->rx_data)
2585                                 /*
2586                                  * This buffer is still being read from - stop
2587                                  * at the current read position
2588                                  */
2589                                 end = state->rx_pos & VCHIQ_SLOT_MASK;
2590
2591                         pos = 0;
2592
2593                         while (pos < end) {
2594                                 struct vchiq_header *header =
2595                                         (struct vchiq_header *)(data + pos);
2596                                 int msgid = header->msgid;
2597                                 int port = VCHIQ_MSG_DSTPORT(msgid);
2598
2599                                 if ((port == service->localport) &&
2600                                         (msgid & VCHIQ_MSGID_CLAIMED)) {
2601                                         vchiq_log_info(vchiq_core_log_level,
2602                                                 "  fsi - hdr %pK", header);
2603                                         release_slot(state, slot_info, header,
2604                                                 NULL);
2605                                 }
2606                                 pos += calc_stride(header->size);
2607                                 if (pos > VCHIQ_SLOT_SIZE) {
2608                                         vchiq_log_error(vchiq_core_log_level,
2609                                                 "fsi - pos %x: header %pK, msgid %x, header->msgid %x, header->size %x",
2610                                                 pos, header, msgid,
2611                                                 header->msgid, header->size);
2612                                         WARN(1, "invalid slot position\n");
2613                                 }
2614                         }
2615                 }
2616         }
2617 }
2618
2619 static int
2620 do_abort_bulks(struct vchiq_service *service)
2621 {
2622         enum vchiq_status status;
2623
2624         /* Abort any outstanding bulk transfers */
2625         if (mutex_lock_killable(&service->bulk_mutex))
2626                 return 0;
2627         abort_outstanding_bulks(service, &service->bulk_tx);
2628         abort_outstanding_bulks(service, &service->bulk_rx);
2629         mutex_unlock(&service->bulk_mutex);
2630
2631         status = notify_bulks(service, &service->bulk_tx, 0/*!retry_poll*/);
2632         if (status != VCHIQ_SUCCESS)
2633                 return 0;
2634
2635         status = notify_bulks(service, &service->bulk_rx, 0/*!retry_poll*/);
2636         return (status == VCHIQ_SUCCESS);
2637 }
2638
2639 static enum vchiq_status
2640 close_service_complete(struct vchiq_service *service, int failstate)
2641 {
2642         enum vchiq_status status;
2643         int is_server = (service->public_fourcc != VCHIQ_FOURCC_INVALID);
2644         int newstate;
2645
2646         switch (service->srvstate) {
2647         case VCHIQ_SRVSTATE_OPEN:
2648         case VCHIQ_SRVSTATE_CLOSESENT:
2649         case VCHIQ_SRVSTATE_CLOSERECVD:
2650                 if (is_server) {
2651                         if (service->auto_close) {
2652                                 service->client_id = 0;
2653                                 service->remoteport = VCHIQ_PORT_FREE;
2654                                 newstate = VCHIQ_SRVSTATE_LISTENING;
2655                         } else
2656                                 newstate = VCHIQ_SRVSTATE_CLOSEWAIT;
2657                 } else
2658                         newstate = VCHIQ_SRVSTATE_CLOSED;
2659                 vchiq_set_service_state(service, newstate);
2660                 break;
2661         case VCHIQ_SRVSTATE_LISTENING:
2662                 break;
2663         default:
2664                 vchiq_log_error(vchiq_core_log_level,
2665                         "%s(%x) called in state %s", __func__,
2666                         service->handle, srvstate_names[service->srvstate]);
2667                 WARN(1, "%s in unexpected state\n", __func__);
2668                 return VCHIQ_ERROR;
2669         }
2670
2671         status = make_service_callback(service,
2672                 VCHIQ_SERVICE_CLOSED, NULL, NULL);
2673
2674         if (status != VCHIQ_RETRY) {
2675                 int uc = service->service_use_count;
2676                 int i;
2677                 /* Complete the close process */
2678                 for (i = 0; i < uc; i++)
2679                         /*
2680                          * cater for cases where close is forced and the
2681                          * client may not close all it's handles
2682                          */
2683                         vchiq_release_service_internal(service);
2684
2685                 service->client_id = 0;
2686                 service->remoteport = VCHIQ_PORT_FREE;
2687
2688                 if (service->srvstate == VCHIQ_SRVSTATE_CLOSED)
2689                         vchiq_free_service_internal(service);
2690                 else if (service->srvstate != VCHIQ_SRVSTATE_CLOSEWAIT) {
2691                         if (is_server)
2692                                 service->closing = 0;
2693
2694                         complete(&service->remove_event);
2695                 }
2696         } else
2697                 vchiq_set_service_state(service, failstate);
2698
2699         return status;
2700 }
2701
2702 /* Called by the slot handler */
2703 enum vchiq_status
2704 vchiq_close_service_internal(struct vchiq_service *service, int close_recvd)
2705 {
2706         struct vchiq_state *state = service->state;
2707         enum vchiq_status status = VCHIQ_SUCCESS;
2708         int is_server = (service->public_fourcc != VCHIQ_FOURCC_INVALID);
2709
2710         vchiq_log_info(vchiq_core_log_level, "%d: csi:%d,%d (%s)",
2711                 service->state->id, service->localport, close_recvd,
2712                 srvstate_names[service->srvstate]);
2713
2714         switch (service->srvstate) {
2715         case VCHIQ_SRVSTATE_CLOSED:
2716         case VCHIQ_SRVSTATE_HIDDEN:
2717         case VCHIQ_SRVSTATE_LISTENING:
2718         case VCHIQ_SRVSTATE_CLOSEWAIT:
2719                 if (close_recvd)
2720                         vchiq_log_error(vchiq_core_log_level,
2721                                 "%s(1) called in state %s",
2722                                 __func__, srvstate_names[service->srvstate]);
2723                 else if (is_server) {
2724                         if (service->srvstate == VCHIQ_SRVSTATE_LISTENING) {
2725                                 status = VCHIQ_ERROR;
2726                         } else {
2727                                 service->client_id = 0;
2728                                 service->remoteport = VCHIQ_PORT_FREE;
2729                                 if (service->srvstate ==
2730                                         VCHIQ_SRVSTATE_CLOSEWAIT)
2731                                         vchiq_set_service_state(service,
2732                                                 VCHIQ_SRVSTATE_LISTENING);
2733                         }
2734                         complete(&service->remove_event);
2735                 } else
2736                         vchiq_free_service_internal(service);
2737                 break;
2738         case VCHIQ_SRVSTATE_OPENING:
2739                 if (close_recvd) {
2740                         /* The open was rejected - tell the user */
2741                         vchiq_set_service_state(service,
2742                                 VCHIQ_SRVSTATE_CLOSEWAIT);
2743                         complete(&service->remove_event);
2744                 } else {
2745                         /* Shutdown mid-open - let the other side know */
2746                         status = queue_message(state, service,
2747                                 VCHIQ_MAKE_MSG
2748                                 (VCHIQ_MSG_CLOSE,
2749                                 service->localport,
2750                                 VCHIQ_MSG_DSTPORT(service->remoteport)),
2751                                 NULL, NULL, 0, 0);
2752                 }
2753                 break;
2754
2755         case VCHIQ_SRVSTATE_OPENSYNC:
2756                 mutex_lock(&state->sync_mutex);
2757                 fallthrough;
2758         case VCHIQ_SRVSTATE_OPEN:
2759                 if (close_recvd) {
2760                         if (!do_abort_bulks(service))
2761                                 status = VCHIQ_RETRY;
2762                 }
2763
2764                 release_service_messages(service);
2765
2766                 if (status == VCHIQ_SUCCESS)
2767                         status = queue_message(state, service,
2768                                 VCHIQ_MAKE_MSG
2769                                 (VCHIQ_MSG_CLOSE,
2770                                 service->localport,
2771                                 VCHIQ_MSG_DSTPORT(service->remoteport)),
2772                                 NULL, NULL, 0, QMFLAGS_NO_MUTEX_UNLOCK);
2773
2774                 if (status != VCHIQ_SUCCESS) {
2775                         if (service->srvstate == VCHIQ_SRVSTATE_OPENSYNC)
2776                                 mutex_unlock(&state->sync_mutex);
2777                         break;
2778                 }
2779
2780                 if (!close_recvd) {
2781                         /* Change the state while the mutex is still held */
2782                         vchiq_set_service_state(service,
2783                                                 VCHIQ_SRVSTATE_CLOSESENT);
2784                         mutex_unlock(&state->slot_mutex);
2785                         if (service->sync)
2786                                 mutex_unlock(&state->sync_mutex);
2787                         break;
2788                 }
2789
2790                 /* Change the state while the mutex is still held */
2791                 vchiq_set_service_state(service, VCHIQ_SRVSTATE_CLOSERECVD);
2792                 mutex_unlock(&state->slot_mutex);
2793                 if (service->sync)
2794                         mutex_unlock(&state->sync_mutex);
2795
2796                 status = close_service_complete(service,
2797                                 VCHIQ_SRVSTATE_CLOSERECVD);
2798                 break;
2799
2800         case VCHIQ_SRVSTATE_CLOSESENT:
2801                 if (!close_recvd)
2802                         /* This happens when a process is killed mid-close */
2803                         break;
2804
2805                 if (!do_abort_bulks(service)) {
2806                         status = VCHIQ_RETRY;
2807                         break;
2808                 }
2809
2810                 if (status == VCHIQ_SUCCESS)
2811                         status = close_service_complete(service,
2812                                 VCHIQ_SRVSTATE_CLOSERECVD);
2813                 break;
2814
2815         case VCHIQ_SRVSTATE_CLOSERECVD:
2816                 if (!close_recvd && is_server)
2817                         /* Force into LISTENING mode */
2818                         vchiq_set_service_state(service,
2819                                 VCHIQ_SRVSTATE_LISTENING);
2820                 status = close_service_complete(service,
2821                         VCHIQ_SRVSTATE_CLOSERECVD);
2822                 break;
2823
2824         default:
2825                 vchiq_log_error(vchiq_core_log_level,
2826                         "%s(%d) called in state %s", __func__,
2827                         close_recvd, srvstate_names[service->srvstate]);
2828                 break;
2829         }
2830
2831         return status;
2832 }
2833
2834 /* Called from the application process upon process death */
2835 void
2836 vchiq_terminate_service_internal(struct vchiq_service *service)
2837 {
2838         struct vchiq_state *state = service->state;
2839
2840         vchiq_log_info(vchiq_core_log_level, "%d: tsi - (%d<->%d)",
2841                 state->id, service->localport, service->remoteport);
2842
2843         mark_service_closing(service);
2844
2845         /* Mark the service for removal by the slot handler */
2846         request_poll(state, service, VCHIQ_POLL_REMOVE);
2847 }
2848
2849 /* Called from the slot handler */
2850 void
2851 vchiq_free_service_internal(struct vchiq_service *service)
2852 {
2853         struct vchiq_state *state = service->state;
2854
2855         vchiq_log_info(vchiq_core_log_level, "%d: fsi - (%d)",
2856                 state->id, service->localport);
2857
2858         switch (service->srvstate) {
2859         case VCHIQ_SRVSTATE_OPENING:
2860         case VCHIQ_SRVSTATE_CLOSED:
2861         case VCHIQ_SRVSTATE_HIDDEN:
2862         case VCHIQ_SRVSTATE_LISTENING:
2863         case VCHIQ_SRVSTATE_CLOSEWAIT:
2864                 break;
2865         default:
2866                 vchiq_log_error(vchiq_core_log_level,
2867                         "%d: fsi - (%d) in state %s",
2868                         state->id, service->localport,
2869                         srvstate_names[service->srvstate]);
2870                 return;
2871         }
2872
2873         vchiq_set_service_state(service, VCHIQ_SRVSTATE_FREE);
2874
2875         complete(&service->remove_event);
2876
2877         /* Release the initial lock */
2878         unlock_service(service);
2879 }
2880
2881 enum vchiq_status
2882 vchiq_connect_internal(struct vchiq_state *state, struct vchiq_instance *instance)
2883 {
2884         struct vchiq_service *service;
2885         int i;
2886
2887         /* Find all services registered to this client and enable them. */
2888         i = 0;
2889         while ((service = next_service_by_instance(state, instance,
2890                 &i)) != NULL) {
2891                 if (service->srvstate == VCHIQ_SRVSTATE_HIDDEN)
2892                         vchiq_set_service_state(service,
2893                                 VCHIQ_SRVSTATE_LISTENING);
2894                 unlock_service(service);
2895         }
2896
2897         if (state->conn_state == VCHIQ_CONNSTATE_DISCONNECTED) {
2898                 if (queue_message(state, NULL,
2899                         VCHIQ_MAKE_MSG(VCHIQ_MSG_CONNECT, 0, 0), NULL, NULL,
2900                         0, QMFLAGS_IS_BLOCKING) == VCHIQ_RETRY)
2901                         return VCHIQ_RETRY;
2902
2903                 vchiq_set_conn_state(state, VCHIQ_CONNSTATE_CONNECTING);
2904         }
2905
2906         if (state->conn_state == VCHIQ_CONNSTATE_CONNECTING) {
2907                 if (wait_for_completion_interruptible(&state->connect))
2908                         return VCHIQ_RETRY;
2909
2910                 vchiq_set_conn_state(state, VCHIQ_CONNSTATE_CONNECTED);
2911                 complete(&state->connect);
2912         }
2913
2914         return VCHIQ_SUCCESS;
2915 }
2916
2917 enum vchiq_status
2918 vchiq_shutdown_internal(struct vchiq_state *state, struct vchiq_instance *instance)
2919 {
2920         struct vchiq_service *service;
2921         int i;
2922
2923         /* Find all services registered to this client and enable them. */
2924         i = 0;
2925         while ((service = next_service_by_instance(state, instance,
2926                 &i)) != NULL) {
2927                 (void)vchiq_remove_service(service->handle);
2928                 unlock_service(service);
2929         }
2930
2931         return VCHIQ_SUCCESS;
2932 }
2933
2934 enum vchiq_status
2935 vchiq_close_service(unsigned int handle)
2936 {
2937         /* Unregister the service */
2938         struct vchiq_service *service = find_service_by_handle(handle);
2939         enum vchiq_status status = VCHIQ_SUCCESS;
2940
2941         if (!service)
2942                 return VCHIQ_ERROR;
2943
2944         vchiq_log_info(vchiq_core_log_level,
2945                 "%d: close_service:%d",
2946                 service->state->id, service->localport);
2947
2948         if ((service->srvstate == VCHIQ_SRVSTATE_FREE) ||
2949             (service->srvstate == VCHIQ_SRVSTATE_LISTENING) ||
2950             (service->srvstate == VCHIQ_SRVSTATE_HIDDEN)) {
2951                 unlock_service(service);
2952                 return VCHIQ_ERROR;
2953         }
2954
2955         mark_service_closing(service);
2956
2957         if (current == service->state->slot_handler_thread) {
2958                 status = vchiq_close_service_internal(service,
2959                         0/*!close_recvd*/);
2960                 WARN_ON(status == VCHIQ_RETRY);
2961         } else {
2962         /* Mark the service for termination by the slot handler */
2963                 request_poll(service->state, service, VCHIQ_POLL_TERMINATE);
2964         }
2965
2966         while (1) {
2967                 if (wait_for_completion_interruptible(&service->remove_event)) {
2968                         status = VCHIQ_RETRY;
2969                         break;
2970                 }
2971
2972                 if ((service->srvstate == VCHIQ_SRVSTATE_FREE) ||
2973                     (service->srvstate == VCHIQ_SRVSTATE_LISTENING) ||
2974                     (service->srvstate == VCHIQ_SRVSTATE_OPEN))
2975                         break;
2976
2977                 vchiq_log_warning(vchiq_core_log_level,
2978                         "%d: close_service:%d - waiting in state %s",
2979                         service->state->id, service->localport,
2980                         srvstate_names[service->srvstate]);
2981         }
2982
2983         if ((status == VCHIQ_SUCCESS) &&
2984             (service->srvstate != VCHIQ_SRVSTATE_FREE) &&
2985             (service->srvstate != VCHIQ_SRVSTATE_LISTENING))
2986                 status = VCHIQ_ERROR;
2987
2988         unlock_service(service);
2989
2990         return status;
2991 }
2992 EXPORT_SYMBOL(vchiq_close_service);
2993
2994 enum vchiq_status
2995 vchiq_remove_service(unsigned int handle)
2996 {
2997         /* Unregister the service */
2998         struct vchiq_service *service = find_service_by_handle(handle);
2999         enum vchiq_status status = VCHIQ_SUCCESS;
3000
3001         if (!service)
3002                 return VCHIQ_ERROR;
3003
3004         vchiq_log_info(vchiq_core_log_level,
3005                 "%d: remove_service:%d",
3006                 service->state->id, service->localport);
3007
3008         if (service->srvstate == VCHIQ_SRVSTATE_FREE) {
3009                 unlock_service(service);
3010                 return VCHIQ_ERROR;
3011         }
3012
3013         mark_service_closing(service);
3014
3015         if ((service->srvstate == VCHIQ_SRVSTATE_HIDDEN) ||
3016             (current == service->state->slot_handler_thread)) {
3017                 /*
3018                  * Make it look like a client, because it must be removed and
3019                  * not left in the LISTENING state.
3020                  */
3021                 service->public_fourcc = VCHIQ_FOURCC_INVALID;
3022
3023                 status = vchiq_close_service_internal(service,
3024                         0/*!close_recvd*/);
3025                 WARN_ON(status == VCHIQ_RETRY);
3026         } else {
3027                 /* Mark the service for removal by the slot handler */
3028                 request_poll(service->state, service, VCHIQ_POLL_REMOVE);
3029         }
3030         while (1) {
3031                 if (wait_for_completion_interruptible(&service->remove_event)) {
3032                         status = VCHIQ_RETRY;
3033                         break;
3034                 }
3035
3036                 if ((service->srvstate == VCHIQ_SRVSTATE_FREE) ||
3037                     (service->srvstate == VCHIQ_SRVSTATE_OPEN))
3038                         break;
3039
3040                 vchiq_log_warning(vchiq_core_log_level,
3041                         "%d: remove_service:%d - waiting in state %s",
3042                         service->state->id, service->localport,
3043                         srvstate_names[service->srvstate]);
3044         }
3045
3046         if ((status == VCHIQ_SUCCESS) &&
3047             (service->srvstate != VCHIQ_SRVSTATE_FREE))
3048                 status = VCHIQ_ERROR;
3049
3050         unlock_service(service);
3051
3052         return status;
3053 }
3054
3055 /*
3056  * This function may be called by kernel threads or user threads.
3057  * User threads may receive VCHIQ_RETRY to indicate that a signal has been
3058  * received and the call should be retried after being returned to user
3059  * context.
3060  * When called in blocking mode, the userdata field points to a bulk_waiter
3061  * structure.
3062  */
3063 enum vchiq_status vchiq_bulk_transfer(unsigned int handle,
3064                                    void *offset, void __user *uoffset,
3065                                    int size, void *userdata,
3066                                    enum vchiq_bulk_mode mode,
3067                                    enum vchiq_bulk_dir dir)
3068 {
3069         struct vchiq_service *service = find_service_by_handle(handle);
3070         struct vchiq_bulk_queue *queue;
3071         struct vchiq_bulk *bulk;
3072         struct vchiq_state *state;
3073         struct bulk_waiter *bulk_waiter = NULL;
3074         const char dir_char = (dir == VCHIQ_BULK_TRANSMIT) ? 't' : 'r';
3075         const int dir_msgtype = (dir == VCHIQ_BULK_TRANSMIT) ?
3076                 VCHIQ_MSG_BULK_TX : VCHIQ_MSG_BULK_RX;
3077         enum vchiq_status status = VCHIQ_ERROR;
3078         int payload[2];
3079
3080         if (!service)
3081                 goto error_exit;
3082
3083         if (service->srvstate != VCHIQ_SRVSTATE_OPEN)
3084                 goto error_exit;
3085
3086         if (!offset && !uoffset)
3087                 goto error_exit;
3088
3089         if (vchiq_check_service(service) != VCHIQ_SUCCESS)
3090                 goto error_exit;
3091
3092         switch (mode) {
3093         case VCHIQ_BULK_MODE_NOCALLBACK:
3094         case VCHIQ_BULK_MODE_CALLBACK:
3095                 break;
3096         case VCHIQ_BULK_MODE_BLOCKING:
3097                 bulk_waiter = userdata;
3098                 init_completion(&bulk_waiter->event);
3099                 bulk_waiter->actual = 0;
3100                 bulk_waiter->bulk = NULL;
3101                 break;
3102         case VCHIQ_BULK_MODE_WAITING:
3103                 bulk_waiter = userdata;
3104                 bulk = bulk_waiter->bulk;
3105                 goto waiting;
3106         default:
3107                 goto error_exit;
3108         }
3109
3110         state = service->state;
3111
3112         queue = (dir == VCHIQ_BULK_TRANSMIT) ?
3113                 &service->bulk_tx : &service->bulk_rx;
3114
3115         if (mutex_lock_killable(&service->bulk_mutex)) {
3116                 status = VCHIQ_RETRY;
3117                 goto error_exit;
3118         }
3119
3120         if (queue->local_insert == queue->remove + VCHIQ_NUM_SERVICE_BULKS) {
3121                 VCHIQ_SERVICE_STATS_INC(service, bulk_stalls);
3122                 do {
3123                         mutex_unlock(&service->bulk_mutex);
3124                         if (wait_for_completion_interruptible(
3125                                                 &service->bulk_remove_event)) {
3126                                 status = VCHIQ_RETRY;
3127                                 goto error_exit;
3128                         }
3129                         if (mutex_lock_killable(&service->bulk_mutex)) {
3130                                 status = VCHIQ_RETRY;
3131                                 goto error_exit;
3132                         }
3133                 } while (queue->local_insert == queue->remove +
3134                                 VCHIQ_NUM_SERVICE_BULKS);
3135         }
3136
3137         bulk = &queue->bulks[BULK_INDEX(queue->local_insert)];
3138
3139         bulk->mode = mode;
3140         bulk->dir = dir;
3141         bulk->userdata = userdata;
3142         bulk->size = size;
3143         bulk->actual = VCHIQ_BULK_ACTUAL_ABORTED;
3144
3145         if (vchiq_prepare_bulk_data(bulk, offset, uoffset, size, dir))
3146                 goto unlock_error_exit;
3147
3148         wmb();
3149
3150         vchiq_log_info(vchiq_core_log_level,
3151                 "%d: bt (%d->%d) %cx %x@%pad %pK",
3152                 state->id, service->localport, service->remoteport, dir_char,
3153                 size, &bulk->data, userdata);
3154
3155         /*
3156          * The slot mutex must be held when the service is being closed, so
3157          * claim it here to ensure that isn't happening
3158          */
3159         if (mutex_lock_killable(&state->slot_mutex)) {
3160                 status = VCHIQ_RETRY;
3161                 goto cancel_bulk_error_exit;
3162         }
3163
3164         if (service->srvstate != VCHIQ_SRVSTATE_OPEN)
3165                 goto unlock_both_error_exit;
3166
3167         payload[0] = lower_32_bits(bulk->data);
3168         payload[1] = bulk->size;
3169         status = queue_message(state,
3170                                NULL,
3171                                VCHIQ_MAKE_MSG(dir_msgtype,
3172                                               service->localport,
3173                                               service->remoteport),
3174                                memcpy_copy_callback,
3175                                &payload,
3176                                sizeof(payload),
3177                                QMFLAGS_IS_BLOCKING |
3178                                QMFLAGS_NO_MUTEX_LOCK |
3179                                QMFLAGS_NO_MUTEX_UNLOCK);
3180         if (status != VCHIQ_SUCCESS)
3181                 goto unlock_both_error_exit;
3182
3183         queue->local_insert++;
3184
3185         mutex_unlock(&state->slot_mutex);
3186         mutex_unlock(&service->bulk_mutex);
3187
3188         vchiq_log_trace(vchiq_core_log_level,
3189                 "%d: bt:%d %cx li=%x ri=%x p=%x",
3190                 state->id,
3191                 service->localport, dir_char,
3192                 queue->local_insert, queue->remote_insert, queue->process);
3193
3194 waiting:
3195         unlock_service(service);
3196
3197         status = VCHIQ_SUCCESS;
3198
3199         if (bulk_waiter) {
3200                 bulk_waiter->bulk = bulk;
3201                 if (wait_for_completion_interruptible(&bulk_waiter->event))
3202                         status = VCHIQ_RETRY;
3203                 else if (bulk_waiter->actual == VCHIQ_BULK_ACTUAL_ABORTED)
3204                         status = VCHIQ_ERROR;
3205         }
3206
3207         return status;
3208
3209 unlock_both_error_exit:
3210         mutex_unlock(&state->slot_mutex);
3211 cancel_bulk_error_exit:
3212         vchiq_complete_bulk(bulk);
3213 unlock_error_exit:
3214         mutex_unlock(&service->bulk_mutex);
3215
3216 error_exit:
3217         if (service)
3218                 unlock_service(service);
3219         return status;
3220 }
3221
3222 enum vchiq_status
3223 vchiq_queue_message(unsigned int handle,
3224                     ssize_t (*copy_callback)(void *context, void *dest,
3225                                              size_t offset, size_t maxsize),
3226                     void *context,
3227                     size_t size)
3228 {
3229         struct vchiq_service *service = find_service_by_handle(handle);
3230         enum vchiq_status status = VCHIQ_ERROR;
3231
3232         if (!service)
3233                 goto error_exit;
3234
3235         if (vchiq_check_service(service) != VCHIQ_SUCCESS)
3236                 goto error_exit;
3237
3238         if (!size) {
3239                 VCHIQ_SERVICE_STATS_INC(service, error_count);
3240                 goto error_exit;
3241
3242         }
3243
3244         if (size > VCHIQ_MAX_MSG_SIZE) {
3245                 VCHIQ_SERVICE_STATS_INC(service, error_count);
3246                 goto error_exit;
3247         }
3248
3249         switch (service->srvstate) {
3250         case VCHIQ_SRVSTATE_OPEN:
3251                 status = queue_message(service->state, service,
3252                                 VCHIQ_MAKE_MSG(VCHIQ_MSG_DATA,
3253                                         service->localport,
3254                                         service->remoteport),
3255                                 copy_callback, context, size, 1);
3256                 break;
3257         case VCHIQ_SRVSTATE_OPENSYNC:
3258                 status = queue_message_sync(service->state, service,
3259                                 VCHIQ_MAKE_MSG(VCHIQ_MSG_DATA,
3260                                         service->localport,
3261                                         service->remoteport),
3262                                 copy_callback, context, size, 1);
3263                 break;
3264         default:
3265                 status = VCHIQ_ERROR;
3266                 break;
3267         }
3268
3269 error_exit:
3270         if (service)
3271                 unlock_service(service);
3272
3273         return status;
3274 }
3275
3276 int vchiq_queue_kernel_message(unsigned int handle, void *data, unsigned int size)
3277 {
3278         enum vchiq_status status;
3279
3280         while (1) {
3281                 status = vchiq_queue_message(handle, memcpy_copy_callback,
3282                                              data, size);
3283
3284                 /*
3285                  * vchiq_queue_message() may return VCHIQ_RETRY, so we need to
3286                  * implement a retry mechanism since this function is supposed
3287                  * to block until queued
3288                  */
3289                 if (status != VCHIQ_RETRY)
3290                         break;
3291
3292                 msleep(1);
3293         }
3294
3295         return status;
3296 }
3297 EXPORT_SYMBOL(vchiq_queue_kernel_message);
3298
3299 void
3300 vchiq_release_message(unsigned int handle,
3301                       struct vchiq_header *header)
3302 {
3303         struct vchiq_service *service = find_service_by_handle(handle);
3304         struct vchiq_shared_state *remote;
3305         struct vchiq_state *state;
3306         int slot_index;
3307
3308         if (!service)
3309                 return;
3310
3311         state = service->state;
3312         remote = state->remote;
3313
3314         slot_index = SLOT_INDEX_FROM_DATA(state, (void *)header);
3315
3316         if ((slot_index >= remote->slot_first) &&
3317             (slot_index <= remote->slot_last)) {
3318                 int msgid = header->msgid;
3319
3320                 if (msgid & VCHIQ_MSGID_CLAIMED) {
3321                         struct vchiq_slot_info *slot_info =
3322                                 SLOT_INFO_FROM_INDEX(state, slot_index);
3323
3324                         release_slot(state, slot_info, header, service);
3325                 }
3326         } else if (slot_index == remote->slot_sync)
3327                 release_message_sync(state, header);
3328
3329         unlock_service(service);
3330 }
3331 EXPORT_SYMBOL(vchiq_release_message);
3332
3333 static void
3334 release_message_sync(struct vchiq_state *state, struct vchiq_header *header)
3335 {
3336         header->msgid = VCHIQ_MSGID_PADDING;
3337         remote_event_signal(&state->remote->sync_release);
3338 }
3339
3340 enum vchiq_status
3341 vchiq_get_peer_version(unsigned int handle, short *peer_version)
3342 {
3343         enum vchiq_status status = VCHIQ_ERROR;
3344         struct vchiq_service *service = find_service_by_handle(handle);
3345
3346         if (!service)
3347                 goto exit;
3348
3349         if (vchiq_check_service(service) != VCHIQ_SUCCESS)
3350                 goto exit;
3351
3352         if (!peer_version)
3353                 goto exit;
3354
3355         *peer_version = service->peer_version;
3356         status = VCHIQ_SUCCESS;
3357
3358 exit:
3359         if (service)
3360                 unlock_service(service);
3361         return status;
3362 }
3363 EXPORT_SYMBOL(vchiq_get_peer_version);
3364
3365 void vchiq_get_config(struct vchiq_config *config)
3366 {
3367         config->max_msg_size           = VCHIQ_MAX_MSG_SIZE;
3368         config->bulk_threshold         = VCHIQ_MAX_MSG_SIZE;
3369         config->max_outstanding_bulks  = VCHIQ_NUM_SERVICE_BULKS;
3370         config->max_services           = VCHIQ_MAX_SERVICES;
3371         config->version                = VCHIQ_VERSION;
3372         config->version_min            = VCHIQ_VERSION_MIN;
3373 }
3374
3375 int
3376 vchiq_set_service_option(unsigned int handle,
3377         enum vchiq_service_option option, int value)
3378 {
3379         struct vchiq_service *service = find_service_by_handle(handle);
3380         struct vchiq_service_quota *quota;
3381         int ret = -EINVAL;
3382
3383         if (!service)
3384                 return -EINVAL;
3385
3386         switch (option) {
3387         case VCHIQ_SERVICE_OPTION_AUTOCLOSE:
3388                 service->auto_close = value;
3389                 ret = 0;
3390                 break;
3391
3392         case VCHIQ_SERVICE_OPTION_SLOT_QUOTA:
3393                 quota = &service->state->service_quotas[service->localport];
3394                 if (value == 0)
3395                         value = service->state->default_slot_quota;
3396                 if ((value >= quota->slot_use_count) &&
3397                     (value < (unsigned short)~0)) {
3398                         quota->slot_quota = value;
3399                         if ((value >= quota->slot_use_count) &&
3400                             (quota->message_quota >= quota->message_use_count))
3401                                 /*
3402                                  * Signal the service that it may have
3403                                  * dropped below its quota
3404                                  */
3405                                 complete(&quota->quota_event);
3406                         ret = 0;
3407                 }
3408                 break;
3409
3410         case VCHIQ_SERVICE_OPTION_MESSAGE_QUOTA:
3411                 quota = &service->state->service_quotas[service->localport];
3412                 if (value == 0)
3413                         value = service->state->default_message_quota;
3414                 if ((value >= quota->message_use_count) &&
3415                     (value < (unsigned short)~0)) {
3416                         quota->message_quota = value;
3417                         if ((value >= quota->message_use_count) &&
3418                             (quota->slot_quota >= quota->slot_use_count))
3419                                 /*
3420                                  * Signal the service that it may have
3421                                  * dropped below its quota
3422                                  */
3423                                 complete(&quota->quota_event);
3424                         ret = 0;
3425                 }
3426                 break;
3427
3428         case VCHIQ_SERVICE_OPTION_SYNCHRONOUS:
3429                 if ((service->srvstate == VCHIQ_SRVSTATE_HIDDEN) ||
3430                     (service->srvstate == VCHIQ_SRVSTATE_LISTENING)) {
3431                         service->sync = value;
3432                         ret = 0;
3433                 }
3434                 break;
3435
3436         case VCHIQ_SERVICE_OPTION_TRACE:
3437                 service->trace = value;
3438                 ret = 0;
3439                 break;
3440
3441         default:
3442                 break;
3443         }
3444         unlock_service(service);
3445
3446         return ret;
3447 }
3448
3449 static int
3450 vchiq_dump_shared_state(void *dump_context, struct vchiq_state *state,
3451                         struct vchiq_shared_state *shared, const char *label)
3452 {
3453         static const char *const debug_names[] = {
3454                 "<entries>",
3455                 "SLOT_HANDLER_COUNT",
3456                 "SLOT_HANDLER_LINE",
3457                 "PARSE_LINE",
3458                 "PARSE_HEADER",
3459                 "PARSE_MSGID",
3460                 "AWAIT_COMPLETION_LINE",
3461                 "DEQUEUE_MESSAGE_LINE",
3462                 "SERVICE_CALLBACK_LINE",
3463                 "MSG_QUEUE_FULL_COUNT",
3464                 "COMPLETION_QUEUE_FULL_COUNT"
3465         };
3466         int i;
3467         char buf[80];
3468         int len;
3469         int err;
3470
3471         len = scnprintf(buf, sizeof(buf),
3472                 "  %s: slots %d-%d tx_pos=%x recycle=%x",
3473                 label, shared->slot_first, shared->slot_last,
3474                 shared->tx_pos, shared->slot_queue_recycle);
3475         err = vchiq_dump(dump_context, buf, len + 1);
3476         if (err)
3477                 return err;
3478
3479         len = scnprintf(buf, sizeof(buf),
3480                 "    Slots claimed:");
3481         err = vchiq_dump(dump_context, buf, len + 1);
3482         if (err)
3483                 return err;
3484
3485         for (i = shared->slot_first; i <= shared->slot_last; i++) {
3486                 struct vchiq_slot_info slot_info =
3487                                                 *SLOT_INFO_FROM_INDEX(state, i);
3488                 if (slot_info.use_count != slot_info.release_count) {
3489                         len = scnprintf(buf, sizeof(buf),
3490                                 "      %d: %d/%d", i, slot_info.use_count,
3491                                 slot_info.release_count);
3492                         err = vchiq_dump(dump_context, buf, len + 1);
3493                         if (err)
3494                                 return err;
3495                 }
3496         }
3497
3498         for (i = 1; i < shared->debug[DEBUG_ENTRIES]; i++) {
3499                 len = scnprintf(buf, sizeof(buf), "    DEBUG: %s = %d(%x)",
3500                         debug_names[i], shared->debug[i], shared->debug[i]);
3501                 err = vchiq_dump(dump_context, buf, len + 1);
3502                 if (err)
3503                         return err;
3504         }
3505         return 0;
3506 }
3507
3508 int vchiq_dump_state(void *dump_context, struct vchiq_state *state)
3509 {
3510         char buf[80];
3511         int len;
3512         int i;
3513         int err;
3514
3515         len = scnprintf(buf, sizeof(buf), "State %d: %s", state->id,
3516                 conn_state_names[state->conn_state]);
3517         err = vchiq_dump(dump_context, buf, len + 1);
3518         if (err)
3519                 return err;
3520
3521         len = scnprintf(buf, sizeof(buf),
3522                 "  tx_pos=%x(@%pK), rx_pos=%x(@%pK)",
3523                 state->local->tx_pos,
3524                 state->tx_data + (state->local_tx_pos & VCHIQ_SLOT_MASK),
3525                 state->rx_pos,
3526                 state->rx_data + (state->rx_pos & VCHIQ_SLOT_MASK));
3527         err = vchiq_dump(dump_context, buf, len + 1);
3528         if (err)
3529                 return err;
3530
3531         len = scnprintf(buf, sizeof(buf),
3532                 "  Version: %d (min %d)",
3533                 VCHIQ_VERSION, VCHIQ_VERSION_MIN);
3534         err = vchiq_dump(dump_context, buf, len + 1);
3535         if (err)
3536                 return err;
3537
3538         if (VCHIQ_ENABLE_STATS) {
3539                 len = scnprintf(buf, sizeof(buf),
3540                         "  Stats: ctrl_tx_count=%d, ctrl_rx_count=%d, error_count=%d",
3541                         state->stats.ctrl_tx_count, state->stats.ctrl_rx_count,
3542                         state->stats.error_count);
3543                 err = vchiq_dump(dump_context, buf, len + 1);
3544                 if (err)
3545                         return err;
3546         }
3547
3548         len = scnprintf(buf, sizeof(buf),
3549                 "  Slots: %d available (%d data), %d recyclable, %d stalls (%d data)",
3550                 ((state->slot_queue_available * VCHIQ_SLOT_SIZE) -
3551                         state->local_tx_pos) / VCHIQ_SLOT_SIZE,
3552                 state->data_quota - state->data_use_count,
3553                 state->local->slot_queue_recycle - state->slot_queue_available,
3554                 state->stats.slot_stalls, state->stats.data_stalls);
3555         err = vchiq_dump(dump_context, buf, len + 1);
3556         if (err)
3557                 return err;
3558
3559         err = vchiq_dump_platform_state(dump_context);
3560         if (err)
3561                 return err;
3562
3563         err = vchiq_dump_shared_state(dump_context,
3564                                       state,
3565                                       state->local,
3566                                       "Local");
3567         if (err)
3568                 return err;
3569         err = vchiq_dump_shared_state(dump_context,
3570                                       state,
3571                                       state->remote,
3572                                       "Remote");
3573         if (err)
3574                 return err;
3575
3576         err = vchiq_dump_platform_instances(dump_context);
3577         if (err)
3578                 return err;
3579
3580         for (i = 0; i < state->unused_service; i++) {
3581                 struct vchiq_service *service = find_service_by_port(state, i);
3582
3583                 if (service) {
3584                         err = vchiq_dump_service_state(dump_context, service);
3585                         unlock_service(service);
3586                         if (err)
3587                                 return err;
3588                 }
3589         }
3590         return 0;
3591 }
3592
3593 int vchiq_dump_service_state(void *dump_context, struct vchiq_service *service)
3594 {
3595         char buf[80];
3596         int len;
3597         int err;
3598         unsigned int ref_count;
3599
3600         /*Don't include the lock just taken*/
3601         ref_count = kref_read(&service->ref_count) - 1;
3602         len = scnprintf(buf, sizeof(buf), "Service %u: %s (ref %u)",
3603                         service->localport, srvstate_names[service->srvstate],
3604                         ref_count);
3605
3606         if (service->srvstate != VCHIQ_SRVSTATE_FREE) {
3607                 char remoteport[30];
3608                 struct vchiq_service_quota *quota =
3609                         &service->state->service_quotas[service->localport];
3610                 int fourcc = service->base.fourcc;
3611                 int tx_pending, rx_pending;
3612
3613                 if (service->remoteport != VCHIQ_PORT_FREE) {
3614                         int len2 = scnprintf(remoteport, sizeof(remoteport),
3615                                 "%u", service->remoteport);
3616
3617                         if (service->public_fourcc != VCHIQ_FOURCC_INVALID)
3618                                 scnprintf(remoteport + len2,
3619                                         sizeof(remoteport) - len2,
3620                                         " (client %x)", service->client_id);
3621                 } else
3622                         strcpy(remoteport, "n/a");
3623
3624                 len += scnprintf(buf + len, sizeof(buf) - len,
3625                         " '%c%c%c%c' remote %s (msg use %d/%d, slot use %d/%d)",
3626                         VCHIQ_FOURCC_AS_4CHARS(fourcc),
3627                         remoteport,
3628                         quota->message_use_count,
3629                         quota->message_quota,
3630                         quota->slot_use_count,
3631                         quota->slot_quota);
3632
3633                 err = vchiq_dump(dump_context, buf, len + 1);
3634                 if (err)
3635                         return err;
3636
3637                 tx_pending = service->bulk_tx.local_insert -
3638                         service->bulk_tx.remote_insert;
3639
3640                 rx_pending = service->bulk_rx.local_insert -
3641                         service->bulk_rx.remote_insert;
3642
3643                 len = scnprintf(buf, sizeof(buf),
3644                         "  Bulk: tx_pending=%d (size %d), rx_pending=%d (size %d)",
3645                         tx_pending,
3646                         tx_pending ? service->bulk_tx.bulks[
3647                         BULK_INDEX(service->bulk_tx.remove)].size : 0,
3648                         rx_pending,
3649                         rx_pending ? service->bulk_rx.bulks[
3650                         BULK_INDEX(service->bulk_rx.remove)].size : 0);
3651
3652                 if (VCHIQ_ENABLE_STATS) {
3653                         err = vchiq_dump(dump_context, buf, len + 1);
3654                         if (err)
3655                                 return err;
3656
3657                         len = scnprintf(buf, sizeof(buf),
3658                                 "  Ctrl: tx_count=%d, tx_bytes=%llu, rx_count=%d, rx_bytes=%llu",
3659                                 service->stats.ctrl_tx_count,
3660                                 service->stats.ctrl_tx_bytes,
3661                                 service->stats.ctrl_rx_count,
3662                                 service->stats.ctrl_rx_bytes);
3663                         err = vchiq_dump(dump_context, buf, len + 1);
3664                         if (err)
3665                                 return err;
3666
3667                         len = scnprintf(buf, sizeof(buf),
3668                                 "  Bulk: tx_count=%d, tx_bytes=%llu, rx_count=%d, rx_bytes=%llu",
3669                                 service->stats.bulk_tx_count,
3670                                 service->stats.bulk_tx_bytes,
3671                                 service->stats.bulk_rx_count,
3672                                 service->stats.bulk_rx_bytes);
3673                         err = vchiq_dump(dump_context, buf, len + 1);
3674                         if (err)
3675                                 return err;
3676
3677                         len = scnprintf(buf, sizeof(buf),
3678                                 "  %d quota stalls, %d slot stalls, %d bulk stalls, %d aborted, %d errors",
3679                                 service->stats.quota_stalls,
3680                                 service->stats.slot_stalls,
3681                                 service->stats.bulk_stalls,
3682                                 service->stats.bulk_aborted_count,
3683                                 service->stats.error_count);
3684                 }
3685         }
3686
3687         err = vchiq_dump(dump_context, buf, len + 1);
3688         if (err)
3689                 return err;
3690
3691         if (service->srvstate != VCHIQ_SRVSTATE_FREE)
3692                 err = vchiq_dump_platform_service_state(dump_context, service);
3693         return err;
3694 }
3695
3696 void
3697 vchiq_loud_error_header(void)
3698 {
3699         vchiq_log_error(vchiq_core_log_level,
3700                 "============================================================================");
3701         vchiq_log_error(vchiq_core_log_level,
3702                 "============================================================================");
3703         vchiq_log_error(vchiq_core_log_level, "=====");
3704 }
3705
3706 void
3707 vchiq_loud_error_footer(void)
3708 {
3709         vchiq_log_error(vchiq_core_log_level, "=====");
3710         vchiq_log_error(vchiq_core_log_level,
3711                 "============================================================================");
3712         vchiq_log_error(vchiq_core_log_level,
3713                 "============================================================================");
3714 }
3715
3716 enum vchiq_status vchiq_send_remote_use(struct vchiq_state *state)
3717 {
3718         if (state->conn_state == VCHIQ_CONNSTATE_DISCONNECTED)
3719                 return VCHIQ_RETRY;
3720
3721         return queue_message(state, NULL,
3722                              VCHIQ_MAKE_MSG(VCHIQ_MSG_REMOTE_USE, 0, 0),
3723                              NULL, NULL, 0, 0);
3724 }
3725
3726 enum vchiq_status vchiq_send_remote_use_active(struct vchiq_state *state)
3727 {
3728         if (state->conn_state == VCHIQ_CONNSTATE_DISCONNECTED)
3729                 return VCHIQ_RETRY;
3730
3731         return queue_message(state, NULL,
3732                              VCHIQ_MAKE_MSG(VCHIQ_MSG_REMOTE_USE_ACTIVE, 0, 0),
3733                              NULL, NULL, 0, 0);
3734 }
3735
3736 void vchiq_log_dump_mem(const char *label, u32 addr, const void *void_mem,
3737         size_t num_bytes)
3738 {
3739         const u8  *mem = void_mem;
3740         size_t          offset;
3741         char            line_buf[100];
3742         char           *s;
3743
3744         while (num_bytes > 0) {
3745                 s = line_buf;
3746
3747                 for (offset = 0; offset < 16; offset++) {
3748                         if (offset < num_bytes)
3749                                 s += scnprintf(s, 4, "%02x ", mem[offset]);
3750                         else
3751                                 s += scnprintf(s, 4, "   ");
3752                 }
3753
3754                 for (offset = 0; offset < 16; offset++) {
3755                         if (offset < num_bytes) {
3756                                 u8 ch = mem[offset];
3757
3758                                 if ((ch < ' ') || (ch > '~'))
3759                                         ch = '.';
3760                                 *s++ = (char)ch;
3761                         }
3762                 }
3763                 *s++ = '\0';
3764
3765                 if (label && (*label != '\0'))
3766                         vchiq_log_trace(VCHIQ_LOG_TRACE,
3767                                 "%s: %08x: %s", label, addr, line_buf);
3768                 else
3769                         vchiq_log_trace(VCHIQ_LOG_TRACE,
3770                                 "%08x: %s", addr, line_buf);
3771
3772                 addr += 16;
3773                 mem += 16;
3774                 if (num_bytes > 16)
3775                         num_bytes -= 16;
3776                 else
3777                         num_bytes = 0;
3778         }
3779 }