staging: vchiq_arm: Fix unlocked access to dequeue_pending
[sfrench/cifs-2.6.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 16
68 #define MAX_SERVICES 64
69 #define MAX_ELEMENTS 8
70 #define MSG_QUEUE_SIZE 64
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         DEBUG_INITIALISE(g_state.local)
212
213         while (instance->completion_insert ==
214                 (instance->completion_remove + MAX_COMPLETIONS)) {
215                 /* Out of space - wait for the client */
216                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
217                 vchiq_log_trace(vchiq_arm_log_level,
218                         "add_completion - completion queue full");
219                 DEBUG_COUNT(COMPLETION_QUEUE_FULL_COUNT);
220                 if (down_interruptible(&instance->remove_event) != 0) {
221                         vchiq_log_info(vchiq_arm_log_level,
222                                 "service_callback interrupted");
223                         return VCHIQ_RETRY;
224                 } else if (instance->closing) {
225                         vchiq_log_info(vchiq_arm_log_level,
226                                 "service_callback closing");
227                         return VCHIQ_ERROR;
228                 }
229                 DEBUG_TRACE(SERVICE_CALLBACK_LINE);
230         }
231
232         completion =
233                  &instance->completions[instance->completion_insert &
234                  (MAX_COMPLETIONS - 1)];
235
236         completion->header = header;
237         completion->reason = reason;
238         /* N.B. service_userdata is updated while processing AWAIT_COMPLETION */
239         completion->service_userdata = user_service->service;
240         completion->bulk_userdata = bulk_userdata;
241
242         if (reason == VCHIQ_SERVICE_CLOSED) {
243                 /* Take an extra reference, to be held until
244                    this CLOSED notification is delivered. */
245                 lock_service(user_service->service);
246                 if (instance->use_close_delivered)
247                         user_service->close_pending = 1;
248         }
249
250         /* A write barrier is needed here to ensure that the entire completion
251                 record is written out before the insert point. */
252         wmb();
253
254         if (reason == VCHIQ_MESSAGE_AVAILABLE)
255                 user_service->message_available_pos =
256                         instance->completion_insert;
257         instance->completion_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                 /* A read memory barrier is needed to stop prefetch of a stale
899                 ** completion record
900                 */
901                 rmb();
902
903                 if (ret == 0) {
904                         int msgbufcount = args.msgbufcount;
905                         for (ret = 0; ret < args.count; ret++) {
906                                 VCHIQ_COMPLETION_DATA_T *completion;
907                                 VCHIQ_SERVICE_T *service;
908                                 USER_SERVICE_T *user_service;
909                                 VCHIQ_HEADER_T *header;
910                                 if (instance->completion_remove ==
911                                         instance->completion_insert)
912                                         break;
913                                 completion = &instance->completions[
914                                         instance->completion_remove &
915                                         (MAX_COMPLETIONS - 1)];
916
917                                 service = completion->service_userdata;
918                                 user_service = service->base.userdata;
919                                 completion->service_userdata =
920                                         user_service->userdata;
921
922                                 header = completion->header;
923                                 if (header) {
924                                         void __user *msgbuf;
925                                         int msglen;
926
927                                         msglen = header->size +
928                                                 sizeof(VCHIQ_HEADER_T);
929                                         /* This must be a VCHIQ-style service */
930                                         if (args.msgbufsize < msglen) {
931                                                 vchiq_log_error(
932                                                         vchiq_arm_log_level,
933                                                         "header %pK: msgbufsize %x < msglen %x",
934                                                         header, args.msgbufsize,
935                                                         msglen);
936                                                 WARN(1, "invalid message "
937                                                         "size\n");
938                                                 if (ret == 0)
939                                                         ret = -EMSGSIZE;
940                                                 break;
941                                         }
942                                         if (msgbufcount <= 0)
943                                                 /* Stall here for lack of a
944                                                 ** buffer for the message. */
945                                                 break;
946                                         /* Get the pointer from user space */
947                                         msgbufcount--;
948                                         if (copy_from_user(&msgbuf,
949                                                 (const void __user *)
950                                                 &args.msgbufs[msgbufcount],
951                                                 sizeof(msgbuf)) != 0) {
952                                                 if (ret == 0)
953                                                         ret = -EFAULT;
954                                                 break;
955                                         }
956
957                                         /* Copy the message to user space */
958                                         if (copy_to_user(msgbuf, header,
959                                                 msglen) != 0) {
960                                                 if (ret == 0)
961                                                         ret = -EFAULT;
962                                                 break;
963                                         }
964
965                                         /* Now it has been copied, the message
966                                         ** can be released. */
967                                         vchiq_release_message(service->handle,
968                                                 header);
969
970                                         /* The completion must point to the
971                                         ** msgbuf. */
972                                         completion->header = msgbuf;
973                                 }
974
975                                 if ((completion->reason ==
976                                         VCHIQ_SERVICE_CLOSED) &&
977                                         !instance->use_close_delivered)
978                                         unlock_service(service);
979
980                                 if (copy_to_user((void __user *)(
981                                         (size_t)args.buf +
982                                         ret * sizeof(VCHIQ_COMPLETION_DATA_T)),
983                                         completion,
984                                         sizeof(VCHIQ_COMPLETION_DATA_T)) != 0) {
985                                                 if (ret == 0)
986                                                         ret = -EFAULT;
987                                         break;
988                                 }
989
990                                 instance->completion_remove++;
991                         }
992
993                         if (msgbufcount != args.msgbufcount) {
994                                 if (copy_to_user((void __user *)
995                                         &((VCHIQ_AWAIT_COMPLETION_T *)arg)->
996                                                 msgbufcount,
997                                         &msgbufcount,
998                                         sizeof(msgbufcount)) != 0) {
999                                         ret = -EFAULT;
1000                                 }
1001                         }
1002                 }
1003
1004                 if (ret != 0)
1005                         up(&instance->remove_event);
1006                 mutex_unlock(&instance->completion_mutex);
1007                 DEBUG_TRACE(AWAIT_COMPLETION_LINE);
1008         } break;
1009
1010         case VCHIQ_IOC_DEQUEUE_MESSAGE: {
1011                 VCHIQ_DEQUEUE_MESSAGE_T args;
1012                 USER_SERVICE_T *user_service;
1013                 VCHIQ_HEADER_T *header;
1014
1015                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1016                 if (copy_from_user
1017                          (&args, (const void __user *)arg,
1018                           sizeof(args)) != 0) {
1019                         ret = -EFAULT;
1020                         break;
1021                 }
1022                 service = find_service_for_instance(instance, args.handle);
1023                 if (!service) {
1024                         ret = -EINVAL;
1025                         break;
1026                 }
1027                 user_service = (USER_SERVICE_T *)service->base.userdata;
1028                 if (user_service->is_vchi == 0) {
1029                         ret = -EINVAL;
1030                         break;
1031                 }
1032
1033                 spin_lock(&msg_queue_spinlock);
1034                 if (user_service->msg_remove == user_service->msg_insert) {
1035                         if (!args.blocking) {
1036                                 spin_unlock(&msg_queue_spinlock);
1037                                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1038                                 ret = -EWOULDBLOCK;
1039                                 break;
1040                         }
1041                         user_service->dequeue_pending = 1;
1042                         do {
1043                                 spin_unlock(&msg_queue_spinlock);
1044                                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1045                                 if (down_interruptible(
1046                                         &user_service->insert_event) != 0) {
1047                                         vchiq_log_info(vchiq_arm_log_level,
1048                                                 "DEQUEUE_MESSAGE interrupted");
1049                                         ret = -EINTR;
1050                                         break;
1051                                 }
1052                                 spin_lock(&msg_queue_spinlock);
1053                         } while (user_service->msg_remove ==
1054                                 user_service->msg_insert);
1055
1056                         if (ret)
1057                                 break;
1058                 }
1059
1060                 BUG_ON((int)(user_service->msg_insert -
1061                         user_service->msg_remove) < 0);
1062
1063                 header = user_service->msg_queue[user_service->msg_remove &
1064                         (MSG_QUEUE_SIZE - 1)];
1065                 user_service->msg_remove++;
1066                 spin_unlock(&msg_queue_spinlock);
1067
1068                 up(&user_service->remove_event);
1069                 if (header == NULL)
1070                         ret = -ENOTCONN;
1071                 else if (header->size <= args.bufsize) {
1072                         /* Copy to user space if msgbuf is not NULL */
1073                         if ((args.buf == NULL) ||
1074                                 (copy_to_user((void __user *)args.buf,
1075                                 header->data,
1076                                 header->size) == 0)) {
1077                                 ret = header->size;
1078                                 vchiq_release_message(
1079                                         service->handle,
1080                                         header);
1081                         } else
1082                                 ret = -EFAULT;
1083                 } else {
1084                         vchiq_log_error(vchiq_arm_log_level,
1085                                 "header %pK: bufsize %x < size %x",
1086                                 header, args.bufsize, header->size);
1087                         WARN(1, "invalid size\n");
1088                         ret = -EMSGSIZE;
1089                 }
1090                 DEBUG_TRACE(DEQUEUE_MESSAGE_LINE);
1091         } break;
1092
1093         case VCHIQ_IOC_GET_CLIENT_ID: {
1094                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
1095
1096                 ret = vchiq_get_client_id(handle);
1097         } break;
1098
1099         case VCHIQ_IOC_GET_CONFIG: {
1100                 VCHIQ_GET_CONFIG_T args;
1101                 VCHIQ_CONFIG_T config;
1102
1103                 if (copy_from_user(&args, (const void __user *)arg,
1104                         sizeof(args)) != 0) {
1105                         ret = -EFAULT;
1106                         break;
1107                 }
1108                 if (args.config_size > sizeof(config)) {
1109                         ret = -EINVAL;
1110                         break;
1111                 }
1112                 status = vchiq_get_config(instance, args.config_size, &config);
1113                 if (status == VCHIQ_SUCCESS) {
1114                         if (copy_to_user((void __user *)args.pconfig,
1115                                     &config, args.config_size) != 0) {
1116                                 ret = -EFAULT;
1117                                 break;
1118                         }
1119                 }
1120         } break;
1121
1122         case VCHIQ_IOC_SET_SERVICE_OPTION: {
1123                 VCHIQ_SET_SERVICE_OPTION_T args;
1124
1125                 if (copy_from_user(
1126                         &args, (const void __user *)arg,
1127                         sizeof(args)) != 0) {
1128                         ret = -EFAULT;
1129                         break;
1130                 }
1131
1132                 service = find_service_for_instance(instance, args.handle);
1133                 if (!service) {
1134                         ret = -EINVAL;
1135                         break;
1136                 }
1137
1138                 status = vchiq_set_service_option(
1139                                 args.handle, args.option, args.value);
1140         } break;
1141
1142         case VCHIQ_IOC_DUMP_PHYS_MEM: {
1143                 VCHIQ_DUMP_MEM_T  args;
1144
1145                 if (copy_from_user
1146                          (&args, (const void __user *)arg,
1147                           sizeof(args)) != 0) {
1148                         ret = -EFAULT;
1149                         break;
1150                 }
1151                 dump_phys_mem(args.virt_addr, args.num_bytes);
1152         } break;
1153
1154         case VCHIQ_IOC_LIB_VERSION: {
1155                 unsigned int lib_version = (unsigned int)arg;
1156
1157                 if (lib_version < VCHIQ_VERSION_MIN)
1158                         ret = -EINVAL;
1159                 else if (lib_version >= VCHIQ_VERSION_CLOSE_DELIVERED)
1160                         instance->use_close_delivered = 1;
1161         } break;
1162
1163         case VCHIQ_IOC_CLOSE_DELIVERED: {
1164                 VCHIQ_SERVICE_HANDLE_T handle = (VCHIQ_SERVICE_HANDLE_T)arg;
1165
1166                 service = find_closed_service_for_instance(instance, handle);
1167                 if (service != NULL) {
1168                         USER_SERVICE_T *user_service =
1169                                 (USER_SERVICE_T *)service->base.userdata;
1170                         close_delivered(user_service);
1171                 }
1172                 else
1173                         ret = -EINVAL;
1174         } break;
1175
1176         default:
1177                 ret = -ENOTTY;
1178                 break;
1179         }
1180
1181         if (service)
1182                 unlock_service(service);
1183
1184         if (ret == 0) {
1185                 if (status == VCHIQ_ERROR)
1186                         ret = -EIO;
1187                 else if (status == VCHIQ_RETRY)
1188                         ret = -EINTR;
1189         }
1190
1191         if ((status == VCHIQ_SUCCESS) && (ret < 0) && (ret != -EINTR) &&
1192                 (ret != -EWOULDBLOCK))
1193                 vchiq_log_info(vchiq_arm_log_level,
1194                         "  ioctl instance %lx, cmd %s -> status %d, %ld",
1195                         (unsigned long)instance,
1196                         (_IOC_NR(cmd) <= VCHIQ_IOC_MAX) ?
1197                                 ioctl_names[_IOC_NR(cmd)] :
1198                                 "<invalid>",
1199                         status, ret);
1200         else
1201                 vchiq_log_trace(vchiq_arm_log_level,
1202                         "  ioctl instance %lx, cmd %s -> status %d, %ld",
1203                         (unsigned long)instance,
1204                         (_IOC_NR(cmd) <= VCHIQ_IOC_MAX) ?
1205                                 ioctl_names[_IOC_NR(cmd)] :
1206                                 "<invalid>",
1207                         status, ret);
1208
1209         return ret;
1210 }
1211
1212 /****************************************************************************
1213 *
1214 *   vchiq_open
1215 *
1216 ***************************************************************************/
1217
1218 static int
1219 vchiq_open(struct inode *inode, struct file *file)
1220 {
1221         int dev = iminor(inode) & 0x0f;
1222         vchiq_log_info(vchiq_arm_log_level, "vchiq_open");
1223         switch (dev) {
1224         case VCHIQ_MINOR: {
1225                 int ret;
1226                 VCHIQ_STATE_T *state = vchiq_get_state();
1227                 VCHIQ_INSTANCE_T instance;
1228
1229                 if (!state) {
1230                         vchiq_log_error(vchiq_arm_log_level,
1231                                 "vchiq has no connection to VideoCore");
1232                         return -ENOTCONN;
1233                 }
1234
1235                 instance = kzalloc(sizeof(*instance), GFP_KERNEL);
1236                 if (!instance)
1237                         return -ENOMEM;
1238
1239                 instance->state = state;
1240                 instance->pid = current->tgid;
1241
1242                 ret = vchiq_debugfs_add_instance(instance);
1243                 if (ret != 0) {
1244                         kfree(instance);
1245                         return ret;
1246                 }
1247
1248                 sema_init(&instance->insert_event, 0);
1249                 sema_init(&instance->remove_event, 0);
1250                 mutex_init(&instance->completion_mutex);
1251                 mutex_init(&instance->bulk_waiter_list_mutex);
1252                 INIT_LIST_HEAD(&instance->bulk_waiter_list);
1253
1254                 file->private_data = instance;
1255         } break;
1256
1257         default:
1258                 vchiq_log_error(vchiq_arm_log_level,
1259                         "Unknown minor device: %d", dev);
1260                 return -ENXIO;
1261         }
1262
1263         return 0;
1264 }
1265
1266 /****************************************************************************
1267 *
1268 *   vchiq_release
1269 *
1270 ***************************************************************************/
1271
1272 static int
1273 vchiq_release(struct inode *inode, struct file *file)
1274 {
1275         int dev = iminor(inode) & 0x0f;
1276         int ret = 0;
1277         switch (dev) {
1278         case VCHIQ_MINOR: {
1279                 VCHIQ_INSTANCE_T instance = file->private_data;
1280                 VCHIQ_STATE_T *state = vchiq_get_state();
1281                 VCHIQ_SERVICE_T *service;
1282                 int i;
1283
1284                 vchiq_log_info(vchiq_arm_log_level,
1285                         "vchiq_release: instance=%lx",
1286                         (unsigned long)instance);
1287
1288                 if (!state) {
1289                         ret = -EPERM;
1290                         goto out;
1291                 }
1292
1293                 /* Ensure videocore is awake to allow termination. */
1294                 vchiq_use_internal(instance->state, NULL,
1295                                 USE_TYPE_VCHIQ);
1296
1297                 mutex_lock(&instance->completion_mutex);
1298
1299                 /* Wake the completion thread and ask it to exit */
1300                 instance->closing = 1;
1301                 up(&instance->insert_event);
1302
1303                 mutex_unlock(&instance->completion_mutex);
1304
1305                 /* Wake the slot handler if the completion queue is full. */
1306                 up(&instance->remove_event);
1307
1308                 /* Mark all services for termination... */
1309                 i = 0;
1310                 while ((service = next_service_by_instance(state, instance,
1311                         &i)) != NULL) {
1312                         USER_SERVICE_T *user_service = service->base.userdata;
1313
1314                         /* Wake the slot handler if the msg queue is full. */
1315                         up(&user_service->remove_event);
1316
1317                         vchiq_terminate_service_internal(service);
1318                         unlock_service(service);
1319                 }
1320
1321                 /* ...and wait for them to die */
1322                 i = 0;
1323                 while ((service = next_service_by_instance(state, instance, &i))
1324                         != NULL) {
1325                         USER_SERVICE_T *user_service = service->base.userdata;
1326
1327                         down(&service->remove_event);
1328
1329                         BUG_ON(service->srvstate != VCHIQ_SRVSTATE_FREE);
1330
1331                         spin_lock(&msg_queue_spinlock);
1332
1333                         while (user_service->msg_remove !=
1334                                 user_service->msg_insert) {
1335                                 VCHIQ_HEADER_T *header = user_service->
1336                                         msg_queue[user_service->msg_remove &
1337                                                 (MSG_QUEUE_SIZE - 1)];
1338                                 user_service->msg_remove++;
1339                                 spin_unlock(&msg_queue_spinlock);
1340
1341                                 if (header)
1342                                         vchiq_release_message(
1343                                                 service->handle,
1344                                                 header);
1345                                 spin_lock(&msg_queue_spinlock);
1346                         }
1347
1348                         spin_unlock(&msg_queue_spinlock);
1349
1350                         unlock_service(service);
1351                 }
1352
1353                 /* Release any closed services */
1354                 while (instance->completion_remove !=
1355                         instance->completion_insert) {
1356                         VCHIQ_COMPLETION_DATA_T *completion;
1357                         VCHIQ_SERVICE_T *service;
1358                         completion = &instance->completions[
1359                                 instance->completion_remove &
1360                                 (MAX_COMPLETIONS - 1)];
1361                         service = completion->service_userdata;
1362                         if (completion->reason == VCHIQ_SERVICE_CLOSED)
1363                         {
1364                                 USER_SERVICE_T *user_service =
1365                                         service->base.userdata;
1366
1367                                 /* Wake any blocked user-thread */
1368                                 if (instance->use_close_delivered)
1369                                         up(&user_service->close_event);
1370                                 unlock_service(service);
1371                         }
1372                         instance->completion_remove++;
1373                 }
1374
1375                 /* Release the PEER service count. */
1376                 vchiq_release_internal(instance->state, NULL);
1377
1378                 {
1379                         struct list_head *pos, *next;
1380                         list_for_each_safe(pos, next,
1381                                 &instance->bulk_waiter_list) {
1382                                 struct bulk_waiter_node *waiter;
1383                                 waiter = list_entry(pos,
1384                                         struct bulk_waiter_node,
1385                                         list);
1386                                 list_del(pos);
1387                                 vchiq_log_info(vchiq_arm_log_level,
1388                                         "bulk_waiter - cleaned up %pK for pid %d",
1389                                         waiter, waiter->pid);
1390                                 kfree(waiter);
1391                         }
1392                 }
1393
1394                 vchiq_debugfs_remove_instance(instance);
1395
1396                 kfree(instance);
1397                 file->private_data = NULL;
1398         } break;
1399
1400         default:
1401                 vchiq_log_error(vchiq_arm_log_level,
1402                         "Unknown minor device: %d", dev);
1403                 ret = -ENXIO;
1404         }
1405
1406 out:
1407         return ret;
1408 }
1409
1410 /****************************************************************************
1411 *
1412 *   vchiq_dump
1413 *
1414 ***************************************************************************/
1415
1416 void
1417 vchiq_dump(void *dump_context, const char *str, int len)
1418 {
1419         DUMP_CONTEXT_T *context = (DUMP_CONTEXT_T *)dump_context;
1420
1421         if (context->actual < context->space) {
1422                 int copy_bytes;
1423                 if (context->offset > 0) {
1424                         int skip_bytes = min(len, (int)context->offset);
1425                         str += skip_bytes;
1426                         len -= skip_bytes;
1427                         context->offset -= skip_bytes;
1428                         if (context->offset > 0)
1429                                 return;
1430                 }
1431                 copy_bytes = min(len, (int)(context->space - context->actual));
1432                 if (copy_bytes == 0)
1433                         return;
1434                 if (copy_to_user(context->buf + context->actual, str,
1435                         copy_bytes))
1436                         context->actual = -EFAULT;
1437                 context->actual += copy_bytes;
1438                 len -= copy_bytes;
1439
1440                 /* If tne terminating NUL is included in the length, then it
1441                 ** marks the end of a line and should be replaced with a
1442                 ** carriage return. */
1443                 if ((len == 0) && (str[copy_bytes - 1] == '\0')) {
1444                         char cr = '\n';
1445                         if (copy_to_user(context->buf + context->actual - 1,
1446                                 &cr, 1))
1447                                 context->actual = -EFAULT;
1448                 }
1449         }
1450 }
1451
1452 /****************************************************************************
1453 *
1454 *   vchiq_dump_platform_instance_state
1455 *
1456 ***************************************************************************/
1457
1458 void
1459 vchiq_dump_platform_instances(void *dump_context)
1460 {
1461         VCHIQ_STATE_T *state = vchiq_get_state();
1462         char buf[80];
1463         int len;
1464         int i;
1465
1466         /* There is no list of instances, so instead scan all services,
1467                 marking those that have been dumped. */
1468
1469         for (i = 0; i < state->unused_service; i++) {
1470                 VCHIQ_SERVICE_T *service = state->services[i];
1471                 VCHIQ_INSTANCE_T instance;
1472
1473                 if (service && (service->base.callback == service_callback)) {
1474                         instance = service->instance;
1475                         if (instance)
1476                                 instance->mark = 0;
1477                 }
1478         }
1479
1480         for (i = 0; i < state->unused_service; i++) {
1481                 VCHIQ_SERVICE_T *service = state->services[i];
1482                 VCHIQ_INSTANCE_T instance;
1483
1484                 if (service && (service->base.callback == service_callback)) {
1485                         instance = service->instance;
1486                         if (instance && !instance->mark) {
1487                                 len = snprintf(buf, sizeof(buf),
1488                                         "Instance %pK: pid %d,%s completions %d/%d",
1489                                         instance, instance->pid,
1490                                         instance->connected ? " connected, " :
1491                                                 "",
1492                                         instance->completion_insert -
1493                                                 instance->completion_remove,
1494                                         MAX_COMPLETIONS);
1495
1496                                 vchiq_dump(dump_context, buf, len + 1);
1497
1498                                 instance->mark = 1;
1499                         }
1500                 }
1501         }
1502 }
1503
1504 /****************************************************************************
1505 *
1506 *   vchiq_dump_platform_service_state
1507 *
1508 ***************************************************************************/
1509
1510 void
1511 vchiq_dump_platform_service_state(void *dump_context, VCHIQ_SERVICE_T *service)
1512 {
1513         USER_SERVICE_T *user_service = (USER_SERVICE_T *)service->base.userdata;
1514         char buf[80];
1515         int len;
1516
1517         len = snprintf(buf, sizeof(buf), "  instance %pK", service->instance);
1518
1519         if ((service->base.callback == service_callback) &&
1520                 user_service->is_vchi) {
1521                 len += snprintf(buf + len, sizeof(buf) - len,
1522                         ", %d/%d messages",
1523                         user_service->msg_insert - user_service->msg_remove,
1524                         MSG_QUEUE_SIZE);
1525
1526                 if (user_service->dequeue_pending)
1527                         len += snprintf(buf + len, sizeof(buf) - len,
1528                                 " (dequeue pending)");
1529         }
1530
1531         vchiq_dump(dump_context, buf, len + 1);
1532 }
1533
1534 /****************************************************************************
1535 *
1536 *   dump_user_mem
1537 *
1538 ***************************************************************************/
1539
1540 static void
1541 dump_phys_mem(void *virt_addr, u32 num_bytes)
1542 {
1543         int            rc;
1544         u8            *end_virt_addr = virt_addr + num_bytes;
1545         int            num_pages;
1546         int            offset;
1547         int            end_offset;
1548         int            page_idx;
1549         int            prev_idx;
1550         struct page   *page;
1551         struct page  **pages;
1552         u8            *kmapped_virt_ptr;
1553
1554         /* Align virtAddr and endVirtAddr to 16 byte boundaries. */
1555
1556         virt_addr = (void *)((unsigned long)virt_addr & ~0x0fuL);
1557         end_virt_addr = (void *)(((unsigned long)end_virt_addr + 15uL) &
1558                 ~0x0fuL);
1559
1560         offset = (int)(long)virt_addr & (PAGE_SIZE - 1);
1561         end_offset = (int)(long)end_virt_addr & (PAGE_SIZE - 1);
1562
1563         num_pages = (offset + num_bytes + PAGE_SIZE - 1) / PAGE_SIZE;
1564
1565         pages = kmalloc(sizeof(struct page *) * num_pages, GFP_KERNEL);
1566         if (pages == NULL) {
1567                 vchiq_log_error(vchiq_arm_log_level,
1568                         "Unable to allocation memory for %d pages\n",
1569                         num_pages);
1570                 return;
1571         }
1572
1573         down_read(&current->mm->mmap_sem);
1574         rc = get_user_pages(
1575                 (unsigned long)virt_addr, /* start */
1576                 num_pages,                /* len */
1577                 0,                        /* gup_flags */
1578                 pages,                    /* pages (array of page pointers) */
1579                 NULL);                    /* vmas */
1580         up_read(&current->mm->mmap_sem);
1581
1582         prev_idx = -1;
1583         page = NULL;
1584
1585         if (rc < 0) {
1586                 vchiq_log_error(vchiq_arm_log_level,
1587                                 "Failed to get user pages: %d\n", rc);
1588                 goto out;
1589         }
1590
1591         while (offset < end_offset) {
1592
1593                 int page_offset = offset % PAGE_SIZE;
1594                 page_idx = offset / PAGE_SIZE;
1595
1596                 if (page_idx != prev_idx) {
1597
1598                         if (page != NULL)
1599                                 kunmap(page);
1600                         page = pages[page_idx];
1601                         kmapped_virt_ptr = kmap(page);
1602
1603                         prev_idx = page_idx;
1604                 }
1605
1606                 if (vchiq_arm_log_level >= VCHIQ_LOG_TRACE)
1607                         vchiq_log_dump_mem("ph",
1608                                 (u32)(unsigned long)&kmapped_virt_ptr[
1609                                         page_offset],
1610                                 &kmapped_virt_ptr[page_offset], 16);
1611
1612                 offset += 16;
1613         }
1614
1615 out:
1616         if (page != NULL)
1617                 kunmap(page);
1618
1619         for (page_idx = 0; page_idx < num_pages; page_idx++)
1620                 put_page(pages[page_idx]);
1621
1622         kfree(pages);
1623 }
1624
1625 /****************************************************************************
1626 *
1627 *   vchiq_read
1628 *
1629 ***************************************************************************/
1630
1631 static ssize_t
1632 vchiq_read(struct file *file, char __user *buf,
1633         size_t count, loff_t *ppos)
1634 {
1635         DUMP_CONTEXT_T context;
1636         context.buf = buf;
1637         context.actual = 0;
1638         context.space = count;
1639         context.offset = *ppos;
1640
1641         vchiq_dump_state(&context, &g_state);
1642
1643         *ppos += context.actual;
1644
1645         return context.actual;
1646 }
1647
1648 VCHIQ_STATE_T *
1649 vchiq_get_state(void)
1650 {
1651
1652         if (g_state.remote == NULL)
1653                 printk(KERN_ERR "%s: g_state.remote == NULL\n", __func__);
1654         else if (g_state.remote->initialised != 1)
1655                 printk(KERN_NOTICE "%s: g_state.remote->initialised != 1 (%d)\n",
1656                         __func__, g_state.remote->initialised);
1657
1658         return ((g_state.remote != NULL) &&
1659                 (g_state.remote->initialised == 1)) ? &g_state : NULL;
1660 }
1661
1662 static const struct file_operations
1663 vchiq_fops = {
1664         .owner = THIS_MODULE,
1665         .unlocked_ioctl = vchiq_ioctl,
1666         .open = vchiq_open,
1667         .release = vchiq_release,
1668         .read = vchiq_read
1669 };
1670
1671 /*
1672  * Autosuspend related functionality
1673  */
1674
1675 int
1676 vchiq_videocore_wanted(VCHIQ_STATE_T *state)
1677 {
1678         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
1679         if (!arm_state)
1680                 /* autosuspend not supported - always return wanted */
1681                 return 1;
1682         else if (arm_state->blocked_count)
1683                 return 1;
1684         else if (!arm_state->videocore_use_count)
1685                 /* usage count zero - check for override unless we're forcing */
1686                 if (arm_state->resume_blocked)
1687                         return 0;
1688                 else
1689                         return vchiq_platform_videocore_wanted(state);
1690         else
1691                 /* non-zero usage count - videocore still required */
1692                 return 1;
1693 }
1694
1695 static VCHIQ_STATUS_T
1696 vchiq_keepalive_vchiq_callback(VCHIQ_REASON_T reason,
1697         VCHIQ_HEADER_T *header,
1698         VCHIQ_SERVICE_HANDLE_T service_user,
1699         void *bulk_user)
1700 {
1701         vchiq_log_error(vchiq_susp_log_level,
1702                 "%s callback reason %d", __func__, reason);
1703         return 0;
1704 }
1705
1706 static int
1707 vchiq_keepalive_thread_func(void *v)
1708 {
1709         VCHIQ_STATE_T *state = (VCHIQ_STATE_T *) v;
1710         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
1711
1712         VCHIQ_STATUS_T status;
1713         VCHIQ_INSTANCE_T instance;
1714         VCHIQ_SERVICE_HANDLE_T ka_handle;
1715
1716         VCHIQ_SERVICE_PARAMS_T params = {
1717                 .fourcc      = VCHIQ_MAKE_FOURCC('K', 'E', 'E', 'P'),
1718                 .callback    = vchiq_keepalive_vchiq_callback,
1719                 .version     = KEEPALIVE_VER,
1720                 .version_min = KEEPALIVE_VER_MIN
1721         };
1722
1723         status = vchiq_initialise(&instance);
1724         if (status != VCHIQ_SUCCESS) {
1725                 vchiq_log_error(vchiq_susp_log_level,
1726                         "%s vchiq_initialise failed %d", __func__, status);
1727                 goto exit;
1728         }
1729
1730         status = vchiq_connect(instance);
1731         if (status != VCHIQ_SUCCESS) {
1732                 vchiq_log_error(vchiq_susp_log_level,
1733                         "%s vchiq_connect failed %d", __func__, status);
1734                 goto shutdown;
1735         }
1736
1737         status = vchiq_add_service(instance, &params, &ka_handle);
1738         if (status != VCHIQ_SUCCESS) {
1739                 vchiq_log_error(vchiq_susp_log_level,
1740                         "%s vchiq_open_service failed %d", __func__, status);
1741                 goto shutdown;
1742         }
1743
1744         while (1) {
1745                 long rc = 0, uc = 0;
1746                 if (wait_for_completion_interruptible(&arm_state->ka_evt)
1747                                 != 0) {
1748                         vchiq_log_error(vchiq_susp_log_level,
1749                                 "%s interrupted", __func__);
1750                         flush_signals(current);
1751                         continue;
1752                 }
1753
1754                 /* read and clear counters.  Do release_count then use_count to
1755                  * prevent getting more releases than uses */
1756                 rc = atomic_xchg(&arm_state->ka_release_count, 0);
1757                 uc = atomic_xchg(&arm_state->ka_use_count, 0);
1758
1759                 /* Call use/release service the requisite number of times.
1760                  * Process use before release so use counts don't go negative */
1761                 while (uc--) {
1762                         atomic_inc(&arm_state->ka_use_ack_count);
1763                         status = vchiq_use_service(ka_handle);
1764                         if (status != VCHIQ_SUCCESS) {
1765                                 vchiq_log_error(vchiq_susp_log_level,
1766                                         "%s vchiq_use_service error %d",
1767                                         __func__, status);
1768                         }
1769                 }
1770                 while (rc--) {
1771                         status = vchiq_release_service(ka_handle);
1772                         if (status != VCHIQ_SUCCESS) {
1773                                 vchiq_log_error(vchiq_susp_log_level,
1774                                         "%s vchiq_release_service error %d",
1775                                         __func__, status);
1776                         }
1777                 }
1778         }
1779
1780 shutdown:
1781         vchiq_shutdown(instance);
1782 exit:
1783         return 0;
1784 }
1785
1786
1787
1788 VCHIQ_STATUS_T
1789 vchiq_arm_init_state(VCHIQ_STATE_T *state, VCHIQ_ARM_STATE_T *arm_state)
1790 {
1791         if (arm_state) {
1792                 rwlock_init(&arm_state->susp_res_lock);
1793
1794                 init_completion(&arm_state->ka_evt);
1795                 atomic_set(&arm_state->ka_use_count, 0);
1796                 atomic_set(&arm_state->ka_use_ack_count, 0);
1797                 atomic_set(&arm_state->ka_release_count, 0);
1798
1799                 init_completion(&arm_state->vc_suspend_complete);
1800
1801                 init_completion(&arm_state->vc_resume_complete);
1802                 /* Initialise to 'done' state.  We only want to block on resume
1803                  * completion while videocore is suspended. */
1804                 set_resume_state(arm_state, VC_RESUME_RESUMED);
1805
1806                 init_completion(&arm_state->resume_blocker);
1807                 /* Initialise to 'done' state.  We only want to block on this
1808                  * completion while resume is blocked */
1809                 complete_all(&arm_state->resume_blocker);
1810
1811                 init_completion(&arm_state->blocked_blocker);
1812                 /* Initialise to 'done' state.  We only want to block on this
1813                  * completion while things are waiting on the resume blocker */
1814                 complete_all(&arm_state->blocked_blocker);
1815
1816                 arm_state->suspend_timer_timeout = SUSPEND_TIMER_TIMEOUT_MS;
1817                 arm_state->suspend_timer_running = 0;
1818                 setup_timer(&arm_state->suspend_timer, suspend_timer_callback,
1819                             (unsigned long)(state));
1820
1821                 arm_state->first_connect = 0;
1822
1823         }
1824         return VCHIQ_SUCCESS;
1825 }
1826
1827 /*
1828 ** Functions to modify the state variables;
1829 **      set_suspend_state
1830 **      set_resume_state
1831 **
1832 ** There are more state variables than we might like, so ensure they remain in
1833 ** step.  Suspend and resume state are maintained separately, since most of
1834 ** these state machines can operate independently.  However, there are a few
1835 ** states where state transitions in one state machine cause a reset to the
1836 ** other state machine.  In addition, there are some completion events which
1837 ** need to occur on state machine reset and end-state(s), so these are also
1838 ** dealt with in these functions.
1839 **
1840 ** In all states we set the state variable according to the input, but in some
1841 ** cases we perform additional steps outlined below;
1842 **
1843 ** VC_SUSPEND_IDLE - Initialise the suspend completion at the same time.
1844 **                      The suspend completion is completed after any suspend
1845 **                      attempt.  When we reset the state machine we also reset
1846 **                      the completion.  This reset occurs when videocore is
1847 **                      resumed, and also if we initiate suspend after a suspend
1848 **                      failure.
1849 **
1850 ** VC_SUSPEND_IN_PROGRESS - This state is considered the point of no return for
1851 **                      suspend - ie from this point on we must try to suspend
1852 **                      before resuming can occur.  We therefore also reset the
1853 **                      resume state machine to VC_RESUME_IDLE in this state.
1854 **
1855 ** VC_SUSPEND_SUSPENDED - Suspend has completed successfully. Also call
1856 **                      complete_all on the suspend completion to notify
1857 **                      anything waiting for suspend to happen.
1858 **
1859 ** VC_SUSPEND_REJECTED - Videocore rejected suspend. Videocore will also
1860 **                      initiate resume, so no need to alter resume state.
1861 **                      We call complete_all on the suspend completion to notify
1862 **                      of suspend rejection.
1863 **
1864 ** VC_SUSPEND_FAILED - We failed to initiate videocore suspend.  We notify the
1865 **                      suspend completion and reset the resume state machine.
1866 **
1867 ** VC_RESUME_IDLE - Initialise the resume completion at the same time.  The
1868 **                      resume completion is in it's 'done' state whenever
1869 **                      videcore is running.  Therfore, the VC_RESUME_IDLE state
1870 **                      implies that videocore is suspended.
1871 **                      Hence, any thread which needs to wait until videocore is
1872 **                      running can wait on this completion - it will only block
1873 **                      if videocore is suspended.
1874 **
1875 ** VC_RESUME_RESUMED - Resume has completed successfully.  Videocore is running.
1876 **                      Call complete_all on the resume completion to unblock
1877 **                      any threads waiting for resume.  Also reset the suspend
1878 **                      state machine to it's idle state.
1879 **
1880 ** VC_RESUME_FAILED - Currently unused - no mechanism to fail resume exists.
1881 */
1882
1883 void
1884 set_suspend_state(VCHIQ_ARM_STATE_T *arm_state,
1885         enum vc_suspend_status new_state)
1886 {
1887         /* set the state in all cases */
1888         arm_state->vc_suspend_state = new_state;
1889
1890         /* state specific additional actions */
1891         switch (new_state) {
1892         case VC_SUSPEND_FORCE_CANCELED:
1893                 complete_all(&arm_state->vc_suspend_complete);
1894                 break;
1895         case VC_SUSPEND_REJECTED:
1896                 complete_all(&arm_state->vc_suspend_complete);
1897                 break;
1898         case VC_SUSPEND_FAILED:
1899                 complete_all(&arm_state->vc_suspend_complete);
1900                 arm_state->vc_resume_state = VC_RESUME_RESUMED;
1901                 complete_all(&arm_state->vc_resume_complete);
1902                 break;
1903         case VC_SUSPEND_IDLE:
1904                 reinit_completion(&arm_state->vc_suspend_complete);
1905                 break;
1906         case VC_SUSPEND_REQUESTED:
1907                 break;
1908         case VC_SUSPEND_IN_PROGRESS:
1909                 set_resume_state(arm_state, VC_RESUME_IDLE);
1910                 break;
1911         case VC_SUSPEND_SUSPENDED:
1912                 complete_all(&arm_state->vc_suspend_complete);
1913                 break;
1914         default:
1915                 BUG();
1916                 break;
1917         }
1918 }
1919
1920 void
1921 set_resume_state(VCHIQ_ARM_STATE_T *arm_state,
1922         enum vc_resume_status new_state)
1923 {
1924         /* set the state in all cases */
1925         arm_state->vc_resume_state = new_state;
1926
1927         /* state specific additional actions */
1928         switch (new_state) {
1929         case VC_RESUME_FAILED:
1930                 break;
1931         case VC_RESUME_IDLE:
1932                 reinit_completion(&arm_state->vc_resume_complete);
1933                 break;
1934         case VC_RESUME_REQUESTED:
1935                 break;
1936         case VC_RESUME_IN_PROGRESS:
1937                 break;
1938         case VC_RESUME_RESUMED:
1939                 complete_all(&arm_state->vc_resume_complete);
1940                 set_suspend_state(arm_state, VC_SUSPEND_IDLE);
1941                 break;
1942         default:
1943                 BUG();
1944                 break;
1945         }
1946 }
1947
1948
1949 /* should be called with the write lock held */
1950 inline void
1951 start_suspend_timer(VCHIQ_ARM_STATE_T *arm_state)
1952 {
1953         del_timer(&arm_state->suspend_timer);
1954         arm_state->suspend_timer.expires = jiffies +
1955                 msecs_to_jiffies(arm_state->
1956                         suspend_timer_timeout);
1957         add_timer(&arm_state->suspend_timer);
1958         arm_state->suspend_timer_running = 1;
1959 }
1960
1961 /* should be called with the write lock held */
1962 static inline void
1963 stop_suspend_timer(VCHIQ_ARM_STATE_T *arm_state)
1964 {
1965         if (arm_state->suspend_timer_running) {
1966                 del_timer(&arm_state->suspend_timer);
1967                 arm_state->suspend_timer_running = 0;
1968         }
1969 }
1970
1971 static inline int
1972 need_resume(VCHIQ_STATE_T *state)
1973 {
1974         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
1975         return (arm_state->vc_suspend_state > VC_SUSPEND_IDLE) &&
1976                         (arm_state->vc_resume_state < VC_RESUME_REQUESTED) &&
1977                         vchiq_videocore_wanted(state);
1978 }
1979
1980 static int
1981 block_resume(VCHIQ_ARM_STATE_T *arm_state)
1982 {
1983         int status = VCHIQ_SUCCESS;
1984         const unsigned long timeout_val =
1985                                 msecs_to_jiffies(FORCE_SUSPEND_TIMEOUT_MS);
1986         int resume_count = 0;
1987
1988         /* Allow any threads which were blocked by the last force suspend to
1989          * complete if they haven't already.  Only give this one shot; if
1990          * blocked_count is incremented after blocked_blocker is completed
1991          * (which only happens when blocked_count hits 0) then those threads
1992          * will have to wait until next time around */
1993         if (arm_state->blocked_count) {
1994                 reinit_completion(&arm_state->blocked_blocker);
1995                 write_unlock_bh(&arm_state->susp_res_lock);
1996                 vchiq_log_info(vchiq_susp_log_level, "%s wait for previously "
1997                         "blocked clients", __func__);
1998                 if (wait_for_completion_interruptible_timeout(
1999                                 &arm_state->blocked_blocker, timeout_val)
2000                                         <= 0) {
2001                         vchiq_log_error(vchiq_susp_log_level, "%s wait for "
2002                                 "previously blocked clients failed", __func__);
2003                         status = VCHIQ_ERROR;
2004                         write_lock_bh(&arm_state->susp_res_lock);
2005                         goto out;
2006                 }
2007                 vchiq_log_info(vchiq_susp_log_level, "%s previously blocked "
2008                         "clients resumed", __func__);
2009                 write_lock_bh(&arm_state->susp_res_lock);
2010         }
2011
2012         /* We need to wait for resume to complete if it's in process */
2013         while (arm_state->vc_resume_state != VC_RESUME_RESUMED &&
2014                         arm_state->vc_resume_state > VC_RESUME_IDLE) {
2015                 if (resume_count > 1) {
2016                         status = VCHIQ_ERROR;
2017                         vchiq_log_error(vchiq_susp_log_level, "%s waited too "
2018                                 "many times for resume", __func__);
2019                         goto out;
2020                 }
2021                 write_unlock_bh(&arm_state->susp_res_lock);
2022                 vchiq_log_info(vchiq_susp_log_level, "%s wait for resume",
2023                         __func__);
2024                 if (wait_for_completion_interruptible_timeout(
2025                                 &arm_state->vc_resume_complete, timeout_val)
2026                                         <= 0) {
2027                         vchiq_log_error(vchiq_susp_log_level, "%s wait for "
2028                                 "resume failed (%s)", __func__,
2029                                 resume_state_names[arm_state->vc_resume_state +
2030                                                         VC_RESUME_NUM_OFFSET]);
2031                         status = VCHIQ_ERROR;
2032                         write_lock_bh(&arm_state->susp_res_lock);
2033                         goto out;
2034                 }
2035                 vchiq_log_info(vchiq_susp_log_level, "%s resumed", __func__);
2036                 write_lock_bh(&arm_state->susp_res_lock);
2037                 resume_count++;
2038         }
2039         reinit_completion(&arm_state->resume_blocker);
2040         arm_state->resume_blocked = 1;
2041
2042 out:
2043         return status;
2044 }
2045
2046 static inline void
2047 unblock_resume(VCHIQ_ARM_STATE_T *arm_state)
2048 {
2049         complete_all(&arm_state->resume_blocker);
2050         arm_state->resume_blocked = 0;
2051 }
2052
2053 /* Initiate suspend via slot handler. Should be called with the write lock
2054  * held */
2055 VCHIQ_STATUS_T
2056 vchiq_arm_vcsuspend(VCHIQ_STATE_T *state)
2057 {
2058         VCHIQ_STATUS_T status = VCHIQ_ERROR;
2059         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2060
2061         if (!arm_state)
2062                 goto out;
2063
2064         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2065         status = VCHIQ_SUCCESS;
2066
2067
2068         switch (arm_state->vc_suspend_state) {
2069         case VC_SUSPEND_REQUESTED:
2070                 vchiq_log_info(vchiq_susp_log_level, "%s: suspend already "
2071                         "requested", __func__);
2072                 break;
2073         case VC_SUSPEND_IN_PROGRESS:
2074                 vchiq_log_info(vchiq_susp_log_level, "%s: suspend already in "
2075                         "progress", __func__);
2076                 break;
2077
2078         default:
2079                 /* We don't expect to be in other states, so log but continue
2080                  * anyway */
2081                 vchiq_log_error(vchiq_susp_log_level,
2082                         "%s unexpected suspend state %s", __func__,
2083                         suspend_state_names[arm_state->vc_suspend_state +
2084                                                 VC_SUSPEND_NUM_OFFSET]);
2085                 /* fall through */
2086         case VC_SUSPEND_REJECTED:
2087         case VC_SUSPEND_FAILED:
2088                 /* Ensure any idle state actions have been run */
2089                 set_suspend_state(arm_state, VC_SUSPEND_IDLE);
2090                 /* fall through */
2091         case VC_SUSPEND_IDLE:
2092                 vchiq_log_info(vchiq_susp_log_level,
2093                         "%s: suspending", __func__);
2094                 set_suspend_state(arm_state, VC_SUSPEND_REQUESTED);
2095                 /* kick the slot handler thread to initiate suspend */
2096                 request_poll(state, NULL, 0);
2097                 break;
2098         }
2099
2100 out:
2101         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, status);
2102         return status;
2103 }
2104
2105 void
2106 vchiq_platform_check_suspend(VCHIQ_STATE_T *state)
2107 {
2108         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2109         int susp = 0;
2110
2111         if (!arm_state)
2112                 goto out;
2113
2114         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2115
2116         write_lock_bh(&arm_state->susp_res_lock);
2117         if (arm_state->vc_suspend_state == VC_SUSPEND_REQUESTED &&
2118                         arm_state->vc_resume_state == VC_RESUME_RESUMED) {
2119                 set_suspend_state(arm_state, VC_SUSPEND_IN_PROGRESS);
2120                 susp = 1;
2121         }
2122         write_unlock_bh(&arm_state->susp_res_lock);
2123
2124         if (susp)
2125                 vchiq_platform_suspend(state);
2126
2127 out:
2128         vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__);
2129         return;
2130 }
2131
2132
2133 static void
2134 output_timeout_error(VCHIQ_STATE_T *state)
2135 {
2136         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2137         char err[50] = "";
2138         int vc_use_count = arm_state->videocore_use_count;
2139         int active_services = state->unused_service;
2140         int i;
2141
2142         if (!arm_state->videocore_use_count) {
2143                 snprintf(err, sizeof(err), " Videocore usecount is 0");
2144                 goto output_msg;
2145         }
2146         for (i = 0; i < active_services; i++) {
2147                 VCHIQ_SERVICE_T *service_ptr = state->services[i];
2148                 if (service_ptr && service_ptr->service_use_count &&
2149                         (service_ptr->srvstate != VCHIQ_SRVSTATE_FREE)) {
2150                         snprintf(err, sizeof(err), " %c%c%c%c(%d) service has "
2151                                 "use count %d%s", VCHIQ_FOURCC_AS_4CHARS(
2152                                         service_ptr->base.fourcc),
2153                                  service_ptr->client_id,
2154                                  service_ptr->service_use_count,
2155                                  service_ptr->service_use_count ==
2156                                          vc_use_count ? "" : " (+ more)");
2157                         break;
2158                 }
2159         }
2160
2161 output_msg:
2162         vchiq_log_error(vchiq_susp_log_level,
2163                 "timed out waiting for vc suspend (%d).%s",
2164                  arm_state->autosuspend_override, err);
2165
2166 }
2167
2168 /* Try to get videocore into suspended state, regardless of autosuspend state.
2169 ** We don't actually force suspend, since videocore may get into a bad state
2170 ** if we force suspend at a bad time.  Instead, we wait for autosuspend to
2171 ** determine a good point to suspend.  If this doesn't happen within 100ms we
2172 ** report failure.
2173 **
2174 ** Returns VCHIQ_SUCCESS if videocore suspended successfully, VCHIQ_RETRY if
2175 ** videocore failed to suspend in time or VCHIQ_ERROR if interrupted.
2176 */
2177 VCHIQ_STATUS_T
2178 vchiq_arm_force_suspend(VCHIQ_STATE_T *state)
2179 {
2180         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2181         VCHIQ_STATUS_T status = VCHIQ_ERROR;
2182         long rc = 0;
2183         int repeat = -1;
2184
2185         if (!arm_state)
2186                 goto out;
2187
2188         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2189
2190         write_lock_bh(&arm_state->susp_res_lock);
2191
2192         status = block_resume(arm_state);
2193         if (status != VCHIQ_SUCCESS)
2194                 goto unlock;
2195         if (arm_state->vc_suspend_state == VC_SUSPEND_SUSPENDED) {
2196                 /* Already suspended - just block resume and exit */
2197                 vchiq_log_info(vchiq_susp_log_level, "%s already suspended",
2198                         __func__);
2199                 status = VCHIQ_SUCCESS;
2200                 goto unlock;
2201         } else if (arm_state->vc_suspend_state <= VC_SUSPEND_IDLE) {
2202                 /* initiate suspend immediately in the case that we're waiting
2203                  * for the timeout */
2204                 stop_suspend_timer(arm_state);
2205                 if (!vchiq_videocore_wanted(state)) {
2206                         vchiq_log_info(vchiq_susp_log_level, "%s videocore "
2207                                 "idle, initiating suspend", __func__);
2208                         status = vchiq_arm_vcsuspend(state);
2209                 } else if (arm_state->autosuspend_override <
2210                                                 FORCE_SUSPEND_FAIL_MAX) {
2211                         vchiq_log_info(vchiq_susp_log_level, "%s letting "
2212                                 "videocore go idle", __func__);
2213                         status = VCHIQ_SUCCESS;
2214                 } else {
2215                         vchiq_log_warning(vchiq_susp_log_level, "%s failed too "
2216                                 "many times - attempting suspend", __func__);
2217                         status = vchiq_arm_vcsuspend(state);
2218                 }
2219         } else {
2220                 vchiq_log_info(vchiq_susp_log_level, "%s videocore suspend "
2221                         "in progress - wait for completion", __func__);
2222                 status = VCHIQ_SUCCESS;
2223         }
2224
2225         /* Wait for suspend to happen due to system idle (not forced..) */
2226         if (status != VCHIQ_SUCCESS)
2227                 goto unblock_resume;
2228
2229         do {
2230                 write_unlock_bh(&arm_state->susp_res_lock);
2231
2232                 rc = wait_for_completion_interruptible_timeout(
2233                                 &arm_state->vc_suspend_complete,
2234                                 msecs_to_jiffies(FORCE_SUSPEND_TIMEOUT_MS));
2235
2236                 write_lock_bh(&arm_state->susp_res_lock);
2237                 if (rc < 0) {
2238                         vchiq_log_warning(vchiq_susp_log_level, "%s "
2239                                 "interrupted waiting for suspend", __func__);
2240                         status = VCHIQ_ERROR;
2241                         goto unblock_resume;
2242                 } else if (rc == 0) {
2243                         if (arm_state->vc_suspend_state > VC_SUSPEND_IDLE) {
2244                                 /* Repeat timeout once if in progress */
2245                                 if (repeat < 0) {
2246                                         repeat = 1;
2247                                         continue;
2248                                 }
2249                         }
2250                         arm_state->autosuspend_override++;
2251                         output_timeout_error(state);
2252
2253                         status = VCHIQ_RETRY;
2254                         goto unblock_resume;
2255                 }
2256         } while (0 < (repeat--));
2257
2258         /* Check and report state in case we need to abort ARM suspend */
2259         if (arm_state->vc_suspend_state != VC_SUSPEND_SUSPENDED) {
2260                 status = VCHIQ_RETRY;
2261                 vchiq_log_error(vchiq_susp_log_level,
2262                         "%s videocore suspend failed (state %s)", __func__,
2263                         suspend_state_names[arm_state->vc_suspend_state +
2264                                                 VC_SUSPEND_NUM_OFFSET]);
2265                 /* Reset the state only if it's still in an error state.
2266                  * Something could have already initiated another suspend. */
2267                 if (arm_state->vc_suspend_state < VC_SUSPEND_IDLE)
2268                         set_suspend_state(arm_state, VC_SUSPEND_IDLE);
2269
2270                 goto unblock_resume;
2271         }
2272
2273         /* successfully suspended - unlock and exit */
2274         goto unlock;
2275
2276 unblock_resume:
2277         /* all error states need to unblock resume before exit */
2278         unblock_resume(arm_state);
2279
2280 unlock:
2281         write_unlock_bh(&arm_state->susp_res_lock);
2282
2283 out:
2284         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, status);
2285         return status;
2286 }
2287
2288 void
2289 vchiq_check_suspend(VCHIQ_STATE_T *state)
2290 {
2291         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2292
2293         if (!arm_state)
2294                 goto out;
2295
2296         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2297
2298         write_lock_bh(&arm_state->susp_res_lock);
2299         if (arm_state->vc_suspend_state != VC_SUSPEND_SUSPENDED &&
2300                         arm_state->first_connect &&
2301                         !vchiq_videocore_wanted(state)) {
2302                 vchiq_arm_vcsuspend(state);
2303         }
2304         write_unlock_bh(&arm_state->susp_res_lock);
2305
2306 out:
2307         vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__);
2308         return;
2309 }
2310
2311
2312 int
2313 vchiq_arm_allow_resume(VCHIQ_STATE_T *state)
2314 {
2315         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2316         int resume = 0;
2317         int ret = -1;
2318
2319         if (!arm_state)
2320                 goto out;
2321
2322         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2323
2324         write_lock_bh(&arm_state->susp_res_lock);
2325         unblock_resume(arm_state);
2326         resume = vchiq_check_resume(state);
2327         write_unlock_bh(&arm_state->susp_res_lock);
2328
2329         if (resume) {
2330                 if (wait_for_completion_interruptible(
2331                         &arm_state->vc_resume_complete) < 0) {
2332                         vchiq_log_error(vchiq_susp_log_level,
2333                                 "%s interrupted", __func__);
2334                         /* failed, cannot accurately derive suspend
2335                          * state, so exit early. */
2336                         goto out;
2337                 }
2338         }
2339
2340         read_lock_bh(&arm_state->susp_res_lock);
2341         if (arm_state->vc_suspend_state == VC_SUSPEND_SUSPENDED) {
2342                 vchiq_log_info(vchiq_susp_log_level,
2343                                 "%s: Videocore remains suspended", __func__);
2344         } else {
2345                 vchiq_log_info(vchiq_susp_log_level,
2346                                 "%s: Videocore resumed", __func__);
2347                 ret = 0;
2348         }
2349         read_unlock_bh(&arm_state->susp_res_lock);
2350 out:
2351         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret);
2352         return ret;
2353 }
2354
2355 /* This function should be called with the write lock held */
2356 int
2357 vchiq_check_resume(VCHIQ_STATE_T *state)
2358 {
2359         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2360         int resume = 0;
2361
2362         if (!arm_state)
2363                 goto out;
2364
2365         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2366
2367         if (need_resume(state)) {
2368                 set_resume_state(arm_state, VC_RESUME_REQUESTED);
2369                 request_poll(state, NULL, 0);
2370                 resume = 1;
2371         }
2372
2373 out:
2374         vchiq_log_trace(vchiq_susp_log_level, "%s exit", __func__);
2375         return resume;
2376 }
2377
2378 VCHIQ_STATUS_T
2379 vchiq_use_internal(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service,
2380                 enum USE_TYPE_E use_type)
2381 {
2382         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2383         VCHIQ_STATUS_T ret = VCHIQ_SUCCESS;
2384         char entity[16];
2385         int *entity_uc;
2386         int local_uc, local_entity_uc;
2387
2388         if (!arm_state)
2389                 goto out;
2390
2391         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2392
2393         if (use_type == USE_TYPE_VCHIQ) {
2394                 sprintf(entity, "VCHIQ:   ");
2395                 entity_uc = &arm_state->peer_use_count;
2396         } else if (service) {
2397                 sprintf(entity, "%c%c%c%c:%03d",
2398                         VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc),
2399                         service->client_id);
2400                 entity_uc = &service->service_use_count;
2401         } else {
2402                 vchiq_log_error(vchiq_susp_log_level, "%s null service "
2403                                 "ptr", __func__);
2404                 ret = VCHIQ_ERROR;
2405                 goto out;
2406         }
2407
2408         write_lock_bh(&arm_state->susp_res_lock);
2409         while (arm_state->resume_blocked) {
2410                 /* If we call 'use' while force suspend is waiting for suspend,
2411                  * then we're about to block the thread which the force is
2412                  * waiting to complete, so we're bound to just time out. In this
2413                  * case, set the suspend state such that the wait will be
2414                  * canceled, so we can complete as quickly as possible. */
2415                 if (arm_state->resume_blocked && arm_state->vc_suspend_state ==
2416                                 VC_SUSPEND_IDLE) {
2417                         set_suspend_state(arm_state, VC_SUSPEND_FORCE_CANCELED);
2418                         break;
2419                 }
2420                 /* If suspend is already in progress then we need to block */
2421                 if (!try_wait_for_completion(&arm_state->resume_blocker)) {
2422                         /* Indicate that there are threads waiting on the resume
2423                          * blocker.  These need to be allowed to complete before
2424                          * a _second_ call to force suspend can complete,
2425                          * otherwise low priority threads might never actually
2426                          * continue */
2427                         arm_state->blocked_count++;
2428                         write_unlock_bh(&arm_state->susp_res_lock);
2429                         vchiq_log_info(vchiq_susp_log_level, "%s %s resume "
2430                                 "blocked - waiting...", __func__, entity);
2431                         if (wait_for_completion_killable(
2432                                         &arm_state->resume_blocker) != 0) {
2433                                 vchiq_log_error(vchiq_susp_log_level, "%s %s "
2434                                         "wait for resume blocker interrupted",
2435                                         __func__, entity);
2436                                 ret = VCHIQ_ERROR;
2437                                 write_lock_bh(&arm_state->susp_res_lock);
2438                                 arm_state->blocked_count--;
2439                                 write_unlock_bh(&arm_state->susp_res_lock);
2440                                 goto out;
2441                         }
2442                         vchiq_log_info(vchiq_susp_log_level, "%s %s resume "
2443                                 "unblocked", __func__, entity);
2444                         write_lock_bh(&arm_state->susp_res_lock);
2445                         if (--arm_state->blocked_count == 0)
2446                                 complete_all(&arm_state->blocked_blocker);
2447                 }
2448         }
2449
2450         stop_suspend_timer(arm_state);
2451
2452         local_uc = ++arm_state->videocore_use_count;
2453         local_entity_uc = ++(*entity_uc);
2454
2455         /* If there's a pending request which hasn't yet been serviced then
2456          * just clear it.  If we're past VC_SUSPEND_REQUESTED state then
2457          * vc_resume_complete will block until we either resume or fail to
2458          * suspend */
2459         if (arm_state->vc_suspend_state <= VC_SUSPEND_REQUESTED)
2460                 set_suspend_state(arm_state, VC_SUSPEND_IDLE);
2461
2462         if ((use_type != USE_TYPE_SERVICE_NO_RESUME) && need_resume(state)) {
2463                 set_resume_state(arm_state, VC_RESUME_REQUESTED);
2464                 vchiq_log_info(vchiq_susp_log_level,
2465                         "%s %s count %d, state count %d",
2466                         __func__, entity, local_entity_uc, local_uc);
2467                 request_poll(state, NULL, 0);
2468         } else
2469                 vchiq_log_trace(vchiq_susp_log_level,
2470                         "%s %s count %d, state count %d",
2471                         __func__, entity, *entity_uc, local_uc);
2472
2473
2474         write_unlock_bh(&arm_state->susp_res_lock);
2475
2476         /* Completion is in a done state when we're not suspended, so this won't
2477          * block for the non-suspended case. */
2478         if (!try_wait_for_completion(&arm_state->vc_resume_complete)) {
2479                 vchiq_log_info(vchiq_susp_log_level, "%s %s wait for resume",
2480                         __func__, entity);
2481                 if (wait_for_completion_killable(
2482                                 &arm_state->vc_resume_complete) != 0) {
2483                         vchiq_log_error(vchiq_susp_log_level, "%s %s wait for "
2484                                 "resume interrupted", __func__, entity);
2485                         ret = VCHIQ_ERROR;
2486                         goto out;
2487                 }
2488                 vchiq_log_info(vchiq_susp_log_level, "%s %s resumed", __func__,
2489                         entity);
2490         }
2491
2492         if (ret == VCHIQ_SUCCESS) {
2493                 VCHIQ_STATUS_T status = VCHIQ_SUCCESS;
2494                 long ack_cnt = atomic_xchg(&arm_state->ka_use_ack_count, 0);
2495                 while (ack_cnt && (status == VCHIQ_SUCCESS)) {
2496                         /* Send the use notify to videocore */
2497                         status = vchiq_send_remote_use_active(state);
2498                         if (status == VCHIQ_SUCCESS)
2499                                 ack_cnt--;
2500                         else
2501                                 atomic_add(ack_cnt,
2502                                         &arm_state->ka_use_ack_count);
2503                 }
2504         }
2505
2506 out:
2507         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret);
2508         return ret;
2509 }
2510
2511 VCHIQ_STATUS_T
2512 vchiq_release_internal(VCHIQ_STATE_T *state, VCHIQ_SERVICE_T *service)
2513 {
2514         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2515         VCHIQ_STATUS_T ret = VCHIQ_SUCCESS;
2516         char entity[16];
2517         int *entity_uc;
2518         int local_uc, local_entity_uc;
2519
2520         if (!arm_state)
2521                 goto out;
2522
2523         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2524
2525         if (service) {
2526                 sprintf(entity, "%c%c%c%c:%03d",
2527                         VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc),
2528                         service->client_id);
2529                 entity_uc = &service->service_use_count;
2530         } else {
2531                 sprintf(entity, "PEER:   ");
2532                 entity_uc = &arm_state->peer_use_count;
2533         }
2534
2535         write_lock_bh(&arm_state->susp_res_lock);
2536         if (!arm_state->videocore_use_count || !(*entity_uc)) {
2537                 /* Don't use BUG_ON - don't allow user thread to crash kernel */
2538                 WARN_ON(!arm_state->videocore_use_count);
2539                 WARN_ON(!(*entity_uc));
2540                 ret = VCHIQ_ERROR;
2541                 goto unlock;
2542         }
2543         local_uc = --arm_state->videocore_use_count;
2544         local_entity_uc = --(*entity_uc);
2545
2546         if (!vchiq_videocore_wanted(state)) {
2547                 if (vchiq_platform_use_suspend_timer() &&
2548                                 !arm_state->resume_blocked) {
2549                         /* Only use the timer if we're not trying to force
2550                          * suspend (=> resume_blocked) */
2551                         start_suspend_timer(arm_state);
2552                 } else {
2553                         vchiq_log_info(vchiq_susp_log_level,
2554                                 "%s %s count %d, state count %d - suspending",
2555                                 __func__, entity, *entity_uc,
2556                                 arm_state->videocore_use_count);
2557                         vchiq_arm_vcsuspend(state);
2558                 }
2559         } else
2560                 vchiq_log_trace(vchiq_susp_log_level,
2561                         "%s %s count %d, state count %d",
2562                         __func__, entity, *entity_uc,
2563                         arm_state->videocore_use_count);
2564
2565 unlock:
2566         write_unlock_bh(&arm_state->susp_res_lock);
2567
2568 out:
2569         vchiq_log_trace(vchiq_susp_log_level, "%s exit %d", __func__, ret);
2570         return ret;
2571 }
2572
2573 void
2574 vchiq_on_remote_use(VCHIQ_STATE_T *state)
2575 {
2576         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2577         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2578         atomic_inc(&arm_state->ka_use_count);
2579         complete(&arm_state->ka_evt);
2580 }
2581
2582 void
2583 vchiq_on_remote_release(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_release_count);
2588         complete(&arm_state->ka_evt);
2589 }
2590
2591 VCHIQ_STATUS_T
2592 vchiq_use_service_internal(VCHIQ_SERVICE_T *service)
2593 {
2594         return vchiq_use_internal(service->state, service, USE_TYPE_SERVICE);
2595 }
2596
2597 VCHIQ_STATUS_T
2598 vchiq_release_service_internal(VCHIQ_SERVICE_T *service)
2599 {
2600         return vchiq_release_internal(service->state, service);
2601 }
2602
2603 VCHIQ_DEBUGFS_NODE_T *
2604 vchiq_instance_get_debugfs_node(VCHIQ_INSTANCE_T instance)
2605 {
2606         return &instance->debugfs_node;
2607 }
2608
2609 int
2610 vchiq_instance_get_use_count(VCHIQ_INSTANCE_T instance)
2611 {
2612         VCHIQ_SERVICE_T *service;
2613         int use_count = 0, i;
2614         i = 0;
2615         while ((service = next_service_by_instance(instance->state,
2616                 instance, &i)) != NULL) {
2617                 use_count += service->service_use_count;
2618                 unlock_service(service);
2619         }
2620         return use_count;
2621 }
2622
2623 int
2624 vchiq_instance_get_pid(VCHIQ_INSTANCE_T instance)
2625 {
2626         return instance->pid;
2627 }
2628
2629 int
2630 vchiq_instance_get_trace(VCHIQ_INSTANCE_T instance)
2631 {
2632         return instance->trace;
2633 }
2634
2635 void
2636 vchiq_instance_set_trace(VCHIQ_INSTANCE_T instance, int trace)
2637 {
2638         VCHIQ_SERVICE_T *service;
2639         int i;
2640         i = 0;
2641         while ((service = next_service_by_instance(instance->state,
2642                 instance, &i)) != NULL) {
2643                 service->trace = trace;
2644                 unlock_service(service);
2645         }
2646         instance->trace = (trace != 0);
2647 }
2648
2649 static void suspend_timer_callback(unsigned long context)
2650 {
2651         VCHIQ_STATE_T *state = (VCHIQ_STATE_T *)context;
2652         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2653         if (!arm_state)
2654                 goto out;
2655         vchiq_log_info(vchiq_susp_log_level,
2656                 "%s - suspend timer expired - check suspend", __func__);
2657         vchiq_check_suspend(state);
2658 out:
2659         return;
2660 }
2661
2662 VCHIQ_STATUS_T
2663 vchiq_use_service_no_resume(VCHIQ_SERVICE_HANDLE_T handle)
2664 {
2665         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
2666         VCHIQ_SERVICE_T *service = find_service_by_handle(handle);
2667         if (service) {
2668                 ret = vchiq_use_internal(service->state, service,
2669                                 USE_TYPE_SERVICE_NO_RESUME);
2670                 unlock_service(service);
2671         }
2672         return ret;
2673 }
2674
2675 VCHIQ_STATUS_T
2676 vchiq_use_service(VCHIQ_SERVICE_HANDLE_T handle)
2677 {
2678         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
2679         VCHIQ_SERVICE_T *service = find_service_by_handle(handle);
2680         if (service) {
2681                 ret = vchiq_use_internal(service->state, service,
2682                                 USE_TYPE_SERVICE);
2683                 unlock_service(service);
2684         }
2685         return ret;
2686 }
2687
2688 VCHIQ_STATUS_T
2689 vchiq_release_service(VCHIQ_SERVICE_HANDLE_T handle)
2690 {
2691         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
2692         VCHIQ_SERVICE_T *service = find_service_by_handle(handle);
2693         if (service) {
2694                 ret = vchiq_release_internal(service->state, service);
2695                 unlock_service(service);
2696         }
2697         return ret;
2698 }
2699
2700 void
2701 vchiq_dump_service_use_state(VCHIQ_STATE_T *state)
2702 {
2703         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2704         int i, j = 0;
2705         /* Only dump 64 services */
2706         static const int local_max_services = 64;
2707         /* If there's more than 64 services, only dump ones with
2708          * non-zero counts */
2709         int only_nonzero = 0;
2710         static const char *nz = "<-- preventing suspend";
2711
2712         enum vc_suspend_status vc_suspend_state;
2713         enum vc_resume_status  vc_resume_state;
2714         int peer_count;
2715         int vc_use_count;
2716         int active_services;
2717         struct service_data_struct {
2718                 int fourcc;
2719                 int clientid;
2720                 int use_count;
2721         } service_data[local_max_services];
2722
2723         if (!arm_state)
2724                 return;
2725
2726         read_lock_bh(&arm_state->susp_res_lock);
2727         vc_suspend_state = arm_state->vc_suspend_state;
2728         vc_resume_state  = arm_state->vc_resume_state;
2729         peer_count = arm_state->peer_use_count;
2730         vc_use_count = arm_state->videocore_use_count;
2731         active_services = state->unused_service;
2732         if (active_services > local_max_services)
2733                 only_nonzero = 1;
2734
2735         for (i = 0; (i < active_services) && (j < local_max_services); i++) {
2736                 VCHIQ_SERVICE_T *service_ptr = state->services[i];
2737                 if (!service_ptr)
2738                         continue;
2739
2740                 if (only_nonzero && !service_ptr->service_use_count)
2741                         continue;
2742
2743                 if (service_ptr->srvstate != VCHIQ_SRVSTATE_FREE) {
2744                         service_data[j].fourcc = service_ptr->base.fourcc;
2745                         service_data[j].clientid = service_ptr->client_id;
2746                         service_data[j++].use_count = service_ptr->
2747                                                         service_use_count;
2748                 }
2749         }
2750
2751         read_unlock_bh(&arm_state->susp_res_lock);
2752
2753         vchiq_log_warning(vchiq_susp_log_level,
2754                 "-- Videcore suspend state: %s --",
2755                 suspend_state_names[vc_suspend_state + VC_SUSPEND_NUM_OFFSET]);
2756         vchiq_log_warning(vchiq_susp_log_level,
2757                 "-- Videcore resume state: %s --",
2758                 resume_state_names[vc_resume_state + VC_RESUME_NUM_OFFSET]);
2759
2760         if (only_nonzero)
2761                 vchiq_log_warning(vchiq_susp_log_level, "Too many active "
2762                         "services (%d).  Only dumping up to first %d services "
2763                         "with non-zero use-count", active_services,
2764                         local_max_services);
2765
2766         for (i = 0; i < j; i++) {
2767                 vchiq_log_warning(vchiq_susp_log_level,
2768                         "----- %c%c%c%c:%d service count %d %s",
2769                         VCHIQ_FOURCC_AS_4CHARS(service_data[i].fourcc),
2770                         service_data[i].clientid,
2771                         service_data[i].use_count,
2772                         service_data[i].use_count ? nz : "");
2773         }
2774         vchiq_log_warning(vchiq_susp_log_level,
2775                 "----- VCHIQ use count count %d", peer_count);
2776         vchiq_log_warning(vchiq_susp_log_level,
2777                 "--- Overall vchiq instance use count %d", vc_use_count);
2778
2779         vchiq_dump_platform_use_state(state);
2780 }
2781
2782 VCHIQ_STATUS_T
2783 vchiq_check_service(VCHIQ_SERVICE_T *service)
2784 {
2785         VCHIQ_ARM_STATE_T *arm_state;
2786         VCHIQ_STATUS_T ret = VCHIQ_ERROR;
2787
2788         if (!service || !service->state)
2789                 goto out;
2790
2791         vchiq_log_trace(vchiq_susp_log_level, "%s", __func__);
2792
2793         arm_state = vchiq_platform_get_arm_state(service->state);
2794
2795         read_lock_bh(&arm_state->susp_res_lock);
2796         if (service->service_use_count)
2797                 ret = VCHIQ_SUCCESS;
2798         read_unlock_bh(&arm_state->susp_res_lock);
2799
2800         if (ret == VCHIQ_ERROR) {
2801                 vchiq_log_error(vchiq_susp_log_level,
2802                         "%s ERROR - %c%c%c%c:%d service count %d, "
2803                         "state count %d, videocore suspend state %s", __func__,
2804                         VCHIQ_FOURCC_AS_4CHARS(service->base.fourcc),
2805                         service->client_id, service->service_use_count,
2806                         arm_state->videocore_use_count,
2807                         suspend_state_names[arm_state->vc_suspend_state +
2808                                                 VC_SUSPEND_NUM_OFFSET]);
2809                 vchiq_dump_service_use_state(service->state);
2810         }
2811 out:
2812         return ret;
2813 }
2814
2815 /* stub functions */
2816 void vchiq_on_remote_use_active(VCHIQ_STATE_T *state)
2817 {
2818         (void)state;
2819 }
2820
2821 void vchiq_platform_conn_state_changed(VCHIQ_STATE_T *state,
2822         VCHIQ_CONNSTATE_T oldstate, VCHIQ_CONNSTATE_T newstate)
2823 {
2824         VCHIQ_ARM_STATE_T *arm_state = vchiq_platform_get_arm_state(state);
2825         vchiq_log_info(vchiq_susp_log_level, "%d: %s->%s", state->id,
2826                 get_conn_state_name(oldstate), get_conn_state_name(newstate));
2827         if (state->conn_state == VCHIQ_CONNSTATE_CONNECTED) {
2828                 write_lock_bh(&arm_state->susp_res_lock);
2829                 if (!arm_state->first_connect) {
2830                         char threadname[16];
2831                         arm_state->first_connect = 1;
2832                         write_unlock_bh(&arm_state->susp_res_lock);
2833                         snprintf(threadname, sizeof(threadname), "vchiq-keep/%d",
2834                                 state->id);
2835                         arm_state->ka_thread = kthread_create(
2836                                 &vchiq_keepalive_thread_func,
2837                                 (void *)state,
2838                                 threadname);
2839                         if (IS_ERR(arm_state->ka_thread)) {
2840                                 vchiq_log_error(vchiq_susp_log_level,
2841                                         "vchiq: FATAL: couldn't create thread %s",
2842                                         threadname);
2843                         } else {
2844                                 wake_up_process(arm_state->ka_thread);
2845                         }
2846                 } else
2847                         write_unlock_bh(&arm_state->susp_res_lock);
2848         }
2849 }
2850
2851 static int vchiq_probe(struct platform_device *pdev)
2852 {
2853         struct device_node *fw_node;
2854         struct rpi_firmware *fw;
2855         int err;
2856         void *ptr_err;
2857
2858         fw_node = of_parse_phandle(pdev->dev.of_node, "firmware", 0);
2859         if (!fw_node) {
2860                 dev_err(&pdev->dev, "Missing firmware node\n");
2861                 return -ENOENT;
2862         }
2863
2864         fw = rpi_firmware_get(fw_node);
2865         of_node_put(fw_node);
2866         if (!fw)
2867                 return -EPROBE_DEFER;
2868
2869         platform_set_drvdata(pdev, fw);
2870
2871         err = vchiq_platform_init(pdev, &g_state);
2872         if (err != 0)
2873                 goto failed_platform_init;
2874
2875         err = alloc_chrdev_region(&vchiq_devid, VCHIQ_MINOR, 1, DEVICE_NAME);
2876         if (err != 0) {
2877                 vchiq_log_error(vchiq_arm_log_level,
2878                         "Unable to allocate device number");
2879                 goto failed_platform_init;
2880         }
2881         cdev_init(&vchiq_cdev, &vchiq_fops);
2882         vchiq_cdev.owner = THIS_MODULE;
2883         err = cdev_add(&vchiq_cdev, vchiq_devid, 1);
2884         if (err != 0) {
2885                 vchiq_log_error(vchiq_arm_log_level,
2886                         "Unable to register device");
2887                 goto failed_cdev_add;
2888         }
2889
2890         /* create sysfs entries */
2891         vchiq_class = class_create(THIS_MODULE, DEVICE_NAME);
2892         ptr_err = vchiq_class;
2893         if (IS_ERR(ptr_err))
2894                 goto failed_class_create;
2895
2896         vchiq_dev = device_create(vchiq_class, NULL,
2897                 vchiq_devid, NULL, "vchiq");
2898         ptr_err = vchiq_dev;
2899         if (IS_ERR(ptr_err))
2900                 goto failed_device_create;
2901
2902         /* create debugfs entries */
2903         err = vchiq_debugfs_init();
2904         if (err != 0)
2905                 goto failed_debugfs_init;
2906
2907         vchiq_log_info(vchiq_arm_log_level,
2908                 "vchiq: initialised - version %d (min %d), device %d.%d",
2909                 VCHIQ_VERSION, VCHIQ_VERSION_MIN,
2910                 MAJOR(vchiq_devid), MINOR(vchiq_devid));
2911
2912         return 0;
2913
2914 failed_debugfs_init:
2915         device_destroy(vchiq_class, vchiq_devid);
2916 failed_device_create:
2917         class_destroy(vchiq_class);
2918 failed_class_create:
2919         cdev_del(&vchiq_cdev);
2920         err = PTR_ERR(ptr_err);
2921 failed_cdev_add:
2922         unregister_chrdev_region(vchiq_devid, 1);
2923 failed_platform_init:
2924         vchiq_log_warning(vchiq_arm_log_level, "could not load vchiq");
2925         return err;
2926 }
2927
2928 static int vchiq_remove(struct platform_device *pdev)
2929 {
2930         vchiq_debugfs_deinit();
2931         device_destroy(vchiq_class, vchiq_devid);
2932         class_destroy(vchiq_class);
2933         cdev_del(&vchiq_cdev);
2934         unregister_chrdev_region(vchiq_devid, 1);
2935
2936         return 0;
2937 }
2938
2939 static const struct of_device_id vchiq_of_match[] = {
2940         { .compatible = "brcm,bcm2835-vchiq", },
2941         {},
2942 };
2943 MODULE_DEVICE_TABLE(of, vchiq_of_match);
2944
2945 static struct platform_driver vchiq_driver = {
2946         .driver = {
2947                 .name = "bcm2835_vchiq",
2948                 .of_match_table = vchiq_of_match,
2949         },
2950         .probe = vchiq_probe,
2951         .remove = vchiq_remove,
2952 };
2953 module_platform_driver(vchiq_driver);
2954
2955 MODULE_LICENSE("GPL");
2956 MODULE_DESCRIPTION("Videocore VCHIQ driver");
2957 MODULE_AUTHOR("Broadcom Corporation");