]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/staging/vc04_services/interface/vchiq_arm/vchiq_arm.c
cb0b7ca36b1ec66d283f694ca88f7c9dd8b40fa2
[karo-tx-linux.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/types.h>
38 #include <linux/errno.h>
39 #include <linux/cdev.h>
40 #include <linux/fs.h>
41 #include <linux/device.h>
42 #include <linux/mm.h>
43 #include <linux/highmem.h>
44 #include <linux/pagemap.h>
45 #include <linux/bug.h>
46 #include <linux/semaphore.h>
47 #include <linux/list.h>
48 #include <linux/of.h>
49 #include <linux/platform_device.h>
50 #include <soc/bcm2835/raspberrypi-firmware.h>
51
52 #include "vchiq_core.h"
53 #include "vchiq_ioctl.h"
54 #include "vchiq_arm.h"
55 #include "vchiq_debugfs.h"
56 #include "vchiq_killable.h"
57
58 #define DEVICE_NAME "vchiq"
59
60 /* Override the default prefix, which would be vchiq_arm (from the filename) */
61 #undef MODULE_PARAM_PREFIX
62 #define MODULE_PARAM_PREFIX DEVICE_NAME "."
63
64 #define VCHIQ_MINOR 0
65
66 /* Some per-instance constants */
67 #define MAX_COMPLETIONS 128
68 #define MAX_SERVICES 64
69 #define MAX_ELEMENTS 8
70 #define MSG_QUEUE_SIZE 128
71
72 #define KEEPALIVE_VER 1
73 #define KEEPALIVE_VER_MIN KEEPALIVE_VER
74
75 /* Run time control of log level, based on KERN_XXX level. */
76 int vchiq_arm_log_level = VCHIQ_LOG_DEFAULT;
77 int vchiq_susp_log_level = VCHIQ_LOG_ERROR;
78
79 #define SUSPEND_TIMER_TIMEOUT_MS 100
80 #define SUSPEND_RETRY_TIMER_TIMEOUT_MS 1000
81
82 #define VC_SUSPEND_NUM_OFFSET 3 /* number of values before idle which are -ve */
83 static const char *const suspend_state_names[] = {
84         "VC_SUSPEND_FORCE_CANCELED",
85         "VC_SUSPEND_REJECTED",
86         "VC_SUSPEND_FAILED",
87         "VC_SUSPEND_IDLE",
88         "VC_SUSPEND_REQUESTED",
89         "VC_SUSPEND_IN_PROGRESS",
90         "VC_SUSPEND_SUSPENDED"
91 };
92 #define VC_RESUME_NUM_OFFSET 1 /* number of values before idle which are -ve */
93 static const char *const resume_state_names[] = {
94         "VC_RESUME_FAILED",
95         "VC_RESUME_IDLE",
96         "VC_RESUME_REQUESTED",
97         "VC_RESUME_IN_PROGRESS",
98         "VC_RESUME_RESUMED"
99 };
100 /* The number of times we allow force suspend to timeout before actually
101 ** _forcing_ suspend.  This is to cater for SW which fails to release vchiq
102 ** correctly - we don't want to prevent ARM suspend indefinitely in this case.
103 */
104 #define FORCE_SUSPEND_FAIL_MAX 8
105
106 /* The time in ms allowed for videocore to go idle when force suspend has been
107  * requested */
108 #define FORCE_SUSPEND_TIMEOUT_MS 200
109
110
111 static void suspend_timer_callback(unsigned long context);
112
113
114 typedef struct user_service_struct {
115         VCHIQ_SERVICE_T *service;
116         void *userdata;
117         VCHIQ_INSTANCE_T instance;
118         char is_vchi;
119         char dequeue_pending;
120         char close_pending;
121         int message_available_pos;
122         int msg_insert;
123         int msg_remove;
124         struct semaphore insert_event;
125         struct semaphore remove_event;
126         struct semaphore close_event;
127         VCHIQ_HEADER_T * msg_queue[MSG_QUEUE_SIZE];
128 } USER_SERVICE_T;
129
130 struct bulk_waiter_node {
131         struct bulk_waiter bulk_waiter;
132         int pid;
133         struct list_head list;
134 };
135
136 struct vchiq_instance_struct {
137         VCHIQ_STATE_T *state;
138         VCHIQ_COMPLETION_DATA_T completions[MAX_COMPLETIONS];
139         int completion_insert;
140         int completion_remove;
141         struct semaphore insert_event;
142         struct semaphore remove_event;
143         struct mutex completion_mutex;
144
145         int connected;
146         int closing;
147         int pid;
148         int mark;
149         int use_close_delivered;
150         int trace;
151
152         struct list_head bulk_waiter_list;
153         struct mutex bulk_waiter_list_mutex;
154
155         VCHIQ_DEBUGFS_NODE_T debugfs_node;
156 };
157
158 typedef struct dump_context_struct {
159         char __user *buf;
160         size_t actual;
161         size_t space;
162         loff_t offset;
163 } DUMP_CONTEXT_T;
164
165 static struct cdev    vchiq_cdev;
166 static dev_t          vchiq_devid;
167 static VCHIQ_STATE_T g_state;
168 static struct class  *vchiq_class;
169 static struct device *vchiq_dev;
170 static DEFINE_SPINLOCK(msg_queue_spinlock);
171
172 static const char *const ioctl_names[] = {
173         "CONNECT",
174         "SHUTDOWN",
175         "CREATE_SERVICE",
176         "REMOVE_SERVICE",
177         "QUEUE_MESSAGE",
178         "QUEUE_BULK_TRANSMIT",
179         "QUEUE_BULK_RECEIVE",
180         "AWAIT_COMPLETION",
181         "DEQUEUE_MESSAGE",
182         "GET_CLIENT_ID",
183         "GET_CONFIG",
184         "CLOSE_SERVICE",
185         "USE_SERVICE",
186         "RELEASE_SERVICE",
187         "SET_SERVICE_OPTION",
188         "DUMP_PHYS_MEM",
189         "LIB_VERSION",
190         "CLOSE_DELIVERED"
191 };
192
193 vchiq_static_assert(ARRAY_SIZE(ioctl_names) ==
194                     (VCHIQ_IOC_MAX + 1));
195
196 static void
197 dump_phys_mem(void *virt_addr, u32 num_bytes);
198
199 /****************************************************************************
200 *
201 *   add_completion
202 *
203 ***************************************************************************/
204
205 static VCHIQ_STATUS_T
206 add_completion(VCHIQ_INSTANCE_T instance, VCHIQ_REASON_T reason,
207         VCHIQ_HEADER_T *header, USER_SERVICE_T *user_service,
208         void *bulk_userdata)
209 {
210         VCHIQ_COMPLETION_DATA_T *completion;
211         int insert;
212         DEBUG_INITIALISE(g_state.local)
213
214         insert = instance->completion_insert;
215         while ((insert - instance->completion_remove) >= MAX_COMPLETIONS) {
216                 /* Out of space - wait for the client */
217                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
218                 vchiq_log_trace(vchiq_arm_log_level,
219                         "add_completion - completion queue full");
220                 DEBUG_COUNT(COMPLETION_QUEUE_FULL_COUNT);
221                 if (down_interruptible(&instance->remove_event) != 0) {
222                         vchiq_log_info(vchiq_arm_log_level,
223                                 "service_callback interrupted");
224                         return VCHIQ_RETRY;
225                 } else if (instance->closing) {
226                         vchiq_log_info(vchiq_arm_log_level,
227                                 "service_callback closing");
228                         return VCHIQ_SUCCESS;
229                 }
230                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
231         }
232
233         completion = &instance->completions[insert & (MAX_COMPLETIONS - 1)];
234
235         completion->header = header;
236         completion->reason = reason;
237         /* N.B. service_userdata is updated while processing AWAIT_COMPLETION */
238         completion->service_userdata = user_service->service;
239         completion->bulk_userdata = bulk_userdata;
240
241         if (reason == VCHIQ_SERVICE_CLOSED) {
242                 /* Take an extra reference, to be held until
243                    this CLOSED notification is delivered. */
244                 lock_service(user_service->service);
245                 if (instance->use_close_delivered)
246                         user_service->close_pending = 1;
247         }
248
249         /* A write barrier is needed here to ensure that the entire completion
250                 record is written out before the insert point. */
251         wmb();
252
253         if (reason == VCHIQ_MESSAGE_AVAILABLE)
254                 user_service->message_available_pos = insert;
255
256         insert++;
257         instance->completion_insert = insert;
258
259         up(&instance->insert_event);
260
261         return VCHIQ_SUCCESS;
262 }
263
264 /****************************************************************************
265 *
266 *   service_callback
267 *
268 ***************************************************************************/
269
270 static VCHIQ_STATUS_T
271 service_callback(VCHIQ_REASON_T reason, VCHIQ_HEADER_T *header,
272         VCHIQ_SERVICE_HANDLE_T handle, void *bulk_userdata)
273 {
274         /* How do we ensure the callback goes to the right client?
275         ** The service_user data points to a USER_SERVICE_T record containing
276         ** the original callback and the user state structure, which contains a
277         ** circular buffer for completion records.
278         */
279         USER_SERVICE_T *user_service;
280         VCHIQ_SERVICE_T *service;
281         VCHIQ_INSTANCE_T instance;
282         bool skip_completion = false;
283         DEBUG_INITIALISE(g_state.local)
284
285         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
286
287         service = handle_to_service(handle);
288         BUG_ON(!service);
289         user_service = (USER_SERVICE_T *)service->base.userdata;
290         instance = user_service->instance;
291
292         if (!instance || instance->closing)
293                 return VCHIQ_SUCCESS;
294
295         vchiq_log_trace(vchiq_arm_log_level,
296                 "service_callback - service %lx(%d,%p), reason %d, header %lx, "
297                 "instance %lx, bulk_userdata %lx",
298                 (unsigned long)user_service,
299                 service->localport, user_service->userdata,
300                 reason, (unsigned long)header,
301                 (unsigned long)instance, (unsigned long)bulk_userdata);
302
303         if (header && user_service->is_vchi) {
304                 spin_lock(&msg_queue_spinlock);
305                 while (user_service->msg_insert ==
306                         (user_service->msg_remove + MSG_QUEUE_SIZE)) {
307                         spin_unlock(&msg_queue_spinlock);
308                         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
309                         DEBUG_COUNT(MSG_QUEUE_FULL_COUNT);
310                         vchiq_log_trace(vchiq_arm_log_level,
311                                 "service_callback - msg queue full");
312                         /* If there is no MESSAGE_AVAILABLE in the completion
313                         ** queue, add one
314                         */
315                         if ((user_service->message_available_pos -
316                                 instance->completion_remove) < 0) {
317                                 VCHIQ_STATUS_T status;
318                                 vchiq_log_info(vchiq_arm_log_level,
319                                         "Inserting extra MESSAGE_AVAILABLE");
320                                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
321                                 status = add_completion(instance, reason,
322                                         NULL, user_service, bulk_userdata);
323                                 if (status != VCHIQ_SUCCESS) {
324                                         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
325                                         return status;
326                                 }
327                         }
328
329                         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
330                         if (down_interruptible(&user_service->remove_event)
331                                 != 0) {
332                                 vchiq_log_info(vchiq_arm_log_level,
333                                         "service_callback interrupted");
334                                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
335                                 return VCHIQ_RETRY;
336                         } else if (instance->closing) {
337                                 vchiq_log_info(vchiq_arm_log_level,
338                                         "service_callback closing");
339                                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
340                                 return VCHIQ_ERROR;
341                         }
342                         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
343                         spin_lock(&msg_queue_spinlock);
344                 }
345
346                 user_service->msg_queue[user_service->msg_insert &
347                         (MSG_QUEUE_SIZE - 1)] = header;
348                 user_service->msg_insert++;
349
350                 /* If there is a thread waiting in DEQUEUE_MESSAGE, or if
351                 ** there is a MESSAGE_AVAILABLE in the completion queue then
352                 ** bypass the completion queue.
353                 */
354                 if (((user_service->message_available_pos -
355                         instance->completion_remove) >= 0) ||
356                         user_service->dequeue_pending) {
357                         user_service->dequeue_pending = 0;
358                         skip_completion = true;
359                 }
360
361                 spin_unlock(&msg_queue_spinlock);
362                 up(&user_service->insert_event);
363
364                 header = NULL;
365         }
366         DEBUG_TRACE(SERVICE_CALLBACK_LINE);
367
368         if (skip_completion)
369                 return VCHIQ_SUCCESS;
370
371         return add_completion(instance, reason, header, user_service,
372                 bulk_userdata);
373 }
374
375 /****************************************************************************
376 *
377 *   user_service_free
378 *
379 ***************************************************************************/
380 static void
381 user_service_free(void *userdata)
382 {
383         kfree(userdata);
384 }
385
386 /****************************************************************************
387 *
388 *   close_delivered
389 *
390 ***************************************************************************/
391 static void close_delivered(USER_SERVICE_T *user_service)
392 {
393         vchiq_log_info(vchiq_arm_log_level,
394                 "close_delivered(handle=%x)",
395                 user_service->service->handle);
396
397         if (user_service->close_pending) {
398                 /* Allow the underlying service to be culled */
399                 unlock_service(user_service->service);
400
401                 /* Wake the user-thread blocked in close_ or remove_service */
402                 up(&user_service->close_event);
403
404                 user_service->close_pending = 0;
405         }
406 }
407
408 struct vchiq_io_copy_callback_context {
409         VCHIQ_ELEMENT_T *current_element;
410         size_t current_element_offset;
411         unsigned long elements_to_go;
412         size_t current_offset;
413 };
414
415 static ssize_t
416 vchiq_ioc_copy_element_data(
417         void *context,
418         void *dest,
419         size_t offset,
420         size_t maxsize)
421 {
422         long res;
423         size_t bytes_this_round;
424         struct vchiq_io_copy_callback_context *copy_context =
425                 (struct vchiq_io_copy_callback_context *)context;
426
427         if (offset != copy_context->current_offset)
428                 return 0;
429
430         if (!copy_context->elements_to_go)
431                 return 0;
432
433         /*
434          * Complex logic here to handle the case of 0 size elements
435          * in the middle of the array of elements.
436          *
437          * Need to skip over these 0 size elements.
438          */
439         while (1) {
440                 bytes_this_round = min(copy_context->current_element->size -
441                                        copy_context->current_element_offset,
442                                        maxsize);
443
444                 if (bytes_this_round)
445                         break;
446
447                 copy_context->elements_to_go--;
448                 copy_context->current_element++;
449                 copy_context->current_element_offset = 0;
450
451                 if (!copy_context->elements_to_go)
452                         return 0;
453         }
454
455         res = copy_from_user(dest,
456                              copy_context->current_element->data +
457                              copy_context->current_element_offset,
458                              bytes_this_round);
459
460         if (res != 0)
461                 return -EFAULT;
462
463         copy_context->current_element_offset += bytes_this_round;
464         copy_context->current_offset += bytes_this_round;
465
466         /*
467          * Check if done with current element, and if so advance to the next.
468          */
469         if (copy_context->current_element_offset ==
470             copy_context->current_element->size) {
471                 copy_context->elements_to_go--;
472                 copy_context->current_element++;
473                 copy_context->current_element_offset = 0;
474         }
475
476         return bytes_this_round;
477 }
478
479 /**************************************************************************
480  *
481  *   vchiq_ioc_queue_message
482  *
483  **************************************************************************/
484 static VCHIQ_STATUS_T
485 vchiq_ioc_queue_message(VCHIQ_SERVICE_HANDLE_T handle,
486                         VCHIQ_ELEMENT_T *elements,
487                         unsigned long count)
488 {
489         struct vchiq_io_copy_callback_context context;
490         unsigned long i;
491         size_t total_size = 0;
492
493         context.current_element = elements;
494         context.current_element_offset = 0;
495         context.elements_to_go = count;
496         context.current_offset = 0;
497
498         for (i = 0; i < count; i++) {
499                 if (!elements[i].data && elements[i].size != 0)
500                         return -EFAULT;
501
502                 total_size += elements[i].size;
503         }
504
505         return vchiq_queue_message(handle, vchiq_ioc_copy_element_data,
506                                    &context, total_size);
507 }
508
509 /****************************************************************************
510 *
511 *   vchiq_ioctl
512 *
513 ***************************************************************************/
514 static long
515 vchiq_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
516 {
517         VCHIQ_INSTANCE_T instance = file->private_data;
518         VCHIQ_STATUS_T status = VCHIQ_SUCCESS;
519         VCHIQ_SERVICE_T *service = NULL;
520         long ret = 0;
521         int i, rc;
522         DEBUG_INITIALISE(g_state.local)
523
524         vchiq_log_trace(vchiq_arm_log_level,
525                 "vchiq_ioctl - instance %pK, cmd %s, arg %lx",
526                 instance,
527                 ((_IOC_TYPE(cmd) == VCHIQ_IOC_MAGIC) &&
528                 (_IOC_NR(cmd) <= VCHIQ_IOC_MAX)) ?
529                 ioctl_names[_IOC_NR(cmd)] : "<invalid>", arg);
530
531         switch (cmd) {
532         case VCHIQ_IOC_SHUTDOWN:
533                 if (!instance->connected)
534                         break;
535
536                 /* Remove all services */
537                 i = 0;
538                 while ((service = next_service_by_instance(instance->state,
539                         instance, &i)) != NULL) {
540                         status = vchiq_remove_service(service->handle);
541                         unlock_service(service);
542                         if (status != VCHIQ_SUCCESS)
543                                 break;
544                 }
545                 service = NULL;
546
547                 if (status == VCHIQ_SUCCESS) {
548                         /* Wake the completion thread and ask it to exit */
549                         instance->closing = 1;
550                         up(&instance->insert_event);
551                 }
552
553                 break;
554
555         case VCHIQ_IOC_CONNECT:
556                 if (instance->connected) {
557                         ret = -EINVAL;
558                         break;
559                 }
560                 rc = mutex_lock_killable(&instance->state->mutex);
561                 if (rc != 0) {
562                         vchiq_log_error(vchiq_arm_log_level,
563                                 "vchiq: connect: could not lock mutex for "
564                                 "state %d: %d",
565                                 instance->state->id, rc);
566                         ret = -EINTR;
567                         break;
568                 }
569                 status = vchiq_connect_internal(instance->state, instance);
570                 mutex_unlock(&instance->state->mutex);
571
572                 if (status == VCHIQ_SUCCESS)
573                         instance->connected = 1;
574                 else
575                         vchiq_log_error(vchiq_arm_log_level,
576                                 "vchiq: could not connect: %d", status);
577                 break;
578
579         case VCHIQ_IOC_CREATE_SERVICE: {
580                 VCHIQ_CREATE_SERVICE_T args;
581                 USER_SERVICE_T *user_service = NULL;
582                 void *userdata;
583                 int srvstate;
584
585                 if (copy_from_user
586                          (&args, (const void __user *)arg,
587                           sizeof(args)) != 0) {
588                         ret = -EFAULT;
589                         break;
590                 }
591
592                 user_service = kmalloc(sizeof(USER_SERVICE_T), GFP_KERNEL);
593                 if (!user_service) {
594                         ret = -ENOMEM;
595                         break;
596                 }
597
598                 if (args.is_open) {
599                         if (!instance->connected) {
600                                 ret = -ENOTCONN;
601                                 kfree(user_service);
602                                 break;
603                         }
604                         srvstate = VCHIQ_SRVSTATE_OPENING;
605                 } else {
606                         srvstate =
607                                  instance->connected ?
608                                  VCHIQ_SRVSTATE_LISTENING :
609                                  VCHIQ_SRVSTATE_HIDDEN;
610                 }
611
612                 userdata = args.params.userdata;
613                 args.params.callback = service_callback;
614                 args.params.userdata = user_service;
615                 service = vchiq_add_service_internal(
616                                 instance->state,
617                                 &args.params, srvstate,
618                                 instance, user_service_free);
619
620                 if (service != NULL) {
621                         user_service->service = service;
622                         user_service->userdata = userdata;
623                         user_service->instance = instance;
624                         user_service->is_vchi = (args.is_vchi != 0);
625                         user_service->dequeue_pending = 0;
626                         user_service->close_pending = 0;
627                         user_service->message_available_pos =
628                                 instance->completion_remove - 1;
629                         user_service->msg_insert = 0;
630                         user_service->msg_remove = 0;
631                         sema_init(&user_service->insert_event, 0);
632                         sema_init(&user_service->remove_event, 0);
633                         sema_init(&user_service->close_event, 0);
634
635                         if (args.is_open) {
636                                 status = vchiq_open_service_internal
637                                         (service, instance->pid);
638                                 if (status != VCHIQ_SUCCESS) {
639                                         vchiq_remove_service(service->handle);
640                                         service = NULL;
641                                         ret = (status == VCHIQ_RETRY) ?
642                                                 -EINTR : -EIO;
643                                         break;
644                                 }
645                         }
646
647                         if (copy_to_user((void __user *)
648                                 &(((VCHIQ_CREATE_SERVICE_T __user *)
649                                         arg)->handle),
650                                 (const void *)&service->handle,
651                                 sizeof(service->handle)) != 0) {
652                                 ret = -EFAULT;
653                                 vchiq_remove_service(service->handle);
654                         }
655
656                         service = NULL;
657                 } else {
658                         ret = -EEXIST;
659                         kfree(user_service);
660                 }
661         } break;
662
663         case VCHIQ_IOC_CLOSE_SERVICE: {
664                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
665
666                 service = find_service_for_instance(instance, handle);
667                 if (service != NULL) {
668                         USER_SERVICE_T *user_service =
669                                 (USER_SERVICE_T *)service->base.userdata;
670                         /* close_pending is false on first entry, and when the
671                            wait in vchiq_close_service has been interrupted. */
672                         if (!user_service->close_pending) {
673                                 status = vchiq_close_service(service->handle);
674                                 if (status != VCHIQ_SUCCESS)
675                                         break;
676                         }
677
678                         /* close_pending is true once the underlying service
679                            has been closed until the client library calls the
680                            CLOSE_DELIVERED ioctl, signalling close_event. */
681                         if (user_service->close_pending &&
682                                 down_interruptible(&user_service->close_event))
683                                 status = VCHIQ_RETRY;
684                 }
685                 else
686                         ret = -EINVAL;
687         } break;
688
689         case VCHIQ_IOC_REMOVE_SERVICE: {
690                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
691
692                 service = find_service_for_instance(instance, handle);
693                 if (service != NULL) {
694                         USER_SERVICE_T *user_service =
695                                 (USER_SERVICE_T *)service->base.userdata;
696                         /* close_pending is false on first entry, and when the
697                            wait in vchiq_close_service has been interrupted. */
698                         if (!user_service->close_pending) {
699                                 status = vchiq_remove_service(service->handle);
700                                 if (status != VCHIQ_SUCCESS)
701                                         break;
702                         }
703
704                         /* close_pending is true once the underlying service
705                            has been closed until the client library calls the
706                            CLOSE_DELIVERED ioctl, signalling close_event. */
707                         if (user_service->close_pending &&
708                                 down_interruptible(&user_service->close_event))
709                                 status = VCHIQ_RETRY;
710                 }
711                 else
712                         ret = -EINVAL;
713         } break;
714
715         case VCHIQ_IOC_USE_SERVICE:
716         case VCHIQ_IOC_RELEASE_SERVICE: {
717                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
718
719                 service = find_service_for_instance(instance, handle);
720                 if (service != NULL) {
721                         status = (cmd == VCHIQ_IOC_USE_SERVICE) ?
722                                 vchiq_use_service_internal(service) :
723                                 vchiq_release_service_internal(service);
724                         if (status != VCHIQ_SUCCESS) {
725                                 vchiq_log_error(vchiq_susp_log_level,
726                                         "%s: cmd %s returned error %d for "
727                                         "service %c%c%c%c:%03d",
728                                         __func__,
729                                         (cmd == VCHIQ_IOC_USE_SERVICE) ?
730                                                 "VCHIQ_IOC_USE_SERVICE" :
731                                                 "VCHIQ_IOC_RELEASE_SERVICE",
732                                         status,
733                                         VCHIQ_FOURCC_AS_4CHARS(
734                                                 service->base.fourcc),
735                                         service->client_id);
736                                 ret = -EINVAL;
737                         }
738                 } else
739                         ret = -EINVAL;
740         } break;
741
742         case VCHIQ_IOC_QUEUE_MESSAGE: {
743                 VCHIQ_QUEUE_MESSAGE_T args;
744                 if (copy_from_user
745                          (&args, (const void __user *)arg,
746                           sizeof(args)) != 0) {
747                         ret = -EFAULT;
748                         break;
749                 }
750
751                 service = find_service_for_instance(instance, args.handle);
752
753                 if ((service != NULL) && (args.count <= MAX_ELEMENTS)) {
754                         /* Copy elements into kernel space */
755                         VCHIQ_ELEMENT_T elements[MAX_ELEMENTS];
756                         if (copy_from_user(elements, args.elements,
757                                 args.count * sizeof(VCHIQ_ELEMENT_T)) == 0)
758                                 status = vchiq_ioc_queue_message
759                                         (args.handle,
760                                         elements, args.count);
761                         else
762                                 ret = -EFAULT;
763                 } else {
764                         ret = -EINVAL;
765                 }
766         } break;
767
768         case VCHIQ_IOC_QUEUE_BULK_TRANSMIT:
769         case VCHIQ_IOC_QUEUE_BULK_RECEIVE: {
770                 VCHIQ_QUEUE_BULK_TRANSFER_T args;
771                 struct bulk_waiter_node *waiter = NULL;
772                 VCHIQ_BULK_DIR_T dir =
773                         (cmd == VCHIQ_IOC_QUEUE_BULK_TRANSMIT) ?
774                         VCHIQ_BULK_TRANSMIT : VCHIQ_BULK_RECEIVE;
775
776                 if (copy_from_user
777                         (&args, (const void __user *)arg,
778                         sizeof(args)) != 0) {
779                         ret = -EFAULT;
780                         break;
781                 }
782
783                 service = find_service_for_instance(instance, args.handle);
784                 if (!service) {
785                         ret = -EINVAL;
786                         break;
787                 }
788
789                 if (args.mode == VCHIQ_BULK_MODE_BLOCKING) {
790                         waiter = kzalloc(sizeof(struct bulk_waiter_node),
791                                 GFP_KERNEL);
792                         if (!waiter) {
793                                 ret = -ENOMEM;
794                                 break;
795                         }
796                         args.userdata = &waiter->bulk_waiter;
797                 } else if (args.mode == VCHIQ_BULK_MODE_WAITING) {
798                         struct list_head *pos;
799                         mutex_lock(&instance->bulk_waiter_list_mutex);
800                         list_for_each(pos, &instance->bulk_waiter_list) {
801                                 if (list_entry(pos, struct bulk_waiter_node,
802                                         list)->pid == current->pid) {
803                                         waiter = list_entry(pos,
804                                                 struct bulk_waiter_node,
805                                                 list);
806                                         list_del(pos);
807                                         break;
808                                 }
809
810                         }
811                         mutex_unlock(&instance->bulk_waiter_list_mutex);
812                         if (!waiter) {
813                                 vchiq_log_error(vchiq_arm_log_level,
814                                         "no bulk_waiter found for pid %d",
815                                         current->pid);
816                                 ret = -ESRCH;
817                                 break;
818                         }
819                         vchiq_log_info(vchiq_arm_log_level,
820                                 "found bulk_waiter %pK for pid %d", waiter,
821                                 current->pid);
822                         args.userdata = &waiter->bulk_waiter;
823                 }
824                 status = vchiq_bulk_transfer
825                         (args.handle,
826                          VCHI_MEM_HANDLE_INVALID,
827                          args.data, args.size,
828                          args.userdata, args.mode,
829                          dir);
830                 if (!waiter)
831                         break;
832                 if ((status != VCHIQ_RETRY) || fatal_signal_pending(current) ||
833                         !waiter->bulk_waiter.bulk) {
834                         if (waiter->bulk_waiter.bulk) {
835                                 /* Cancel the signal when the transfer
836                                 ** completes. */
837                                 spin_lock(&bulk_waiter_spinlock);
838                                 waiter->bulk_waiter.bulk->userdata = NULL;
839                                 spin_unlock(&bulk_waiter_spinlock);
840                         }
841                         kfree(waiter);
842                 } else {
843                         const VCHIQ_BULK_MODE_T mode_waiting =
844                                 VCHIQ_BULK_MODE_WAITING;
845                         waiter->pid = current->pid;
846                         mutex_lock(&instance->bulk_waiter_list_mutex);
847                         list_add(&waiter->list, &instance->bulk_waiter_list);
848                         mutex_unlock(&instance->bulk_waiter_list_mutex);
849                         vchiq_log_info(vchiq_arm_log_level,
850                                 "saved bulk_waiter %pK for pid %d",
851                                 waiter, current->pid);
852
853                         if (copy_to_user((void __user *)
854                                 &(((VCHIQ_QUEUE_BULK_TRANSFER_T __user *)
855                                         arg)->mode),
856                                 (const void *)&mode_waiting,
857                                 sizeof(mode_waiting)) != 0)
858                                 ret = -EFAULT;
859                 }
860         } break;
861
862         case VCHIQ_IOC_AWAIT_COMPLETION: {
863                 VCHIQ_AWAIT_COMPLETION_T args;
864
865                 DEBUG_TRACE(AWAIT_COMPLETION_LINE);
866                 if (!instance->connected) {
867                         ret = -ENOTCONN;
868                         break;
869                 }
870
871                 if (copy_from_user(&args, (const void __user *)arg,
872                         sizeof(args)) != 0) {
873                         ret = -EFAULT;
874                         break;
875                 }
876
877                 mutex_lock(&instance->completion_mutex);
878
879                 DEBUG_TRACE(AWAIT_COMPLETION_LINE);
880                 while ((instance->completion_remove ==
881                         instance->completion_insert)
882                         && !instance->closing) {
883                         int rc;
884                         DEBUG_TRACE(AWAIT_COMPLETION_LINE);
885                         mutex_unlock(&instance->completion_mutex);
886                         rc = down_interruptible(&instance->insert_event);
887                         mutex_lock(&instance->completion_mutex);
888                         if (rc != 0) {
889                                 DEBUG_TRACE(AWAIT_COMPLETION_LINE);
890                                 vchiq_log_info(vchiq_arm_log_level,
891                                         "AWAIT_COMPLETION interrupted");
892                                 ret = -EINTR;
893                                 break;
894                         }
895                 }
896                 DEBUG_TRACE(AWAIT_COMPLETION_LINE);
897
898                 if (ret == 0) {
899                         int msgbufcount = args.msgbufcount;
900                         int remove = instance->completion_remove;
901
902                         for (ret = 0; ret < args.count; ret++) {
903                                 VCHIQ_COMPLETION_DATA_T *completion;
904                                 VCHIQ_SERVICE_T *service;
905                                 USER_SERVICE_T *user_service;
906                                 VCHIQ_HEADER_T *header;
907
908                                 if (remove == instance->completion_insert)
909                                         break;
910
911                                 completion = &instance->completions[
912                                         remove & (MAX_COMPLETIONS - 1)];
913
914                                 /*
915                                  * A read memory barrier is needed to stop
916                                  * prefetch of a stale completion record
917                                  */
918                                 rmb();
919
920                                 service = completion->service_userdata;
921                                 user_service = service->base.userdata;
922                                 completion->service_userdata =
923                                         user_service->userdata;
924
925                                 header = completion->header;
926                                 if (header) {
927                                         void __user *msgbuf;
928                                         int msglen;
929
930                                         msglen = header->size +
931                                                 sizeof(VCHIQ_HEADER_T);
932                                         /* This must be a VCHIQ-style service */
933                                         if (args.msgbufsize < msglen) {
934                                                 vchiq_log_error(
935                                                         vchiq_arm_log_level,
936                                                         "header %pK: msgbufsize %x < msglen %x",
937                                                         header, args.msgbufsize,
938                                                         msglen);
939                                                 WARN(1, "invalid message "
940                                                         "size\n");
941                                                 if (ret == 0)
942                                                         ret = -EMSGSIZE;
943                                                 break;
944                                         }
945                                         if (msgbufcount <= 0)
946                                                 /* Stall here for lack of a
947                                                 ** buffer for the message. */
948                                                 break;
949                                         /* Get the pointer from user space */
950                                         msgbufcount--;
951                                         if (copy_from_user(&msgbuf,
952                                                 (const void __user *)
953                                                 &args.msgbufs[msgbufcount],
954                                                 sizeof(msgbuf)) != 0) {
955                                                 if (ret == 0)
956                                                         ret = -EFAULT;
957                                                 break;
958                                         }
959
960                                         /* Copy the message to user space */
961                                         if (copy_to_user(msgbuf, header,
962                                                 msglen) != 0) {
963                                                 if (ret == 0)
964                                                         ret = -EFAULT;
965                                                 break;
966                                         }
967
968                                         /* Now it has been copied, the message
969                                         ** can be released. */
970                                         vchiq_release_message(service->handle,
971                                                 header);
972
973                                         /* The completion must point to the
974                                         ** msgbuf. */
975                                         completion->header = msgbuf;
976                                 }
977
978                                 if ((completion->reason ==
979                                         VCHIQ_SERVICE_CLOSED) &&
980                                         !instance->use_close_delivered)
981                                         unlock_service(service);
982
983                                 if (copy_to_user((void __user *)(
984                                         (size_t)args.buf +
985                                         ret * sizeof(VCHIQ_COMPLETION_DATA_T)),
986                                         completion,
987                                         sizeof(VCHIQ_COMPLETION_DATA_T)) != 0) {
988                                                 if (ret == 0)
989                                                         ret = -EFAULT;
990                                         break;
991                                 }
992
993                                 /*
994                                  * Ensure that the above copy has completed
995                                  * before advancing the remove pointer.
996                                  */
997                                 mb();
998                                 remove++;
999                                 instance->completion_remove = remove;
1000                         }
1001
1002                         if (msgbufcount != args.msgbufcount) {
1003                                 if (copy_to_user((void __user *)
1004                                         &((VCHIQ_AWAIT_COMPLETION_T *)arg)->
1005                                                 msgbufcount,
1006                                         &msgbufcount,
1007                                         sizeof(msgbufcount)) != 0) {
1008                                         ret = -EFAULT;
1009                                 }
1010                         }
1011                 }
1012
1013                 if (ret != 0)
1014                         up(&instance->remove_event);
1015                 mutex_unlock(&instance->completion_mutex);
1016                 DEBUG_TRACE(AWAIT_COMPLETION_LINE);
1017         } break;
1018
1019         case VCHIQ_IOC_DEQUEUE_MESSAGE: {
1020                 VCHIQ_DEQUEUE_MESSAGE_T args;
1021                 USER_SERVICE_T *user_service;
1022                 VCHIQ_HEADER_T *header;
1023
1024                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1025                 if (copy_from_user
1026                          (&args, (const void __user *)arg,
1027                           sizeof(args)) != 0) {
1028                         ret = -EFAULT;
1029                         break;
1030                 }
1031                 service = find_service_for_instance(instance, args.handle);
1032                 if (!service) {
1033                         ret = -EINVAL;
1034                         break;
1035                 }
1036                 user_service = (USER_SERVICE_T *)service->base.userdata;
1037                 if (user_service->is_vchi == 0) {
1038                         ret = -EINVAL;
1039                         break;
1040                 }
1041
1042                 spin_lock(&msg_queue_spinlock);
1043                 if (user_service->msg_remove == user_service->msg_insert) {
1044                         if (!args.blocking) {
1045                                 spin_unlock(&msg_queue_spinlock);
1046                                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1047                                 ret = -EWOULDBLOCK;
1048                                 break;
1049                         }
1050                         user_service->dequeue_pending = 1;
1051                         do {
1052                                 spin_unlock(&msg_queue_spinlock);
1053                                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1054                                 if (down_interruptible(
1055                                         &user_service->insert_event) != 0) {
1056                                         vchiq_log_info(vchiq_arm_log_level,
1057                                                 "DEQUEUE_MESSAGE interrupted");
1058                                         ret = -EINTR;
1059                                         break;
1060                                 }
1061                                 spin_lock(&msg_queue_spinlock);
1062                         } while (user_service->msg_remove ==
1063                                 user_service->msg_insert);
1064
1065                         if (ret)
1066                                 break;
1067                 }
1068
1069                 BUG_ON((int)(user_service->msg_insert -
1070                         user_service->msg_remove) < 0);
1071
1072                 header = user_service->msg_queue[user_service->msg_remove &
1073                         (MSG_QUEUE_SIZE - 1)];
1074                 user_service->msg_remove++;
1075                 spin_unlock(&msg_queue_spinlock);
1076
1077                 up(&user_service->remove_event);
1078                 if (header == NULL)
1079                         ret = -ENOTCONN;
1080                 else if (header->size <= args.bufsize) {
1081                         /* Copy to user space if msgbuf is not NULL */
1082                         if ((args.buf == NULL) ||
1083                                 (copy_to_user((void __user *)args.buf,
1084                                 header->data,
1085                                 header->size) == 0)) {
1086                                 ret = header->size;
1087                                 vchiq_release_message(
1088                                         service->handle,
1089                                         header);
1090                         } else
1091                                 ret = -EFAULT;
1092                 } else {
1093                         vchiq_log_error(vchiq_arm_log_level,
1094                                 "header %pK: bufsize %x < size %x",
1095                                 header, args.bufsize, header->size);
1096                         WARN(1, "invalid size\n");
1097                         ret = -EMSGSIZE;
1098                 }
1099                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1100         } break;
1101
1102         case VCHIQ_IOC_GET_CLIENT_ID: {
1103                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
1104
1105                 ret = vchiq_get_client_id(handle);
1106         } break;
1107
1108         case VCHIQ_IOC_GET_CONFIG: {
1109                 VCHIQ_GET_CONFIG_T args;
1110                 VCHIQ_CONFIG_T config;
1111
1112                 if (copy_from_user(&args, (const void __user *)arg,
1113                         sizeof(args)) != 0) {
1114                         ret = -EFAULT;
1115                         break;
1116                 }
1117                 if (args.config_size > sizeof(config)) {
1118                         ret = -EINVAL;
1119                         break;
1120                 }
1121                 status = vchiq_get_config(instance, args.config_size, &config);
1122                 if (status == VCHIQ_SUCCESS) {
1123                         if (copy_to_user((void __user *)args.pconfig,
1124                                     &config, args.config_size) != 0) {
1125                                 ret = -EFAULT;
1126                                 break;
1127                         }
1128                 }
1129         } break;
1130
1131         case VCHIQ_IOC_SET_SERVICE_OPTION: {
1132                 VCHIQ_SET_SERVICE_OPTION_T args;
1133
1134                 if (copy_from_user(
1135                         &args, (const void __user *)arg,
1136                         sizeof(args)) != 0) {
1137                         ret = -EFAULT;
1138                         break;
1139                 }
1140
1141                 service = find_service_for_instance(instance, args.handle);
1142                 if (!service) {
1143                         ret = -EINVAL;
1144                         break;
1145                 }
1146
1147                 status = vchiq_set_service_option(
1148                                 args.handle, args.option, args.value);
1149         } break;
1150
1151         case VCHIQ_IOC_DUMP_PHYS_MEM: {
1152                 VCHIQ_DUMP_MEM_T  args;
1153
1154                 if (copy_from_user
1155                          (&args, (const void __user *)arg,
1156                           sizeof(args)) != 0) {
1157                         ret = -EFAULT;
1158                         break;
1159                 }
1160                 dump_phys_mem(args.virt_addr, args.num_bytes);
1161         } break;
1162
1163         case VCHIQ_IOC_LIB_VERSION: {
1164                 unsigned int lib_version = (unsigned int)arg;
1165
1166                 if (lib_version < VCHIQ_VERSION_MIN)
1167                         ret = -EINVAL;
1168                 else if (lib_version >= VCHIQ_VERSION_CLOSE_DELIVERED)
1169                         instance->use_close_delivered = 1;
1170         } break;
1171
1172         case VCHIQ_IOC_CLOSE_DELIVERED: {
1173                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
1174
1175                 service = find_closed_service_for_instance(instance, handle);
1176                 if (service != NULL) {
1177                         USER_SERVICE_T *user_service =
1178                                 (USER_SERVICE_T *)service->base.userdata;
1179                         close_delivered(user_service);
1180                 }
1181                 else
1182                         ret = -EINVAL;
1183         } break;
1184
1185         default:
1186                 ret = -ENOTTY;
1187                 break;
1188         }
1189
1190         if (service)
1191                 unlock_service(service);
1192
1193         if (ret == 0) {
1194                 if (status == VCHIQ_ERROR)
1195                         ret = -EIO;
1196                 else if (status == VCHIQ_RETRY)
1197                         ret = -EINTR;
1198         }
1199
1200         if ((status == VCHIQ_SUCCESS) && (ret < 0) && (ret != -EINTR) &&
1201                 (ret != -EWOULDBLOCK))
1202                 vchiq_log_info(vchiq_arm_log_level,
1203                         "  ioctl instance %lx, cmd %s -> status %d, %ld",
1204                         (unsigned long)instance,
1205                         (_IOC_NR(cmd) <= VCHIQ_IOC_MAX) ?
1206                                 ioctl_names[_IOC_NR(cmd)] :
1207                                 "<invalid>",
1208                         status, ret);
1209         else
1210                 vchiq_log_trace(vchiq_arm_log_level,
1211                         "  ioctl instance %lx, cmd %s -> status %d, %ld",
1212                         (unsigned long)instance,
1213                         (_IOC_NR(cmd) <= VCHIQ_IOC_MAX) ?
1214                                 ioctl_names[_IOC_NR(cmd)] :
1215                                 "<invalid>",
1216                         status, ret);
1217
1218         return ret;
1219 }
1220
1221 /****************************************************************************
1222 *
1223 *   vchiq_open
1224 *
1225 ***************************************************************************/
1226
1227 static int
1228 vchiq_open(struct inode *inode, struct file *file)
1229 {
1230         int dev = iminor(inode) & 0x0f;
1231         vchiq_log_info(vchiq_arm_log_level, "vchiq_open");
1232         switch (dev) {
1233         case VCHIQ_MINOR: {
1234                 int ret;
1235                 VCHIQ_STATE_T *state = vchiq_get_state();
1236                 VCHIQ_INSTANCE_T instance;
1237
1238                 if (!state) {
1239                         vchiq_log_error(vchiq_arm_log_level,
1240                                 "vchiq has no connection to VideoCore");
1241                         return -ENOTCONN;
1242                 }
1243
1244                 instance = kzalloc(sizeof(*instance), GFP_KERNEL);
1245                 if (!instance)
1246                         return -ENOMEM;
1247
1248                 instance->state = state;
1249                 instance->pid = current->tgid;
1250
1251                 ret = vchiq_debugfs_add_instance(instance);
1252                 if (ret != 0) {
1253                         kfree(instance);
1254                         return ret;
1255                 }
1256
1257                 sema_init(&instance->insert_event, 0);
1258                 sema_init(&instance->remove_event, 0);
1259                 mutex_init(&instance->completion_mutex);
1260                 mutex_init(&instance->bulk_waiter_list_mutex);
1261                 INIT_LIST_HEAD(&instance->bulk_waiter_list);
1262
1263                 file->private_data = instance;
1264         } break;
1265
1266         default:
1267                 vchiq_log_error(vchiq_arm_log_level,
1268                         "Unknown minor device: %d", dev);
1269                 return -ENXIO;
1270         }
1271
1272         return 0;
1273 }
1274
1275 /****************************************************************************
1276 *
1277 *   vchiq_release
1278 *
1279 ***************************************************************************/
1280
1281 static int
1282 vchiq_release(struct inode *inode, struct file *file)
1283 {
1284         int dev = iminor(inode) & 0x0f;
1285         int ret = 0;
1286         switch (dev) {
1287         case VCHIQ_MINOR: {
1288                 VCHIQ_INSTANCE_T instance = file->private_data;
1289                 VCHIQ_STATE_T *state = vchiq_get_state();
1290                 VCHIQ_SERVICE_T *service;
1291                 int i;
1292
1293                 vchiq_log_info(vchiq_arm_log_level,
1294                         "vchiq_release: instance=%lx",
1295                         (unsigned long)instance);
1296
1297                 if (!state) {
1298                         ret = -EPERM;
1299                         goto out;
1300                 }
1301
1302                 /* Ensure videocore is awake to allow termination. */
1303                 vchiq_use_internal(instance->state, NULL,
1304                                 USE_TYPE_VCHIQ);
1305
1306                 mutex_lock(&instance->completion_mutex);
1307
1308                 /* Wake the completion thread and ask it to exit */
1309                 instance->closing = 1;
1310                 up(&instance->insert_event);
1311
1312                 mutex_unlock(&instance->completion_mutex);
1313
1314                 /* Wake the slot handler if the completion queue is full. */
1315                 up(&instance->remove_event);
1316
1317                 /* Mark all services for termination... */
1318                 i = 0;
1319                 while ((service = next_service_by_instance(state, instance,
1320                         &i)) != NULL) {
1321                         USER_SERVICE_T *user_service = service->base.userdata;
1322
1323                         /* Wake the slot handler if the msg queue is full. */
1324                         up(&user_service->remove_event);
1325
1326                         vchiq_terminate_service_internal(service);
1327                         unlock_service(service);
1328                 }
1329
1330                 /* ...and wait for them to die */
1331                 i = 0;
1332                 while ((service = next_service_by_instance(state, instance, &i))
1333                         != NULL) {
1334                         USER_SERVICE_T *user_service = service->base.userdata;
1335
1336                         down(&service->remove_event);
1337
1338                         BUG_ON(service->srvstate != VCHIQ_SRVSTATE_FREE);
1339
1340                         spin_lock(&msg_queue_spinlock);
1341
1342                         while (user_service->msg_remove !=
1343                                 user_service->msg_insert) {
1344                                 VCHIQ_HEADER_T *header = user_service->
1345                                         msg_queue[user_service->msg_remove &
1346                                                 (MSG_QUEUE_SIZE - 1)];
1347                                 user_service->msg_remove++;
1348                                 spin_unlock(&msg_queue_spinlock);
1349
1350                                 if (header)
1351                                         vchiq_release_message(
1352                                                 service->handle,
1353                                                 header);
1354                                 spin_lock(&msg_queue_spinlock);
1355                         }
1356
1357                         spin_unlock(&msg_queue_spinlock);
1358
1359                         unlock_service(service);
1360                 }
1361
1362                 /* Release any closed services */
1363                 while (instance->completion_remove !=
1364                         instance->completion_insert) {
1365                         VCHIQ_COMPLETION_DATA_T *completion;
1366                         VCHIQ_SERVICE_T *service;
1367                         completion = &instance->completions[
1368                                 instance->completion_remove &
1369                                 (MAX_COMPLETIONS - 1)];
1370                         service = completion->service_userdata;
1371                         if (completion->reason == VCHIQ_SERVICE_CLOSED)
1372                         {
1373                                 USER_SERVICE_T *user_service =
1374                                         service->base.userdata;
1375
1376                                 /* Wake any blocked user-thread */
1377                                 if (instance->use_close_delivered)
1378                                         up(&user_service->close_event);
1379                                 unlock_service(service);
1380                         }
1381                         instance->completion_remove++;
1382                 }
1383
1384                 /* Release the PEER service count. */
1385                 vchiq_release_internal(instance->state, NULL);
1386
1387                 {
1388                         struct list_head *pos, *next;
1389                         list_for_each_safe(pos, next,
1390                                 &instance->bulk_waiter_list) {
1391                                 struct bulk_waiter_node *waiter;
1392                                 waiter = list_entry(pos,
1393                                         struct bulk_waiter_node,
1394                                         list);
1395                                 list_del(pos);
1396                                 vchiq_log_info(vchiq_arm_log_level,
1397                                         "bulk_waiter - cleaned up %pK for pid %d",
1398                                         waiter, waiter->pid);
1399                                 kfree(waiter);
1400                         }
1401                 }
1402
1403                 vchiq_debugfs_remove_instance(instance);
1404
1405                 kfree(instance);
1406                 file->private_data = NULL;
1407         } break;
1408
1409         default:
1410                 vchiq_log_error(vchiq_arm_log_level,
1411                         "Unknown minor device: %d", dev);
1412                 ret = -ENXIO;
1413         }
1414
1415 out:
1416         return ret;
1417 }
1418
1419 /****************************************************************************
1420 *
1421 *   vchiq_dump
1422 *
1423 ***************************************************************************/
1424
1425 void
1426 vchiq_dump(void *dump_context, const char *str, int len)
1427 {
1428         DUMP_CONTEXT_T *context = (DUMP_CONTEXT_T *)dump_context;
1429
1430         if (context->actual < context->space) {
1431                 int copy_bytes;
1432                 if (context->offset > 0) {
1433                         int skip_bytes = min(len, (int)context->offset);
1434                         str += skip_bytes;
1435                         len -= skip_bytes;
1436                         context->offset -= skip_bytes;
1437                         if (context->offset > 0)
1438                                 return;
1439                 }
1440                 copy_bytes = min(len, (int)(context->space - context->actual));
1441                 if (copy_bytes == 0)
1442                         return;
1443                 if (copy_to_user(context->buf + context->actual, str,
1444                         copy_bytes))
1445                         context->actual = -EFAULT;
1446                 context->actual += copy_bytes;
1447                 len -= copy_bytes;
1448
1449                 /* If tne terminating NUL is included in the length, then it
1450                 ** marks the end of a line and should be replaced with a
1451                 ** carriage return. */
1452                 if ((len == 0) && (str[copy_bytes - 1] == '\0')) {
1453                         char cr = '\n';
1454                         if (copy_to_user(context->buf + context->actual - 1,
1455                                 &cr, 1))
1456                                 context->actual = -EFAULT;
1457                 }
1458         }
1459 }
1460
1461 /****************************************************************************
1462 *
1463 *   vchiq_dump_platform_instance_state
1464 *
1465 ***************************************************************************/
1466
1467 void
1468 vchiq_dump_platform_instances(void *dump_context)
1469 {
1470         VCHIQ_STATE_T *state = vchiq_get_state();
1471         char buf[80];
1472         int len;
1473         int i;
1474
1475         /* There is no list of instances, so instead scan all services,
1476                 marking those that have been dumped. */
1477
1478         for (i = 0; i < state->unused_service; i++) {
1479                 VCHIQ_SERVICE_T *service = state->services[i];
1480                 VCHIQ_INSTANCE_T instance;
1481
1482                 if (service && (service->base.callback == service_callback)) {
1483                         instance = service->instance;
1484                         if (instance)
1485                                 instance->mark = 0;
1486                 }
1487         }
1488
1489         for (i = 0; i < state->unused_service; i++) {
1490                 VCHIQ_SERVICE_T *service = state->services[i];
1491                 VCHIQ_INSTANCE_T instance;
1492
1493                 if (service && (service->base.callback == service_callback)) {
1494                         instance = service->instance;
1495                         if (instance && !instance->mark) {
1496                                 len = snprintf(buf, sizeof(buf),
1497                                         "Instance %pK: pid %d,%s completions %d/%d",
1498                                         instance, instance->pid,
1499                                         instance->connected ? " connected, " :
1500                                                 "",
1501                                         instance->completion_insert -
1502                                                 instance->completion_remove,
1503                                         MAX_COMPLETIONS);
1504
1505                                 vchiq_dump(dump_context, buf, len + 1);
1506
1507                                 instance->mark = 1;
1508                         }
1509                 }
1510         }
1511 }
1512
1513 /****************************************************************************
1514 *
1515 *   vchiq_dump_platform_service_state
1516 *
1517 ***************************************************************************/
1518
1519 void
1520 vchiq_dump_platform_service_state(void *dump_context, VCHIQ_SERVICE_T *service)
1521 {
1522         USER_SERVICE_T *user_service = (USER_SERVICE_T *)service->base.userdata;
1523         char buf[80];
1524         int len;
1525
1526         len = snprintf(buf, sizeof(buf), "  instance %pK", service->instance);
1527
1528         if ((service->base.callback == service_callback) &&
1529                 user_service->is_vchi) {
1530                 len += snprintf(buf + len, sizeof(buf) - len,
1531                         ", %d/%d messages",
1532                         user_service->msg_insert - user_service->msg_remove,
1533                         MSG_QUEUE_SIZE);
1534
1535                 if (user_service->dequeue_pending)
1536                         len += snprintf(buf + len, sizeof(buf) - len,
1537                                 " (dequeue pending)");
1538         }
1539
1540         vchiq_dump(dump_context, buf, len + 1);
1541 }
1542
1543 /****************************************************************************
1544 *
1545 *   dump_user_mem
1546 *
1547 ***************************************************************************/
1548
1549 static void
1550 dump_phys_mem(void *virt_addr, u32 num_bytes)
1551 {
1552         int            rc;
1553         u8            *end_virt_addr = virt_addr + num_bytes;
1554         int            num_pages;
1555         int            offset;
1556         int            end_offset;
1557         int            page_idx;
1558         int            prev_idx;
1559         struct page   *page;
1560         struct page  **pages;
1561         u8            *kmapped_virt_ptr;
1562
1563         /* Align virtAddr and endVirtAddr to 16 byte boundaries. */
1564
1565         virt_addr = (void *)((unsigned long)virt_addr & ~0x0fuL);
1566         end_virt_addr = (void *)(((unsigned long)end_virt_addr + 15uL) &
1567                 ~0x0fuL);
1568
1569         offset = (int)(long)virt_addr & (PAGE_SIZE - 1);
1570         end_offset = (int)(long)end_virt_addr & (PAGE_SIZE - 1);
1571
1572         num_pages = (offset + num_bytes + PAGE_SIZE - 1) / PAGE_SIZE;
1573
1574         pages = kmalloc(sizeof(struct page *) * num_pages, GFP_KERNEL);
1575         if (pages == NULL) {
1576                 vchiq_log_error(vchiq_arm_log_level,
1577                         "Unable to allocation memory for %d pages\n",
1578                         num_pages);
1579                 return;
1580         }
1581
1582         down_read(&current->mm->mmap_sem);
1583         rc = get_user_pages(
1584                 (unsigned long)virt_addr, /* start */
1585                 num_pages,                /* len */
1586                 0,                        /* gup_flags */
1587                 pages,                    /* pages (array of page pointers) */
1588                 NULL);                    /* vmas */
1589         up_read(&current->mm->mmap_sem);
1590
1591         prev_idx = -1;
1592         page = NULL;
1593
1594         if (rc < 0) {
1595                 vchiq_log_error(vchiq_arm_log_level,
1596                                 "Failed to get user pages: %d\n", rc);
1597                 goto out;
1598         }
1599
1600         while (offset < end_offset) {
1601
1602                 int page_offset = offset % PAGE_SIZE;
1603                 page_idx = offset / PAGE_SIZE;
1604
1605                 if (page_idx != prev_idx) {
1606
1607                         if (page != NULL)
1608                                 kunmap(page);
1609                         page = pages[page_idx];
1610                         kmapped_virt_ptr = kmap(page);
1611
1612                         prev_idx = page_idx;
1613                 }
1614
1615                 if (vchiq_arm_log_level >= VCHIQ_LOG_TRACE)
1616                         vchiq_log_dump_mem("ph",
1617                                 (u32)(unsigned long)&kmapped_virt_ptr[
1618                                         page_offset],
1619                                 &kmapped_virt_ptr[page_offset], 16);
1620
1621                 offset += 16;
1622         }
1623
1624 out:
1625         if (page != NULL)
1626                 kunmap(page);
1627
1628         for (page_idx = 0; page_idx < num_pages; page_idx++)
1629                 put_page(pages[page_idx]);
1630
1631         kfree(pages);
1632 }
1633
1634 /****************************************************************************
1635 *
1636 *   vchiq_read
1637 *
1638 ***************************************************************************/
1639
1640 static ssize_t
1641 vchiq_read(struct file *file, char __user *buf,
1642         size_t count, loff_t *ppos)
1643 {
1644         DUMP_CONTEXT_T context;
1645         context.buf = buf;
1646         context.actual = 0;
1647         context.space = count;
1648         context.offset = *ppos;
1649
1650         vchiq_dump_state(&context, &g_state);
1651
1652         *ppos += context.actual;
1653
1654         return context.actual;
1655 }
1656
1657 VCHIQ_STATE_T *
1658 vchiq_get_state(void)
1659 {
1660
1661         if (g_state.remote == NULL)
1662                 printk(KERN_ERR "%s: g_state.remote == NULL\n", __func__);
1663         else if (g_state.remote->initialised != 1)
1664                 printk(KERN_NOTICE "%s: g_state.remote->initialised != 1 (%d)\n",
1665                         __func__, g_state.remote->initialised);
1666
1667         return ((g_state.remote != NULL) &&
1668                 (g_state.remote->initialised == 1)) ? &g_state : NULL;
1669 }
1670
1671 static const struct file_operations
1672 vchiq_fops = {
1673         .owner = THIS_MODULE,
1674         .unlocked_ioctl = vchiq_ioctl,
1675         .open = vchiq_open,
1676         .release = vchiq_release,
1677         .read = vchiq_read
1678 };
1679
1680 /*
1681  * Autosuspend related functionality
1682  */
1683
1684 int
1685 vchiq_videocore_wanted(VCHIQ_STATE_T *state)
1686 {
1687         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
1688         if (!arm_state)
1689                 /* autosuspend not supported - always return wanted */
1690                 return 1;
1691         else if (arm_state->blocked_count)
1692                 return 1;
1693         else if (!arm_state->videocore_use_count)
1694                 /* usage count zero - check for override unless we're forcing */
1695                 if (arm_state->resume_blocked)
1696                         return 0;
1697                 else
1698                         return vchiq_platform_videocore_wanted(state);
1699         else
1700                 /* non-zero usage count - videocore still required */
1701                 return 1;
1702 }
1703
1704 static VCHIQ_STATUS_T
1705 vchiq_keepalive_vchiq_callback(VCHIQ_REASON_T reason,
1706         VCHIQ_HEADER_T *header,
1707         VCHIQ_SERVICE_HANDLE_T service_user,
1708         void *bulk_user)
1709 {
1710         vchiq_log_error(vchiq_susp_log_level,
1711                 "%s callback reason %d", __func__, reason);
1712         return 0;
1713 }
1714
1715 static int
1716 vchiq_keepalive_thread_func(void *v)
1717 {
1718         VCHIQ_STATE_T *state = (VCHIQ_STATE_T *) v;
1719         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
1720
1721         VCHIQ_STATUS_T status;
1722         VCHIQ_INSTANCE_T instance;
1723         VCHIQ_SERVICE_HANDLE_T ka_handle;
1724
1725         VCHIQ_SERVICE_PARAMS_T params = {
1726                 .fourcc      = VCHIQ_MAKE_FOURCC('K', 'E', 'E', 'P'),
1727                 .callback    = vchiq_keepalive_vchiq_callback,
1728                 .version     = KEEPALIVE_VER,
1729                 .version_min = KEEPALIVE_VER_MIN
1730         };
1731
1732         status = vchiq_initialise(&instance);
1733         if (status != VCHIQ_SUCCESS) {
1734                 vchiq_log_error(vchiq_susp_log_level,
1735                         "%s vchiq_initialise failed %d", __func__, status);
1736                 goto exit;
1737         }
1738
1739         status = vchiq_connect(instance);
1740         if (status != VCHIQ_SUCCESS) {
1741                 vchiq_log_error(vchiq_susp_log_level,
1742                         "%s vchiq_connect failed %d", __func__, status);
1743                 goto shutdown;
1744         }
1745
1746         status = vchiq_add_service(instance, &params, &ka_handle);
1747         if (status != VCHIQ_SUCCESS) {
1748                 vchiq_log_error(vchiq_susp_log_level,
1749                         "%s vchiq_open_service failed %d", __func__, status);
1750                 goto shutdown;
1751         }
1752
1753         while (1) {
1754                 long rc = 0, uc = 0;
1755                 if (wait_for_completion_interruptible(&arm_state->ka_evt)
1756                                 != 0) {
1757                         vchiq_log_error(vchiq_susp_log_level,
1758                                 "%s interrupted", __func__);
1759                         flush_signals(current);
1760                         continue;
1761                 }
1762
1763                 /* read and clear counters.  Do release_count then use_count to
1764                  * prevent getting more releases than uses */
1765                 rc = atomic_xchg(&arm_state->ka_release_count, 0);
1766                 uc = atomic_xchg(&arm_state->ka_use_count, 0);
1767
1768                 /* Call use/release service the requisite number of times.
1769                  * Process use before release so use counts don't go negative */
1770                 while (uc--) {
1771                         atomic_inc(&arm_state->ka_use_ack_count);
1772                         status = vchiq_use_service(ka_handle);
1773                         if (status != VCHIQ_SUCCESS) {
1774                                 vchiq_log_error(vchiq_susp_log_level,
1775                                         "%s vchiq_use_service error %d",
1776                                         __func__, status);
1777                         }
1778                 }
1779                 while (rc--) {
1780                         status = vchiq_release_service(ka_handle);
1781                         if (status != VCHIQ_SUCCESS) {
1782                                 vchiq_log_error(vchiq_susp_log_level,
1783                                         "%s vchiq_release_service error %d",
1784                                         __func__, status);
1785                         }
1786                 }
1787         }
1788
1789 shutdown:
1790         vchiq_shutdown(instance);
1791 exit:
1792         return 0;
1793 }
1794
1795
1796
1797 VCHIQ_STATUS_T
1798 vchiq_arm_init_state(VCHIQ_STATE_T *state, VCHIQ_ARM_STATE_T *arm_state)
1799 {
1800         if (arm_state) {
1801                 rwlock_init(&arm_state->susp_res_lock);
1802
1803                 init_completion(&arm_state->ka_evt);
1804                 atomic_set(&arm_state->ka_use_count, 0);
1805                 atomic_set(&arm_state->ka_use_ack_count, 0);
1806                 atomic_set(&arm_state->ka_release_count, 0);
1807
1808                 init_completion(&arm_state->vc_suspend_complete);
1809
1810                 init_completion(&arm_state->vc_resume_complete);
1811                 /* Initialise to 'done' state.  We only want to block on resume
1812                  * completion while videocore is suspended. */
1813                 set_resume_state(arm_state, VC_RESUME_RESUMED);
1814
1815                 init_completion(&arm_state->resume_blocker);
1816                 /* Initialise to 'done' state.  We only want to block on this
1817                  * completion while resume is blocked */
1818                 complete_all(&arm_state->resume_blocker);
1819
1820                 init_completion(&arm_state->blocked_blocker);
1821                 /* Initialise to 'done' state.  We only want to block on this
1822                  * completion while things are waiting on the resume blocker */
1823                 complete_all(&arm_state->blocked_blocker);
1824
1825                 arm_state->suspend_timer_timeout = SUSPEND_TIMER_TIMEOUT_MS;
1826                 arm_state->suspend_timer_running = 0;
1827                 setup_timer(&arm_state->suspend_timer, suspend_timer_callback,
1828                             (unsigned long)(state));
1829
1830                 arm_state->first_connect = 0;
1831
1832         }
1833         return VCHIQ_SUCCESS;
1834 }
1835
1836 /*
1837 ** Functions to modify the state variables;
1838 **      set_suspend_state
1839 **      set_resume_state
1840 **
1841 ** There are more state variables than we might like, so ensure they remain in
1842 ** step.  Suspend and resume state are maintained separately, since most of
1843 ** these state machines can operate independently.  However, there are a few
1844 ** states where state transitions in one state machine cause a reset to the
1845 ** other state machine.  In addition, there are some completion events which
1846 ** need to occur on state machine reset and end-state(s), so these are also
1847 ** dealt with in these functions.
1848 **
1849 ** In all states we set the state variable according to the input, but in some
1850 ** cases we perform additional steps outlined below;
1851 **
1852 ** VC_SUSPEND_IDLE - Initialise the suspend completion at the same time.
1853 **                      The suspend completion is completed after any suspend
1854 **                      attempt.  When we reset the state machine we also reset
1855 **                      the completion.  This reset occurs when videocore is
1856 **                      resumed, and also if we initiate suspend after a suspend
1857 **                      failure.
1858 **
1859 ** VC_SUSPEND_IN_PROGRESS - This state is considered the point of no return for
1860 **                      suspend - ie from this point on we must try to suspend
1861 **                      before resuming can occur.  We therefore also reset the
1862 **                      resume state machine to VC_RESUME_IDLE in this state.
1863 **
1864 ** VC_SUSPEND_SUSPENDED - Suspend has completed successfully. Also call
1865 **                      complete_all on the suspend completion to notify
1866 **                      anything waiting for suspend to happen.
1867 **
1868 ** VC_SUSPEND_REJECTED - Videocore rejected suspend. Videocore will also
1869 **                      initiate resume, so no need to alter resume state.
1870 **                      We call complete_all on the suspend completion to notify
1871 **                      of suspend rejection.
1872 **
1873 ** VC_SUSPEND_FAILED - We failed to initiate videocore suspend.  We notify the
1874 **                      suspend completion and reset the resume state machine.
1875 **
1876 ** VC_RESUME_IDLE - Initialise the resume completion at the same time.  The
1877 **                      resume completion is in it's 'done' state whenever
1878 **                      videcore is running.  Therefore, the VC_RESUME_IDLE
1879 **                      state implies that videocore is suspended.
1880 **                      Hence, any thread which needs to wait until videocore is
1881 **                      running can wait on this completion - it will only block
1882 **                      if videocore is suspended.
1883 **
1884 ** VC_RESUME_RESUMED - Resume has completed successfully.  Videocore is running.
1885 **                      Call complete_all on the resume completion to unblock
1886 **                      any threads waiting for resume.  Also reset the suspend
1887 **                      state machine to it's idle state.
1888 **
1889 ** VC_RESUME_FAILED - Currently unused - no mechanism to fail resume exists.
1890 */
1891
1892 void
1893 set_suspend_state(VCHIQ_ARM_STATE_T *arm_state,
1894         enum vc_suspend_status new_state)
1895 {
1896         /* set the state in all cases */
1897         arm_state->vc_suspend_state = new_state;
1898
1899         /* state specific additional actions */
1900         switch (new_state) {
1901         case VC_SUSPEND_FORCE_CANCELED:
1902                 complete_all(&arm_state->vc_suspend_complete);
1903                 break;
1904         case VC_SUSPEND_REJECTED:
1905                 complete_all(&arm_state->vc_suspend_complete);
1906                 break;
1907         case VC_SUSPEND_FAILED:
1908                 complete_all(&arm_state->vc_suspend_complete);
1909                 arm_state->vc_resume_state = VC_RESUME_RESUMED;
1910                 complete_all(&arm_state->vc_resume_complete);
1911                 break;
1912         case VC_SUSPEND_IDLE:
1913                 reinit_completion(&arm_state->vc_suspend_complete);
1914                 break;
1915         case VC_SUSPEND_REQUESTED:
1916                 break;
1917         case VC_SUSPEND_IN_PROGRESS:
1918                 set_resume_state(arm_state, VC_RESUME_IDLE);
1919                 break;
1920         case VC_SUSPEND_SUSPENDED:
1921                 complete_all(&arm_state->vc_suspend_complete);
1922                 break;
1923         default:
1924                 BUG();
1925                 break;
1926         }
1927 }
1928
1929 void
1930 set_resume_state(VCHIQ_ARM_STATE_T *arm_state,
1931         enum vc_resume_status new_state)
1932 {
1933         /* set the state in all cases */
1934         arm_state->vc_resume_state = new_state;
1935
1936         /* state specific additional actions */
1937         switch (new_state) {
1938         case VC_RESUME_FAILED:
1939                 break;
1940         case VC_RESUME_IDLE:
1941                 reinit_completion(&arm_state->vc_resume_complete);
1942                 break;
1943         case VC_RESUME_REQUESTED:
1944                 break;
1945         case VC_RESUME_IN_PROGRESS:
1946                 break;
1947         case VC_RESUME_RESUMED:
1948                 complete_all(&arm_state->vc_resume_complete);
1949                 set_suspend_state(arm_state, VC_SUSPEND_IDLE);
1950                 break;
1951         default:
1952                 BUG();
1953                 break;
1954         }
1955 }
1956
1957
1958 /* should be called with the write lock held */
1959 inline void
1960 start_suspend_timer(VCHIQ_ARM_STATE_T *arm_state)
1961 {
1962         del_timer(&arm_state->suspend_timer);
1963         arm_state->suspend_timer.expires = jiffies +
1964                 msecs_to_jiffies(arm_state->
1965                         suspend_timer_timeout);
1966         add_timer(&arm_state->suspend_timer);
1967         arm_state->suspend_timer_running = 1;
1968 }
1969
1970 /* should be called with the write lock held */
1971 static inline void
1972 stop_suspend_timer(VCHIQ_ARM_STATE_T *arm_state)
1973 {
1974         if (arm_state->suspend_timer_running) {
1975                 del_timer(&arm_state->suspend_timer);
1976                 arm_state->suspend_timer_running = 0;
1977         }
1978 }
1979
1980 static inline int
1981 need_resume(VCHIQ_STATE_T *state)
1982 {
1983         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
1984         return (arm_state->vc_suspend_state > VC_SUSPEND_IDLE) &&
1985                         (arm_state->vc_resume_state < VC_RESUME_REQUESTED) &&
1986                         vchiq_videocore_wanted(state);
1987 }
1988
1989 static int
1990 block_resume(VCHIQ_ARM_STATE_T *arm_state)
1991 {
1992         int status = VCHIQ_SUCCESS;
1993         const unsigned long timeout_val =
1994                                 msecs_to_jiffies(FORCE_SUSPEND_TIMEOUT_MS);
1995         int resume_count = 0;
1996
1997         /* Allow any threads which were blocked by the last force suspend to
1998          * complete if they haven't already.  Only give this one shot; if
1999          * blocked_count is incremented after blocked_blocker is completed
2000          * (which only happens when blocked_count hits 0) then those threads
2001          * will have to wait until next time around */
2002         if (arm_state->blocked_count) {
2003                 reinit_completion(&arm_state->blocked_blocker);
2004                 write_unlock_bh(&arm_state->susp_res_lock);
2005                 vchiq_log_info(vchiq_susp_log_level, "%s wait for previously "
2006                         "blocked clients", __func__);
2007                 if (wait_for_completion_interruptible_timeout(
2008                                 &arm_state->blocked_blocker, timeout_val)
2009                                         <= 0) {
2010                         vchiq_log_error(vchiq_susp_log_level, "%s wait for "
2011                                 "previously blocked clients failed", __func__);
2012                         status = VCHIQ_ERROR;
2013                         write_lock_bh(&arm_state->susp_res_lock);
2014                         goto out;
2015                 }
2016                 vchiq_log_info(vchiq_susp_log_level, "%s previously blocked "
2017                         "clients resumed", __func__);
2018                 write_lock_bh(&arm_state->susp_res_lock);
2019         }
2020
2021         /* We need to wait for resume to complete if it's in process */
2022         while (arm_state->vc_resume_state != VC_RESUME_RESUMED &&
2023                         arm_state->vc_resume_state > VC_RESUME_IDLE) {
2024                 if (resume_count > 1) {
2025                         status = VCHIQ_ERROR;
2026                         vchiq_log_error(vchiq_susp_log_level, "%s waited too "
2027                                 "many times for resume", __func__);
2028                         goto out;
2029                 }
2030                 write_unlock_bh(&arm_state->susp_res_lock);
2031                 vchiq_log_info(vchiq_susp_log_level, "%s wait for resume",
2032                         __func__);
2033                 if (wait_for_completion_interruptible_timeout(
2034                                 &arm_state->vc_resume_complete, timeout_val)
2035                                         <= 0) {
2036                         vchiq_log_error(vchiq_susp_log_level, "%s wait for "
2037                                 "resume failed (%s)", __func__,
2038                                 resume_state_names[arm_state->vc_resume_state +
2039                                                         VC_RESUME_NUM_OFFSET]);
2040                         status = VCHIQ_ERROR;
2041                         write_lock_bh(&arm_state->susp_res_lock);
2042                         goto out;
2043                 }
2044                 vchiq_log_info(vchiq_susp_log_level, "%s resumed", __func__);
2045                 write_lock_bh(&arm_state->susp_res_lock);
2046                 resume_count++;
2047         }
2048         reinit_completion(&arm_state->resume_blocker);
2049         arm_state->resume_blocked = 1;
2050
2051 out:
2052         return status;
2053 }
2054
2055 static inline void
2056 unblock_resume(VCHIQ_ARM_STATE_T *arm_state)
2057 {
2058         complete_all(&arm_state->resume_blocker);
2059         arm_state->resume_blocked = 0;
2060 }
2061
2062 /* Initiate suspend via slot handler. Should be called with the write lock
2063  * held */
2064 VCHIQ_STATUS_T
2065 vchiq_arm_vcsuspend(VCHIQ_STATE_T *state)
2066 {
2067         VCHIQ_STATUS_T status = VCHIQ_ERROR;
2068         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2069
2070         if (!arm_state)
2071                 goto out;
2072
2073         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2074         status = VCHIQ_SUCCESS;
2075
2076
2077         switch (arm_state->vc_suspend_state) {
2078         case VC_SUSPEND_REQUESTED:
2079                 vchiq_log_info(vchiq_susp_log_level, "%s: suspend already "
2080                         "requested", __func__);
2081                 break;
2082         case VC_SUSPEND_IN_PROGRESS:
2083                 vchiq_log_info(vchiq_susp_log_level, "%s: suspend already in "
2084                         "progress", __func__);
2085                 break;
2086
2087         default:
2088                 /* We don't expect to be in other states, so log but continue
2089                  * anyway */
2090                 vchiq_log_error(vchiq_susp_log_level,
2091                         "%s unexpected suspend state %s", __func__,
2092                         suspend_state_names[arm_state->vc_suspend_state +
2093                                                 VC_SUSPEND_NUM_OFFSET]);
2094                 /* fall through */
2095         case VC_SUSPEND_REJECTED:
2096         case VC_SUSPEND_FAILED:
2097                 /* Ensure any idle state actions have been run */
2098                 set_suspend_state(arm_state, VC_SUSPEND_IDLE);
2099                 /* fall through */
2100         case VC_SUSPEND_IDLE:
2101                 vchiq_log_info(vchiq_susp_log_level,
2102                         "%s: suspending", __func__);
2103                 set_suspend_state(arm_state, VC_SUSPEND_REQUESTED);
2104                 /* kick the slot handler thread to initiate suspend */
2105                 request_poll(state, NULL, 0);
2106                 break;
2107         }
2108
2109 out:
2110         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, status);
2111         return status;
2112 }
2113
2114 void
2115 vchiq_platform_check_suspend(VCHIQ_STATE_T *state)
2116 {
2117         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2118         int susp = 0;
2119
2120         if (!arm_state)
2121                 goto out;
2122
2123         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2124
2125         write_lock_bh(&arm_state->susp_res_lock);
2126         if (arm_state->vc_suspend_state == VC_SUSPEND_REQUESTED &&
2127                         arm_state->vc_resume_state == VC_RESUME_RESUMED) {
2128                 set_suspend_state(arm_state, VC_SUSPEND_IN_PROGRESS);
2129                 susp = 1;
2130         }
2131         write_unlock_bh(&arm_state->susp_res_lock);
2132
2133         if (susp)
2134                 vchiq_platform_suspend(state);
2135
2136 out:
2137         vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__);
2138         return;
2139 }
2140
2141
2142 static void
2143 output_timeout_error(VCHIQ_STATE_T *state)
2144 {
2145         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2146         char err[50] = "";
2147         int vc_use_count = arm_state->videocore_use_count;
2148         int active_services = state->unused_service;
2149         int i;
2150
2151         if (!arm_state->videocore_use_count) {
2152                 snprintf(err, sizeof(err), " Videocore usecount is 0");
2153                 goto output_msg;
2154         }
2155         for (i = 0; i < active_services; i++) {
2156                 VCHIQ_SERVICE_T *service_ptr = state->services[i];
2157                 if (service_ptr && service_ptr->service_use_count &&
2158                         (service_ptr->srvstate != VCHIQ_SRVSTATE_FREE)) {
2159                         snprintf(err, sizeof(err), " %c%c%c%c(%d) service has "
2160                                 "use count %d%s", VCHIQ_FOURCC_AS_4CHARS(
2161                                         service_ptr->base.fourcc),
2162                                  service_ptr->client_id,
2163                                  service_ptr->service_use_count,
2164                                  service_ptr->service_use_count ==
2165                                          vc_use_count ? "" : " (+ more)");
2166                         break;
2167                 }
2168         }
2169
2170 output_msg:
2171         vchiq_log_error(vchiq_susp_log_level,
2172                 "timed out waiting for vc suspend (%d).%s",
2173                  arm_state->autosuspend_override, err);
2174
2175 }
2176
2177 /* Try to get videocore into suspended state, regardless of autosuspend state.
2178 ** We don't actually force suspend, since videocore may get into a bad state
2179 ** if we force suspend at a bad time.  Instead, we wait for autosuspend to
2180 ** determine a good point to suspend.  If this doesn't happen within 100ms we
2181 ** report failure.
2182 **
2183 ** Returns VCHIQ_SUCCESS if videocore suspended successfully, VCHIQ_RETRY if
2184 ** videocore failed to suspend in time or VCHIQ_ERROR if interrupted.
2185 */
2186 VCHIQ_STATUS_T
2187 vchiq_arm_force_suspend(VCHIQ_STATE_T *state)
2188 {
2189         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2190         VCHIQ_STATUS_T status = VCHIQ_ERROR;
2191         long rc = 0;
2192         int repeat = -1;
2193
2194         if (!arm_state)
2195                 goto out;
2196
2197         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2198
2199         write_lock_bh(&arm_state->susp_res_lock);
2200
2201         status = block_resume(arm_state);
2202         if (status != VCHIQ_SUCCESS)
2203                 goto unlock;
2204         if (arm_state->vc_suspend_state == VC_SUSPEND_SUSPENDED) {
2205                 /* Already suspended - just block resume and exit */
2206                 vchiq_log_info(vchiq_susp_log_level, "%s already suspended",
2207                         __func__);
2208                 status = VCHIQ_SUCCESS;
2209                 goto unlock;
2210         } else if (arm_state->vc_suspend_state <= VC_SUSPEND_IDLE) {
2211                 /* initiate suspend immediately in the case that we're waiting
2212                  * for the timeout */
2213                 stop_suspend_timer(arm_state);
2214                 if (!vchiq_videocore_wanted(state)) {
2215                         vchiq_log_info(vchiq_susp_log_level, "%s videocore "
2216                                 "idle, initiating suspend", __func__);
2217                         status = vchiq_arm_vcsuspend(state);
2218                 } else if (arm_state->autosuspend_override <
2219                                                 FORCE_SUSPEND_FAIL_MAX) {
2220                         vchiq_log_info(vchiq_susp_log_level, "%s letting "
2221                                 "videocore go idle", __func__);
2222                         status = VCHIQ_SUCCESS;
2223                 } else {
2224                         vchiq_log_warning(vchiq_susp_log_level, "%s failed too "
2225                                 "many times - attempting suspend", __func__);
2226                         status = vchiq_arm_vcsuspend(state);
2227                 }
2228         } else {
2229                 vchiq_log_info(vchiq_susp_log_level, "%s videocore suspend "
2230                         "in progress - wait for completion", __func__);
2231                 status = VCHIQ_SUCCESS;
2232         }
2233
2234         /* Wait for suspend to happen due to system idle (not forced..) */
2235         if (status != VCHIQ_SUCCESS)
2236                 goto unblock_resume;
2237
2238         do {
2239                 write_unlock_bh(&arm_state->susp_res_lock);
2240
2241                 rc = wait_for_completion_interruptible_timeout(
2242                                 &arm_state->vc_suspend_complete,
2243                                 msecs_to_jiffies(FORCE_SUSPEND_TIMEOUT_MS));
2244
2245                 write_lock_bh(&arm_state->susp_res_lock);
2246                 if (rc < 0) {
2247                         vchiq_log_warning(vchiq_susp_log_level, "%s "
2248                                 "interrupted waiting for suspend", __func__);
2249                         status = VCHIQ_ERROR;
2250                         goto unblock_resume;
2251                 } else if (rc == 0) {
2252                         if (arm_state->vc_suspend_state > VC_SUSPEND_IDLE) {
2253                                 /* Repeat timeout once if in progress */
2254                                 if (repeat < 0) {
2255                                         repeat = 1;
2256                                         continue;
2257                                 }
2258                         }
2259                         arm_state->autosuspend_override++;
2260                         output_timeout_error(state);
2261
2262                         status = VCHIQ_RETRY;
2263                         goto unblock_resume;
2264                 }
2265         } while (0 < (repeat--));
2266
2267         /* Check and report state in case we need to abort ARM suspend */
2268         if (arm_state->vc_suspend_state != VC_SUSPEND_SUSPENDED) {
2269                 status = VCHIQ_RETRY;
2270                 vchiq_log_error(vchiq_susp_log_level,
2271                         "%s videocore suspend failed (state %s)", __func__,
2272                         suspend_state_names[arm_state->vc_suspend_state +
2273                                                 VC_SUSPEND_NUM_OFFSET]);
2274                 /* Reset the state only if it's still in an error state.
2275                  * Something could have already initiated another suspend. */
2276                 if (arm_state->vc_suspend_state < VC_SUSPEND_IDLE)
2277                         set_suspend_state(arm_state, VC_SUSPEND_IDLE);
2278
2279                 goto unblock_resume;
2280         }
2281
2282         /* successfully suspended - unlock and exit */
2283         goto unlock;
2284
2285 unblock_resume:
2286         /* all error states need to unblock resume before exit */
2287         unblock_resume(arm_state);
2288
2289 unlock:
2290         write_unlock_bh(&arm_state->susp_res_lock);
2291
2292 out:
2293         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, status);
2294         return status;
2295 }
2296
2297 void
2298 vchiq_check_suspend(VCHIQ_STATE_T *state)
2299 {
2300         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2301
2302         if (!arm_state)
2303                 goto out;
2304
2305         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2306
2307         write_lock_bh(&arm_state->susp_res_lock);
2308         if (arm_state->vc_suspend_state != VC_SUSPEND_SUSPENDED &&
2309                         arm_state->first_connect &&
2310                         !vchiq_videocore_wanted(state)) {
2311                 vchiq_arm_vcsuspend(state);
2312         }
2313         write_unlock_bh(&arm_state->susp_res_lock);
2314
2315 out:
2316         vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__);
2317         return;
2318 }
2319
2320
2321 int
2322 vchiq_arm_allow_resume(VCHIQ_STATE_T *state)
2323 {
2324         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2325         int resume = 0;
2326         int ret = -1;
2327
2328         if (!arm_state)
2329                 goto out;
2330
2331         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2332
2333         write_lock_bh(&arm_state->susp_res_lock);
2334         unblock_resume(arm_state);
2335         resume = vchiq_check_resume(state);
2336         write_unlock_bh(&arm_state->susp_res_lock);
2337
2338         if (resume) {
2339                 if (wait_for_completion_interruptible(
2340                         &arm_state->vc_resume_complete) < 0) {
2341                         vchiq_log_error(vchiq_susp_log_level,
2342                                 "%s interrupted", __func__);
2343                         /* failed, cannot accurately derive suspend
2344                          * state, so exit early. */
2345                         goto out;
2346                 }
2347         }
2348
2349         read_lock_bh(&arm_state->susp_res_lock);
2350         if (arm_state->vc_suspend_state == VC_SUSPEND_SUSPENDED) {
2351                 vchiq_log_info(vchiq_susp_log_level,
2352                                 "%s: Videocore remains suspended", __func__);
2353         } else {
2354                 vchiq_log_info(vchiq_susp_log_level,
2355                                 "%s: Videocore resumed", __func__);
2356                 ret = 0;
2357         }
2358         read_unlock_bh(&arm_state->susp_res_lock);
2359 out:
2360         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret);
2361         return ret;
2362 }
2363
2364 /* This function should be called with the write lock held */
2365 int
2366 vchiq_check_resume(VCHIQ_STATE_T *state)
2367 {
2368         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2369         int resume = 0;
2370
2371         if (!arm_state)
2372                 goto out;
2373
2374         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2375
2376         if (need_resume(state)) {
2377                 set_resume_state(arm_state, VC_RESUME_REQUESTED);
2378                 request_poll(state, NULL, 0);
2379                 resume = 1;
2380         }
2381
2382 out:
2383         vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__);
2384         return resume;
2385 }
2386
2387 VCHIQ_STATUS_T
2388 vchiq_use_internal(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service,
2389                 enum USE_TYPE_E use_type)
2390 {
2391         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2392         VCHIQ_STATUS_T ret = VCHIQ_SUCCESS;
2393         char entity[16];
2394         int *entity_uc;
2395         int local_uc, local_entity_uc;
2396
2397         if (!arm_state)
2398                 goto out;
2399
2400         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2401
2402         if (use_type == USE_TYPE_VCHIQ) {
2403                 sprintf(entity, "VCHIQ:   ");
2404                 entity_uc = &arm_state->peer_use_count;
2405         } else if (service) {
2406                 sprintf(entity, "%c%c%c%c:%03d",
2407                         VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc),
2408                         service->client_id);
2409                 entity_uc = &service->service_use_count;
2410         } else {
2411                 vchiq_log_error(vchiq_susp_log_level, "%s null service "
2412                                 "ptr", __func__);
2413                 ret = VCHIQ_ERROR;
2414                 goto out;
2415         }
2416
2417         write_lock_bh(&arm_state->susp_res_lock);
2418         while (arm_state->resume_blocked) {
2419                 /* If we call 'use' while force suspend is waiting for suspend,
2420                  * then we're about to block the thread which the force is
2421                  * waiting to complete, so we're bound to just time out. In this
2422                  * case, set the suspend state such that the wait will be
2423                  * canceled, so we can complete as quickly as possible. */
2424                 if (arm_state->resume_blocked && arm_state->vc_suspend_state ==
2425                                 VC_SUSPEND_IDLE) {
2426                         set_suspend_state(arm_state, VC_SUSPEND_FORCE_CANCELED);
2427                         break;
2428                 }
2429                 /* If suspend is already in progress then we need to block */
2430                 if (!try_wait_for_completion(&arm_state->resume_blocker)) {
2431                         /* Indicate that there are threads waiting on the resume
2432                          * blocker.  These need to be allowed to complete before
2433                          * a _second_ call to force suspend can complete,
2434                          * otherwise low priority threads might never actually
2435                          * continue */
2436                         arm_state->blocked_count++;
2437                         write_unlock_bh(&arm_state->susp_res_lock);
2438                         vchiq_log_info(vchiq_susp_log_level, "%s %s resume "
2439                                 "blocked - waiting...", __func__, entity);
2440                         if (wait_for_completion_killable(
2441                                         &arm_state->resume_blocker) != 0) {
2442                                 vchiq_log_error(vchiq_susp_log_level, "%s %s "
2443                                         "wait for resume blocker interrupted",
2444                                         __func__, entity);
2445                                 ret = VCHIQ_ERROR;
2446                                 write_lock_bh(&arm_state->susp_res_lock);
2447                                 arm_state->blocked_count--;
2448                                 write_unlock_bh(&arm_state->susp_res_lock);
2449                                 goto out;
2450                         }
2451                         vchiq_log_info(vchiq_susp_log_level, "%s %s resume "
2452                                 "unblocked", __func__, entity);
2453                         write_lock_bh(&arm_state->susp_res_lock);
2454                         if (--arm_state->blocked_count == 0)
2455                                 complete_all(&arm_state->blocked_blocker);
2456                 }
2457         }
2458
2459         stop_suspend_timer(arm_state);
2460
2461         local_uc = ++arm_state->videocore_use_count;
2462         local_entity_uc = ++(*entity_uc);
2463
2464         /* If there's a pending request which hasn't yet been serviced then
2465          * just clear it.  If we're past VC_SUSPEND_REQUESTED state then
2466          * vc_resume_complete will block until we either resume or fail to
2467          * suspend */
2468         if (arm_state->vc_suspend_state <= VC_SUSPEND_REQUESTED)
2469                 set_suspend_state(arm_state, VC_SUSPEND_IDLE);
2470
2471         if ((use_type != USE_TYPE_SERVICE_NO_RESUME) && need_resume(state)) {
2472                 set_resume_state(arm_state, VC_RESUME_REQUESTED);
2473                 vchiq_log_info(vchiq_susp_log_level,
2474                         "%s %s count %d, state count %d",
2475                         __func__, entity, local_entity_uc, local_uc);
2476                 request_poll(state, NULL, 0);
2477         } else
2478                 vchiq_log_trace(vchiq_susp_log_level,
2479                         "%s %s count %d, state count %d",
2480                         __func__, entity, *entity_uc, local_uc);
2481
2482
2483         write_unlock_bh(&arm_state->susp_res_lock);
2484
2485         /* Completion is in a done state when we're not suspended, so this won't
2486          * block for the non-suspended case. */
2487         if (!try_wait_for_completion(&arm_state->vc_resume_complete)) {
2488                 vchiq_log_info(vchiq_susp_log_level, "%s %s wait for resume",
2489                         __func__, entity);
2490                 if (wait_for_completion_killable(
2491                                 &arm_state->vc_resume_complete) != 0) {
2492                         vchiq_log_error(vchiq_susp_log_level, "%s %s wait for "
2493                                 "resume interrupted", __func__, entity);
2494                         ret = VCHIQ_ERROR;
2495                         goto out;
2496                 }
2497                 vchiq_log_info(vchiq_susp_log_level, "%s %s resumed", __func__,
2498                         entity);
2499         }
2500
2501         if (ret == VCHIQ_SUCCESS) {
2502                 VCHIQ_STATUS_T status = VCHIQ_SUCCESS;
2503                 long ack_cnt = atomic_xchg(&arm_state->ka_use_ack_count, 0);
2504                 while (ack_cnt && (status == VCHIQ_SUCCESS)) {
2505                         /* Send the use notify to videocore */
2506                         status = vchiq_send_remote_use_active(state);
2507                         if (status == VCHIQ_SUCCESS)
2508                                 ack_cnt--;
2509                         else
2510                                 atomic_add(ack_cnt,
2511                                         &arm_state->ka_use_ack_count);
2512                 }
2513         }
2514
2515 out:
2516         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret);
2517         return ret;
2518 }
2519
2520 VCHIQ_STATUS_T
2521 vchiq_release_internal(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service)
2522 {
2523         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2524         VCHIQ_STATUS_T ret = VCHIQ_SUCCESS;
2525         char entity[16];
2526         int *entity_uc;
2527         int local_uc, local_entity_uc;
2528
2529         if (!arm_state)
2530                 goto out;
2531
2532         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2533
2534         if (service) {
2535                 sprintf(entity, "%c%c%c%c:%03d",
2536                         VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc),
2537                         service->client_id);
2538                 entity_uc = &service->service_use_count;
2539         } else {
2540                 sprintf(entity, "PEER:   ");
2541                 entity_uc = &arm_state->peer_use_count;
2542         }
2543
2544         write_lock_bh(&arm_state->susp_res_lock);
2545         if (!arm_state->videocore_use_count || !(*entity_uc)) {
2546                 /* Don't use BUG_ON - don't allow user thread to crash kernel */
2547                 WARN_ON(!arm_state->videocore_use_count);
2548                 WARN_ON(!(*entity_uc));
2549                 ret = VCHIQ_ERROR;
2550                 goto unlock;
2551         }
2552         local_uc = --arm_state->videocore_use_count;
2553         local_entity_uc = --(*entity_uc);
2554
2555         if (!vchiq_videocore_wanted(state)) {
2556                 if (vchiq_platform_use_suspend_timer() &&
2557                                 !arm_state->resume_blocked) {
2558                         /* Only use the timer if we're not trying to force
2559                          * suspend (=> resume_blocked) */
2560                         start_suspend_timer(arm_state);
2561                 } else {
2562                         vchiq_log_info(vchiq_susp_log_level,
2563                                 "%s %s count %d, state count %d - suspending",
2564                                 __func__, entity, *entity_uc,
2565                                 arm_state->videocore_use_count);
2566                         vchiq_arm_vcsuspend(state);
2567                 }
2568         } else
2569                 vchiq_log_trace(vchiq_susp_log_level,
2570                         "%s %s count %d, state count %d",
2571                         __func__, entity, *entity_uc,
2572                         arm_state->videocore_use_count);
2573
2574 unlock:
2575         write_unlock_bh(&arm_state->susp_res_lock);
2576
2577 out:
2578         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret);
2579         return ret;
2580 }
2581
2582 void
2583 vchiq_on_remote_use(VCHIQ_STATE_T *state)
2584 {
2585         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2586         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2587         atomic_inc(&arm_state->ka_use_count);
2588         complete(&arm_state->ka_evt);
2589 }
2590
2591 void
2592 vchiq_on_remote_release(VCHIQ_STATE_T *state)
2593 {
2594         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2595         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2596         atomic_inc(&arm_state->ka_release_count);
2597         complete(&arm_state->ka_evt);
2598 }
2599
2600 VCHIQ_STATUS_T
2601 vchiq_use_service_internal(VCHIQ_SERVICE_T *service)
2602 {
2603         return vchiq_use_internal(service->state, service, USE_TYPE_SERVICE);
2604 }
2605
2606 VCHIQ_STATUS_T
2607 vchiq_release_service_internal(VCHIQ_SERVICE_T *service)
2608 {
2609         return vchiq_release_internal(service->state, service);
2610 }
2611
2612 VCHIQ_DEBUGFS_NODE_T *
2613 vchiq_instance_get_debugfs_node(VCHIQ_INSTANCE_T instance)
2614 {
2615         return &instance->debugfs_node;
2616 }
2617
2618 int
2619 vchiq_instance_get_use_count(VCHIQ_INSTANCE_T instance)
2620 {
2621         VCHIQ_SERVICE_T *service;
2622         int use_count = 0, i;
2623         i = 0;
2624         while ((service = next_service_by_instance(instance->state,
2625                 instance, &i)) != NULL) {
2626                 use_count += service->service_use_count;
2627                 unlock_service(service);
2628         }
2629         return use_count;
2630 }
2631
2632 int
2633 vchiq_instance_get_pid(VCHIQ_INSTANCE_T instance)
2634 {
2635         return instance->pid;
2636 }
2637
2638 int
2639 vchiq_instance_get_trace(VCHIQ_INSTANCE_T instance)
2640 {
2641         return instance->trace;
2642 }
2643
2644 void
2645 vchiq_instance_set_trace(VCHIQ_INSTANCE_T instance, int trace)
2646 {
2647         VCHIQ_SERVICE_T *service;
2648         int i;
2649         i = 0;
2650         while ((service = next_service_by_instance(instance->state,
2651                 instance, &i)) != NULL) {
2652                 service->trace = trace;
2653                 unlock_service(service);
2654         }
2655         instance->trace = (trace != 0);
2656 }
2657
2658 static void suspend_timer_callback(unsigned long context)
2659 {
2660         VCHIQ_STATE_T *state = (VCHIQ_STATE_T *)context;
2661         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2662         if (!arm_state)
2663                 goto out;
2664         vchiq_log_info(vchiq_susp_log_level,
2665                 "%s - suspend timer expired - check suspend", __func__);
2666         vchiq_check_suspend(state);
2667 out:
2668         return;
2669 }
2670
2671 VCHIQ_STATUS_T
2672 vchiq_use_service_no_resume(VCHIQ_SERVICE_HANDLE_T handle)
2673 {
2674         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
2675         VCHIQ_SERVICE_T *service = find_service_by_handle(handle);
2676         if (service) {
2677                 ret = vchiq_use_internal(service->state, service,
2678                                 USE_TYPE_SERVICE_NO_RESUME);
2679                 unlock_service(service);
2680         }
2681         return ret;
2682 }
2683
2684 VCHIQ_STATUS_T
2685 vchiq_use_service(VCHIQ_SERVICE_HANDLE_T handle)
2686 {
2687         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
2688         VCHIQ_SERVICE_T *service = find_service_by_handle(handle);
2689         if (service) {
2690                 ret = vchiq_use_internal(service->state, service,
2691                                 USE_TYPE_SERVICE);
2692                 unlock_service(service);
2693         }
2694         return ret;
2695 }
2696
2697 VCHIQ_STATUS_T
2698 vchiq_release_service(VCHIQ_SERVICE_HANDLE_T handle)
2699 {
2700         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
2701         VCHIQ_SERVICE_T *service = find_service_by_handle(handle);
2702         if (service) {
2703                 ret = vchiq_release_internal(service->state, service);
2704                 unlock_service(service);
2705         }
2706         return ret;
2707 }
2708
2709 void
2710 vchiq_dump_service_use_state(VCHIQ_STATE_T *state)
2711 {
2712         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2713         int i, j = 0;
2714         /* Only dump 64 services */
2715         static const int local_max_services = 64;
2716         /* If there's more than 64 services, only dump ones with
2717          * non-zero counts */
2718         int only_nonzero = 0;
2719         static const char *nz = "<-- preventing suspend";
2720
2721         enum vc_suspend_status vc_suspend_state;
2722         enum vc_resume_status  vc_resume_state;
2723         int peer_count;
2724         int vc_use_count;
2725         int active_services;
2726         struct service_data_struct {
2727                 int fourcc;
2728                 int clientid;
2729                 int use_count;
2730         } service_data[local_max_services];
2731
2732         if (!arm_state)
2733                 return;
2734
2735         read_lock_bh(&arm_state->susp_res_lock);
2736         vc_suspend_state = arm_state->vc_suspend_state;
2737         vc_resume_state  = arm_state->vc_resume_state;
2738         peer_count = arm_state->peer_use_count;
2739         vc_use_count = arm_state->videocore_use_count;
2740         active_services = state->unused_service;
2741         if (active_services > local_max_services)
2742                 only_nonzero = 1;
2743
2744         for (i = 0; (i < active_services) && (j < local_max_services); i++) {
2745                 VCHIQ_SERVICE_T *service_ptr = state->services[i];
2746                 if (!service_ptr)
2747                         continue;
2748
2749                 if (only_nonzero && !service_ptr->service_use_count)
2750                         continue;
2751
2752                 if (service_ptr->srvstate != VCHIQ_SRVSTATE_FREE) {
2753                         service_data[j].fourcc = service_ptr->base.fourcc;
2754                         service_data[j].clientid = service_ptr->client_id;
2755                         service_data[j++].use_count = service_ptr->
2756                                                         service_use_count;
2757                 }
2758         }
2759
2760         read_unlock_bh(&arm_state->susp_res_lock);
2761
2762         vchiq_log_warning(vchiq_susp_log_level,
2763                 "-- Videcore suspend state: %s --",
2764                 suspend_state_names[vc_suspend_state + VC_SUSPEND_NUM_OFFSET]);
2765         vchiq_log_warning(vchiq_susp_log_level,
2766                 "-- Videcore resume state: %s --",
2767                 resume_state_names[vc_resume_state + VC_RESUME_NUM_OFFSET]);
2768
2769         if (only_nonzero)
2770                 vchiq_log_warning(vchiq_susp_log_level, "Too many active "
2771                         "services (%d).  Only dumping up to first %d services "
2772                         "with non-zero use-count", active_services,
2773                         local_max_services);
2774
2775         for (i = 0; i < j; i++) {
2776                 vchiq_log_warning(vchiq_susp_log_level,
2777                         "----- %c%c%c%c:%d service count %d %s",
2778                         VCHIQ_FOURCC_AS_4CHARS(service_data[i].fourcc),
2779                         service_data[i].clientid,
2780                         service_data[i].use_count,
2781                         service_data[i].use_count ? nz : "");
2782         }
2783         vchiq_log_warning(vchiq_susp_log_level,
2784                 "----- VCHIQ use count count %d", peer_count);
2785         vchiq_log_warning(vchiq_susp_log_level,
2786                 "--- Overall vchiq instance use count %d", vc_use_count);
2787
2788         vchiq_dump_platform_use_state(state);
2789 }
2790
2791 VCHIQ_STATUS_T
2792 vchiq_check_service(VCHIQ_SERVICE_T *service)
2793 {
2794         VCHIQ_ARM_STATE_T *arm_state;
2795         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
2796
2797         if (!service || !service->state)
2798                 goto out;
2799
2800         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2801
2802         arm_state = vchiq_platform_get_arm_state(service->state);
2803
2804         read_lock_bh(&arm_state->susp_res_lock);
2805         if (service->service_use_count)
2806                 ret = VCHIQ_SUCCESS;
2807         read_unlock_bh(&arm_state->susp_res_lock);
2808
2809         if (ret == VCHIQ_ERROR) {
2810                 vchiq_log_error(vchiq_susp_log_level,
2811                         "%s ERROR - %c%c%c%c:%d service count %d, "
2812                         "state count %d, videocore suspend state %s", __func__,
2813                         VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc),
2814                         service->client_id, service->service_use_count,
2815                         arm_state->videocore_use_count,
2816                         suspend_state_names[arm_state->vc_suspend_state +
2817                                                 VC_SUSPEND_NUM_OFFSET]);
2818                 vchiq_dump_service_use_state(service->state);
2819         }
2820 out:
2821         return ret;
2822 }
2823
2824 /* stub functions */
2825 void vchiq_on_remote_use_active(VCHIQ_STATE_T *state)
2826 {
2827         (void)state;
2828 }
2829
2830 void vchiq_platform_conn_state_changed(VCHIQ_STATE_T *state,
2831         VCHIQ_CONNSTATE_T oldstate, VCHIQ_CONNSTATE_T newstate)
2832 {
2833         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2834         vchiq_log_info(vchiq_susp_log_level, "%d: %s->%s", state->id,
2835                 get_conn_state_name(oldstate), get_conn_state_name(newstate));
2836         if (state->conn_state == VCHIQ_CONNSTATE_CONNECTED) {
2837                 write_lock_bh(&arm_state->susp_res_lock);
2838                 if (!arm_state->first_connect) {
2839                         char threadname[16];
2840                         arm_state->first_connect = 1;
2841                         write_unlock_bh(&arm_state->susp_res_lock);
2842                         snprintf(threadname, sizeof(threadname), "vchiq-keep/%d",
2843                                 state->id);
2844                         arm_state->ka_thread = kthread_create(
2845                                 &vchiq_keepalive_thread_func,
2846                                 (void *)state,
2847                                 threadname);
2848                         if (IS_ERR(arm_state->ka_thread)) {
2849                                 vchiq_log_error(vchiq_susp_log_level,
2850                                         "vchiq: FATAL: couldn't create thread %s",
2851                                         threadname);
2852                         } else {
2853                                 wake_up_process(arm_state->ka_thread);
2854                         }
2855                 } else
2856                         write_unlock_bh(&arm_state->susp_res_lock);
2857         }
2858 }
2859
2860 static int vchiq_probe(struct platform_device *pdev)
2861 {
2862         struct device_node *fw_node;
2863         struct rpi_firmware *fw;
2864         int err;
2865         void *ptr_err;
2866
2867         fw_node = of_parse_phandle(pdev->dev.of_node, "firmware", 0);
2868         if (!fw_node) {
2869                 dev_err(&pdev->dev, "Missing firmware node\n");
2870                 return -ENOENT;
2871         }
2872
2873         fw = rpi_firmware_get(fw_node);
2874         of_node_put(fw_node);
2875         if (!fw)
2876                 return -EPROBE_DEFER;
2877
2878         platform_set_drvdata(pdev, fw);
2879
2880         err = vchiq_platform_init(pdev, &g_state);
2881         if (err != 0)
2882                 goto failed_platform_init;
2883
2884         err = alloc_chrdev_region(&vchiq_devid, VCHIQ_MINOR, 1, DEVICE_NAME);
2885         if (err != 0) {
2886                 vchiq_log_error(vchiq_arm_log_level,
2887                         "Unable to allocate device number");
2888                 goto failed_platform_init;
2889         }
2890         cdev_init(&vchiq_cdev, &vchiq_fops);
2891         vchiq_cdev.owner = THIS_MODULE;
2892         err = cdev_add(&vchiq_cdev, vchiq_devid, 1);
2893         if (err != 0) {
2894                 vchiq_log_error(vchiq_arm_log_level,
2895                         "Unable to register device");
2896                 goto failed_cdev_add;
2897         }
2898
2899         /* create sysfs entries */
2900         vchiq_class = class_create(THIS_MODULE, DEVICE_NAME);
2901         ptr_err = vchiq_class;
2902         if (IS_ERR(ptr_err))
2903                 goto failed_class_create;
2904
2905         vchiq_dev = device_create(vchiq_class, NULL,
2906                 vchiq_devid, NULL, "vchiq");
2907         ptr_err = vchiq_dev;
2908         if (IS_ERR(ptr_err))
2909                 goto failed_device_create;
2910
2911         /* create debugfs entries */
2912         err = vchiq_debugfs_init();
2913         if (err != 0)
2914                 goto failed_debugfs_init;
2915
2916         vchiq_log_info(vchiq_arm_log_level,
2917                 "vchiq: initialised - version %d (min %d), device %d.%d",
2918                 VCHIQ_VERSION, VCHIQ_VERSION_MIN,
2919                 MAJOR(vchiq_devid), MINOR(vchiq_devid));
2920
2921         return 0;
2922
2923 failed_debugfs_init:
2924         device_destroy(vchiq_class, vchiq_devid);
2925 failed_device_create:
2926         class_destroy(vchiq_class);
2927 failed_class_create:
2928         cdev_del(&vchiq_cdev);
2929         err = PTR_ERR(ptr_err);
2930 failed_cdev_add:
2931         unregister_chrdev_region(vchiq_devid, 1);
2932 failed_platform_init:
2933         vchiq_log_warning(vchiq_arm_log_level, "could not load vchiq");
2934         return err;
2935 }
2936
2937 static int vchiq_remove(struct platform_device *pdev)
2938 {
2939         vchiq_debugfs_deinit();
2940         device_destroy(vchiq_class, vchiq_devid);
2941         class_destroy(vchiq_class);
2942         cdev_del(&vchiq_cdev);
2943         unregister_chrdev_region(vchiq_devid, 1);
2944
2945         return 0;
2946 }
2947
2948 static const struct of_device_id vchiq_of_match[] = {
2949         { .compatible = "brcm,bcm2835-vchiq", },
2950         {},
2951 };
2952 MODULE_DEVICE_TABLE(of, vchiq_of_match);
2953
2954 static struct platform_driver vchiq_driver = {
2955         .driver = {
2956                 .name = "bcm2835_vchiq",
2957                 .of_match_table = vchiq_of_match,
2958         },
2959         .probe = vchiq_probe,
2960         .remove = vchiq_remove,
2961 };
2962 module_platform_driver(vchiq_driver);
2963
2964 MODULE_LICENSE("GPL");
2965 MODULE_DESCRIPTION("Videocore VCHIQ driver");
2966 MODULE_AUTHOR("Broadcom Corporation");