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