31df413f5901c8c09d2f6bab686bef4393e6375a
[cascardo/linux.git] / drivers / staging / greybus / operation.c
1 /*
2  * Greybus operations
3  *
4  * Copyright 2014-2015 Google Inc.
5  * Copyright 2014-2015 Linaro Ltd.
6  *
7  * Released under the GPLv2 only.
8  */
9
10 #include <linux/kernel.h>
11 #include <linux/slab.h>
12 #include <linux/module.h>
13 #include <linux/sched.h>
14 #include <linux/wait.h>
15 #include <linux/workqueue.h>
16
17 #include "greybus.h"
18 #include "greybus_trace.h"
19
20 static struct kmem_cache *gb_operation_cache;
21 static struct kmem_cache *gb_message_cache;
22
23 /* Workqueue to handle Greybus operation completions. */
24 static struct workqueue_struct *gb_operation_completion_wq;
25
26 /* Wait queue for synchronous cancellations. */
27 static DECLARE_WAIT_QUEUE_HEAD(gb_operation_cancellation_queue);
28
29 /*
30  * Protects updates to operation->errno.
31  */
32 static DEFINE_SPINLOCK(gb_operations_lock);
33
34 static int gb_operation_response_send(struct gb_operation *operation,
35                                         int errno);
36
37 /*
38  * Increment operation active count and add to connection list unless the
39  * connection is going away.
40  *
41  * Caller holds operation reference.
42  */
43 static int gb_operation_get_active(struct gb_operation *operation)
44 {
45         struct gb_connection *connection = operation->connection;
46         unsigned long flags;
47
48         spin_lock_irqsave(&connection->lock, flags);
49
50         if (connection->state != GB_CONNECTION_STATE_ENABLED &&
51                         connection->state != GB_CONNECTION_STATE_ENABLED_TX &&
52                         !gb_operation_is_incoming(operation)) {
53                 spin_unlock_irqrestore(&connection->lock, flags);
54                 return -ENOTCONN;
55         }
56
57         if (operation->active++ == 0)
58                 list_add_tail(&operation->links, &connection->operations);
59
60         spin_unlock_irqrestore(&connection->lock, flags);
61
62         return 0;
63 }
64
65 /* Caller holds operation reference. */
66 static void gb_operation_put_active(struct gb_operation *operation)
67 {
68         struct gb_connection *connection = operation->connection;
69         unsigned long flags;
70
71         spin_lock_irqsave(&connection->lock, flags);
72         if (--operation->active == 0) {
73                 list_del(&operation->links);
74                 if (atomic_read(&operation->waiters))
75                         wake_up(&gb_operation_cancellation_queue);
76         }
77         spin_unlock_irqrestore(&connection->lock, flags);
78 }
79
80 static bool gb_operation_is_active(struct gb_operation *operation)
81 {
82         struct gb_connection *connection = operation->connection;
83         unsigned long flags;
84         bool ret;
85
86         spin_lock_irqsave(&connection->lock, flags);
87         ret = operation->active;
88         spin_unlock_irqrestore(&connection->lock, flags);
89
90         return ret;
91 }
92
93 /*
94  * Set an operation's result.
95  *
96  * Initially an outgoing operation's errno value is -EBADR.
97  * If no error occurs before sending the request message the only
98  * valid value operation->errno can be set to is -EINPROGRESS,
99  * indicating the request has been (or rather is about to be) sent.
100  * At that point nobody should be looking at the result until the
101  * response arrives.
102  *
103  * The first time the result gets set after the request has been
104  * sent, that result "sticks."  That is, if two concurrent threads
105  * race to set the result, the first one wins.  The return value
106  * tells the caller whether its result was recorded; if not the
107  * caller has nothing more to do.
108  *
109  * The result value -EILSEQ is reserved to signal an implementation
110  * error; if it's ever observed, the code performing the request has
111  * done something fundamentally wrong.  It is an error to try to set
112  * the result to -EBADR, and attempts to do so result in a warning,
113  * and -EILSEQ is used instead.  Similarly, the only valid result
114  * value to set for an operation in initial state is -EINPROGRESS.
115  * Attempts to do otherwise will also record a (successful) -EILSEQ
116  * operation result.
117  */
118 static bool gb_operation_result_set(struct gb_operation *operation, int result)
119 {
120         unsigned long flags;
121         int prev;
122
123         if (result == -EINPROGRESS) {
124                 /*
125                  * -EINPROGRESS is used to indicate the request is
126                  * in flight.  It should be the first result value
127                  * set after the initial -EBADR.  Issue a warning
128                  * and record an implementation error if it's
129                  * set at any other time.
130                  */
131                 spin_lock_irqsave(&gb_operations_lock, flags);
132                 prev = operation->errno;
133                 if (prev == -EBADR)
134                         operation->errno = result;
135                 else
136                         operation->errno = -EILSEQ;
137                 spin_unlock_irqrestore(&gb_operations_lock, flags);
138                 WARN_ON(prev != -EBADR);
139
140                 return true;
141         }
142
143         /*
144          * The first result value set after a request has been sent
145          * will be the final result of the operation.  Subsequent
146          * attempts to set the result are ignored.
147          *
148          * Note that -EBADR is a reserved "initial state" result
149          * value.  Attempts to set this value result in a warning,
150          * and the result code is set to -EILSEQ instead.
151          */
152         if (WARN_ON(result == -EBADR))
153                 result = -EILSEQ; /* Nobody should be setting -EBADR */
154
155         spin_lock_irqsave(&gb_operations_lock, flags);
156         prev = operation->errno;
157         if (prev == -EINPROGRESS)
158                 operation->errno = result;      /* First and final result */
159         spin_unlock_irqrestore(&gb_operations_lock, flags);
160
161         return prev == -EINPROGRESS;
162 }
163
164 int gb_operation_result(struct gb_operation *operation)
165 {
166         int result = operation->errno;
167
168         WARN_ON(result == -EBADR);
169         WARN_ON(result == -EINPROGRESS);
170
171         return result;
172 }
173 EXPORT_SYMBOL_GPL(gb_operation_result);
174
175 /*
176  * Looks up an outgoing operation on a connection and returns a refcounted
177  * pointer if found, or NULL otherwise.
178  */
179 static struct gb_operation *
180 gb_operation_find_outgoing(struct gb_connection *connection, u16 operation_id)
181 {
182         struct gb_operation *operation;
183         unsigned long flags;
184         bool found = false;
185
186         spin_lock_irqsave(&connection->lock, flags);
187         list_for_each_entry(operation, &connection->operations, links)
188                 if (operation->id == operation_id &&
189                                 !gb_operation_is_incoming(operation)) {
190                         gb_operation_get(operation);
191                         found = true;
192                         break;
193                 }
194         spin_unlock_irqrestore(&connection->lock, flags);
195
196         return found ? operation : NULL;
197 }
198
199 static int gb_message_send(struct gb_message *message, gfp_t gfp)
200 {
201         struct gb_connection *connection = message->operation->connection;
202
203         trace_gb_message_send(message);
204         return connection->hd->driver->message_send(connection->hd,
205                                         connection->hd_cport_id,
206                                         message,
207                                         gfp);
208 }
209
210 /*
211  * Cancel a message we have passed to the host device layer to be sent.
212  */
213 static void gb_message_cancel(struct gb_message *message)
214 {
215         struct gb_host_device *hd = message->operation->connection->hd;
216
217         hd->driver->message_cancel(message);
218 }
219
220 static void gb_operation_request_handle(struct gb_operation *operation)
221 {
222         struct gb_connection *connection = operation->connection;
223         int status;
224         int ret;
225
226         if (connection->handler) {
227                 status = connection->handler(operation);
228         } else {
229                 dev_err(&connection->hd->dev,
230                         "%s: unexpected incoming request of type 0x%02x\n",
231                         connection->name, operation->type);
232
233                 status = -EPROTONOSUPPORT;
234         }
235
236         ret = gb_operation_response_send(operation, status);
237         if (ret) {
238                 dev_err(&connection->hd->dev,
239                         "%s: failed to send response %d for type 0x%02x: %d\n",
240                         connection->name, status, operation->type, ret);
241                 return;
242         }
243 }
244
245 /*
246  * Process operation work.
247  *
248  * For incoming requests, call the protocol request handler. The operation
249  * result should be -EINPROGRESS at this point.
250  *
251  * For outgoing requests, the operation result value should have
252  * been set before queueing this.  The operation callback function
253  * allows the original requester to know the request has completed
254  * and its result is available.
255  */
256 static void gb_operation_work(struct work_struct *work)
257 {
258         struct gb_operation *operation;
259
260         operation = container_of(work, struct gb_operation, work);
261
262         if (gb_operation_is_incoming(operation))
263                 gb_operation_request_handle(operation);
264         else
265                 operation->callback(operation);
266
267         gb_operation_put_active(operation);
268         gb_operation_put(operation);
269 }
270
271 static void gb_operation_message_init(struct gb_host_device *hd,
272                                 struct gb_message *message, u16 operation_id,
273                                 size_t payload_size, u8 type)
274 {
275         struct gb_operation_msg_hdr *header;
276
277         header = message->buffer;
278
279         message->header = header;
280         message->payload = payload_size ? header + 1 : NULL;
281         message->payload_size = payload_size;
282
283         /*
284          * The type supplied for incoming message buffers will be
285          * GB_REQUEST_TYPE_INVALID. Such buffers will be overwritten by
286          * arriving data so there's no need to initialize the message header.
287          */
288         if (type != GB_REQUEST_TYPE_INVALID) {
289                 u16 message_size = (u16)(sizeof(*header) + payload_size);
290
291                 /*
292                  * For a request, the operation id gets filled in
293                  * when the message is sent.  For a response, it
294                  * will be copied from the request by the caller.
295                  *
296                  * The result field in a request message must be
297                  * zero.  It will be set just prior to sending for
298                  * a response.
299                  */
300                 header->size = cpu_to_le16(message_size);
301                 header->operation_id = 0;
302                 header->type = type;
303                 header->result = 0;
304         }
305 }
306
307 /*
308  * Allocate a message to be used for an operation request or response.
309  * Both types of message contain a common header.  The request message
310  * for an outgoing operation is outbound, as is the response message
311  * for an incoming operation.  The message header for an outbound
312  * message is partially initialized here.
313  *
314  * The headers for inbound messages don't need to be initialized;
315  * they'll be filled in by arriving data.
316  *
317  * Our message buffers have the following layout:
318  *      message header  \_ these combined are
319  *      message payload /  the message size
320  */
321 static struct gb_message *
322 gb_operation_message_alloc(struct gb_host_device *hd, u8 type,
323                                 size_t payload_size, gfp_t gfp_flags)
324 {
325         struct gb_message *message;
326         struct gb_operation_msg_hdr *header;
327         size_t message_size = payload_size + sizeof(*header);
328
329         if (message_size > hd->buffer_size_max) {
330                 dev_warn(&hd->dev, "requested message size too big (%zu > %zu)\n",
331                                 message_size, hd->buffer_size_max);
332                 return NULL;
333         }
334
335         /* Allocate the message structure and buffer. */
336         message = kmem_cache_zalloc(gb_message_cache, gfp_flags);
337         if (!message)
338                 return NULL;
339
340         message->buffer = kzalloc(message_size, gfp_flags);
341         if (!message->buffer)
342                 goto err_free_message;
343
344         /* Initialize the message.  Operation id is filled in later. */
345         gb_operation_message_init(hd, message, 0, payload_size, type);
346
347         return message;
348
349 err_free_message:
350         kmem_cache_free(gb_message_cache, message);
351
352         return NULL;
353 }
354
355 static void gb_operation_message_free(struct gb_message *message)
356 {
357         kfree(message->buffer);
358         kmem_cache_free(gb_message_cache, message);
359 }
360
361 /*
362  * Map an enum gb_operation_status value (which is represented in a
363  * message as a single byte) to an appropriate Linux negative errno.
364  */
365 static int gb_operation_status_map(u8 status)
366 {
367         switch (status) {
368         case GB_OP_SUCCESS:
369                 return 0;
370         case GB_OP_INTERRUPTED:
371                 return -EINTR;
372         case GB_OP_TIMEOUT:
373                 return -ETIMEDOUT;
374         case GB_OP_NO_MEMORY:
375                 return -ENOMEM;
376         case GB_OP_PROTOCOL_BAD:
377                 return -EPROTONOSUPPORT;
378         case GB_OP_OVERFLOW:
379                 return -EMSGSIZE;
380         case GB_OP_INVALID:
381                 return -EINVAL;
382         case GB_OP_RETRY:
383                 return -EAGAIN;
384         case GB_OP_NONEXISTENT:
385                 return -ENODEV;
386         case GB_OP_MALFUNCTION:
387                 return -EILSEQ;
388         case GB_OP_UNKNOWN_ERROR:
389         default:
390                 return -EIO;
391         }
392 }
393
394 /*
395  * Map a Linux errno value (from operation->errno) into the value
396  * that should represent it in a response message status sent
397  * over the wire.  Returns an enum gb_operation_status value (which
398  * is represented in a message as a single byte).
399  */
400 static u8 gb_operation_errno_map(int errno)
401 {
402         switch (errno) {
403         case 0:
404                 return GB_OP_SUCCESS;
405         case -EINTR:
406                 return GB_OP_INTERRUPTED;
407         case -ETIMEDOUT:
408                 return GB_OP_TIMEOUT;
409         case -ENOMEM:
410                 return GB_OP_NO_MEMORY;
411         case -EPROTONOSUPPORT:
412                 return GB_OP_PROTOCOL_BAD;
413         case -EMSGSIZE:
414                 return GB_OP_OVERFLOW;  /* Could be underflow too */
415         case -EINVAL:
416                 return GB_OP_INVALID;
417         case -EAGAIN:
418                 return GB_OP_RETRY;
419         case -EILSEQ:
420                 return GB_OP_MALFUNCTION;
421         case -ENODEV:
422                 return GB_OP_NONEXISTENT;
423         case -EIO:
424         default:
425                 return GB_OP_UNKNOWN_ERROR;
426         }
427 }
428
429 bool gb_operation_response_alloc(struct gb_operation *operation,
430                                         size_t response_size, gfp_t gfp)
431 {
432         struct gb_host_device *hd = operation->connection->hd;
433         struct gb_operation_msg_hdr *request_header;
434         struct gb_message *response;
435         u8 type;
436
437         type = operation->type | GB_MESSAGE_TYPE_RESPONSE;
438         response = gb_operation_message_alloc(hd, type, response_size, gfp);
439         if (!response)
440                 return false;
441         response->operation = operation;
442
443         /*
444          * Size and type get initialized when the message is
445          * allocated.  The errno will be set before sending.  All
446          * that's left is the operation id, which we copy from the
447          * request message header (as-is, in little-endian order).
448          */
449         request_header = operation->request->header;
450         response->header->operation_id = request_header->operation_id;
451         operation->response = response;
452
453         return true;
454 }
455 EXPORT_SYMBOL_GPL(gb_operation_response_alloc);
456
457 /*
458  * Create a Greybus operation to be sent over the given connection.
459  * The request buffer will be big enough for a payload of the given
460  * size.
461  *
462  * For outgoing requests, the request message's header will be
463  * initialized with the type of the request and the message size.
464  * Outgoing operations must also specify the response buffer size,
465  * which must be sufficient to hold all expected response data.  The
466  * response message header will eventually be overwritten, so there's
467  * no need to initialize it here.
468  *
469  * Request messages for incoming operations can arrive in interrupt
470  * context, so they must be allocated with GFP_ATOMIC.  In this case
471  * the request buffer will be immediately overwritten, so there is
472  * no need to initialize the message header.  Responsibility for
473  * allocating a response buffer lies with the incoming request
474  * handler for a protocol.  So we don't allocate that here.
475  *
476  * Returns a pointer to the new operation or a null pointer if an
477  * error occurs.
478  */
479 static struct gb_operation *
480 gb_operation_create_common(struct gb_connection *connection, u8 type,
481                                 size_t request_size, size_t response_size,
482                                 unsigned long op_flags, gfp_t gfp_flags)
483 {
484         struct gb_host_device *hd = connection->hd;
485         struct gb_operation *operation;
486
487         operation = kmem_cache_zalloc(gb_operation_cache, gfp_flags);
488         if (!operation)
489                 return NULL;
490         operation->connection = connection;
491
492         operation->request = gb_operation_message_alloc(hd, type, request_size,
493                                                         gfp_flags);
494         if (!operation->request)
495                 goto err_cache;
496         operation->request->operation = operation;
497
498         /* Allocate the response buffer for outgoing operations */
499         if (!(op_flags & GB_OPERATION_FLAG_INCOMING)) {
500                 if (!gb_operation_response_alloc(operation, response_size,
501                                                  gfp_flags)) {
502                         goto err_request;
503                 }
504         }
505
506         operation->flags = op_flags;
507         operation->type = type;
508         operation->errno = -EBADR;  /* Initial value--means "never set" */
509
510         INIT_WORK(&operation->work, gb_operation_work);
511         init_completion(&operation->completion);
512         kref_init(&operation->kref);
513         atomic_set(&operation->waiters, 0);
514
515         return operation;
516
517 err_request:
518         gb_operation_message_free(operation->request);
519 err_cache:
520         kmem_cache_free(gb_operation_cache, operation);
521
522         return NULL;
523 }
524
525 /*
526  * Create a new operation associated with the given connection.  The
527  * request and response sizes provided are the number of bytes
528  * required to hold the request/response payload only.  Both of
529  * these are allowed to be 0.  Note that 0x00 is reserved as an
530  * invalid operation type for all protocols, and this is enforced
531  * here.
532  */
533 struct gb_operation *
534 gb_operation_create_flags(struct gb_connection *connection,
535                                 u8 type, size_t request_size,
536                                 size_t response_size, unsigned long flags,
537                                 gfp_t gfp)
538 {
539         if (WARN_ON_ONCE(type == GB_REQUEST_TYPE_INVALID))
540                 return NULL;
541         if (WARN_ON_ONCE(type & GB_MESSAGE_TYPE_RESPONSE))
542                 type &= ~GB_MESSAGE_TYPE_RESPONSE;
543
544         if (WARN_ON_ONCE(flags & ~GB_OPERATION_FLAG_USER_MASK))
545                 flags &= GB_OPERATION_FLAG_USER_MASK;
546
547         return gb_operation_create_common(connection, type,
548                                                 request_size, response_size,
549                                                 flags, gfp);
550 }
551 EXPORT_SYMBOL_GPL(gb_operation_create_flags);
552
553 size_t gb_operation_get_payload_size_max(struct gb_connection *connection)
554 {
555         struct gb_host_device *hd = connection->hd;
556
557         return hd->buffer_size_max - sizeof(struct gb_operation_msg_hdr);
558 }
559 EXPORT_SYMBOL_GPL(gb_operation_get_payload_size_max);
560
561 static struct gb_operation *
562 gb_operation_create_incoming(struct gb_connection *connection, u16 id,
563                                 u8 type, void *data, size_t size)
564 {
565         struct gb_operation *operation;
566         size_t request_size;
567         unsigned long flags = GB_OPERATION_FLAG_INCOMING;
568
569         /* Caller has made sure we at least have a message header. */
570         request_size = size - sizeof(struct gb_operation_msg_hdr);
571
572         if (!id)
573                 flags |= GB_OPERATION_FLAG_UNIDIRECTIONAL;
574
575         operation = gb_operation_create_common(connection, type,
576                                                 request_size,
577                                                 GB_REQUEST_TYPE_INVALID,
578                                                 flags, GFP_ATOMIC);
579         if (!operation)
580                 return NULL;
581
582         operation->id = id;
583         memcpy(operation->request->header, data, size);
584
585         return operation;
586 }
587
588 /*
589  * Get an additional reference on an operation.
590  */
591 void gb_operation_get(struct gb_operation *operation)
592 {
593         kref_get(&operation->kref);
594 }
595 EXPORT_SYMBOL_GPL(gb_operation_get);
596
597 /*
598  * Destroy a previously created operation.
599  */
600 static void _gb_operation_destroy(struct kref *kref)
601 {
602         struct gb_operation *operation;
603
604         operation = container_of(kref, struct gb_operation, kref);
605
606         if (operation->response)
607                 gb_operation_message_free(operation->response);
608         gb_operation_message_free(operation->request);
609
610         kmem_cache_free(gb_operation_cache, operation);
611 }
612
613 /*
614  * Drop a reference on an operation, and destroy it when the last
615  * one is gone.
616  */
617 void gb_operation_put(struct gb_operation *operation)
618 {
619         if (WARN_ON(!operation))
620                 return;
621
622         kref_put(&operation->kref, _gb_operation_destroy);
623 }
624 EXPORT_SYMBOL_GPL(gb_operation_put);
625
626 /* Tell the requester we're done */
627 static void gb_operation_sync_callback(struct gb_operation *operation)
628 {
629         complete(&operation->completion);
630 }
631
632 /**
633  * gb_operation_request_send() - send an operation request message
634  * @operation:  the operation to initiate
635  * @callback:   the operation completion callback
636  * @gfp:        the memory flags to use for any allocations
637  *
638  * The caller has filled in any payload so the request message is ready to go.
639  * The callback function supplied will be called when the response message has
640  * arrived, a unidirectional request has been sent, or the operation is
641  * cancelled, indicating that the operation is complete. The callback function
642  * can fetch the result of the operation using gb_operation_result() if
643  * desired.
644  *
645  * Return: 0 if the request was successfully queued in the host-driver queues,
646  * or a negative errno.
647  */
648 int gb_operation_request_send(struct gb_operation *operation,
649                                 gb_operation_callback callback,
650                                 gfp_t gfp)
651 {
652         struct gb_connection *connection = operation->connection;
653         struct gb_operation_msg_hdr *header;
654         unsigned int cycle;
655         int ret;
656
657         if (gb_connection_is_offloaded(connection))
658                 return -EBUSY;
659
660         if (!callback)
661                 return -EINVAL;
662
663         /*
664          * Record the callback function, which is executed in
665          * non-atomic (workqueue) context when the final result
666          * of an operation has been set.
667          */
668         operation->callback = callback;
669
670         /*
671          * Assign the operation's id, and store it in the request header.
672          * Zero is a reserved operation id for unidirectional operations.
673          */
674         if (gb_operation_is_unidirectional(operation)) {
675                 operation->id = 0;
676         } else {
677                 cycle = (unsigned int)atomic_inc_return(&connection->op_cycle);
678                 operation->id = (u16)(cycle % U16_MAX + 1);
679         }
680
681         header = operation->request->header;
682         header->operation_id = cpu_to_le16(operation->id);
683
684         gb_operation_result_set(operation, -EINPROGRESS);
685
686         /*
687          * Get an extra reference on the operation. It'll be dropped when the
688          * operation completes.
689          */
690         gb_operation_get(operation);
691         ret = gb_operation_get_active(operation);
692         if (ret)
693                 goto err_put;
694
695         ret = gb_message_send(operation->request, gfp);
696         if (ret)
697                 goto err_put_active;
698
699         return 0;
700
701 err_put_active:
702         gb_operation_put_active(operation);
703 err_put:
704         gb_operation_put(operation);
705
706         return ret;
707 }
708 EXPORT_SYMBOL_GPL(gb_operation_request_send);
709
710 /*
711  * Send a synchronous operation.  This function is expected to
712  * block, returning only when the response has arrived, (or when an
713  * error is detected.  The return value is the result of the
714  * operation.
715  */
716 int gb_operation_request_send_sync_timeout(struct gb_operation *operation,
717                                                 unsigned int timeout)
718 {
719         int ret;
720         unsigned long timeout_jiffies;
721
722         ret = gb_operation_request_send(operation, gb_operation_sync_callback,
723                                         GFP_KERNEL);
724         if (ret)
725                 return ret;
726
727         if (timeout)
728                 timeout_jiffies = msecs_to_jiffies(timeout);
729         else
730                 timeout_jiffies = MAX_SCHEDULE_TIMEOUT;
731
732         ret = wait_for_completion_interruptible_timeout(&operation->completion,
733                                                         timeout_jiffies);
734         if (ret < 0) {
735                 /* Cancel the operation if interrupted */
736                 gb_operation_cancel(operation, -ECANCELED);
737         } else if (ret == 0) {
738                 /* Cancel the operation if op timed out */
739                 gb_operation_cancel(operation, -ETIMEDOUT);
740         }
741
742         return gb_operation_result(operation);
743 }
744 EXPORT_SYMBOL_GPL(gb_operation_request_send_sync_timeout);
745
746 /*
747  * Send a response for an incoming operation request.  A non-zero
748  * errno indicates a failed operation.
749  *
750  * If there is any response payload, the incoming request handler is
751  * responsible for allocating the response message.  Otherwise the
752  * it can simply supply the result errno; this function will
753  * allocate the response message if necessary.
754  */
755 static int gb_operation_response_send(struct gb_operation *operation,
756                                         int errno)
757 {
758         struct gb_connection *connection = operation->connection;
759         int ret;
760
761         if (!operation->response &&
762                         !gb_operation_is_unidirectional(operation)) {
763                 if (!gb_operation_response_alloc(operation, 0, GFP_KERNEL))
764                         return -ENOMEM;
765         }
766
767         /* Record the result */
768         if (!gb_operation_result_set(operation, errno)) {
769                 dev_err(&connection->hd->dev, "request result already set\n");
770                 return -EIO;    /* Shouldn't happen */
771         }
772
773         /* Sender of request does not care about response. */
774         if (gb_operation_is_unidirectional(operation))
775                 return 0;
776
777         /* Reference will be dropped when message has been sent. */
778         gb_operation_get(operation);
779         ret = gb_operation_get_active(operation);
780         if (ret)
781                 goto err_put;
782
783         /* Fill in the response header and send it */
784         operation->response->header->result = gb_operation_errno_map(errno);
785
786         ret = gb_message_send(operation->response, GFP_KERNEL);
787         if (ret)
788                 goto err_put_active;
789
790         return 0;
791
792 err_put_active:
793         gb_operation_put_active(operation);
794 err_put:
795         gb_operation_put(operation);
796
797         return ret;
798 }
799
800 /*
801  * This function is called when a message send request has completed.
802  */
803 void greybus_message_sent(struct gb_host_device *hd,
804                                         struct gb_message *message, int status)
805 {
806         struct gb_operation *operation = message->operation;
807         struct gb_connection *connection = operation->connection;
808
809         /*
810          * If the message was a response, we just need to drop our
811          * reference to the operation.  If an error occurred, report
812          * it.
813          *
814          * For requests, if there's no error and the operation in not
815          * unidirectional, there's nothing more to do until the response
816          * arrives. If an error occurred attempting to send it, or if the
817          * operation is unidrectional, record the result of the operation and
818          * schedule its completion.
819          */
820         if (message == operation->response) {
821                 if (status) {
822                         dev_err(&connection->hd->dev,
823                                 "%s: error sending response 0x%02x: %d\n",
824                                 connection->name, operation->type, status);
825                 }
826
827                 gb_operation_put_active(operation);
828                 gb_operation_put(operation);
829         } else if (status || gb_operation_is_unidirectional(operation)) {
830                 if (gb_operation_result_set(operation, status)) {
831                         queue_work(gb_operation_completion_wq,
832                                         &operation->work);
833                 }
834         }
835 }
836 EXPORT_SYMBOL_GPL(greybus_message_sent);
837
838 /*
839  * We've received data on a connection, and it doesn't look like a
840  * response, so we assume it's a request.
841  *
842  * This is called in interrupt context, so just copy the incoming
843  * data into the request buffer and handle the rest via workqueue.
844  */
845 static void gb_connection_recv_request(struct gb_connection *connection,
846                                        u16 operation_id, u8 type,
847                                        void *data, size_t size)
848 {
849         struct gb_operation *operation;
850         int ret;
851
852         operation = gb_operation_create_incoming(connection, operation_id,
853                                                 type, data, size);
854         if (!operation) {
855                 dev_err(&connection->hd->dev,
856                         "%s: can't create incoming operation\n",
857                         connection->name);
858                 return;
859         }
860
861         ret = gb_operation_get_active(operation);
862         if (ret) {
863                 gb_operation_put(operation);
864                 return;
865         }
866         trace_gb_message_recv_request(operation->request);
867
868         /*
869          * The initial reference to the operation will be dropped when the
870          * request handler returns.
871          */
872         if (gb_operation_result_set(operation, -EINPROGRESS))
873                 queue_work(connection->wq, &operation->work);
874 }
875
876 /*
877  * We've received data that appears to be an operation response
878  * message.  Look up the operation, and record that we've received
879  * its response.
880  *
881  * This is called in interrupt context, so just copy the incoming
882  * data into the response buffer and handle the rest via workqueue.
883  */
884 static void gb_connection_recv_response(struct gb_connection *connection,
885                         u16 operation_id, u8 result, void *data, size_t size)
886 {
887         struct gb_operation_msg_hdr *header;
888         struct gb_operation *operation;
889         struct gb_message *message;
890         int errno = gb_operation_status_map(result);
891         size_t message_size;
892
893         if (!operation_id) {
894                 dev_err_ratelimited(&connection->hd->dev,
895                                 "%s: invalid response id 0 received\n",
896                                 connection->name);
897                 return;
898         }
899
900         operation = gb_operation_find_outgoing(connection, operation_id);
901         if (!operation) {
902                 dev_err_ratelimited(&connection->hd->dev,
903                                 "%s: unexpected response id 0x%04x received\n",
904                                 connection->name, operation_id);
905                 return;
906         }
907
908         message = operation->response;
909         header = message->header;
910         message_size = sizeof(*header) + message->payload_size;
911         if (!errno && size > message_size) {
912                 dev_err_ratelimited(&connection->hd->dev,
913                                 "%s: malformed response 0x%02x received (%zu > %zu)\n",
914                                 connection->name, header->type,
915                                 size, message_size);
916                 errno = -EMSGSIZE;
917         } else if (!errno && size < message_size) {
918                 if (gb_operation_short_response_allowed(operation)) {
919                         message->payload_size = size - sizeof(*header);
920                 } else {
921                         dev_err_ratelimited(&connection->hd->dev,
922                                         "%s: short response 0x%02x received (%zu < %zu)\n",
923                                         connection->name, header->type,
924                                         size, message_size);
925                         errno = -EMSGSIZE;
926                 }
927         }
928         trace_gb_message_recv_response(operation->response);
929
930         /* We must ignore the payload if a bad status is returned */
931         if (errno)
932                 size = sizeof(*header);
933
934         /* The rest will be handled in work queue context */
935         if (gb_operation_result_set(operation, errno)) {
936                 memcpy(header, data, size);
937                 queue_work(gb_operation_completion_wq, &operation->work);
938         }
939
940         gb_operation_put(operation);
941 }
942
943 /*
944  * Handle data arriving on a connection.  As soon as we return the
945  * supplied data buffer will be reused (so unless we do something
946  * with, it's effectively dropped).
947  */
948 void gb_connection_recv(struct gb_connection *connection,
949                                 void *data, size_t size)
950 {
951         struct gb_operation_msg_hdr header;
952         struct device *dev = &connection->hd->dev;
953         size_t msg_size;
954         u16 operation_id;
955
956         if ((connection->state != GB_CONNECTION_STATE_ENABLED &&
957                         connection->state != GB_CONNECTION_STATE_ENABLED_TX) ||
958                         gb_connection_is_offloaded(connection)) {
959                 dev_warn_ratelimited(dev, "%s: dropping %zu received bytes\n",
960                                 connection->name, size);
961                 return;
962         }
963
964         if (size < sizeof(header)) {
965                 dev_err_ratelimited(dev, "%s: short message received\n",
966                                 connection->name);
967                 return;
968         }
969
970         /* Use memcpy as data may be unaligned */
971         memcpy(&header, data, sizeof(header));
972         msg_size = le16_to_cpu(header.size);
973         if (size < msg_size) {
974                 dev_err_ratelimited(dev,
975                                 "%s: incomplete message 0x%04x of type 0x%02x received (%zu < %zu)\n",
976                                 connection->name,
977                                 le16_to_cpu(header.operation_id),
978                                 header.type, size, msg_size);
979                 return;         /* XXX Should still complete operation */
980         }
981
982         operation_id = le16_to_cpu(header.operation_id);
983         if (header.type & GB_MESSAGE_TYPE_RESPONSE)
984                 gb_connection_recv_response(connection, operation_id,
985                                                 header.result, data, msg_size);
986         else
987                 gb_connection_recv_request(connection, operation_id,
988                                                 header.type, data, msg_size);
989 }
990
991 /*
992  * Cancel an outgoing operation synchronously, and record the given error to
993  * indicate why.
994  */
995 void gb_operation_cancel(struct gb_operation *operation, int errno)
996 {
997         if (WARN_ON(gb_operation_is_incoming(operation)))
998                 return;
999
1000         if (gb_operation_result_set(operation, errno)) {
1001                 gb_message_cancel(operation->request);
1002                 queue_work(gb_operation_completion_wq, &operation->work);
1003         }
1004         trace_gb_message_cancel_outgoing(operation->request);
1005
1006         atomic_inc(&operation->waiters);
1007         wait_event(gb_operation_cancellation_queue,
1008                         !gb_operation_is_active(operation));
1009         atomic_dec(&operation->waiters);
1010 }
1011 EXPORT_SYMBOL_GPL(gb_operation_cancel);
1012
1013 /*
1014  * Cancel an incoming operation synchronously. Called during connection tear
1015  * down.
1016  */
1017 void gb_operation_cancel_incoming(struct gb_operation *operation, int errno)
1018 {
1019         if (WARN_ON(!gb_operation_is_incoming(operation)))
1020                 return;
1021
1022         if (!gb_operation_is_unidirectional(operation)) {
1023                 /*
1024                  * Make sure the request handler has submitted the response
1025                  * before cancelling it.
1026                  */
1027                 flush_work(&operation->work);
1028                 if (!gb_operation_result_set(operation, errno))
1029                         gb_message_cancel(operation->response);
1030         }
1031         trace_gb_message_cancel_incoming(operation->response);
1032
1033         atomic_inc(&operation->waiters);
1034         wait_event(gb_operation_cancellation_queue,
1035                         !gb_operation_is_active(operation));
1036         atomic_dec(&operation->waiters);
1037 }
1038
1039 /**
1040  * gb_operation_sync_timeout() - implement a "simple" synchronous operation
1041  * @connection: the Greybus connection to send this to
1042  * @type: the type of operation to send
1043  * @request: pointer to a memory buffer to copy the request from
1044  * @request_size: size of @request
1045  * @response: pointer to a memory buffer to copy the response to
1046  * @response_size: the size of @response.
1047  * @timeout: operation timeout in milliseconds
1048  *
1049  * This function implements a simple synchronous Greybus operation.  It sends
1050  * the provided operation request and waits (sleeps) until the corresponding
1051  * operation response message has been successfully received, or an error
1052  * occurs.  @request and @response are buffers to hold the request and response
1053  * data respectively, and if they are not NULL, their size must be specified in
1054  * @request_size and @response_size.
1055  *
1056  * If a response payload is to come back, and @response is not NULL,
1057  * @response_size number of bytes will be copied into @response if the operation
1058  * is successful.
1059  *
1060  * If there is an error, the response buffer is left alone.
1061  */
1062 int gb_operation_sync_timeout(struct gb_connection *connection, int type,
1063                                 void *request, int request_size,
1064                                 void *response, int response_size,
1065                                 unsigned int timeout)
1066 {
1067         struct gb_operation *operation;
1068         int ret;
1069
1070         if ((response_size && !response) ||
1071             (request_size && !request))
1072                 return -EINVAL;
1073
1074         operation = gb_operation_create(connection, type,
1075                                         request_size, response_size,
1076                                         GFP_KERNEL);
1077         if (!operation)
1078                 return -ENOMEM;
1079
1080         if (request_size)
1081                 memcpy(operation->request->payload, request, request_size);
1082
1083         ret = gb_operation_request_send_sync_timeout(operation, timeout);
1084         if (ret) {
1085                 dev_err(&connection->hd->dev,
1086                         "%s: synchronous operation of type 0x%02x failed: %d\n",
1087                         connection->name, type, ret);
1088         } else {
1089                 if (response_size) {
1090                         memcpy(response, operation->response->payload,
1091                                response_size);
1092                 }
1093         }
1094
1095         gb_operation_put(operation);
1096
1097         return ret;
1098 }
1099 EXPORT_SYMBOL_GPL(gb_operation_sync_timeout);
1100
1101 /**
1102  * gb_operation_unidirectional_timeout() - initiate a unidirectional operation
1103  * @connection:         connection to use
1104  * @type:               type of operation to send
1105  * @request:            memory buffer to copy the request from
1106  * @request_size:       size of @request
1107  * @timeout:            send timeout in milliseconds
1108  *
1109  * Initiate a unidirectional operation by sending a request message and
1110  * waiting for it to be acknowledged as sent by the host device.
1111  *
1112  * Note that successful send of a unidirectional operation does not imply that
1113  * the request as actually reached the remote end of the connection.
1114  */
1115 int gb_operation_unidirectional_timeout(struct gb_connection *connection,
1116                                 int type, void *request, int request_size,
1117                                 unsigned int timeout)
1118 {
1119         struct gb_operation *operation;
1120         int ret;
1121
1122         if (request_size && !request)
1123                 return -EINVAL;
1124
1125         operation = gb_operation_create_flags(connection, type,
1126                                         request_size, 0,
1127                                         GB_OPERATION_FLAG_UNIDIRECTIONAL,
1128                                         GFP_KERNEL);
1129         if (!operation)
1130                 return -ENOMEM;
1131
1132         if (request_size)
1133                 memcpy(operation->request->payload, request, request_size);
1134
1135         ret = gb_operation_request_send_sync_timeout(operation, timeout);
1136         if (ret) {
1137                 dev_err(&connection->hd->dev,
1138                         "%s: unidirectional operation of type 0x%02x failed: %d\n",
1139                         connection->name, type, ret);
1140         }
1141
1142         gb_operation_put(operation);
1143
1144         return ret;
1145 }
1146 EXPORT_SYMBOL_GPL(gb_operation_unidirectional_timeout);
1147
1148 int __init gb_operation_init(void)
1149 {
1150         gb_message_cache = kmem_cache_create("gb_message_cache",
1151                                 sizeof(struct gb_message), 0, 0, NULL);
1152         if (!gb_message_cache)
1153                 return -ENOMEM;
1154
1155         gb_operation_cache = kmem_cache_create("gb_operation_cache",
1156                                 sizeof(struct gb_operation), 0, 0, NULL);
1157         if (!gb_operation_cache)
1158                 goto err_destroy_message_cache;
1159
1160         gb_operation_completion_wq = alloc_workqueue("greybus_completion",
1161                                 0, 0);
1162         if (!gb_operation_completion_wq)
1163                 goto err_destroy_operation_cache;
1164
1165         return 0;
1166
1167 err_destroy_operation_cache:
1168         kmem_cache_destroy(gb_operation_cache);
1169         gb_operation_cache = NULL;
1170 err_destroy_message_cache:
1171         kmem_cache_destroy(gb_message_cache);
1172         gb_message_cache = NULL;
1173
1174         return -ENOMEM;
1175 }
1176
1177 void gb_operation_exit(void)
1178 {
1179         destroy_workqueue(gb_operation_completion_wq);
1180         gb_operation_completion_wq = NULL;
1181         kmem_cache_destroy(gb_operation_cache);
1182         gb_operation_cache = NULL;
1183         kmem_cache_destroy(gb_message_cache);
1184         gb_message_cache = NULL;
1185 }