staging: vchiq: Use the old dma controller for OF config on platform devices
[platform/kernel/linux-rpi.git] / drivers / staging / vc04_services / interface / vchiq_arm / vchiq_arm.c
1 /**
2  * Copyright (c) 2014 Raspberry Pi (Trading) Ltd. All rights reserved.
3  * Copyright (c) 2010-2012 Broadcom. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions, and the following disclaimer,
10  *    without modification.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The names of the above-listed copyright holders may not be used
15  *    to endorse or promote products derived from this software without
16  *    specific prior written permission.
17  *
18  * ALTERNATIVELY, this software may be distributed under the terms of the
19  * GNU General Public License ("GPL") version 2, as published by the Free
20  * Software Foundation.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
23  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
26  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
31  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 #include <linux/kernel.h>
36 #include <linux/module.h>
37 #include <linux/sched/signal.h>
38 #include <linux/types.h>
39 #include <linux/errno.h>
40 #include <linux/cdev.h>
41 #include <linux/fs.h>
42 #include <linux/device.h>
43 #include <linux/mm.h>
44 #include <linux/highmem.h>
45 #include <linux/pagemap.h>
46 #include <linux/bug.h>
47 #include <linux/semaphore.h>
48 #include <linux/list.h>
49 #include <linux/of.h>
50 #include <linux/platform_device.h>
51 #include <linux/compat.h>
52 #include <linux/dma-mapping.h>
53 #include <soc/bcm2835/raspberrypi-firmware.h>
54
55 #include "vchiq_core.h"
56 #include "vchiq_ioctl.h"
57 #include "vchiq_arm.h"
58 #include "vchiq_debugfs.h"
59 #include "vchiq_killable.h"
60
61 #define DEVICE_NAME "vchiq"
62
63 /* Override the default prefix, which would be vchiq_arm (from the filename) */
64 #undef MODULE_PARAM_PREFIX
65 #define MODULE_PARAM_PREFIX DEVICE_NAME "."
66
67 #define VCHIQ_MINOR 0
68
69 /* Some per-instance constants */
70 #define MAX_COMPLETIONS 128
71 #define MAX_SERVICES 64
72 #define MAX_ELEMENTS 8
73 #define MSG_QUEUE_SIZE 128
74
75 #define KEEPALIVE_VER 1
76 #define KEEPALIVE_VER_MIN KEEPALIVE_VER
77
78 /* Run time control of log level, based on KERN_XXX level. */
79 int vchiq_arm_log_level = VCHIQ_LOG_DEFAULT;
80 int vchiq_susp_log_level = VCHIQ_LOG_ERROR;
81
82 #define SUSPEND_TIMER_TIMEOUT_MS 100
83 #define SUSPEND_RETRY_TIMER_TIMEOUT_MS 1000
84
85 #define VC_SUSPEND_NUM_OFFSET 3 /* number of values before idle which are -ve */
86 static const char *const suspend_state_names[] = {
87         "VC_SUSPEND_FORCE_CANCELED",
88         "VC_SUSPEND_REJECTED",
89         "VC_SUSPEND_FAILED",
90         "VC_SUSPEND_IDLE",
91         "VC_SUSPEND_REQUESTED",
92         "VC_SUSPEND_IN_PROGRESS",
93         "VC_SUSPEND_SUSPENDED"
94 };
95 #define VC_RESUME_NUM_OFFSET 1 /* number of values before idle which are -ve */
96 static const char *const resume_state_names[] = {
97         "VC_RESUME_FAILED",
98         "VC_RESUME_IDLE",
99         "VC_RESUME_REQUESTED",
100         "VC_RESUME_IN_PROGRESS",
101         "VC_RESUME_RESUMED"
102 };
103 /* The number of times we allow force suspend to timeout before actually
104 ** _forcing_ suspend.  This is to cater for SW which fails to release vchiq
105 ** correctly - we don't want to prevent ARM suspend indefinitely in this case.
106 */
107 #define FORCE_SUSPEND_FAIL_MAX 8
108
109 /* The time in ms allowed for videocore to go idle when force suspend has been
110  * requested */
111 #define FORCE_SUSPEND_TIMEOUT_MS 200
112
113 static void suspend_timer_callback(struct timer_list *t);
114
115 typedef struct user_service_struct {
116         VCHIQ_SERVICE_T *service;
117         void *userdata;
118         VCHIQ_INSTANCE_T instance;
119         char is_vchi;
120         char dequeue_pending;
121         char close_pending;
122         int message_available_pos;
123         int msg_insert;
124         int msg_remove;
125         struct semaphore insert_event;
126         struct semaphore remove_event;
127         struct semaphore close_event;
128         VCHIQ_HEADER_T * msg_queue[MSG_QUEUE_SIZE];
129 } USER_SERVICE_T;
130
131 struct bulk_waiter_node {
132         struct bulk_waiter bulk_waiter;
133         int pid;
134         struct list_head list;
135 };
136
137 struct vchiq_instance_struct {
138         VCHIQ_STATE_T *state;
139         VCHIQ_COMPLETION_DATA_T completions[MAX_COMPLETIONS];
140         int completion_insert;
141         int completion_remove;
142         struct semaphore insert_event;
143         struct semaphore remove_event;
144         struct mutex completion_mutex;
145
146         int connected;
147         int closing;
148         int pid;
149         int mark;
150         int use_close_delivered;
151         int trace;
152
153         struct list_head bulk_waiter_list;
154         struct mutex bulk_waiter_list_mutex;
155
156         VCHIQ_DEBUGFS_NODE_T debugfs_node;
157 };
158
159 typedef struct dump_context_struct {
160         char __user *buf;
161         size_t actual;
162         size_t space;
163         loff_t offset;
164 } DUMP_CONTEXT_T;
165
166 static struct cdev    vchiq_cdev;
167 static dev_t          vchiq_devid;
168 static VCHIQ_STATE_T g_state;
169 static struct class  *vchiq_class;
170 static struct device *vchiq_dev;
171 static DEFINE_SPINLOCK(msg_queue_spinlock);
172 static struct platform_device *bcm2835_camera;
173 static struct platform_device *bcm2835_codec;
174 static struct platform_device *vcsm_cma;
175
176 static struct vchiq_drvdata bcm2835_drvdata = {
177         .cache_line_size = 32,
178 };
179
180 static struct vchiq_drvdata bcm2836_drvdata = {
181         .cache_line_size = 64,
182 };
183
184 static struct vchiq_drvdata bcm2838_drvdata = {
185         .cache_line_size = 64,
186         .use_36bit_addrs = true,
187 };
188
189 static const char *const ioctl_names[] = {
190         "CONNECT",
191         "SHUTDOWN",
192         "CREATE_SERVICE",
193         "REMOVE_SERVICE",
194         "QUEUE_MESSAGE",
195         "QUEUE_BULK_TRANSMIT",
196         "QUEUE_BULK_RECEIVE",
197         "AWAIT_COMPLETION",
198         "DEQUEUE_MESSAGE",
199         "GET_CLIENT_ID",
200         "GET_CONFIG",
201         "CLOSE_SERVICE",
202         "USE_SERVICE",
203         "RELEASE_SERVICE",
204         "SET_SERVICE_OPTION",
205         "DUMP_PHYS_MEM",
206         "LIB_VERSION",
207         "CLOSE_DELIVERED"
208 };
209
210 vchiq_static_assert(ARRAY_SIZE(ioctl_names) ==
211                     (VCHIQ_IOC_MAX + 1));
212
213 static VCHIQ_STATUS_T
214 vchiq_blocking_bulk_transfer(VCHIQ_SERVICE_HANDLE_T handle, void *data,
215         unsigned int size, VCHIQ_BULK_DIR_T dir);
216
217 #define VCHIQ_INIT_RETRIES 10
218 VCHIQ_STATUS_T vchiq_initialise(VCHIQ_INSTANCE_T *instance_out)
219 {
220         VCHIQ_STATUS_T status = VCHIQ_ERROR;
221         VCHIQ_STATE_T *state;
222         VCHIQ_INSTANCE_T instance = NULL;
223         int i;
224
225         vchiq_log_trace(vchiq_core_log_level, "%s called", __func__);
226
227         /* VideoCore may not be ready due to boot up timing.
228          * It may never be ready if kernel and firmware are mismatched,so don't
229          * block forever.
230          */
231         for (i = 0; i < VCHIQ_INIT_RETRIES; i++) {
232                 state = vchiq_get_state();
233                 if (state)
234                         break;
235                 usleep_range(500, 600);
236         }
237         if (i == VCHIQ_INIT_RETRIES) {
238                 vchiq_log_error(vchiq_core_log_level,
239                         "%s: videocore not initialized\n", __func__);
240                 goto failed;
241         } else if (i > 0) {
242                 vchiq_log_warning(vchiq_core_log_level,
243                         "%s: videocore initialized after %d retries\n",
244                         __func__, i);
245         }
246
247         instance = kzalloc(sizeof(*instance), GFP_KERNEL);
248         if (!instance) {
249                 vchiq_log_error(vchiq_core_log_level,
250                         "%s: error allocating vchiq instance\n", __func__);
251                 goto failed;
252         }
253
254         instance->connected = 0;
255         instance->state = state;
256         mutex_init(&instance->bulk_waiter_list_mutex);
257         INIT_LIST_HEAD(&instance->bulk_waiter_list);
258
259         *instance_out = instance;
260
261         status = VCHIQ_SUCCESS;
262
263 failed:
264         vchiq_log_trace(vchiq_core_log_level,
265                 "%s(%p): returning %d", __func__, instance, status);
266
267         return status;
268 }
269 EXPORT_SYMBOL(vchiq_initialise);
270
271 VCHIQ_STATUS_T vchiq_shutdown(VCHIQ_INSTANCE_T instance)
272 {
273         VCHIQ_STATUS_T status;
274         VCHIQ_STATE_T *state = instance->state;
275
276         vchiq_log_trace(vchiq_core_log_level,
277                 "%s(%p) called", __func__, instance);
278
279         if (mutex_lock_killable(&state->mutex) != 0)
280                 return VCHIQ_RETRY;
281
282         /* Remove all services */
283         status = vchiq_shutdown_internal(state, instance);
284
285         mutex_unlock(&state->mutex);
286
287         vchiq_log_trace(vchiq_core_log_level,
288                 "%s(%p): returning %d", __func__, instance, status);
289
290         if (status == VCHIQ_SUCCESS) {
291                 struct list_head *pos, *next;
292
293                 list_for_each_safe(pos, next,
294                                 &instance->bulk_waiter_list) {
295                         struct bulk_waiter_node *waiter;
296
297                         waiter = list_entry(pos,
298                                         struct bulk_waiter_node,
299                                         list);
300                         list_del(pos);
301                         vchiq_log_info(vchiq_arm_log_level,
302                                         "bulk_waiter - cleaned up %pK for pid %d",
303                                         waiter, waiter->pid);
304                         kfree(waiter);
305                 }
306                 kfree(instance);
307         }
308
309         return status;
310 }
311 EXPORT_SYMBOL(vchiq_shutdown);
312
313 static int vchiq_is_connected(VCHIQ_INSTANCE_T instance)
314 {
315         return instance->connected;
316 }
317
318 VCHIQ_STATUS_T vchiq_connect(VCHIQ_INSTANCE_T instance)
319 {
320         VCHIQ_STATUS_T status;
321         VCHIQ_STATE_T *state = instance->state;
322
323         vchiq_log_trace(vchiq_core_log_level,
324                 "%s(%p) called", __func__, instance);
325
326         if (mutex_lock_killable(&state->mutex) != 0) {
327                 vchiq_log_trace(vchiq_core_log_level,
328                         "%s: call to mutex_lock failed", __func__);
329                 status = VCHIQ_RETRY;
330                 goto failed;
331         }
332         status = vchiq_connect_internal(state, instance);
333
334         if (status == VCHIQ_SUCCESS)
335                 instance->connected = 1;
336
337         mutex_unlock(&state->mutex);
338
339 failed:
340         vchiq_log_trace(vchiq_core_log_level,
341                 "%s(%p): returning %d", __func__, instance, status);
342
343         return status;
344 }
345 EXPORT_SYMBOL(vchiq_connect);
346
347 VCHIQ_STATUS_T vchiq_add_service(
348         VCHIQ_INSTANCE_T              instance,
349         const VCHIQ_SERVICE_PARAMS_T *params,
350         VCHIQ_SERVICE_HANDLE_T       *phandle)
351 {
352         VCHIQ_STATUS_T status;
353         VCHIQ_STATE_T *state = instance->state;
354         VCHIQ_SERVICE_T *service = NULL;
355         int srvstate;
356
357         vchiq_log_trace(vchiq_core_log_level,
358                 "%s(%p) called", __func__, instance);
359
360         *phandle = VCHIQ_SERVICE_HANDLE_INVALID;
361
362         srvstate = vchiq_is_connected(instance)
363                 ? VCHIQ_SRVSTATE_LISTENING
364                 : VCHIQ_SRVSTATE_HIDDEN;
365
366         service = vchiq_add_service_internal(
367                 state,
368                 params,
369                 srvstate,
370                 instance,
371                 NULL);
372
373         if (service) {
374                 *phandle = service->handle;
375                 status = VCHIQ_SUCCESS;
376         } else
377                 status = VCHIQ_ERROR;
378
379         vchiq_log_trace(vchiq_core_log_level,
380                 "%s(%p): returning %d", __func__, instance, status);
381
382         return status;
383 }
384 EXPORT_SYMBOL(vchiq_add_service);
385
386 VCHIQ_STATUS_T vchiq_open_service(
387         VCHIQ_INSTANCE_T              instance,
388         const VCHIQ_SERVICE_PARAMS_T *params,
389         VCHIQ_SERVICE_HANDLE_T       *phandle)
390 {
391         VCHIQ_STATUS_T   status = VCHIQ_ERROR;
392         VCHIQ_STATE_T   *state = instance->state;
393         VCHIQ_SERVICE_T *service = NULL;
394
395         vchiq_log_trace(vchiq_core_log_level,
396                 "%s(%p) called", __func__, instance);
397
398         *phandle = VCHIQ_SERVICE_HANDLE_INVALID;
399
400         if (!vchiq_is_connected(instance))
401                 goto failed;
402
403         service = vchiq_add_service_internal(state,
404                 params,
405                 VCHIQ_SRVSTATE_OPENING,
406                 instance,
407                 NULL);
408
409         if (service) {
410                 *phandle = service->handle;
411                 status = vchiq_open_service_internal(service, current->pid);
412                 if (status != VCHIQ_SUCCESS) {
413                         vchiq_remove_service(service->handle);
414                         *phandle = VCHIQ_SERVICE_HANDLE_INVALID;
415                 }
416         }
417
418 failed:
419         vchiq_log_trace(vchiq_core_log_level,
420                 "%s(%p): returning %d", __func__, instance, status);
421
422         return status;
423 }
424 EXPORT_SYMBOL(vchiq_open_service);
425
426 VCHIQ_STATUS_T
427 vchiq_bulk_transmit(VCHIQ_SERVICE_HANDLE_T handle, const void *data,
428         unsigned int size, void *userdata, VCHIQ_BULK_MODE_T mode)
429 {
430         VCHIQ_STATUS_T status;
431
432         switch (mode) {
433         case VCHIQ_BULK_MODE_NOCALLBACK:
434         case VCHIQ_BULK_MODE_CALLBACK:
435                 status = vchiq_bulk_transfer(handle,
436                         VCHI_MEM_HANDLE_INVALID, (void *)data, size, userdata,
437                         mode, VCHIQ_BULK_TRANSMIT);
438                 break;
439         case VCHIQ_BULK_MODE_BLOCKING:
440                 status = vchiq_blocking_bulk_transfer(handle,
441                         (void *)data, size, VCHIQ_BULK_TRANSMIT);
442                 break;
443         default:
444                 return VCHIQ_ERROR;
445         }
446
447         return status;
448 }
449 EXPORT_SYMBOL(vchiq_bulk_transmit);
450
451 VCHIQ_STATUS_T
452 vchiq_bulk_receive(VCHIQ_SERVICE_HANDLE_T handle, void *data,
453         unsigned int size, void *userdata, VCHIQ_BULK_MODE_T mode)
454 {
455         VCHIQ_STATUS_T status;
456
457         switch (mode) {
458         case VCHIQ_BULK_MODE_NOCALLBACK:
459         case VCHIQ_BULK_MODE_CALLBACK:
460                 status = vchiq_bulk_transfer(handle,
461                         VCHI_MEM_HANDLE_INVALID, data, size, userdata,
462                         mode, VCHIQ_BULK_RECEIVE);
463                 break;
464         case VCHIQ_BULK_MODE_BLOCKING:
465                 status = vchiq_blocking_bulk_transfer(handle,
466                         (void *)data, size, VCHIQ_BULK_RECEIVE);
467                 break;
468         default:
469                 return VCHIQ_ERROR;
470         }
471
472         return status;
473 }
474 EXPORT_SYMBOL(vchiq_bulk_receive);
475
476 static VCHIQ_STATUS_T
477 vchiq_blocking_bulk_transfer(VCHIQ_SERVICE_HANDLE_T handle, void *data,
478         unsigned int size, VCHIQ_BULK_DIR_T dir)
479 {
480         VCHIQ_INSTANCE_T instance;
481         VCHIQ_SERVICE_T *service;
482         VCHIQ_STATUS_T status;
483         struct bulk_waiter_node *waiter = NULL;
484         struct list_head *pos;
485
486         service = find_service_by_handle(handle);
487         if (!service)
488                 return VCHIQ_ERROR;
489
490         instance = service->instance;
491
492         unlock_service(service);
493
494         mutex_lock(&instance->bulk_waiter_list_mutex);
495         list_for_each(pos, &instance->bulk_waiter_list) {
496                 if (list_entry(pos, struct bulk_waiter_node,
497                                 list)->pid == current->pid) {
498                         waiter = list_entry(pos,
499                                 struct bulk_waiter_node,
500                                 list);
501                         list_del(pos);
502                         break;
503                 }
504         }
505         mutex_unlock(&instance->bulk_waiter_list_mutex);
506
507         if (waiter) {
508                 VCHIQ_BULK_T *bulk = waiter->bulk_waiter.bulk;
509
510                 if (bulk) {
511                         /* This thread has an outstanding bulk transfer. */
512                         if ((bulk->data != data) ||
513                                 (bulk->size != size)) {
514                                 /* This is not a retry of the previous one.
515                                  * Cancel the signal when the transfer
516                                  * completes.
517                                  */
518                                 spin_lock(&bulk_waiter_spinlock);
519                                 bulk->userdata = NULL;
520                                 spin_unlock(&bulk_waiter_spinlock);
521                         }
522                 }
523         }
524
525         if (!waiter) {
526                 waiter = kzalloc(sizeof(struct bulk_waiter_node), GFP_KERNEL);
527                 if (!waiter) {
528                         vchiq_log_error(vchiq_core_log_level,
529                                 "%s - out of memory", __func__);
530                         return VCHIQ_ERROR;
531                 }
532         }
533
534         status = vchiq_bulk_transfer(handle, VCHI_MEM_HANDLE_INVALID,
535                 data, size, &waiter->bulk_waiter, VCHIQ_BULK_MODE_BLOCKING,
536                 dir);
537         if ((status != VCHIQ_RETRY) || fatal_signal_pending(current) ||
538                 !waiter->bulk_waiter.bulk) {
539                 VCHIQ_BULK_T *bulk = waiter->bulk_waiter.bulk;
540
541                 if (bulk) {
542                         /* Cancel the signal when the transfer
543                          * completes.
544                          */
545                         spin_lock(&bulk_waiter_spinlock);
546                         bulk->userdata = NULL;
547                         spin_unlock(&bulk_waiter_spinlock);
548                 }
549                 kfree(waiter);
550         } else {
551                 waiter->pid = current->pid;
552                 mutex_lock(&instance->bulk_waiter_list_mutex);
553                 list_add(&waiter->list, &instance->bulk_waiter_list);
554                 mutex_unlock(&instance->bulk_waiter_list_mutex);
555                 vchiq_log_info(vchiq_arm_log_level,
556                                 "saved bulk_waiter %pK for pid %d",
557                                 waiter, current->pid);
558         }
559
560         return status;
561 }
562 /****************************************************************************
563 *
564 *   add_completion
565 *
566 ***************************************************************************/
567
568 static VCHIQ_STATUS_T
569 add_completion(VCHIQ_INSTANCE_T instance, VCHIQ_REASON_T reason,
570         VCHIQ_HEADER_T *header, USER_SERVICE_T *user_service,
571         void *bulk_userdata)
572 {
573         VCHIQ_COMPLETION_DATA_T *completion;
574         int insert;
575
576         DEBUG_INITIALISE(g_state.local)
577
578         insert = instance->completion_insert;
579         while ((insert - instance->completion_remove) >= MAX_COMPLETIONS) {
580                 /* Out of space - wait for the client */
581                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
582                 vchiq_log_trace(vchiq_arm_log_level,
583                         "%s - completion queue full", __func__);
584                 DEBUG_COUNT(COMPLETION_QUEUE_FULL_COUNT);
585                 if (down_interruptible(&instance->remove_event) != 0) {
586                         vchiq_log_info(vchiq_arm_log_level,
587                                 "service_callback interrupted");
588                         return VCHIQ_RETRY;
589                 } else if (instance->closing) {
590                         vchiq_log_info(vchiq_arm_log_level,
591                                 "service_callback closing");
592                         return VCHIQ_SUCCESS;
593                 }
594                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
595         }
596
597         completion = &instance->completions[insert & (MAX_COMPLETIONS - 1)];
598
599         completion->header = header;
600         completion->reason = reason;
601         /* N.B. service_userdata is updated while processing AWAIT_COMPLETION */
602         completion->service_userdata = user_service->service;
603         completion->bulk_userdata = bulk_userdata;
604
605         if (reason == VCHIQ_SERVICE_CLOSED) {
606                 /* Take an extra reference, to be held until
607                    this CLOSED notification is delivered. */
608                 lock_service(user_service->service);
609                 if (instance->use_close_delivered)
610                         user_service->close_pending = 1;
611         }
612
613         /* A write barrier is needed here to ensure that the entire completion
614                 record is written out before the insert point. */
615         wmb();
616
617         if (reason == VCHIQ_MESSAGE_AVAILABLE)
618                 user_service->message_available_pos = insert;
619
620         insert++;
621         instance->completion_insert = insert;
622
623         up(&instance->insert_event);
624
625         return VCHIQ_SUCCESS;
626 }
627
628 /****************************************************************************
629 *
630 *   service_callback
631 *
632 ***************************************************************************/
633
634 static VCHIQ_STATUS_T
635 service_callback(VCHIQ_REASON_T reason, VCHIQ_HEADER_T *header,
636         VCHIQ_SERVICE_HANDLE_T handle, void *bulk_userdata)
637 {
638         /* How do we ensure the callback goes to the right client?
639         ** The service_user data points to a USER_SERVICE_T record containing
640         ** the original callback and the user state structure, which contains a
641         ** circular buffer for completion records.
642         */
643         USER_SERVICE_T *user_service;
644         VCHIQ_SERVICE_T *service;
645         VCHIQ_INSTANCE_T instance;
646         bool skip_completion = false;
647
648         DEBUG_INITIALISE(g_state.local)
649
650         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
651
652         service = handle_to_service(handle);
653         BUG_ON(!service);
654         user_service = (USER_SERVICE_T *)service->base.userdata;
655         instance = user_service->instance;
656
657         if (!instance || instance->closing)
658                 return VCHIQ_SUCCESS;
659
660         vchiq_log_trace(vchiq_arm_log_level,
661                 "%s - service %lx(%d,%p), reason %d, header %lx, "
662                 "instance %lx, bulk_userdata %lx",
663                 __func__, (unsigned long)user_service,
664                 service->localport, user_service->userdata,
665                 reason, (unsigned long)header,
666                 (unsigned long)instance, (unsigned long)bulk_userdata);
667
668         if (header && user_service->is_vchi) {
669                 spin_lock(&msg_queue_spinlock);
670                 while (user_service->msg_insert ==
671                         (user_service->msg_remove + MSG_QUEUE_SIZE)) {
672                         spin_unlock(&msg_queue_spinlock);
673                         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
674                         DEBUG_COUNT(MSG_QUEUE_FULL_COUNT);
675                         vchiq_log_trace(vchiq_arm_log_level,
676                                 "service_callback - msg queue full");
677                         /* If there is no MESSAGE_AVAILABLE in the completion
678                         ** queue, add one
679                         */
680                         if ((user_service->message_available_pos -
681                                 instance->completion_remove) < 0) {
682                                 VCHIQ_STATUS_T status;
683
684                                 vchiq_log_info(vchiq_arm_log_level,
685                                         "Inserting extra MESSAGE_AVAILABLE");
686                                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
687                                 status = add_completion(instance, reason,
688                                         NULL, user_service, bulk_userdata);
689                                 if (status != VCHIQ_SUCCESS) {
690                                         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
691                                         return status;
692                                 }
693                         }
694
695                         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
696                         if (down_interruptible(&user_service->remove_event)
697                                 != 0) {
698                                 vchiq_log_info(vchiq_arm_log_level,
699                                         "%s interrupted", __func__);
700                                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
701                                 return VCHIQ_RETRY;
702                         } else if (instance->closing) {
703                                 vchiq_log_info(vchiq_arm_log_level,
704                                         "%s closing", __func__);
705                                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
706                                 return VCHIQ_ERROR;
707                         }
708                         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
709                         spin_lock(&msg_queue_spinlock);
710                 }
711
712                 user_service->msg_queue[user_service->msg_insert &
713                         (MSG_QUEUE_SIZE - 1)] = header;
714                 user_service->msg_insert++;
715
716                 /* If there is a thread waiting in DEQUEUE_MESSAGE, or if
717                 ** there is a MESSAGE_AVAILABLE in the completion queue then
718                 ** bypass the completion queue.
719                 */
720                 if (((user_service->message_available_pos -
721                         instance->completion_remove) >= 0) ||
722                         user_service->dequeue_pending) {
723                         user_service->dequeue_pending = 0;
724                         skip_completion = true;
725                 }
726
727                 spin_unlock(&msg_queue_spinlock);
728                 up(&user_service->insert_event);
729
730                 header = NULL;
731         }
732         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
733
734         if (skip_completion)
735                 return VCHIQ_SUCCESS;
736
737         return add_completion(instance, reason, header, user_service,
738                 bulk_userdata);
739 }
740
741 /****************************************************************************
742 *
743 *   user_service_free
744 *
745 ***************************************************************************/
746 static void
747 user_service_free(void *userdata)
748 {
749         kfree(userdata);
750 }
751
752 /****************************************************************************
753 *
754 *   close_delivered
755 *
756 ***************************************************************************/
757 static void close_delivered(USER_SERVICE_T *user_service)
758 {
759         vchiq_log_info(vchiq_arm_log_level,
760                 "%s(handle=%x)",
761                 __func__, user_service->service->handle);
762
763         if (user_service->close_pending) {
764                 /* Allow the underlying service to be culled */
765                 unlock_service(user_service->service);
766
767                 /* Wake the user-thread blocked in close_ or remove_service */
768                 up(&user_service->close_event);
769
770                 user_service->close_pending = 0;
771         }
772 }
773
774 struct vchiq_io_copy_callback_context {
775         struct vchiq_element *current_element;
776         size_t current_element_offset;
777         unsigned long elements_to_go;
778         size_t current_offset;
779 };
780
781 static ssize_t
782 vchiq_ioc_copy_element_data(
783         void *context,
784         void *dest,
785         size_t offset,
786         size_t maxsize)
787 {
788         long res;
789         size_t bytes_this_round;
790         struct vchiq_io_copy_callback_context *copy_context =
791                 (struct vchiq_io_copy_callback_context *)context;
792
793         if (offset != copy_context->current_offset)
794                 return 0;
795
796         if (!copy_context->elements_to_go)
797                 return 0;
798
799         /*
800          * Complex logic here to handle the case of 0 size elements
801          * in the middle of the array of elements.
802          *
803          * Need to skip over these 0 size elements.
804          */
805         while (1) {
806                 bytes_this_round = min(copy_context->current_element->size -
807                                        copy_context->current_element_offset,
808                                        maxsize);
809
810                 if (bytes_this_round)
811                         break;
812
813                 copy_context->elements_to_go--;
814                 copy_context->current_element++;
815                 copy_context->current_element_offset = 0;
816
817                 if (!copy_context->elements_to_go)
818                         return 0;
819         }
820
821         res = copy_from_user(dest,
822                              copy_context->current_element->data +
823                              copy_context->current_element_offset,
824                              bytes_this_round);
825
826         if (res != 0)
827                 return -EFAULT;
828
829         copy_context->current_element_offset += bytes_this_round;
830         copy_context->current_offset += bytes_this_round;
831
832         /*
833          * Check if done with current element, and if so advance to the next.
834          */
835         if (copy_context->current_element_offset ==
836             copy_context->current_element->size) {
837                 copy_context->elements_to_go--;
838                 copy_context->current_element++;
839                 copy_context->current_element_offset = 0;
840         }
841
842         return bytes_this_round;
843 }
844
845 /**************************************************************************
846  *
847  *   vchiq_ioc_queue_message
848  *
849  **************************************************************************/
850 static VCHIQ_STATUS_T
851 vchiq_ioc_queue_message(VCHIQ_SERVICE_HANDLE_T handle,
852                         struct vchiq_element *elements,
853                         unsigned long count)
854 {
855         struct vchiq_io_copy_callback_context context;
856         unsigned long i;
857         size_t total_size = 0;
858
859         context.current_element = elements;
860         context.current_element_offset = 0;
861         context.elements_to_go = count;
862         context.current_offset = 0;
863
864         for (i = 0; i < count; i++) {
865                 if (!elements[i].data && elements[i].size != 0)
866                         return -EFAULT;
867
868                 total_size += elements[i].size;
869         }
870
871         return vchiq_queue_message(handle, vchiq_ioc_copy_element_data,
872                                    &context, total_size);
873 }
874
875 /****************************************************************************
876 *
877 *   vchiq_ioctl
878 *
879 ***************************************************************************/
880 static long
881 vchiq_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
882 {
883         VCHIQ_INSTANCE_T instance = file->private_data;
884         VCHIQ_STATUS_T status = VCHIQ_SUCCESS;
885         VCHIQ_SERVICE_T *service = NULL;
886         long ret = 0;
887         int i, rc;
888
889         DEBUG_INITIALISE(g_state.local)
890
891         vchiq_log_trace(vchiq_arm_log_level,
892                 "%s - instance %pK, cmd %s, arg %lx",
893                 __func__, instance,
894                 ((_IOC_TYPE(cmd) == VCHIQ_IOC_MAGIC) &&
895                 (_IOC_NR(cmd) <= VCHIQ_IOC_MAX)) ?
896                 ioctl_names[_IOC_NR(cmd)] : "<invalid>", arg);
897
898         switch (cmd) {
899         case VCHIQ_IOC_SHUTDOWN:
900                 if (!instance->connected)
901                         break;
902
903                 /* Remove all services */
904                 i = 0;
905                 while ((service = next_service_by_instance(instance->state,
906                         instance, &i)) != NULL) {
907                         status = vchiq_remove_service(service->handle);
908                         unlock_service(service);
909                         if (status != VCHIQ_SUCCESS)
910                                 break;
911                 }
912                 service = NULL;
913
914                 if (status == VCHIQ_SUCCESS) {
915                         /* Wake the completion thread and ask it to exit */
916                         instance->closing = 1;
917                         up(&instance->insert_event);
918                 }
919
920                 break;
921
922         case VCHIQ_IOC_CONNECT:
923                 if (instance->connected) {
924                         ret = -EINVAL;
925                         break;
926                 }
927                 rc = mutex_lock_killable(&instance->state->mutex);
928                 if (rc != 0) {
929                         vchiq_log_error(vchiq_arm_log_level,
930                                 "vchiq: connect: could not lock mutex for "
931                                 "state %d: %d",
932                                 instance->state->id, rc);
933                         ret = -EINTR;
934                         break;
935                 }
936                 status = vchiq_connect_internal(instance->state, instance);
937                 mutex_unlock(&instance->state->mutex);
938
939                 if (status == VCHIQ_SUCCESS)
940                         instance->connected = 1;
941                 else
942                         vchiq_log_error(vchiq_arm_log_level,
943                                 "vchiq: could not connect: %d", status);
944                 break;
945
946         case VCHIQ_IOC_CREATE_SERVICE: {
947                 VCHIQ_CREATE_SERVICE_T args;
948                 USER_SERVICE_T *user_service = NULL;
949                 void *userdata;
950                 int srvstate;
951
952                 if (copy_from_user
953                          (&args, (const void __user *)arg,
954                           sizeof(args)) != 0) {
955                         ret = -EFAULT;
956                         break;
957                 }
958
959                 user_service = kmalloc(sizeof(USER_SERVICE_T), GFP_KERNEL);
960                 if (!user_service) {
961                         ret = -ENOMEM;
962                         break;
963                 }
964
965                 if (args.is_open) {
966                         if (!instance->connected) {
967                                 ret = -ENOTCONN;
968                                 kfree(user_service);
969                                 break;
970                         }
971                         srvstate = VCHIQ_SRVSTATE_OPENING;
972                 } else {
973                         srvstate =
974                                  instance->connected ?
975                                  VCHIQ_SRVSTATE_LISTENING :
976                                  VCHIQ_SRVSTATE_HIDDEN;
977                 }
978
979                 userdata = args.params.userdata;
980                 args.params.callback = service_callback;
981                 args.params.userdata = user_service;
982                 service = vchiq_add_service_internal(
983                                 instance->state,
984                                 &args.params, srvstate,
985                                 instance, user_service_free);
986
987                 if (service != NULL) {
988                         user_service->service = service;
989                         user_service->userdata = userdata;
990                         user_service->instance = instance;
991                         user_service->is_vchi = (args.is_vchi != 0);
992                         user_service->dequeue_pending = 0;
993                         user_service->close_pending = 0;
994                         user_service->message_available_pos =
995                                 instance->completion_remove - 1;
996                         user_service->msg_insert = 0;
997                         user_service->msg_remove = 0;
998                         sema_init(&user_service->insert_event, 0);
999                         sema_init(&user_service->remove_event, 0);
1000                         sema_init(&user_service->close_event, 0);
1001
1002                         if (args.is_open) {
1003                                 status = vchiq_open_service_internal
1004                                         (service, instance->pid);
1005                                 if (status != VCHIQ_SUCCESS) {
1006                                         vchiq_remove_service(service->handle);
1007                                         service = NULL;
1008                                         ret = (status == VCHIQ_RETRY) ?
1009                                                 -EINTR : -EIO;
1010                                         break;
1011                                 }
1012                         }
1013
1014                         if (copy_to_user((void __user *)
1015                                 &(((VCHIQ_CREATE_SERVICE_T __user *)
1016                                         arg)->handle),
1017                                 (const void *)&service->handle,
1018                                 sizeof(service->handle)) != 0) {
1019                                 ret = -EFAULT;
1020                                 vchiq_remove_service(service->handle);
1021                         }
1022
1023                         service = NULL;
1024                 } else {
1025                         ret = -EEXIST;
1026                         kfree(user_service);
1027                 }
1028         } break;
1029
1030         case VCHIQ_IOC_CLOSE_SERVICE: {
1031                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
1032
1033                 service = find_service_for_instance(instance, handle);
1034                 if (service != NULL) {
1035                         USER_SERVICE_T *user_service =
1036                                 (USER_SERVICE_T *)service->base.userdata;
1037                         /* close_pending is false on first entry, and when the
1038                            wait in vchiq_close_service has been interrupted. */
1039                         if (!user_service->close_pending) {
1040                                 status = vchiq_close_service(service->handle);
1041                                 if (status != VCHIQ_SUCCESS)
1042                                         break;
1043                         }
1044
1045                         /* close_pending is true once the underlying service
1046                            has been closed until the client library calls the
1047                            CLOSE_DELIVERED ioctl, signalling close_event. */
1048                         if (user_service->close_pending &&
1049                                 down_interruptible(&user_service->close_event))
1050                                 status = VCHIQ_RETRY;
1051                 } else
1052                         ret = -EINVAL;
1053         } break;
1054
1055         case VCHIQ_IOC_REMOVE_SERVICE: {
1056                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
1057
1058                 service = find_service_for_instance(instance, handle);
1059                 if (service != NULL) {
1060                         USER_SERVICE_T *user_service =
1061                                 (USER_SERVICE_T *)service->base.userdata;
1062                         /* close_pending is false on first entry, and when the
1063                            wait in vchiq_close_service has been interrupted. */
1064                         if (!user_service->close_pending) {
1065                                 status = vchiq_remove_service(service->handle);
1066                                 if (status != VCHIQ_SUCCESS)
1067                                         break;
1068                         }
1069
1070                         /* close_pending is true once the underlying service
1071                            has been closed until the client library calls the
1072                            CLOSE_DELIVERED ioctl, signalling close_event. */
1073                         if (user_service->close_pending &&
1074                                 down_interruptible(&user_service->close_event))
1075                                 status = VCHIQ_RETRY;
1076                 } else
1077                         ret = -EINVAL;
1078         } break;
1079
1080         case VCHIQ_IOC_USE_SERVICE:
1081         case VCHIQ_IOC_RELEASE_SERVICE: {
1082                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
1083
1084                 service = find_service_for_instance(instance, handle);
1085                 if (service != NULL) {
1086                         status = (cmd == VCHIQ_IOC_USE_SERVICE) ?
1087                                 vchiq_use_service_internal(service) :
1088                                 vchiq_release_service_internal(service);
1089                         if (status != VCHIQ_SUCCESS) {
1090                                 vchiq_log_error(vchiq_susp_log_level,
1091                                         "%s: cmd %s returned error %d for "
1092                                         "service %c%c%c%c:%03d",
1093                                         __func__,
1094                                         (cmd == VCHIQ_IOC_USE_SERVICE) ?
1095                                                 "VCHIQ_IOC_USE_SERVICE" :
1096                                                 "VCHIQ_IOC_RELEASE_SERVICE",
1097                                         status,
1098                                         VCHIQ_FOURCC_AS_4CHARS(
1099                                                 service->base.fourcc),
1100                                         service->client_id);
1101                                 ret = -EINVAL;
1102                         }
1103                 } else
1104                         ret = -EINVAL;
1105         } break;
1106
1107         case VCHIQ_IOC_QUEUE_MESSAGE: {
1108                 VCHIQ_QUEUE_MESSAGE_T args;
1109
1110                 if (copy_from_user
1111                          (&args, (const void __user *)arg,
1112                           sizeof(args)) != 0) {
1113                         ret = -EFAULT;
1114                         break;
1115                 }
1116
1117                 service = find_service_for_instance(instance, args.handle);
1118
1119                 if ((service != NULL) && (args.count <= MAX_ELEMENTS)) {
1120                         /* Copy elements into kernel space */
1121                         struct vchiq_element elements[MAX_ELEMENTS];
1122
1123                         if (copy_from_user(elements, args.elements,
1124                                 args.count * sizeof(struct vchiq_element)) == 0)
1125                                 status = vchiq_ioc_queue_message
1126                                         (args.handle,
1127                                         elements, args.count);
1128                         else
1129                                 ret = -EFAULT;
1130                 } else {
1131                         ret = -EINVAL;
1132                 }
1133         } break;
1134
1135         case VCHIQ_IOC_QUEUE_BULK_TRANSMIT:
1136         case VCHIQ_IOC_QUEUE_BULK_RECEIVE: {
1137                 VCHIQ_QUEUE_BULK_TRANSFER_T args;
1138                 struct bulk_waiter_node *waiter = NULL;
1139
1140                 VCHIQ_BULK_DIR_T dir =
1141                         (cmd == VCHIQ_IOC_QUEUE_BULK_TRANSMIT) ?
1142                         VCHIQ_BULK_TRANSMIT : VCHIQ_BULK_RECEIVE;
1143
1144                 if (copy_from_user
1145                         (&args, (const void __user *)arg,
1146                         sizeof(args)) != 0) {
1147                         ret = -EFAULT;
1148                         break;
1149                 }
1150
1151                 service = find_service_for_instance(instance, args.handle);
1152                 if (!service) {
1153                         ret = -EINVAL;
1154                         break;
1155                 }
1156
1157                 if (args.mode == VCHIQ_BULK_MODE_BLOCKING) {
1158                         waiter = kzalloc(sizeof(struct bulk_waiter_node),
1159                                 GFP_KERNEL);
1160                         if (!waiter) {
1161                                 ret = -ENOMEM;
1162                                 break;
1163                         }
1164                         args.userdata = &waiter->bulk_waiter;
1165                 } else if (args.mode == VCHIQ_BULK_MODE_WAITING) {
1166                         struct list_head *pos;
1167
1168                         mutex_lock(&instance->bulk_waiter_list_mutex);
1169                         list_for_each(pos, &instance->bulk_waiter_list) {
1170                                 if (list_entry(pos, struct bulk_waiter_node,
1171                                         list)->pid == current->pid) {
1172                                         waiter = list_entry(pos,
1173                                                 struct bulk_waiter_node,
1174                                                 list);
1175                                         list_del(pos);
1176                                         break;
1177                                 }
1178
1179                         }
1180                         mutex_unlock(&instance->bulk_waiter_list_mutex);
1181                         if (!waiter) {
1182                                 vchiq_log_error(vchiq_arm_log_level,
1183                                         "no bulk_waiter found for pid %d",
1184                                         current->pid);
1185                                 ret = -ESRCH;
1186                                 break;
1187                         }
1188                         vchiq_log_info(vchiq_arm_log_level,
1189                                 "found bulk_waiter %pK for pid %d", waiter,
1190                                 current->pid);
1191                         args.userdata = &waiter->bulk_waiter;
1192                 }
1193                 status = vchiq_bulk_transfer
1194                         (args.handle,
1195                          VCHI_MEM_HANDLE_INVALID,
1196                          args.data, args.size,
1197                          args.userdata, args.mode,
1198                          dir);
1199                 if (!waiter)
1200                         break;
1201                 if ((status != VCHIQ_RETRY) || fatal_signal_pending(current) ||
1202                         !waiter->bulk_waiter.bulk) {
1203                         if (waiter->bulk_waiter.bulk) {
1204                                 /* Cancel the signal when the transfer
1205                                 ** completes. */
1206                                 spin_lock(&bulk_waiter_spinlock);
1207                                 waiter->bulk_waiter.bulk->userdata = NULL;
1208                                 spin_unlock(&bulk_waiter_spinlock);
1209                         }
1210                         kfree(waiter);
1211                 } else {
1212                         const VCHIQ_BULK_MODE_T mode_waiting =
1213                                 VCHIQ_BULK_MODE_WAITING;
1214                         waiter->pid = current->pid;
1215                         mutex_lock(&instance->bulk_waiter_list_mutex);
1216                         list_add(&waiter->list, &instance->bulk_waiter_list);
1217                         mutex_unlock(&instance->bulk_waiter_list_mutex);
1218                         vchiq_log_info(vchiq_arm_log_level,
1219                                 "saved bulk_waiter %pK for pid %d",
1220                                 waiter, current->pid);
1221
1222                         if (copy_to_user((void __user *)
1223                                 &(((VCHIQ_QUEUE_BULK_TRANSFER_T __user *)
1224                                         arg)->mode),
1225                                 (const void *)&mode_waiting,
1226                                 sizeof(mode_waiting)) != 0)
1227                                 ret = -EFAULT;
1228                 }
1229         } break;
1230
1231         case VCHIQ_IOC_AWAIT_COMPLETION: {
1232                 VCHIQ_AWAIT_COMPLETION_T args;
1233
1234                 DEBUG_TRACE(AWAIT_COMPLETION_LINE);
1235                 if (!instance->connected) {
1236                         ret = -ENOTCONN;
1237                         break;
1238                 }
1239
1240                 if (copy_from_user(&args, (const void __user *)arg,
1241                         sizeof(args)) != 0) {
1242                         ret = -EFAULT;
1243                         break;
1244                 }
1245
1246                 mutex_lock(&instance->completion_mutex);
1247
1248                 DEBUG_TRACE(AWAIT_COMPLETION_LINE);
1249                 while ((instance->completion_remove ==
1250                         instance->completion_insert)
1251                         && !instance->closing) {
1252                         int rc;
1253
1254                         DEBUG_TRACE(AWAIT_COMPLETION_LINE);
1255                         mutex_unlock(&instance->completion_mutex);
1256                         rc = down_interruptible(&instance->insert_event);
1257                         mutex_lock(&instance->completion_mutex);
1258                         if (rc != 0) {
1259                                 DEBUG_TRACE(AWAIT_COMPLETION_LINE);
1260                                 vchiq_log_info(vchiq_arm_log_level,
1261                                         "AWAIT_COMPLETION interrupted");
1262                                 ret = -EINTR;
1263                                 break;
1264                         }
1265                 }
1266                 DEBUG_TRACE(AWAIT_COMPLETION_LINE);
1267
1268                 if (ret == 0) {
1269                         int msgbufcount = args.msgbufcount;
1270                         int remove = instance->completion_remove;
1271
1272                         for (ret = 0; ret < args.count; ret++) {
1273                                 VCHIQ_COMPLETION_DATA_T *completion;
1274                                 VCHIQ_SERVICE_T *service;
1275                                 USER_SERVICE_T *user_service;
1276                                 VCHIQ_HEADER_T *header;
1277
1278                                 if (remove == instance->completion_insert)
1279                                         break;
1280
1281                                 completion = &instance->completions[
1282                                         remove & (MAX_COMPLETIONS - 1)];
1283
1284                                 /*
1285                                  * A read memory barrier is needed to stop
1286                                  * prefetch of a stale completion record
1287                                  */
1288                                 rmb();
1289
1290                                 service = completion->service_userdata;
1291                                 user_service = service->base.userdata;
1292                                 completion->service_userdata =
1293                                         user_service->userdata;
1294
1295                                 header = completion->header;
1296                                 if (header) {
1297                                         void __user *msgbuf;
1298                                         int msglen;
1299
1300                                         msglen = header->size +
1301                                                 sizeof(VCHIQ_HEADER_T);
1302                                         /* This must be a VCHIQ-style service */
1303                                         if (args.msgbufsize < msglen) {
1304                                                 vchiq_log_error(
1305                                                         vchiq_arm_log_level,
1306                                                         "header %pK: msgbufsize %x < msglen %x",
1307                                                         header, args.msgbufsize,
1308                                                         msglen);
1309                                                 WARN(1, "invalid message "
1310                                                         "size\n");
1311                                                 if (ret == 0)
1312                                                         ret = -EMSGSIZE;
1313                                                 break;
1314                                         }
1315                                         if (msgbufcount <= 0)
1316                                                 /* Stall here for lack of a
1317                                                 ** buffer for the message. */
1318                                                 break;
1319                                         /* Get the pointer from user space */
1320                                         msgbufcount--;
1321                                         if (copy_from_user(&msgbuf,
1322                                                 (const void __user *)
1323                                                 &args.msgbufs[msgbufcount],
1324                                                 sizeof(msgbuf)) != 0) {
1325                                                 if (ret == 0)
1326                                                         ret = -EFAULT;
1327                                                 break;
1328                                         }
1329
1330                                         /* Copy the message to user space */
1331                                         if (copy_to_user(msgbuf, header,
1332                                                 msglen) != 0) {
1333                                                 if (ret == 0)
1334                                                         ret = -EFAULT;
1335                                                 break;
1336                                         }
1337
1338                                         /* Now it has been copied, the message
1339                                         ** can be released. */
1340                                         vchiq_release_message(service->handle,
1341                                                 header);
1342
1343                                         /* The completion must point to the
1344                                         ** msgbuf. */
1345                                         completion->header = msgbuf;
1346                                 }
1347
1348                                 if ((completion->reason ==
1349                                         VCHIQ_SERVICE_CLOSED) &&
1350                                         !instance->use_close_delivered)
1351                                         unlock_service(service);
1352
1353                                 if (copy_to_user((void __user *)(
1354                                         (size_t)args.buf +
1355                                         ret * sizeof(VCHIQ_COMPLETION_DATA_T)),
1356                                         completion,
1357                                         sizeof(VCHIQ_COMPLETION_DATA_T)) != 0) {
1358                                                 if (ret == 0)
1359                                                         ret = -EFAULT;
1360                                         break;
1361                                 }
1362
1363                                 /*
1364                                  * Ensure that the above copy has completed
1365                                  * before advancing the remove pointer.
1366                                  */
1367                                 mb();
1368                                 remove++;
1369                                 instance->completion_remove = remove;
1370                         }
1371
1372                         if (msgbufcount != args.msgbufcount) {
1373                                 if (copy_to_user((void __user *)
1374                                         &((VCHIQ_AWAIT_COMPLETION_T *)arg)->
1375                                                 msgbufcount,
1376                                         &msgbufcount,
1377                                         sizeof(msgbufcount)) != 0) {
1378                                         ret = -EFAULT;
1379                                 }
1380                         }
1381                 }
1382
1383                 if (ret != 0)
1384                         up(&instance->remove_event);
1385                 mutex_unlock(&instance->completion_mutex);
1386                 DEBUG_TRACE(AWAIT_COMPLETION_LINE);
1387         } break;
1388
1389         case VCHIQ_IOC_DEQUEUE_MESSAGE: {
1390                 VCHIQ_DEQUEUE_MESSAGE_T args;
1391                 USER_SERVICE_T *user_service;
1392                 VCHIQ_HEADER_T *header;
1393
1394                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1395                 if (copy_from_user
1396                          (&args, (const void __user *)arg,
1397                           sizeof(args)) != 0) {
1398                         ret = -EFAULT;
1399                         break;
1400                 }
1401                 service = find_service_for_instance(instance, args.handle);
1402                 if (!service) {
1403                         ret = -EINVAL;
1404                         break;
1405                 }
1406                 user_service = (USER_SERVICE_T *)service->base.userdata;
1407                 if (user_service->is_vchi == 0) {
1408                         ret = -EINVAL;
1409                         break;
1410                 }
1411
1412                 spin_lock(&msg_queue_spinlock);
1413                 if (user_service->msg_remove == user_service->msg_insert) {
1414                         if (!args.blocking) {
1415                                 spin_unlock(&msg_queue_spinlock);
1416                                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1417                                 ret = -EWOULDBLOCK;
1418                                 break;
1419                         }
1420                         user_service->dequeue_pending = 1;
1421                         do {
1422                                 spin_unlock(&msg_queue_spinlock);
1423                                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1424                                 if (down_interruptible(
1425                                         &user_service->insert_event) != 0) {
1426                                         vchiq_log_info(vchiq_arm_log_level,
1427                                                 "DEQUEUE_MESSAGE interrupted");
1428                                         ret = -EINTR;
1429                                         break;
1430                                 }
1431                                 spin_lock(&msg_queue_spinlock);
1432                         } while (user_service->msg_remove ==
1433                                 user_service->msg_insert);
1434
1435                         if (ret)
1436                                 break;
1437                 }
1438
1439                 BUG_ON((int)(user_service->msg_insert -
1440                         user_service->msg_remove) < 0);
1441
1442                 header = user_service->msg_queue[user_service->msg_remove &
1443                         (MSG_QUEUE_SIZE - 1)];
1444                 user_service->msg_remove++;
1445                 spin_unlock(&msg_queue_spinlock);
1446
1447                 up(&user_service->remove_event);
1448                 if (header == NULL)
1449                         ret = -ENOTCONN;
1450                 else if (header->size <= args.bufsize) {
1451                         /* Copy to user space if msgbuf is not NULL */
1452                         if ((args.buf == NULL) ||
1453                                 (copy_to_user((void __user *)args.buf,
1454                                 header->data,
1455                                 header->size) == 0)) {
1456                                 ret = header->size;
1457                                 vchiq_release_message(
1458                                         service->handle,
1459                                         header);
1460                         } else
1461                                 ret = -EFAULT;
1462                 } else {
1463                         vchiq_log_error(vchiq_arm_log_level,
1464                                 "header %pK: bufsize %x < size %x",
1465                                 header, args.bufsize, header->size);
1466                         WARN(1, "invalid size\n");
1467                         ret = -EMSGSIZE;
1468                 }
1469                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1470         } break;
1471
1472         case VCHIQ_IOC_GET_CLIENT_ID: {
1473                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
1474
1475                 ret = vchiq_get_client_id(handle);
1476         } break;
1477
1478         case VCHIQ_IOC_GET_CONFIG: {
1479                 VCHIQ_GET_CONFIG_T args;
1480                 VCHIQ_CONFIG_T config;
1481
1482                 if (copy_from_user(&args, (const void __user *)arg,
1483                         sizeof(args)) != 0) {
1484                         ret = -EFAULT;
1485                         break;
1486                 }
1487                 if (args.config_size > sizeof(config)) {
1488                         ret = -EINVAL;
1489                         break;
1490                 }
1491                 status = vchiq_get_config(instance, args.config_size, &config);
1492                 if (status == VCHIQ_SUCCESS) {
1493                         if (copy_to_user((void __user *)args.pconfig,
1494                                     &config, args.config_size) != 0) {
1495                                 ret = -EFAULT;
1496                                 break;
1497                         }
1498                 }
1499         } break;
1500
1501         case VCHIQ_IOC_SET_SERVICE_OPTION: {
1502                 VCHIQ_SET_SERVICE_OPTION_T args;
1503
1504                 if (copy_from_user(
1505                         &args, (const void __user *)arg,
1506                         sizeof(args)) != 0) {
1507                         ret = -EFAULT;
1508                         break;
1509                 }
1510
1511                 service = find_service_for_instance(instance, args.handle);
1512                 if (!service) {
1513                         ret = -EINVAL;
1514                         break;
1515                 }
1516
1517                 status = vchiq_set_service_option(
1518                                 args.handle, args.option, args.value);
1519         } break;
1520
1521         case VCHIQ_IOC_LIB_VERSION: {
1522                 unsigned int lib_version = (unsigned int)arg;
1523
1524                 if (lib_version < VCHIQ_VERSION_MIN)
1525                         ret = -EINVAL;
1526                 else if (lib_version >= VCHIQ_VERSION_CLOSE_DELIVERED)
1527                         instance->use_close_delivered = 1;
1528         } break;
1529
1530         case VCHIQ_IOC_CLOSE_DELIVERED: {
1531                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
1532
1533                 service = find_closed_service_for_instance(instance, handle);
1534                 if (service != NULL) {
1535                         USER_SERVICE_T *user_service =
1536                                 (USER_SERVICE_T *)service->base.userdata;
1537                         close_delivered(user_service);
1538                 } else
1539                         ret = -EINVAL;
1540         } break;
1541
1542         default:
1543                 ret = -ENOTTY;
1544                 break;
1545         }
1546
1547         if (service)
1548                 unlock_service(service);
1549
1550         if (ret == 0) {
1551                 if (status == VCHIQ_ERROR)
1552                         ret = -EIO;
1553                 else if (status == VCHIQ_RETRY)
1554                         ret = -EINTR;
1555         }
1556
1557         if ((status == VCHIQ_SUCCESS) && (ret < 0) && (ret != -EINTR) &&
1558                 (ret != -EWOULDBLOCK))
1559                 vchiq_log_info(vchiq_arm_log_level,
1560                         "  ioctl instance %lx, cmd %s -> status %d, %ld",
1561                         (unsigned long)instance,
1562                         (_IOC_NR(cmd) <= VCHIQ_IOC_MAX) ?
1563                                 ioctl_names[_IOC_NR(cmd)] :
1564                                 "<invalid>",
1565                         status, ret);
1566         else
1567                 vchiq_log_trace(vchiq_arm_log_level,
1568                         "  ioctl instance %lx, cmd %s -> status %d, %ld",
1569                         (unsigned long)instance,
1570                         (_IOC_NR(cmd) <= VCHIQ_IOC_MAX) ?
1571                                 ioctl_names[_IOC_NR(cmd)] :
1572                                 "<invalid>",
1573                         status, ret);
1574
1575         return ret;
1576 }
1577
1578 #if defined(CONFIG_COMPAT)
1579
1580 struct vchiq_service_params32 {
1581         int fourcc;
1582         compat_uptr_t callback;
1583         compat_uptr_t userdata;
1584         short version; /* Increment for non-trivial changes */
1585         short version_min; /* Update for incompatible changes */
1586 };
1587
1588 struct vchiq_create_service32 {
1589         struct vchiq_service_params32 params;
1590         int is_open;
1591         int is_vchi;
1592         unsigned int handle; /* OUT */
1593 };
1594
1595 #define VCHIQ_IOC_CREATE_SERVICE32 \
1596         _IOWR(VCHIQ_IOC_MAGIC, 2, struct vchiq_create_service32)
1597
1598 static long
1599 vchiq_compat_ioctl_create_service(
1600         struct file *file,
1601         unsigned int cmd,
1602         unsigned long arg)
1603 {
1604         VCHIQ_CREATE_SERVICE_T __user *args;
1605         struct vchiq_create_service32 __user *ptrargs32 =
1606                 (struct vchiq_create_service32 __user *)arg;
1607         struct vchiq_create_service32 args32;
1608         long ret;
1609
1610         args = compat_alloc_user_space(sizeof(*args));
1611         if (!args)
1612                 return -EFAULT;
1613
1614         if (copy_from_user(&args32,
1615                            (struct vchiq_create_service32 __user *)arg,
1616                            sizeof(args32)))
1617                 return -EFAULT;
1618
1619         if (put_user(args32.params.fourcc, &args->params.fourcc) ||
1620             put_user(compat_ptr(args32.params.callback),
1621                      &args->params.callback) ||
1622             put_user(compat_ptr(args32.params.userdata),
1623                      &args->params.userdata) ||
1624             put_user(args32.params.version, &args->params.version) ||
1625             put_user(args32.params.version_min,
1626                      &args->params.version_min) ||
1627             put_user(args32.is_open, &args->is_open) ||
1628             put_user(args32.is_vchi, &args->is_vchi) ||
1629             put_user(args32.handle, &args->handle))
1630                 return -EFAULT;
1631
1632         ret = vchiq_ioctl(file, VCHIQ_IOC_CREATE_SERVICE, (unsigned long)args);
1633
1634         if (ret < 0)
1635                 return ret;
1636
1637         if (get_user(args32.handle, &args->handle))
1638                 return -EFAULT;
1639
1640         if (copy_to_user(&ptrargs32->handle,
1641                          &args32.handle,
1642                          sizeof(args32.handle)))
1643                 return -EFAULT;
1644
1645         return 0;
1646 }
1647
1648 struct vchiq_element32 {
1649         compat_uptr_t data;
1650         unsigned int size;
1651 };
1652
1653 struct vchiq_queue_message32 {
1654         unsigned int handle;
1655         unsigned int count;
1656         compat_uptr_t elements;
1657 };
1658
1659 #define VCHIQ_IOC_QUEUE_MESSAGE32 \
1660         _IOW(VCHIQ_IOC_MAGIC,  4, struct vchiq_queue_message32)
1661
1662 static long
1663 vchiq_compat_ioctl_queue_message(struct file *file,
1664                                  unsigned int cmd,
1665                                  unsigned long arg)
1666 {
1667         VCHIQ_QUEUE_MESSAGE_T *args;
1668         struct vchiq_element *elements;
1669         struct vchiq_queue_message32 args32;
1670         unsigned int count;
1671
1672         if (copy_from_user(&args32,
1673                            (struct vchiq_queue_message32 __user *)arg,
1674                            sizeof(args32)))
1675                 return -EFAULT;
1676
1677         args = compat_alloc_user_space(sizeof(*args) +
1678                                        (sizeof(*elements) * MAX_ELEMENTS));
1679
1680         if (!args)
1681                 return -EFAULT;
1682
1683         if (put_user(args32.handle, &args->handle) ||
1684             put_user(args32.count, &args->count) ||
1685             put_user(compat_ptr(args32.elements), &args->elements))
1686                 return -EFAULT;
1687
1688         if (args32.count > MAX_ELEMENTS)
1689                 return -EINVAL;
1690
1691         if (args32.elements && args32.count) {
1692                 struct vchiq_element32 tempelement32[MAX_ELEMENTS];
1693
1694                 elements = (struct vchiq_element __user *)(args + 1);
1695
1696                 if (copy_from_user(&tempelement32,
1697                                    compat_ptr(args32.elements),
1698                                    sizeof(tempelement32)))
1699                         return -EFAULT;
1700
1701                 for (count = 0; count < args32.count; count++) {
1702                         if (put_user(compat_ptr(tempelement32[count].data),
1703                                      &elements[count].data) ||
1704                             put_user(tempelement32[count].size,
1705                                      &elements[count].size))
1706                                 return -EFAULT;
1707                 }
1708
1709                 if (put_user(elements, &args->elements))
1710                         return -EFAULT;
1711         }
1712
1713         return vchiq_ioctl(file, VCHIQ_IOC_QUEUE_MESSAGE, (unsigned long)args);
1714 }
1715
1716 struct vchiq_queue_bulk_transfer32 {
1717         unsigned int handle;
1718         compat_uptr_t data;
1719         unsigned int size;
1720         compat_uptr_t userdata;
1721         VCHIQ_BULK_MODE_T mode;
1722 };
1723
1724 #define VCHIQ_IOC_QUEUE_BULK_TRANSMIT32 \
1725         _IOWR(VCHIQ_IOC_MAGIC, 5, struct vchiq_queue_bulk_transfer32)
1726 #define VCHIQ_IOC_QUEUE_BULK_RECEIVE32 \
1727         _IOWR(VCHIQ_IOC_MAGIC, 6, struct vchiq_queue_bulk_transfer32)
1728
1729 static long
1730 vchiq_compat_ioctl_queue_bulk(struct file *file,
1731                               unsigned int cmd,
1732                               unsigned long arg)
1733 {
1734         VCHIQ_QUEUE_BULK_TRANSFER_T *args;
1735         struct vchiq_queue_bulk_transfer32 args32;
1736         struct vchiq_queue_bulk_transfer32 *ptrargs32 =
1737                 (struct vchiq_queue_bulk_transfer32 *)arg;
1738         long ret;
1739
1740         args = compat_alloc_user_space(sizeof(*args));
1741         if (!args)
1742                 return -EFAULT;
1743
1744         if (copy_from_user(&args32,
1745                            (struct vchiq_queue_bulk_transfer32 __user *)arg,
1746                            sizeof(args32)))
1747                 return -EFAULT;
1748
1749         if (put_user(args32.handle, &args->handle) ||
1750             put_user(compat_ptr(args32.data), &args->data) ||
1751             put_user(args32.size, &args->size) ||
1752             put_user(compat_ptr(args32.userdata), &args->userdata) ||
1753             put_user(args32.mode, &args->mode))
1754                 return -EFAULT;
1755
1756         if (cmd == VCHIQ_IOC_QUEUE_BULK_TRANSMIT32)
1757                 cmd = VCHIQ_IOC_QUEUE_BULK_TRANSMIT;
1758         else
1759                 cmd = VCHIQ_IOC_QUEUE_BULK_RECEIVE;
1760
1761         ret = vchiq_ioctl(file, cmd, (unsigned long)args);
1762
1763         if (ret < 0)
1764                 return ret;
1765
1766         if (get_user(args32.mode, &args->mode))
1767                 return -EFAULT;
1768
1769         if (copy_to_user(&ptrargs32->mode,
1770                          &args32.mode,
1771                          sizeof(args32.mode)))
1772                 return -EFAULT;
1773
1774         return 0;
1775 }
1776
1777 struct vchiq_completion_data32 {
1778         VCHIQ_REASON_T reason;
1779         compat_uptr_t header;
1780         compat_uptr_t service_userdata;
1781         compat_uptr_t bulk_userdata;
1782 };
1783
1784 struct vchiq_await_completion32 {
1785         unsigned int count;
1786         compat_uptr_t buf;
1787         unsigned int msgbufsize;
1788         unsigned int msgbufcount; /* IN/OUT */
1789         compat_uptr_t msgbufs;
1790 };
1791
1792 #define VCHIQ_IOC_AWAIT_COMPLETION32 \
1793         _IOWR(VCHIQ_IOC_MAGIC, 7, struct vchiq_await_completion32)
1794
1795 static long
1796 vchiq_compat_ioctl_await_completion(struct file *file,
1797                                     unsigned int cmd,
1798                                     unsigned long arg)
1799 {
1800         VCHIQ_AWAIT_COMPLETION_T *args;
1801         VCHIQ_COMPLETION_DATA_T *completion;
1802         VCHIQ_COMPLETION_DATA_T completiontemp;
1803         struct vchiq_await_completion32 args32;
1804         struct vchiq_completion_data32 completion32;
1805         unsigned int *msgbufcount32;
1806         unsigned int msgbufcount_native;
1807         compat_uptr_t msgbuf32;
1808         void *msgbuf;
1809         void **msgbufptr;
1810         long ret;
1811
1812         args = compat_alloc_user_space(sizeof(*args) +
1813                                        sizeof(*completion) +
1814                                        sizeof(*msgbufptr));
1815         if (!args)
1816                 return -EFAULT;
1817
1818         completion = (VCHIQ_COMPLETION_DATA_T *)(args + 1);
1819         msgbufptr = (void __user **)(completion + 1);
1820
1821         if (copy_from_user(&args32,
1822                            (struct vchiq_completion_data32 *)arg,
1823                            sizeof(args32)))
1824                 return -EFAULT;
1825
1826         if (put_user(args32.count, &args->count) ||
1827             put_user(compat_ptr(args32.buf), &args->buf) ||
1828             put_user(args32.msgbufsize, &args->msgbufsize) ||
1829             put_user(args32.msgbufcount, &args->msgbufcount) ||
1830             put_user(compat_ptr(args32.msgbufs), &args->msgbufs))
1831                 return -EFAULT;
1832
1833         /* These are simple cases, so just fall into the native handler */
1834         if (!args32.count || !args32.buf || !args32.msgbufcount)
1835                 return vchiq_ioctl(file,
1836                                    VCHIQ_IOC_AWAIT_COMPLETION,
1837                                    (unsigned long)args);
1838
1839         /*
1840          * These are the more complex cases.  Typical applications of this
1841          * ioctl will use a very large count, with a very large msgbufcount.
1842          * Since the native ioctl can asynchronously fill in the returned
1843          * buffers and the application can in theory begin processing messages
1844          * even before the ioctl returns, a bit of a trick is used here.
1845          *
1846          * By forcing both count and msgbufcount to be 1, it forces the native
1847          * ioctl to only claim at most 1 message is available.   This tricks
1848          * the calling application into thinking only 1 message was actually
1849          * available in the queue so like all good applications it will retry
1850          * waiting until all the required messages are received.
1851          *
1852          * This trick has been tested and proven to work with vchiq_test,
1853          * Minecraft_PI, the "hello pi" examples, and various other
1854          * applications that are included in Raspbian.
1855          */
1856
1857         if (copy_from_user(&msgbuf32,
1858                            compat_ptr(args32.msgbufs) +
1859                            (sizeof(compat_uptr_t) *
1860                            (args32.msgbufcount - 1)),
1861                            sizeof(msgbuf32)))
1862                 return -EFAULT;
1863
1864         msgbuf = compat_ptr(msgbuf32);
1865
1866         if (copy_to_user(msgbufptr,
1867                          &msgbuf,
1868                          sizeof(msgbuf)))
1869                 return -EFAULT;
1870
1871         if (copy_to_user(&args->msgbufs,
1872                          &msgbufptr,
1873                          sizeof(msgbufptr)))
1874                 return -EFAULT;
1875
1876         if (put_user(1U, &args->count) ||
1877             put_user(completion, &args->buf) ||
1878             put_user(1U, &args->msgbufcount))
1879                 return -EFAULT;
1880
1881         ret = vchiq_ioctl(file,
1882                           VCHIQ_IOC_AWAIT_COMPLETION,
1883                           (unsigned long)args);
1884
1885         /*
1886          * An return value of 0 here means that no messages where available
1887          * in the message queue.  In this case the native ioctl does not
1888          * return any data to the application at all.  Not even to update
1889          * msgbufcount.  This functionality needs to be kept here for
1890          * compatibility.
1891          *
1892          * Of course, < 0 means that an error occurred and no data is being
1893          * returned.
1894          *
1895          * Since count and msgbufcount was forced to 1, that means
1896          * the only other possible return value is 1. Meaning that 1 message
1897          * was available, so that multiple message case does not need to be
1898          * handled here.
1899          */
1900         if (ret <= 0)
1901                 return ret;
1902
1903         if (copy_from_user(&completiontemp, completion, sizeof(*completion)))
1904                 return -EFAULT;
1905
1906         completion32.reason = completiontemp.reason;
1907         completion32.header = ptr_to_compat(completiontemp.header);
1908         completion32.service_userdata =
1909                 ptr_to_compat(completiontemp.service_userdata);
1910         completion32.bulk_userdata =
1911                 ptr_to_compat(completiontemp.bulk_userdata);
1912
1913         if (copy_to_user(compat_ptr(args32.buf),
1914                          &completion32,
1915                          sizeof(completion32)))
1916                 return -EFAULT;
1917
1918         if (get_user(msgbufcount_native, &args->msgbufcount))
1919                 return -EFAULT;
1920
1921         if (!msgbufcount_native)
1922                 args32.msgbufcount--;
1923
1924         msgbufcount32 =
1925                 &((struct vchiq_await_completion32 __user *)arg)->msgbufcount;
1926
1927         if (copy_to_user(msgbufcount32,
1928                          &args32.msgbufcount,
1929                          sizeof(args32.msgbufcount)))
1930                 return -EFAULT;
1931
1932         return 1;
1933 }
1934
1935 struct vchiq_dequeue_message32 {
1936         unsigned int handle;
1937         int blocking;
1938         unsigned int bufsize;
1939         compat_uptr_t buf;
1940 };
1941
1942 #define VCHIQ_IOC_DEQUEUE_MESSAGE32 \
1943         _IOWR(VCHIQ_IOC_MAGIC, 8, struct vchiq_dequeue_message32)
1944
1945 static long
1946 vchiq_compat_ioctl_dequeue_message(struct file *file,
1947                                    unsigned int cmd,
1948                                    unsigned long arg)
1949 {
1950         VCHIQ_DEQUEUE_MESSAGE_T *args;
1951         struct vchiq_dequeue_message32 args32;
1952
1953         args = compat_alloc_user_space(sizeof(*args));
1954         if (!args)
1955                 return -EFAULT;
1956
1957         if (copy_from_user(&args32,
1958                            (struct vchiq_dequeue_message32 *)arg,
1959                            sizeof(args32)))
1960                 return -EFAULT;
1961
1962         if (put_user(args32.handle, &args->handle) ||
1963             put_user(args32.blocking, &args->blocking) ||
1964             put_user(args32.bufsize, &args->bufsize) ||
1965             put_user(compat_ptr(args32.buf), &args->buf))
1966                 return -EFAULT;
1967
1968         return vchiq_ioctl(file, VCHIQ_IOC_DEQUEUE_MESSAGE,
1969                            (unsigned long)args);
1970 }
1971
1972 struct vchiq_get_config32 {
1973         unsigned int config_size;
1974         compat_uptr_t pconfig;
1975 };
1976
1977 #define VCHIQ_IOC_GET_CONFIG32 \
1978         _IOWR(VCHIQ_IOC_MAGIC, 10, struct vchiq_get_config32)
1979
1980 static long
1981 vchiq_compat_ioctl_get_config(struct file *file,
1982                               unsigned int cmd,
1983                               unsigned long arg)
1984 {
1985         VCHIQ_GET_CONFIG_T *args;
1986         struct vchiq_get_config32 args32;
1987
1988         args = compat_alloc_user_space(sizeof(*args));
1989         if (!args)
1990                 return -EFAULT;
1991
1992         if (copy_from_user(&args32,
1993                            (struct vchiq_get_config32 *)arg,
1994                            sizeof(args32)))
1995                 return -EFAULT;
1996
1997         if (put_user(args32.config_size, &args->config_size) ||
1998             put_user(compat_ptr(args32.pconfig), &args->pconfig))
1999                 return -EFAULT;
2000
2001         return vchiq_ioctl(file, VCHIQ_IOC_GET_CONFIG, (unsigned long)args);
2002 }
2003
2004 static long
2005 vchiq_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2006 {
2007         switch (cmd) {
2008         case VCHIQ_IOC_CREATE_SERVICE32:
2009                 return vchiq_compat_ioctl_create_service(file, cmd, arg);
2010         case VCHIQ_IOC_QUEUE_MESSAGE32:
2011                 return vchiq_compat_ioctl_queue_message(file, cmd, arg);
2012         case VCHIQ_IOC_QUEUE_BULK_TRANSMIT32:
2013         case VCHIQ_IOC_QUEUE_BULK_RECEIVE32:
2014                 return vchiq_compat_ioctl_queue_bulk(file, cmd, arg);
2015         case VCHIQ_IOC_AWAIT_COMPLETION32:
2016                 return vchiq_compat_ioctl_await_completion(file, cmd, arg);
2017         case VCHIQ_IOC_DEQUEUE_MESSAGE32:
2018                 return vchiq_compat_ioctl_dequeue_message(file, cmd, arg);
2019         case VCHIQ_IOC_GET_CONFIG32:
2020                 return vchiq_compat_ioctl_get_config(file, cmd, arg);
2021         default:
2022                 return vchiq_ioctl(file, cmd, arg);
2023         }
2024 }
2025
2026 #endif
2027
2028 /****************************************************************************
2029 *
2030 *   vchiq_open
2031 *
2032 ***************************************************************************/
2033
2034 static int
2035 vchiq_open(struct inode *inode, struct file *file)
2036 {
2037         int dev = iminor(inode) & 0x0f;
2038
2039         vchiq_log_info(vchiq_arm_log_level, "vchiq_open");
2040         switch (dev) {
2041         case VCHIQ_MINOR: {
2042                 VCHIQ_STATE_T *state = vchiq_get_state();
2043                 VCHIQ_INSTANCE_T instance;
2044
2045                 if (!state) {
2046                         vchiq_log_error(vchiq_arm_log_level,
2047                                 "vchiq has no connection to VideoCore");
2048                         return -ENOTCONN;
2049                 }
2050
2051                 instance = kzalloc(sizeof(*instance), GFP_KERNEL);
2052                 if (!instance)
2053                         return -ENOMEM;
2054
2055                 instance->state = state;
2056                 instance->pid = current->tgid;
2057
2058                 vchiq_debugfs_add_instance(instance);
2059
2060                 sema_init(&instance->insert_event, 0);
2061                 sema_init(&instance->remove_event, 0);
2062                 mutex_init(&instance->completion_mutex);
2063                 mutex_init(&instance->bulk_waiter_list_mutex);
2064                 INIT_LIST_HEAD(&instance->bulk_waiter_list);
2065
2066                 file->private_data = instance;
2067         } break;
2068
2069         default:
2070                 vchiq_log_error(vchiq_arm_log_level,
2071                         "Unknown minor device: %d", dev);
2072                 return -ENXIO;
2073         }
2074
2075         return 0;
2076 }
2077
2078 /****************************************************************************
2079 *
2080 *   vchiq_release
2081 *
2082 ***************************************************************************/
2083
2084 static int
2085 vchiq_release(struct inode *inode, struct file *file)
2086 {
2087         int dev = iminor(inode) & 0x0f;
2088         int ret = 0;
2089
2090         switch (dev) {
2091         case VCHIQ_MINOR: {
2092                 VCHIQ_INSTANCE_T instance = file->private_data;
2093                 VCHIQ_STATE_T *state = vchiq_get_state();
2094                 VCHIQ_SERVICE_T *service;
2095                 int i;
2096
2097                 vchiq_log_info(vchiq_arm_log_level,
2098                         "%s: instance=%lx",
2099                         __func__, (unsigned long)instance);
2100
2101                 if (!state) {
2102                         ret = -EPERM;
2103                         goto out;
2104                 }
2105
2106                 /* Ensure videocore is awake to allow termination. */
2107                 vchiq_use_internal(instance->state, NULL,
2108                                 USE_TYPE_VCHIQ);
2109
2110                 mutex_lock(&instance->completion_mutex);
2111
2112                 /* Wake the completion thread and ask it to exit */
2113                 instance->closing = 1;
2114                 up(&instance->insert_event);
2115
2116                 mutex_unlock(&instance->completion_mutex);
2117
2118                 /* Wake the slot handler if the completion queue is full. */
2119                 up(&instance->remove_event);
2120
2121                 /* Mark all services for termination... */
2122                 i = 0;
2123                 while ((service = next_service_by_instance(state, instance,
2124                         &i)) != NULL) {
2125                         USER_SERVICE_T *user_service = service->base.userdata;
2126
2127                         /* Wake the slot handler if the msg queue is full. */
2128                         up(&user_service->remove_event);
2129
2130                         vchiq_terminate_service_internal(service);
2131                         unlock_service(service);
2132                 }
2133
2134                 /* ...and wait for them to die */
2135                 i = 0;
2136                 while ((service = next_service_by_instance(state, instance, &i))
2137                         != NULL) {
2138                         USER_SERVICE_T *user_service = service->base.userdata;
2139
2140                         down(&service->remove_event);
2141
2142                         BUG_ON(service->srvstate != VCHIQ_SRVSTATE_FREE);
2143
2144                         spin_lock(&msg_queue_spinlock);
2145
2146                         while (user_service->msg_remove !=
2147                                 user_service->msg_insert) {
2148                                 VCHIQ_HEADER_T *header;
2149                                 int m = user_service->msg_remove &
2150                                         (MSG_QUEUE_SIZE - 1);
2151
2152                                 header = user_service->msg_queue[m];
2153                                 user_service->msg_remove++;
2154                                 spin_unlock(&msg_queue_spinlock);
2155
2156                                 if (header)
2157                                         vchiq_release_message(
2158                                                 service->handle,
2159                                                 header);
2160                                 spin_lock(&msg_queue_spinlock);
2161                         }
2162
2163                         spin_unlock(&msg_queue_spinlock);
2164
2165                         unlock_service(service);
2166                 }
2167
2168                 /* Release any closed services */
2169                 while (instance->completion_remove !=
2170                         instance->completion_insert) {
2171                         VCHIQ_COMPLETION_DATA_T *completion;
2172                         VCHIQ_SERVICE_T *service;
2173
2174                         completion = &instance->completions[
2175                                 instance->completion_remove &
2176                                 (MAX_COMPLETIONS - 1)];
2177                         service = completion->service_userdata;
2178                         if (completion->reason == VCHIQ_SERVICE_CLOSED) {
2179                                 USER_SERVICE_T *user_service =
2180                                         service->base.userdata;
2181
2182                                 /* Wake any blocked user-thread */
2183                                 if (instance->use_close_delivered)
2184                                         up(&user_service->close_event);
2185                                 unlock_service(service);
2186                         }
2187                         instance->completion_remove++;
2188                 }
2189
2190                 /* Release the PEER service count. */
2191                 vchiq_release_internal(instance->state, NULL);
2192
2193                 {
2194                         struct list_head *pos, *next;
2195
2196                         list_for_each_safe(pos, next,
2197                                 &instance->bulk_waiter_list) {
2198                                 struct bulk_waiter_node *waiter;
2199
2200                                 waiter = list_entry(pos,
2201                                         struct bulk_waiter_node,
2202                                         list);
2203                                 list_del(pos);
2204                                 vchiq_log_info(vchiq_arm_log_level,
2205                                         "bulk_waiter - cleaned up %pK for pid %d",
2206                                         waiter, waiter->pid);
2207                                 kfree(waiter);
2208                         }
2209                 }
2210
2211                 vchiq_debugfs_remove_instance(instance);
2212
2213                 kfree(instance);
2214                 file->private_data = NULL;
2215         } break;
2216
2217         default:
2218                 vchiq_log_error(vchiq_arm_log_level,
2219                         "Unknown minor device: %d", dev);
2220                 ret = -ENXIO;
2221         }
2222
2223 out:
2224         return ret;
2225 }
2226
2227 /****************************************************************************
2228 *
2229 *   vchiq_dump
2230 *
2231 ***************************************************************************/
2232
2233 void
2234 vchiq_dump(void *dump_context, const char *str, int len)
2235 {
2236         DUMP_CONTEXT_T *context = (DUMP_CONTEXT_T *)dump_context;
2237
2238         if (context->actual < context->space) {
2239                 int copy_bytes;
2240
2241                 if (context->offset > 0) {
2242                         int skip_bytes = min(len, (int)context->offset);
2243
2244                         str += skip_bytes;
2245                         len -= skip_bytes;
2246                         context->offset -= skip_bytes;
2247                         if (context->offset > 0)
2248                                 return;
2249                 }
2250                 copy_bytes = min(len, (int)(context->space - context->actual));
2251                 if (copy_bytes == 0)
2252                         return;
2253                 if (copy_to_user(context->buf + context->actual, str,
2254                         copy_bytes))
2255                         context->actual = -EFAULT;
2256                 context->actual += copy_bytes;
2257                 len -= copy_bytes;
2258
2259                 /* If tne terminating NUL is included in the length, then it
2260                 ** marks the end of a line and should be replaced with a
2261                 ** carriage return. */
2262                 if ((len == 0) && (str[copy_bytes - 1] == '\0')) {
2263                         char cr = '\n';
2264
2265                         if (copy_to_user(context->buf + context->actual - 1,
2266                                 &cr, 1))
2267                                 context->actual = -EFAULT;
2268                 }
2269         }
2270 }
2271
2272 /****************************************************************************
2273 *
2274 *   vchiq_dump_platform_instance_state
2275 *
2276 ***************************************************************************/
2277
2278 void
2279 vchiq_dump_platform_instances(void *dump_context)
2280 {
2281         VCHIQ_STATE_T *state = vchiq_get_state();
2282         char buf[80];
2283         int len;
2284         int i;
2285
2286         /* There is no list of instances, so instead scan all services,
2287                 marking those that have been dumped. */
2288
2289         for (i = 0; i < state->unused_service; i++) {
2290                 VCHIQ_SERVICE_T *service = state->services[i];
2291                 VCHIQ_INSTANCE_T instance;
2292
2293                 if (service && (service->base.callback == service_callback)) {
2294                         instance = service->instance;
2295                         if (instance)
2296                                 instance->mark = 0;
2297                 }
2298         }
2299
2300         for (i = 0; i < state->unused_service; i++) {
2301                 VCHIQ_SERVICE_T *service = state->services[i];
2302                 VCHIQ_INSTANCE_T instance;
2303
2304                 if (service && (service->base.callback == service_callback)) {
2305                         instance = service->instance;
2306                         if (instance && !instance->mark) {
2307                                 len = snprintf(buf, sizeof(buf),
2308                                         "Instance %pK: pid %d,%s completions %d/%d",
2309                                         instance, instance->pid,
2310                                         instance->connected ? " connected, " :
2311                                                 "",
2312                                         instance->completion_insert -
2313                                                 instance->completion_remove,
2314                                         MAX_COMPLETIONS);
2315
2316                                 vchiq_dump(dump_context, buf, len + 1);
2317
2318                                 instance->mark = 1;
2319                         }
2320                 }
2321         }
2322 }
2323
2324 /****************************************************************************
2325 *
2326 *   vchiq_dump_platform_service_state
2327 *
2328 ***************************************************************************/
2329
2330 void
2331 vchiq_dump_platform_service_state(void *dump_context, VCHIQ_SERVICE_T *service)
2332 {
2333         USER_SERVICE_T *user_service = (USER_SERVICE_T *)service->base.userdata;
2334         char buf[80];
2335         int len;
2336
2337         len = snprintf(buf, sizeof(buf), "  instance %pK", service->instance);
2338
2339         if ((service->base.callback == service_callback) &&
2340                 user_service->is_vchi) {
2341                 len += snprintf(buf + len, sizeof(buf) - len,
2342                         ", %d/%d messages",
2343                         user_service->msg_insert - user_service->msg_remove,
2344                         MSG_QUEUE_SIZE);
2345
2346                 if (user_service->dequeue_pending)
2347                         len += snprintf(buf + len, sizeof(buf) - len,
2348                                 " (dequeue pending)");
2349         }
2350
2351         vchiq_dump(dump_context, buf, len + 1);
2352 }
2353
2354 /****************************************************************************
2355 *
2356 *   vchiq_read
2357 *
2358 ***************************************************************************/
2359
2360 static ssize_t
2361 vchiq_read(struct file *file, char __user *buf,
2362         size_t count, loff_t *ppos)
2363 {
2364         DUMP_CONTEXT_T context;
2365
2366         context.buf = buf;
2367         context.actual = 0;
2368         context.space = count;
2369         context.offset = *ppos;
2370
2371         vchiq_dump_state(&context, &g_state);
2372
2373         *ppos += context.actual;
2374
2375         return context.actual;
2376 }
2377
2378 VCHIQ_STATE_T *
2379 vchiq_get_state(void)
2380 {
2381
2382         if (g_state.remote == NULL)
2383                 printk(KERN_ERR "%s: g_state.remote == NULL\n", __func__);
2384         else if (g_state.remote->initialised != 1)
2385                 printk(KERN_NOTICE "%s: g_state.remote->initialised != 1 (%d)\n",
2386                         __func__, g_state.remote->initialised);
2387
2388         return ((g_state.remote != NULL) &&
2389                 (g_state.remote->initialised == 1)) ? &g_state : NULL;
2390 }
2391
2392 static const struct file_operations
2393 vchiq_fops = {
2394         .owner = THIS_MODULE,
2395         .unlocked_ioctl = vchiq_ioctl,
2396 #if defined(CONFIG_COMPAT)
2397         .compat_ioctl = vchiq_compat_ioctl,
2398 #endif
2399         .open = vchiq_open,
2400         .release = vchiq_release,
2401         .read = vchiq_read
2402 };
2403
2404 /*
2405  * Autosuspend related functionality
2406  */
2407
2408 int
2409 vchiq_videocore_wanted(VCHIQ_STATE_T *state)
2410 {
2411         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2412
2413         if (!arm_state)
2414                 /* autosuspend not supported - always return wanted */
2415                 return 1;
2416         else if (arm_state->blocked_count)
2417                 return 1;
2418         else if (!arm_state->videocore_use_count)
2419                 /* usage count zero - check for override unless we're forcing */
2420                 if (arm_state->resume_blocked)
2421                         return 0;
2422                 else
2423                         return vchiq_platform_videocore_wanted(state);
2424         else
2425                 /* non-zero usage count - videocore still required */
2426                 return 1;
2427 }
2428
2429 static VCHIQ_STATUS_T
2430 vchiq_keepalive_vchiq_callback(VCHIQ_REASON_T reason,
2431         VCHIQ_HEADER_T *header,
2432         VCHIQ_SERVICE_HANDLE_T service_user,
2433         void *bulk_user)
2434 {
2435         vchiq_log_error(vchiq_susp_log_level,
2436                 "%s callback reason %d", __func__, reason);
2437         return 0;
2438 }
2439
2440 static int
2441 vchiq_keepalive_thread_func(void *v)
2442 {
2443         VCHIQ_STATE_T *state = (VCHIQ_STATE_T *) v;
2444         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2445
2446         VCHIQ_STATUS_T status;
2447         VCHIQ_INSTANCE_T instance;
2448         VCHIQ_SERVICE_HANDLE_T ka_handle;
2449
2450         VCHIQ_SERVICE_PARAMS_T params = {
2451                 .fourcc      = VCHIQ_MAKE_FOURCC('K', 'E', 'E', 'P'),
2452                 .callback    = vchiq_keepalive_vchiq_callback,
2453                 .version     = KEEPALIVE_VER,
2454                 .version_min = KEEPALIVE_VER_MIN
2455         };
2456
2457         status = vchiq_initialise(&instance);
2458         if (status != VCHIQ_SUCCESS) {
2459                 vchiq_log_error(vchiq_susp_log_level,
2460                         "%s vchiq_initialise failed %d", __func__, status);
2461                 goto exit;
2462         }
2463
2464         status = vchiq_connect(instance);
2465         if (status != VCHIQ_SUCCESS) {
2466                 vchiq_log_error(vchiq_susp_log_level,
2467                         "%s vchiq_connect failed %d", __func__, status);
2468                 goto shutdown;
2469         }
2470
2471         status = vchiq_add_service(instance, &params, &ka_handle);
2472         if (status != VCHIQ_SUCCESS) {
2473                 vchiq_log_error(vchiq_susp_log_level,
2474                         "%s vchiq_open_service failed %d", __func__, status);
2475                 goto shutdown;
2476         }
2477
2478         while (1) {
2479                 long rc = 0, uc = 0;
2480
2481                 if (wait_for_completion_interruptible(&arm_state->ka_evt)
2482                                 != 0) {
2483                         vchiq_log_error(vchiq_susp_log_level,
2484                                 "%s interrupted", __func__);
2485                         flush_signals(current);
2486                         continue;
2487                 }
2488
2489                 /* read and clear counters.  Do release_count then use_count to
2490                  * prevent getting more releases than uses */
2491                 rc = atomic_xchg(&arm_state->ka_release_count, 0);
2492                 uc = atomic_xchg(&arm_state->ka_use_count, 0);
2493
2494                 /* Call use/release service the requisite number of times.
2495                  * Process use before release so use counts don't go negative */
2496                 while (uc--) {
2497                         atomic_inc(&arm_state->ka_use_ack_count);
2498                         status = vchiq_use_service(ka_handle);
2499                         if (status != VCHIQ_SUCCESS) {
2500                                 vchiq_log_error(vchiq_susp_log_level,
2501                                         "%s vchiq_use_service error %d",
2502                                         __func__, status);
2503                         }
2504                 }
2505                 while (rc--) {
2506                         status = vchiq_release_service(ka_handle);
2507                         if (status != VCHIQ_SUCCESS) {
2508                                 vchiq_log_error(vchiq_susp_log_level,
2509                                         "%s vchiq_release_service error %d",
2510                                         __func__, status);
2511                         }
2512                 }
2513         }
2514
2515 shutdown:
2516         vchiq_shutdown(instance);
2517 exit:
2518         return 0;
2519 }
2520
2521 VCHIQ_STATUS_T
2522 vchiq_arm_init_state(VCHIQ_STATE_T *state, VCHIQ_ARM_STATE_T *arm_state)
2523 {
2524         if (arm_state) {
2525                 rwlock_init(&arm_state->susp_res_lock);
2526
2527                 init_completion(&arm_state->ka_evt);
2528                 atomic_set(&arm_state->ka_use_count, 0);
2529                 atomic_set(&arm_state->ka_use_ack_count, 0);
2530                 atomic_set(&arm_state->ka_release_count, 0);
2531
2532                 init_completion(&arm_state->vc_suspend_complete);
2533
2534                 init_completion(&arm_state->vc_resume_complete);
2535                 /* Initialise to 'done' state.  We only want to block on resume
2536                  * completion while videocore is suspended. */
2537                 set_resume_state(arm_state, VC_RESUME_RESUMED);
2538
2539                 init_completion(&arm_state->resume_blocker);
2540                 /* Initialise to 'done' state.  We only want to block on this
2541                  * completion while resume is blocked */
2542                 complete_all(&arm_state->resume_blocker);
2543
2544                 init_completion(&arm_state->blocked_blocker);
2545                 /* Initialise to 'done' state.  We only want to block on this
2546                  * completion while things are waiting on the resume blocker */
2547                 complete_all(&arm_state->blocked_blocker);
2548
2549                 arm_state->suspend_timer_timeout = SUSPEND_TIMER_TIMEOUT_MS;
2550                 arm_state->suspend_timer_running = 0;
2551                 arm_state->state = state;
2552                 timer_setup(&arm_state->suspend_timer, suspend_timer_callback,
2553                             0);
2554
2555                 arm_state->first_connect = 0;
2556
2557         }
2558         return VCHIQ_SUCCESS;
2559 }
2560
2561 /*
2562 ** Functions to modify the state variables;
2563 **      set_suspend_state
2564 **      set_resume_state
2565 **
2566 ** There are more state variables than we might like, so ensure they remain in
2567 ** step.  Suspend and resume state are maintained separately, since most of
2568 ** these state machines can operate independently.  However, there are a few
2569 ** states where state transitions in one state machine cause a reset to the
2570 ** other state machine.  In addition, there are some completion events which
2571 ** need to occur on state machine reset and end-state(s), so these are also
2572 ** dealt with in these functions.
2573 **
2574 ** In all states we set the state variable according to the input, but in some
2575 ** cases we perform additional steps outlined below;
2576 **
2577 ** VC_SUSPEND_IDLE - Initialise the suspend completion at the same time.
2578 **                      The suspend completion is completed after any suspend
2579 **                      attempt.  When we reset the state machine we also reset
2580 **                      the completion.  This reset occurs when videocore is
2581 **                      resumed, and also if we initiate suspend after a suspend
2582 **                      failure.
2583 **
2584 ** VC_SUSPEND_IN_PROGRESS - This state is considered the point of no return for
2585 **                      suspend - ie from this point on we must try to suspend
2586 **                      before resuming can occur.  We therefore also reset the
2587 **                      resume state machine to VC_RESUME_IDLE in this state.
2588 **
2589 ** VC_SUSPEND_SUSPENDED - Suspend has completed successfully. Also call
2590 **                      complete_all on the suspend completion to notify
2591 **                      anything waiting for suspend to happen.
2592 **
2593 ** VC_SUSPEND_REJECTED - Videocore rejected suspend. Videocore will also
2594 **                      initiate resume, so no need to alter resume state.
2595 **                      We call complete_all on the suspend completion to notify
2596 **                      of suspend rejection.
2597 **
2598 ** VC_SUSPEND_FAILED - We failed to initiate videocore suspend.  We notify the
2599 **                      suspend completion and reset the resume state machine.
2600 **
2601 ** VC_RESUME_IDLE - Initialise the resume completion at the same time.  The
2602 **                      resume completion is in it's 'done' state whenever
2603 **                      videcore is running.  Therefore, the VC_RESUME_IDLE
2604 **                      state implies that videocore is suspended.
2605 **                      Hence, any thread which needs to wait until videocore is
2606 **                      running can wait on this completion - it will only block
2607 **                      if videocore is suspended.
2608 **
2609 ** VC_RESUME_RESUMED - Resume has completed successfully.  Videocore is running.
2610 **                      Call complete_all on the resume completion to unblock
2611 **                      any threads waiting for resume.  Also reset the suspend
2612 **                      state machine to it's idle state.
2613 **
2614 ** VC_RESUME_FAILED - Currently unused - no mechanism to fail resume exists.
2615 */
2616
2617 void
2618 set_suspend_state(VCHIQ_ARM_STATE_T *arm_state,
2619         enum vc_suspend_status new_state)
2620 {
2621         /* set the state in all cases */
2622         arm_state->vc_suspend_state = new_state;
2623
2624         /* state specific additional actions */
2625         switch (new_state) {
2626         case VC_SUSPEND_FORCE_CANCELED:
2627                 complete_all(&arm_state->vc_suspend_complete);
2628                 break;
2629         case VC_SUSPEND_REJECTED:
2630                 complete_all(&arm_state->vc_suspend_complete);
2631                 break;
2632         case VC_SUSPEND_FAILED:
2633                 complete_all(&arm_state->vc_suspend_complete);
2634                 arm_state->vc_resume_state = VC_RESUME_RESUMED;
2635                 complete_all(&arm_state->vc_resume_complete);
2636                 break;
2637         case VC_SUSPEND_IDLE:
2638                 reinit_completion(&arm_state->vc_suspend_complete);
2639                 break;
2640         case VC_SUSPEND_REQUESTED:
2641                 break;
2642         case VC_SUSPEND_IN_PROGRESS:
2643                 set_resume_state(arm_state, VC_RESUME_IDLE);
2644                 break;
2645         case VC_SUSPEND_SUSPENDED:
2646                 complete_all(&arm_state->vc_suspend_complete);
2647                 break;
2648         default:
2649                 BUG();
2650                 break;
2651         }
2652 }
2653
2654 void
2655 set_resume_state(VCHIQ_ARM_STATE_T *arm_state,
2656         enum vc_resume_status new_state)
2657 {
2658         /* set the state in all cases */
2659         arm_state->vc_resume_state = new_state;
2660
2661         /* state specific additional actions */
2662         switch (new_state) {
2663         case VC_RESUME_FAILED:
2664                 break;
2665         case VC_RESUME_IDLE:
2666                 reinit_completion(&arm_state->vc_resume_complete);
2667                 break;
2668         case VC_RESUME_REQUESTED:
2669                 break;
2670         case VC_RESUME_IN_PROGRESS:
2671                 break;
2672         case VC_RESUME_RESUMED:
2673                 complete_all(&arm_state->vc_resume_complete);
2674                 set_suspend_state(arm_state, VC_SUSPEND_IDLE);
2675                 break;
2676         default:
2677                 BUG();
2678                 break;
2679         }
2680 }
2681
2682 /* should be called with the write lock held */
2683 inline void
2684 start_suspend_timer(VCHIQ_ARM_STATE_T *arm_state)
2685 {
2686         del_timer(&arm_state->suspend_timer);
2687         arm_state->suspend_timer.expires = jiffies +
2688                 msecs_to_jiffies(arm_state->suspend_timer_timeout);
2689         add_timer(&arm_state->suspend_timer);
2690         arm_state->suspend_timer_running = 1;
2691 }
2692
2693 /* should be called with the write lock held */
2694 static inline void
2695 stop_suspend_timer(VCHIQ_ARM_STATE_T *arm_state)
2696 {
2697         if (arm_state->suspend_timer_running) {
2698                 del_timer(&arm_state->suspend_timer);
2699                 arm_state->suspend_timer_running = 0;
2700         }
2701 }
2702
2703 static inline int
2704 need_resume(VCHIQ_STATE_T *state)
2705 {
2706         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2707
2708         return (arm_state->vc_suspend_state > VC_SUSPEND_IDLE) &&
2709                         (arm_state->vc_resume_state < VC_RESUME_REQUESTED) &&
2710                         vchiq_videocore_wanted(state);
2711 }
2712
2713 static int
2714 block_resume(VCHIQ_ARM_STATE_T *arm_state)
2715 {
2716         int status = VCHIQ_SUCCESS;
2717         const unsigned long timeout_val =
2718                                 msecs_to_jiffies(FORCE_SUSPEND_TIMEOUT_MS);
2719         int resume_count = 0;
2720
2721         /* Allow any threads which were blocked by the last force suspend to
2722          * complete if they haven't already.  Only give this one shot; if
2723          * blocked_count is incremented after blocked_blocker is completed
2724          * (which only happens when blocked_count hits 0) then those threads
2725          * will have to wait until next time around */
2726         if (arm_state->blocked_count) {
2727                 reinit_completion(&arm_state->blocked_blocker);
2728                 write_unlock_bh(&arm_state->susp_res_lock);
2729                 vchiq_log_info(vchiq_susp_log_level, "%s wait for previously "
2730                         "blocked clients", __func__);
2731                 if (wait_for_completion_interruptible_timeout(
2732                                 &arm_state->blocked_blocker, timeout_val)
2733                                         <= 0) {
2734                         vchiq_log_error(vchiq_susp_log_level, "%s wait for "
2735                                 "previously blocked clients failed", __func__);
2736                         status = VCHIQ_ERROR;
2737                         write_lock_bh(&arm_state->susp_res_lock);
2738                         goto out;
2739                 }
2740                 vchiq_log_info(vchiq_susp_log_level, "%s previously blocked "
2741                         "clients resumed", __func__);
2742                 write_lock_bh(&arm_state->susp_res_lock);
2743         }
2744
2745         /* We need to wait for resume to complete if it's in process */
2746         while (arm_state->vc_resume_state != VC_RESUME_RESUMED &&
2747                         arm_state->vc_resume_state > VC_RESUME_IDLE) {
2748                 if (resume_count > 1) {
2749                         status = VCHIQ_ERROR;
2750                         vchiq_log_error(vchiq_susp_log_level, "%s waited too "
2751                                 "many times for resume", __func__);
2752                         goto out;
2753                 }
2754                 write_unlock_bh(&arm_state->susp_res_lock);
2755                 vchiq_log_info(vchiq_susp_log_level, "%s wait for resume",
2756                         __func__);
2757                 if (wait_for_completion_interruptible_timeout(
2758                                 &arm_state->vc_resume_complete, timeout_val)
2759                                         <= 0) {
2760                         vchiq_log_error(vchiq_susp_log_level, "%s wait for "
2761                                 "resume failed (%s)", __func__,
2762                                 resume_state_names[arm_state->vc_resume_state +
2763                                                         VC_RESUME_NUM_OFFSET]);
2764                         status = VCHIQ_ERROR;
2765                         write_lock_bh(&arm_state->susp_res_lock);
2766                         goto out;
2767                 }
2768                 vchiq_log_info(vchiq_susp_log_level, "%s resumed", __func__);
2769                 write_lock_bh(&arm_state->susp_res_lock);
2770                 resume_count++;
2771         }
2772         reinit_completion(&arm_state->resume_blocker);
2773         arm_state->resume_blocked = 1;
2774
2775 out:
2776         return status;
2777 }
2778
2779 static inline void
2780 unblock_resume(VCHIQ_ARM_STATE_T *arm_state)
2781 {
2782         complete_all(&arm_state->resume_blocker);
2783         arm_state->resume_blocked = 0;
2784 }
2785
2786 /* Initiate suspend via slot handler. Should be called with the write lock
2787  * held */
2788 VCHIQ_STATUS_T
2789 vchiq_arm_vcsuspend(VCHIQ_STATE_T *state)
2790 {
2791         VCHIQ_STATUS_T status = VCHIQ_ERROR;
2792         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2793
2794         if (!arm_state)
2795                 goto out;
2796
2797         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2798         status = VCHIQ_SUCCESS;
2799
2800         switch (arm_state->vc_suspend_state) {
2801         case VC_SUSPEND_REQUESTED:
2802                 vchiq_log_info(vchiq_susp_log_level, "%s: suspend already "
2803                         "requested", __func__);
2804                 break;
2805         case VC_SUSPEND_IN_PROGRESS:
2806                 vchiq_log_info(vchiq_susp_log_level, "%s: suspend already in "
2807                         "progress", __func__);
2808                 break;
2809
2810         default:
2811                 /* We don't expect to be in other states, so log but continue
2812                  * anyway */
2813                 vchiq_log_error(vchiq_susp_log_level,
2814                         "%s unexpected suspend state %s", __func__,
2815                         suspend_state_names[arm_state->vc_suspend_state +
2816                                                 VC_SUSPEND_NUM_OFFSET]);
2817                 /* fall through */
2818         case VC_SUSPEND_REJECTED:
2819         case VC_SUSPEND_FAILED:
2820                 /* Ensure any idle state actions have been run */
2821                 set_suspend_state(arm_state, VC_SUSPEND_IDLE);
2822                 /* fall through */
2823         case VC_SUSPEND_IDLE:
2824                 vchiq_log_info(vchiq_susp_log_level,
2825                         "%s: suspending", __func__);
2826                 set_suspend_state(arm_state, VC_SUSPEND_REQUESTED);
2827                 /* kick the slot handler thread to initiate suspend */
2828                 request_poll(state, NULL, 0);
2829                 break;
2830         }
2831
2832 out:
2833         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, status);
2834         return status;
2835 }
2836
2837 void
2838 vchiq_platform_check_suspend(VCHIQ_STATE_T *state)
2839 {
2840         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2841         int susp = 0;
2842
2843         if (!arm_state)
2844                 goto out;
2845
2846         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2847
2848         write_lock_bh(&arm_state->susp_res_lock);
2849         if (arm_state->vc_suspend_state == VC_SUSPEND_REQUESTED &&
2850                         arm_state->vc_resume_state == VC_RESUME_RESUMED) {
2851                 set_suspend_state(arm_state, VC_SUSPEND_IN_PROGRESS);
2852                 susp = 1;
2853         }
2854         write_unlock_bh(&arm_state->susp_res_lock);
2855
2856         if (susp)
2857                 vchiq_platform_suspend(state);
2858
2859 out:
2860         vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__);
2861         return;
2862 }
2863
2864 static void
2865 output_timeout_error(VCHIQ_STATE_T *state)
2866 {
2867         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2868         char err[50] = "";
2869         int vc_use_count = arm_state->videocore_use_count;
2870         int active_services = state->unused_service;
2871         int i;
2872
2873         if (!arm_state->videocore_use_count) {
2874                 snprintf(err, sizeof(err), " Videocore usecount is 0");
2875                 goto output_msg;
2876         }
2877         for (i = 0; i < active_services; i++) {
2878                 VCHIQ_SERVICE_T *service_ptr = state->services[i];
2879
2880                 if (service_ptr && service_ptr->service_use_count &&
2881                         (service_ptr->srvstate != VCHIQ_SRVSTATE_FREE)) {
2882                         snprintf(err, sizeof(err), " %c%c%c%c(%d) service has "
2883                                 "use count %d%s", VCHIQ_FOURCC_AS_4CHARS(
2884                                         service_ptr->base.fourcc),
2885                                  service_ptr->client_id,
2886                                  service_ptr->service_use_count,
2887                                  service_ptr->service_use_count ==
2888                                          vc_use_count ? "" : " (+ more)");
2889                         break;
2890                 }
2891         }
2892
2893 output_msg:
2894         vchiq_log_error(vchiq_susp_log_level,
2895                 "timed out waiting for vc suspend (%d).%s",
2896                  arm_state->autosuspend_override, err);
2897
2898 }
2899
2900 /* Try to get videocore into suspended state, regardless of autosuspend state.
2901 ** We don't actually force suspend, since videocore may get into a bad state
2902 ** if we force suspend at a bad time.  Instead, we wait for autosuspend to
2903 ** determine a good point to suspend.  If this doesn't happen within 100ms we
2904 ** report failure.
2905 **
2906 ** Returns VCHIQ_SUCCESS if videocore suspended successfully, VCHIQ_RETRY if
2907 ** videocore failed to suspend in time or VCHIQ_ERROR if interrupted.
2908 */
2909 VCHIQ_STATUS_T
2910 vchiq_arm_force_suspend(VCHIQ_STATE_T *state)
2911 {
2912         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2913         VCHIQ_STATUS_T status = VCHIQ_ERROR;
2914         long rc = 0;
2915         int repeat = -1;
2916
2917         if (!arm_state)
2918                 goto out;
2919
2920         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2921
2922         write_lock_bh(&arm_state->susp_res_lock);
2923
2924         status = block_resume(arm_state);
2925         if (status != VCHIQ_SUCCESS)
2926                 goto unlock;
2927         if (arm_state->vc_suspend_state == VC_SUSPEND_SUSPENDED) {
2928                 /* Already suspended - just block resume and exit */
2929                 vchiq_log_info(vchiq_susp_log_level, "%s already suspended",
2930                         __func__);
2931                 status = VCHIQ_SUCCESS;
2932                 goto unlock;
2933         } else if (arm_state->vc_suspend_state <= VC_SUSPEND_IDLE) {
2934                 /* initiate suspend immediately in the case that we're waiting
2935                  * for the timeout */
2936                 stop_suspend_timer(arm_state);
2937                 if (!vchiq_videocore_wanted(state)) {
2938                         vchiq_log_info(vchiq_susp_log_level, "%s videocore "
2939                                 "idle, initiating suspend", __func__);
2940                         status = vchiq_arm_vcsuspend(state);
2941                 } else if (arm_state->autosuspend_override <
2942                                                 FORCE_SUSPEND_FAIL_MAX) {
2943                         vchiq_log_info(vchiq_susp_log_level, "%s letting "
2944                                 "videocore go idle", __func__);
2945                         status = VCHIQ_SUCCESS;
2946                 } else {
2947                         vchiq_log_warning(vchiq_susp_log_level, "%s failed too "
2948                                 "many times - attempting suspend", __func__);
2949                         status = vchiq_arm_vcsuspend(state);
2950                 }
2951         } else {
2952                 vchiq_log_info(vchiq_susp_log_level, "%s videocore suspend "
2953                         "in progress - wait for completion", __func__);
2954                 status = VCHIQ_SUCCESS;
2955         }
2956
2957         /* Wait for suspend to happen due to system idle (not forced..) */
2958         if (status != VCHIQ_SUCCESS)
2959                 goto unblock_resume;
2960
2961         do {
2962                 write_unlock_bh(&arm_state->susp_res_lock);
2963
2964                 rc = wait_for_completion_interruptible_timeout(
2965                                 &arm_state->vc_suspend_complete,
2966                                 msecs_to_jiffies(FORCE_SUSPEND_TIMEOUT_MS));
2967
2968                 write_lock_bh(&arm_state->susp_res_lock);
2969                 if (rc < 0) {
2970                         vchiq_log_warning(vchiq_susp_log_level, "%s "
2971                                 "interrupted waiting for suspend", __func__);
2972                         status = VCHIQ_ERROR;
2973                         goto unblock_resume;
2974                 } else if (rc == 0) {
2975                         if (arm_state->vc_suspend_state > VC_SUSPEND_IDLE) {
2976                                 /* Repeat timeout once if in progress */
2977                                 if (repeat < 0) {
2978                                         repeat = 1;
2979                                         continue;
2980                                 }
2981                         }
2982                         arm_state->autosuspend_override++;
2983                         output_timeout_error(state);
2984
2985                         status = VCHIQ_RETRY;
2986                         goto unblock_resume;
2987                 }
2988         } while (0 < (repeat--));
2989
2990         /* Check and report state in case we need to abort ARM suspend */
2991         if (arm_state->vc_suspend_state != VC_SUSPEND_SUSPENDED) {
2992                 status = VCHIQ_RETRY;
2993                 vchiq_log_error(vchiq_susp_log_level,
2994                         "%s videocore suspend failed (state %s)", __func__,
2995                         suspend_state_names[arm_state->vc_suspend_state +
2996                                                 VC_SUSPEND_NUM_OFFSET]);
2997                 /* Reset the state only if it's still in an error state.
2998                  * Something could have already initiated another suspend. */
2999                 if (arm_state->vc_suspend_state < VC_SUSPEND_IDLE)
3000                         set_suspend_state(arm_state, VC_SUSPEND_IDLE);
3001
3002                 goto unblock_resume;
3003         }
3004
3005         /* successfully suspended - unlock and exit */
3006         goto unlock;
3007
3008 unblock_resume:
3009         /* all error states need to unblock resume before exit */
3010         unblock_resume(arm_state);
3011
3012 unlock:
3013         write_unlock_bh(&arm_state->susp_res_lock);
3014
3015 out:
3016         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, status);
3017         return status;
3018 }
3019
3020 void
3021 vchiq_check_suspend(VCHIQ_STATE_T *state)
3022 {
3023         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
3024
3025         if (!arm_state)
3026                 goto out;
3027
3028         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
3029
3030         write_lock_bh(&arm_state->susp_res_lock);
3031         if (arm_state->vc_suspend_state != VC_SUSPEND_SUSPENDED &&
3032                         arm_state->first_connect &&
3033                         !vchiq_videocore_wanted(state)) {
3034                 vchiq_arm_vcsuspend(state);
3035         }
3036         write_unlock_bh(&arm_state->susp_res_lock);
3037
3038 out:
3039         vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__);
3040 }
3041
3042 int
3043 vchiq_arm_allow_resume(VCHIQ_STATE_T *state)
3044 {
3045         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
3046         int resume = 0;
3047         int ret = -1;
3048
3049         if (!arm_state)
3050                 goto out;
3051
3052         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
3053
3054         write_lock_bh(&arm_state->susp_res_lock);
3055         unblock_resume(arm_state);
3056         resume = vchiq_check_resume(state);
3057         write_unlock_bh(&arm_state->susp_res_lock);
3058
3059         if (resume) {
3060                 if (wait_for_completion_interruptible(
3061                         &arm_state->vc_resume_complete) < 0) {
3062                         vchiq_log_error(vchiq_susp_log_level,
3063                                 "%s interrupted", __func__);
3064                         /* failed, cannot accurately derive suspend
3065                          * state, so exit early. */
3066                         goto out;
3067                 }
3068         }
3069
3070         read_lock_bh(&arm_state->susp_res_lock);
3071         if (arm_state->vc_suspend_state == VC_SUSPEND_SUSPENDED) {
3072                 vchiq_log_info(vchiq_susp_log_level,
3073                                 "%s: Videocore remains suspended", __func__);
3074         } else {
3075                 vchiq_log_info(vchiq_susp_log_level,
3076                                 "%s: Videocore resumed", __func__);
3077                 ret = 0;
3078         }
3079         read_unlock_bh(&arm_state->susp_res_lock);
3080 out:
3081         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret);
3082         return ret;
3083 }
3084
3085 /* This function should be called with the write lock held */
3086 int
3087 vchiq_check_resume(VCHIQ_STATE_T *state)
3088 {
3089         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
3090         int resume = 0;
3091
3092         if (!arm_state)
3093                 goto out;
3094
3095         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
3096
3097         if (need_resume(state)) {
3098                 set_resume_state(arm_state, VC_RESUME_REQUESTED);
3099                 request_poll(state, NULL, 0);
3100                 resume = 1;
3101         }
3102
3103 out:
3104         vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__);
3105         return resume;
3106 }
3107
3108 VCHIQ_STATUS_T
3109 vchiq_use_internal(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service,
3110                 enum USE_TYPE_E use_type)
3111 {
3112         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
3113         VCHIQ_STATUS_T ret = VCHIQ_SUCCESS;
3114         char entity[16];
3115         int *entity_uc;
3116         int local_uc, local_entity_uc;
3117
3118         if (!arm_state)
3119                 goto out;
3120
3121         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
3122
3123         if (use_type == USE_TYPE_VCHIQ) {
3124                 sprintf(entity, "VCHIQ:   ");
3125                 entity_uc = &arm_state->peer_use_count;
3126         } else if (service) {
3127                 sprintf(entity, "%c%c%c%c:%03d",
3128                         VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc),
3129                         service->client_id);
3130                 entity_uc = &service->service_use_count;
3131         } else {
3132                 vchiq_log_error(vchiq_susp_log_level, "%s null service "
3133                                 "ptr", __func__);
3134                 ret = VCHIQ_ERROR;
3135                 goto out;
3136         }
3137
3138         write_lock_bh(&arm_state->susp_res_lock);
3139         while (arm_state->resume_blocked) {
3140                 /* If we call 'use' while force suspend is waiting for suspend,
3141                  * then we're about to block the thread which the force is
3142                  * waiting to complete, so we're bound to just time out. In this
3143                  * case, set the suspend state such that the wait will be
3144                  * canceled, so we can complete as quickly as possible. */
3145                 if (arm_state->resume_blocked && arm_state->vc_suspend_state ==
3146                                 VC_SUSPEND_IDLE) {
3147                         set_suspend_state(arm_state, VC_SUSPEND_FORCE_CANCELED);
3148                         break;
3149                 }
3150                 /* If suspend is already in progress then we need to block */
3151                 if (!try_wait_for_completion(&arm_state->resume_blocker)) {
3152                         /* Indicate that there are threads waiting on the resume
3153                          * blocker.  These need to be allowed to complete before
3154                          * a _second_ call to force suspend can complete,
3155                          * otherwise low priority threads might never actually
3156                          * continue */
3157                         arm_state->blocked_count++;
3158                         write_unlock_bh(&arm_state->susp_res_lock);
3159                         vchiq_log_info(vchiq_susp_log_level, "%s %s resume "
3160                                 "blocked - waiting...", __func__, entity);
3161                         if (wait_for_completion_killable(
3162                                         &arm_state->resume_blocker) != 0) {
3163                                 vchiq_log_error(vchiq_susp_log_level, "%s %s "
3164                                         "wait for resume blocker interrupted",
3165                                         __func__, entity);
3166                                 ret = VCHIQ_ERROR;
3167                                 write_lock_bh(&arm_state->susp_res_lock);
3168                                 arm_state->blocked_count--;
3169                                 write_unlock_bh(&arm_state->susp_res_lock);
3170                                 goto out;
3171                         }
3172                         vchiq_log_info(vchiq_susp_log_level, "%s %s resume "
3173                                 "unblocked", __func__, entity);
3174                         write_lock_bh(&arm_state->susp_res_lock);
3175                         if (--arm_state->blocked_count == 0)
3176                                 complete_all(&arm_state->blocked_blocker);
3177                 }
3178         }
3179
3180         stop_suspend_timer(arm_state);
3181
3182         local_uc = ++arm_state->videocore_use_count;
3183         local_entity_uc = ++(*entity_uc);
3184
3185         /* If there's a pending request which hasn't yet been serviced then
3186          * just clear it.  If we're past VC_SUSPEND_REQUESTED state then
3187          * vc_resume_complete will block until we either resume or fail to
3188          * suspend */
3189         if (arm_state->vc_suspend_state <= VC_SUSPEND_REQUESTED)
3190                 set_suspend_state(arm_state, VC_SUSPEND_IDLE);
3191
3192         if ((use_type != USE_TYPE_SERVICE_NO_RESUME) && need_resume(state)) {
3193                 set_resume_state(arm_state, VC_RESUME_REQUESTED);
3194                 vchiq_log_info(vchiq_susp_log_level,
3195                         "%s %s count %d, state count %d",
3196                         __func__, entity, local_entity_uc, local_uc);
3197                 request_poll(state, NULL, 0);
3198         } else
3199                 vchiq_log_trace(vchiq_susp_log_level,
3200                         "%s %s count %d, state count %d",
3201                         __func__, entity, *entity_uc, local_uc);
3202
3203         write_unlock_bh(&arm_state->susp_res_lock);
3204
3205         /* Completion is in a done state when we're not suspended, so this won't
3206          * block for the non-suspended case. */
3207         if (!try_wait_for_completion(&arm_state->vc_resume_complete)) {
3208                 vchiq_log_info(vchiq_susp_log_level, "%s %s wait for resume",
3209                         __func__, entity);
3210                 if (wait_for_completion_killable(
3211                                 &arm_state->vc_resume_complete) != 0) {
3212                         vchiq_log_error(vchiq_susp_log_level, "%s %s wait for "
3213                                 "resume interrupted", __func__, entity);
3214                         ret = VCHIQ_ERROR;
3215                         goto out;
3216                 }
3217                 vchiq_log_info(vchiq_susp_log_level, "%s %s resumed", __func__,
3218                         entity);
3219         }
3220
3221         if (ret == VCHIQ_SUCCESS) {
3222                 VCHIQ_STATUS_T status = VCHIQ_SUCCESS;
3223                 long ack_cnt = atomic_xchg(&arm_state->ka_use_ack_count, 0);
3224
3225                 while (ack_cnt && (status == VCHIQ_SUCCESS)) {
3226                         /* Send the use notify to videocore */
3227                         status = vchiq_send_remote_use_active(state);
3228                         if (status == VCHIQ_SUCCESS)
3229                                 ack_cnt--;
3230                         else
3231                                 atomic_add(ack_cnt,
3232                                         &arm_state->ka_use_ack_count);
3233                 }
3234         }
3235
3236 out:
3237         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret);
3238         return ret;
3239 }
3240
3241 VCHIQ_STATUS_T
3242 vchiq_release_internal(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service)
3243 {
3244         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
3245         VCHIQ_STATUS_T ret = VCHIQ_SUCCESS;
3246         char entity[16];
3247         int *entity_uc;
3248         int local_uc, local_entity_uc;
3249
3250         if (!arm_state)
3251                 goto out;
3252
3253         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
3254
3255         if (service) {
3256                 sprintf(entity, "%c%c%c%c:%03d",
3257                         VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc),
3258                         service->client_id);
3259                 entity_uc = &service->service_use_count;
3260         } else {
3261                 sprintf(entity, "PEER:   ");
3262                 entity_uc = &arm_state->peer_use_count;
3263         }
3264
3265         write_lock_bh(&arm_state->susp_res_lock);
3266         if (!arm_state->videocore_use_count || !(*entity_uc)) {
3267                 /* Don't use BUG_ON - don't allow user thread to crash kernel */
3268                 WARN_ON(!arm_state->videocore_use_count);
3269                 WARN_ON(!(*entity_uc));
3270                 ret = VCHIQ_ERROR;
3271                 goto unlock;
3272         }
3273         local_uc = --arm_state->videocore_use_count;
3274         local_entity_uc = --(*entity_uc);
3275
3276         if (!vchiq_videocore_wanted(state)) {
3277                 if (vchiq_platform_use_suspend_timer() &&
3278                                 !arm_state->resume_blocked) {
3279                         /* Only use the timer if we're not trying to force
3280                          * suspend (=> resume_blocked) */
3281                         start_suspend_timer(arm_state);
3282                 } else {
3283                         vchiq_log_info(vchiq_susp_log_level,
3284                                 "%s %s count %d, state count %d - suspending",
3285                                 __func__, entity, *entity_uc,
3286                                 arm_state->videocore_use_count);
3287                         vchiq_arm_vcsuspend(state);
3288                 }
3289         } else
3290                 vchiq_log_trace(vchiq_susp_log_level,
3291                         "%s %s count %d, state count %d",
3292                         __func__, entity, *entity_uc,
3293                         arm_state->videocore_use_count);
3294
3295 unlock:
3296         write_unlock_bh(&arm_state->susp_res_lock);
3297
3298 out:
3299         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret);
3300         return ret;
3301 }
3302
3303 void
3304 vchiq_on_remote_use(VCHIQ_STATE_T *state)
3305 {
3306         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
3307
3308         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
3309         atomic_inc(&arm_state->ka_use_count);
3310         complete(&arm_state->ka_evt);
3311 }
3312
3313 void
3314 vchiq_on_remote_release(VCHIQ_STATE_T *state)
3315 {
3316         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
3317
3318         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
3319         atomic_inc(&arm_state->ka_release_count);
3320         complete(&arm_state->ka_evt);
3321 }
3322
3323 VCHIQ_STATUS_T
3324 vchiq_use_service_internal(VCHIQ_SERVICE_T *service)
3325 {
3326         return vchiq_use_internal(service->state, service, USE_TYPE_SERVICE);
3327 }
3328
3329 VCHIQ_STATUS_T
3330 vchiq_release_service_internal(VCHIQ_SERVICE_T *service)
3331 {
3332         return vchiq_release_internal(service->state, service);
3333 }
3334
3335 VCHIQ_DEBUGFS_NODE_T *
3336 vchiq_instance_get_debugfs_node(VCHIQ_INSTANCE_T instance)
3337 {
3338         return &instance->debugfs_node;
3339 }
3340
3341 int
3342 vchiq_instance_get_use_count(VCHIQ_INSTANCE_T instance)
3343 {
3344         VCHIQ_SERVICE_T *service;
3345         int use_count = 0, i;
3346
3347         i = 0;
3348         while ((service = next_service_by_instance(instance->state,
3349                 instance, &i)) != NULL) {
3350                 use_count += service->service_use_count;
3351                 unlock_service(service);
3352         }
3353         return use_count;
3354 }
3355
3356 int
3357 vchiq_instance_get_pid(VCHIQ_INSTANCE_T instance)
3358 {
3359         return instance->pid;
3360 }
3361
3362 int
3363 vchiq_instance_get_trace(VCHIQ_INSTANCE_T instance)
3364 {
3365         return instance->trace;
3366 }
3367
3368 void
3369 vchiq_instance_set_trace(VCHIQ_INSTANCE_T instance, int trace)
3370 {
3371         VCHIQ_SERVICE_T *service;
3372         int i;
3373
3374         i = 0;
3375         while ((service = next_service_by_instance(instance->state,
3376                 instance, &i)) != NULL) {
3377                 service->trace = trace;
3378                 unlock_service(service);
3379         }
3380         instance->trace = (trace != 0);
3381 }
3382
3383 static void suspend_timer_callback(struct timer_list *t)
3384 {
3385         VCHIQ_ARM_STATE_T *arm_state = from_timer(arm_state, t, suspend_timer);
3386         VCHIQ_STATE_T *state = arm_state->state;
3387
3388         vchiq_log_info(vchiq_susp_log_level,
3389                 "%s - suspend timer expired - check suspend", __func__);
3390         vchiq_check_suspend(state);
3391 }
3392
3393 VCHIQ_STATUS_T
3394 vchiq_use_service_no_resume(VCHIQ_SERVICE_HANDLE_T handle)
3395 {
3396         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
3397         VCHIQ_SERVICE_T *service = find_service_by_handle(handle);
3398
3399         if (service) {
3400                 ret = vchiq_use_internal(service->state, service,
3401                                 USE_TYPE_SERVICE_NO_RESUME);
3402                 unlock_service(service);
3403         }
3404         return ret;
3405 }
3406
3407 VCHIQ_STATUS_T
3408 vchiq_use_service(VCHIQ_SERVICE_HANDLE_T handle)
3409 {
3410         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
3411         VCHIQ_SERVICE_T *service = find_service_by_handle(handle);
3412
3413         if (service) {
3414                 ret = vchiq_use_internal(service->state, service,
3415                                 USE_TYPE_SERVICE);
3416                 unlock_service(service);
3417         }
3418         return ret;
3419 }
3420
3421 VCHIQ_STATUS_T
3422 vchiq_release_service(VCHIQ_SERVICE_HANDLE_T handle)
3423 {
3424         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
3425         VCHIQ_SERVICE_T *service = find_service_by_handle(handle);
3426
3427         if (service) {
3428                 ret = vchiq_release_internal(service->state, service);
3429                 unlock_service(service);
3430         }
3431         return ret;
3432 }
3433
3434 struct service_data_struct {
3435         int fourcc;
3436         int clientid;
3437         int use_count;
3438 };
3439
3440 void
3441 vchiq_dump_service_use_state(VCHIQ_STATE_T *state)
3442 {
3443         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
3444         struct service_data_struct *service_data;
3445         int i, found = 0;
3446         /* If there's more than 64 services, only dump ones with
3447          * non-zero counts */
3448         int only_nonzero = 0;
3449         static const char *nz = "<-- preventing suspend";
3450
3451         enum vc_suspend_status vc_suspend_state;
3452         enum vc_resume_status  vc_resume_state;
3453         int peer_count;
3454         int vc_use_count;
3455         int active_services;
3456
3457         if (!arm_state)
3458                 return;
3459
3460         service_data = kmalloc_array(MAX_SERVICES, sizeof(*service_data),
3461                                      GFP_KERNEL);
3462         if (!service_data)
3463                 return;
3464
3465         read_lock_bh(&arm_state->susp_res_lock);
3466         vc_suspend_state = arm_state->vc_suspend_state;
3467         vc_resume_state  = arm_state->vc_resume_state;
3468         peer_count = arm_state->peer_use_count;
3469         vc_use_count = arm_state->videocore_use_count;
3470         active_services = state->unused_service;
3471         if (active_services > MAX_SERVICES)
3472                 only_nonzero = 1;
3473
3474         for (i = 0; i < active_services; i++) {
3475                 VCHIQ_SERVICE_T *service_ptr = state->services[i];
3476
3477                 if (!service_ptr)
3478                         continue;
3479
3480                 if (only_nonzero && !service_ptr->service_use_count)
3481                         continue;
3482
3483                 if (service_ptr->srvstate == VCHIQ_SRVSTATE_FREE)
3484                         continue;
3485
3486                 service_data[found].fourcc = service_ptr->base.fourcc;
3487                 service_data[found].clientid = service_ptr->client_id;
3488                 service_data[found].use_count = service_ptr->service_use_count;
3489                 found++;
3490                 if (found >= MAX_SERVICES)
3491                         break;
3492         }
3493
3494         read_unlock_bh(&arm_state->susp_res_lock);
3495
3496         vchiq_log_warning(vchiq_susp_log_level,
3497                 "-- Videcore suspend state: %s --",
3498                 suspend_state_names[vc_suspend_state + VC_SUSPEND_NUM_OFFSET]);
3499         vchiq_log_warning(vchiq_susp_log_level,
3500                 "-- Videcore resume state: %s --",
3501                 resume_state_names[vc_resume_state + VC_RESUME_NUM_OFFSET]);
3502
3503         if (only_nonzero)
3504                 vchiq_log_warning(vchiq_susp_log_level, "Too many active "
3505                         "services (%d).  Only dumping up to first %d services "
3506                         "with non-zero use-count", active_services, found);
3507
3508         for (i = 0; i < found; i++) {
3509                 vchiq_log_warning(vchiq_susp_log_level,
3510                         "----- %c%c%c%c:%d service count %d %s",
3511                         VCHIQ_FOURCC_AS_4CHARS(service_data[i].fourcc),
3512                         service_data[i].clientid,
3513                         service_data[i].use_count,
3514                         service_data[i].use_count ? nz : "");
3515         }
3516         vchiq_log_warning(vchiq_susp_log_level,
3517                 "----- VCHIQ use count count %d", peer_count);
3518         vchiq_log_warning(vchiq_susp_log_level,
3519                 "--- Overall vchiq instance use count %d", vc_use_count);
3520
3521         kfree(service_data);
3522
3523         vchiq_dump_platform_use_state(state);
3524 }
3525
3526 VCHIQ_STATUS_T
3527 vchiq_check_service(VCHIQ_SERVICE_T *service)
3528 {
3529         VCHIQ_ARM_STATE_T *arm_state;
3530         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
3531
3532         if (!service || !service->state)
3533                 goto out;
3534
3535         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
3536
3537         arm_state = vchiq_platform_get_arm_state(service->state);
3538
3539         read_lock_bh(&arm_state->susp_res_lock);
3540         if (service->service_use_count)
3541                 ret = VCHIQ_SUCCESS;
3542         read_unlock_bh(&arm_state->susp_res_lock);
3543
3544         if (ret == VCHIQ_ERROR) {
3545                 vchiq_log_error(vchiq_susp_log_level,
3546                         "%s ERROR - %c%c%c%c:%d service count %d, "
3547                         "state count %d, videocore suspend state %s", __func__,
3548                         VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc),
3549                         service->client_id, service->service_use_count,
3550                         arm_state->videocore_use_count,
3551                         suspend_state_names[arm_state->vc_suspend_state +
3552                                                 VC_SUSPEND_NUM_OFFSET]);
3553                 vchiq_dump_service_use_state(service->state);
3554         }
3555 out:
3556         return ret;
3557 }
3558
3559 /* stub functions */
3560 void vchiq_on_remote_use_active(VCHIQ_STATE_T *state)
3561 {
3562         (void)state;
3563 }
3564
3565 void vchiq_platform_conn_state_changed(VCHIQ_STATE_T *state,
3566         VCHIQ_CONNSTATE_T oldstate, VCHIQ_CONNSTATE_T newstate)
3567 {
3568         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
3569
3570         vchiq_log_info(vchiq_susp_log_level, "%d: %s->%s", state->id,
3571                 get_conn_state_name(oldstate), get_conn_state_name(newstate));
3572         if (state->conn_state == VCHIQ_CONNSTATE_CONNECTED) {
3573                 write_lock_bh(&arm_state->susp_res_lock);
3574                 if (!arm_state->first_connect) {
3575                         char threadname[16];
3576
3577                         arm_state->first_connect = 1;
3578                         write_unlock_bh(&arm_state->susp_res_lock);
3579                         snprintf(threadname, sizeof(threadname), "vchiq-keep/%d",
3580                                 state->id);
3581                         arm_state->ka_thread = kthread_create(
3582                                 &vchiq_keepalive_thread_func,
3583                                 (void *)state,
3584                                 threadname);
3585                         if (IS_ERR(arm_state->ka_thread)) {
3586                                 vchiq_log_error(vchiq_susp_log_level,
3587                                         "vchiq: FATAL: couldn't create thread %s",
3588                                         threadname);
3589                         } else {
3590                                 wake_up_process(arm_state->ka_thread);
3591                         }
3592                 } else
3593                         write_unlock_bh(&arm_state->susp_res_lock);
3594         }
3595 }
3596
3597 static struct platform_device *
3598 vchiq_register_child(struct platform_device *pdev, const char *name)
3599 {
3600         struct platform_device_info pdevinfo;
3601         struct platform_device *new_dev;
3602         struct device_node *np;
3603
3604         memset(&pdevinfo, 0, sizeof(pdevinfo));
3605
3606         pdevinfo.parent = &pdev->dev;
3607         pdevinfo.name = name;
3608         pdevinfo.id = PLATFORM_DEVID_NONE;
3609         pdevinfo.dma_mask = DMA_BIT_MASK(32);
3610
3611         new_dev = platform_device_register_full(&pdevinfo);
3612         if (!new_dev)
3613                 return NULL;
3614
3615         /*
3616          * We want the dma-ranges etc to be copied from a device with the
3617          * correct dma-ranges for the VPU.
3618          * VCHIQ on Pi4 is now under scb which doesn't get those dma-ranges.
3619          * Take the "dma" node as going to be suitable as it sees the world
3620          * through the same eyes as the VPU.
3621          */
3622         np = of_find_node_by_path("dma");
3623         if (!np)
3624                 np = pdev->dev.of_node;
3625
3626         of_dma_configure(&new_dev->dev, np, true);
3627
3628         if (np != pdev->dev.of_node)
3629                 of_node_put(np);
3630
3631         return new_dev;
3632 }
3633
3634 static const struct of_device_id vchiq_of_match[] = {
3635         { .compatible = "brcm,bcm2835-vchiq", .data = &bcm2835_drvdata },
3636         { .compatible = "brcm,bcm2836-vchiq", .data = &bcm2836_drvdata },
3637         { .compatible = "brcm,bcm2838-vchiq", .data = &bcm2838_drvdata },
3638         {},
3639 };
3640 MODULE_DEVICE_TABLE(of, vchiq_of_match);
3641
3642 static int vchiq_probe(struct platform_device *pdev)
3643 {
3644         struct device_node *fw_node;
3645         const struct of_device_id *of_id;
3646         struct vchiq_drvdata *drvdata;
3647         int err;
3648
3649         of_id = of_match_node(vchiq_of_match, pdev->dev.of_node);
3650         drvdata = (struct vchiq_drvdata *)of_id->data;
3651         if (!drvdata)
3652                 return -EINVAL;
3653
3654         fw_node = of_find_compatible_node(NULL, NULL,
3655                                           "raspberrypi,bcm2835-firmware");
3656         if (!fw_node) {
3657                 dev_err(&pdev->dev, "Missing firmware node\n");
3658                 return -ENOENT;
3659         }
3660
3661         drvdata->fw = rpi_firmware_get(fw_node);
3662         of_node_put(fw_node);
3663         if (!drvdata->fw)
3664                 return -EPROBE_DEFER;
3665
3666         platform_set_drvdata(pdev, drvdata);
3667
3668         err = vchiq_platform_init(pdev, &g_state);
3669         if (err != 0)
3670                 goto failed_platform_init;
3671
3672         err = alloc_chrdev_region(&vchiq_devid, VCHIQ_MINOR, 1, DEVICE_NAME);
3673         if (err != 0) {
3674                 vchiq_log_error(vchiq_arm_log_level,
3675                         "Unable to allocate device number");
3676                 goto failed_platform_init;
3677         }
3678         cdev_init(&vchiq_cdev, &vchiq_fops);
3679         vchiq_cdev.owner = THIS_MODULE;
3680         err = cdev_add(&vchiq_cdev, vchiq_devid, 1);
3681         if (err != 0) {
3682                 vchiq_log_error(vchiq_arm_log_level,
3683                         "Unable to register device");
3684                 goto failed_cdev_add;
3685         }
3686
3687         /* create sysfs entries */
3688         vchiq_class = class_create(THIS_MODULE, DEVICE_NAME);
3689         err = PTR_ERR(vchiq_class);
3690         if (IS_ERR(vchiq_class))
3691                 goto failed_class_create;
3692
3693         vchiq_dev = device_create(vchiq_class, NULL,
3694                 vchiq_devid, NULL, "vchiq");
3695         err = PTR_ERR(vchiq_dev);
3696         if (IS_ERR(vchiq_dev))
3697                 goto failed_device_create;
3698
3699         /* create debugfs entries */
3700         vchiq_debugfs_init();
3701
3702         vchiq_log_info(vchiq_arm_log_level,
3703                 "vchiq: initialised - version %d (min %d), device %d.%d",
3704                 VCHIQ_VERSION, VCHIQ_VERSION_MIN,
3705                 MAJOR(vchiq_devid), MINOR(vchiq_devid));
3706
3707         vcsm_cma = vchiq_register_child(pdev, "vcsm-cma");
3708         if (IS_ERR(vcsm_cma))
3709                 vcsm_cma = NULL;
3710         bcm2835_camera = vchiq_register_child(pdev, "bcm2835-camera");
3711         if (IS_ERR(bcm2835_camera))
3712                 bcm2835_camera = NULL;
3713         bcm2835_codec = vchiq_register_child(pdev, "bcm2835-codec");
3714         if (IS_ERR(bcm2835_codec))
3715                 bcm2835_codec = NULL;
3716
3717         return 0;
3718
3719 failed_device_create:
3720         class_destroy(vchiq_class);
3721 failed_class_create:
3722         cdev_del(&vchiq_cdev);
3723 failed_cdev_add:
3724         unregister_chrdev_region(vchiq_devid, 1);
3725 failed_platform_init:
3726         vchiq_log_warning(vchiq_arm_log_level, "could not load vchiq");
3727         return err;
3728 }
3729
3730 static int vchiq_remove(struct platform_device *pdev)
3731 {
3732         platform_device_unregister(bcm2835_codec);
3733         platform_device_unregister(bcm2835_camera);
3734         platform_device_unregister(vcsm_cma);
3735         vchiq_debugfs_deinit();
3736         device_destroy(vchiq_class, vchiq_devid);
3737         class_destroy(vchiq_class);
3738         cdev_del(&vchiq_cdev);
3739         unregister_chrdev_region(vchiq_devid, 1);
3740
3741         return 0;
3742 }
3743
3744 static struct platform_driver vchiq_driver = {
3745         .driver = {
3746                 .name = "bcm2835_vchiq",
3747                 .of_match_table = vchiq_of_match,
3748         },
3749         .probe = vchiq_probe,
3750         .remove = vchiq_remove,
3751 };
3752 module_platform_driver(vchiq_driver);
3753
3754 MODULE_LICENSE("Dual BSD/GPL");
3755 MODULE_DESCRIPTION("Videocore VCHIQ driver");
3756 MODULE_AUTHOR("Broadcom Corporation");