greybus: remove redundant latency-tag sanity checks
[cascardo/linux.git] / drivers / staging / greybus / es2.c
1 /*
2  * Greybus "AP" USB driver for "ES2" controller chips
3  *
4  * Copyright 2014-2015 Google Inc.
5  * Copyright 2014-2015 Linaro Ltd.
6  *
7  * Released under the GPLv2 only.
8  */
9 #include <linux/kthread.h>
10 #include <linux/sizes.h>
11 #include <linux/usb.h>
12 #include <linux/kfifo.h>
13 #include <linux/debugfs.h>
14 #include <asm/unaligned.h>
15
16 #include "greybus.h"
17 #include "kernel_ver.h"
18 #include "connection.h"
19 #include "greybus_trace.h"
20
21
22 /* Fixed CPort numbers */
23 #define ES2_CPORT_CDSI0         16
24 #define ES2_CPORT_CDSI1         17
25
26 /* Memory sizes for the buffers sent to/from the ES2 controller */
27 #define ES2_GBUF_MSG_SIZE_MAX   2048
28
29 static const struct usb_device_id id_table[] = {
30         { USB_DEVICE(0x18d1, 0x1eaf) },
31         { },
32 };
33 MODULE_DEVICE_TABLE(usb, id_table);
34
35 #define APB1_LOG_SIZE           SZ_16K
36
37 /* Number of bulk in and bulk out couple */
38 #define NUM_BULKS               7
39
40 /*
41  * Number of CPort IN urbs in flight at any point in time.
42  * Adjust if we are having stalls in the USB buffer due to not enough urbs in
43  * flight.
44  */
45 #define NUM_CPORT_IN_URB        4
46
47 /* Number of CPort OUT urbs in flight at any point in time.
48  * Adjust if we get messages saying we are out of urbs in the system log.
49  */
50 #define NUM_CPORT_OUT_URB       (8 * NUM_BULKS)
51
52 /*
53  * @endpoint: bulk in endpoint for CPort data
54  * @urb: array of urbs for the CPort in messages
55  * @buffer: array of buffers for the @cport_in_urb urbs
56  */
57 struct es2_cport_in {
58         __u8 endpoint;
59         struct urb *urb[NUM_CPORT_IN_URB];
60         u8 *buffer[NUM_CPORT_IN_URB];
61 };
62
63 /*
64  * @endpoint: bulk out endpoint for CPort data
65  */
66 struct es2_cport_out {
67         __u8 endpoint;
68 };
69
70 /**
71  * es2_ap_dev - ES2 USB Bridge to AP structure
72  * @usb_dev: pointer to the USB device we are.
73  * @usb_intf: pointer to the USB interface we are bound to.
74  * @hd: pointer to our gb_host_device structure
75
76  * @cport_in: endpoint, urbs and buffer for cport in messages
77  * @cport_out: endpoint for for cport out messages
78  * @cport_out_urb: array of urbs for the CPort out messages
79  * @cport_out_urb_busy: array of flags to see if the @cport_out_urb is busy or
80  *                      not.
81  * @cport_out_urb_cancelled: array of flags indicating whether the
82  *                      corresponding @cport_out_urb is being cancelled
83  * @cport_out_urb_lock: locks the @cport_out_urb_busy "list"
84  *
85  * @apb_log_task: task pointer for logging thread
86  * @apb_log_dentry: file system entry for the log file interface
87  * @apb_log_enable_dentry: file system entry for enabling logging
88  * @apb_log_fifo: kernel FIFO to carry logged data
89  */
90 struct es2_ap_dev {
91         struct usb_device *usb_dev;
92         struct usb_interface *usb_intf;
93         struct gb_host_device *hd;
94
95         struct es2_cport_in cport_in[NUM_BULKS];
96         struct es2_cport_out cport_out[NUM_BULKS];
97         struct urb *cport_out_urb[NUM_CPORT_OUT_URB];
98         bool cport_out_urb_busy[NUM_CPORT_OUT_URB];
99         bool cport_out_urb_cancelled[NUM_CPORT_OUT_URB];
100         spinlock_t cport_out_urb_lock;
101
102         bool cdsi1_in_use;
103
104         int *cport_to_ep;
105
106         struct task_struct *apb_log_task;
107         struct dentry *apb_log_dentry;
108         struct dentry *apb_log_enable_dentry;
109         DECLARE_KFIFO(apb_log_fifo, char, APB1_LOG_SIZE);
110 };
111
112 /**
113  * cport_to_ep - information about cport to endpoints mapping
114  * @cport_id: the id of cport to map to endpoints
115  * @endpoint_in: the endpoint number to use for in transfer
116  * @endpoint_out: he endpoint number to use for out transfer
117  */
118 struct cport_to_ep {
119         __le16 cport_id;
120         __u8 endpoint_in;
121         __u8 endpoint_out;
122 };
123
124 /**
125  * timesync_enable_request - Enable timesync in an APBridge
126  * @count: number of TimeSync Pulses to expect
127  * @frame_time: the initial FrameTime at the first TimeSync Pulse
128  * @strobe_delay: the expected delay in microseconds between each TimeSync Pulse
129  * @refclk: The AP mandated reference clock to run FrameTime at
130  */
131 struct timesync_enable_request {
132         __u8    count;
133         __le64  frame_time;
134         __le32  strobe_delay;
135         __le32  refclk;
136 } __packed;
137
138 /**
139  * timesync_authoritative_request - Transmit authoritative FrameTime to APBridge
140  * @frame_time: An array of authoritative FrameTimes provided by the SVC
141  *              and relayed to the APBridge by the AP
142  */
143 struct timesync_authoritative_request {
144         __le64  frame_time[GB_TIMESYNC_MAX_STROBES];
145 } __packed;
146
147 static inline struct es2_ap_dev *hd_to_es2(struct gb_host_device *hd)
148 {
149         return (struct es2_ap_dev *)&hd->hd_priv;
150 }
151
152 static void cport_out_callback(struct urb *urb);
153 static void usb_log_enable(struct es2_ap_dev *es2);
154 static void usb_log_disable(struct es2_ap_dev *es2);
155
156 /* Get the endpoints pair mapped to the cport */
157 static int cport_to_ep_pair(struct es2_ap_dev *es2, u16 cport_id)
158 {
159         if (cport_id >= es2->hd->num_cports)
160                 return 0;
161         return es2->cport_to_ep[cport_id];
162 }
163
164 #define ES2_TIMEOUT     500     /* 500 ms for the SVC to do something */
165
166 /* Disable for now until we work all of this out to keep a warning-free build */
167 #if 0
168 /* Test if the endpoints pair is already mapped to a cport */
169 static int ep_pair_in_use(struct es2_ap_dev *es2, int ep_pair)
170 {
171         int i;
172
173         for (i = 0; i < es2->hd->num_cports; i++) {
174                 if (es2->cport_to_ep[i] == ep_pair)
175                         return 1;
176         }
177         return 0;
178 }
179
180 /* Configure the endpoint mapping and send the request to APBridge */
181 static int map_cport_to_ep(struct es2_ap_dev *es2,
182                                 u16 cport_id, int ep_pair)
183 {
184         int retval;
185         struct cport_to_ep *cport_to_ep;
186
187         if (ep_pair < 0 || ep_pair >= NUM_BULKS)
188                 return -EINVAL;
189         if (cport_id >= es2->hd->num_cports)
190                 return -EINVAL;
191         if (ep_pair && ep_pair_in_use(es2, ep_pair))
192                 return -EINVAL;
193
194         cport_to_ep = kmalloc(sizeof(*cport_to_ep), GFP_KERNEL);
195         if (!cport_to_ep)
196                 return -ENOMEM;
197
198         es2->cport_to_ep[cport_id] = ep_pair;
199         cport_to_ep->cport_id = cpu_to_le16(cport_id);
200         cport_to_ep->endpoint_in = es2->cport_in[ep_pair].endpoint;
201         cport_to_ep->endpoint_out = es2->cport_out[ep_pair].endpoint;
202
203         retval = usb_control_msg(es2->usb_dev,
204                                  usb_sndctrlpipe(es2->usb_dev, 0),
205                                  GB_APB_REQUEST_EP_MAPPING,
206                                  USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
207                                  0x00, 0x00,
208                                  (char *)cport_to_ep,
209                                  sizeof(*cport_to_ep),
210                                  ES2_TIMEOUT);
211         if (retval == sizeof(*cport_to_ep))
212                 retval = 0;
213         kfree(cport_to_ep);
214
215         return retval;
216 }
217
218 /* Unmap a cport: use the muxed endpoints pair */
219 static int unmap_cport(struct es2_ap_dev *es2, u16 cport_id)
220 {
221         return map_cport_to_ep(es2, cport_id, 0);
222 }
223 #endif
224
225 static int output_sync(struct es2_ap_dev *es2, void *req, u16 size, u8 cmd)
226 {
227         struct usb_device *udev = es2->usb_dev;
228         u8 *data;
229         int retval;
230
231         data = kmalloc(size, GFP_KERNEL);
232         if (!data)
233                 return -ENOMEM;
234         memcpy(data, req, size);
235
236         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
237                                  cmd,
238                                  USB_DIR_OUT | USB_TYPE_VENDOR |
239                                  USB_RECIP_INTERFACE,
240                                  0, 0, data, size, ES2_TIMEOUT);
241         if (retval < 0)
242                 dev_err(&udev->dev, "%s: return error %d\n", __func__, retval);
243         else
244                 retval = 0;
245
246         kfree(data);
247         return retval;
248 }
249
250 static void ap_urb_complete(struct urb *urb)
251 {
252         struct usb_ctrlrequest *dr = urb->context;
253
254         kfree(dr);
255         usb_free_urb(urb);
256 }
257
258 static int output_async(struct es2_ap_dev *es2, void *req, u16 size, u8 cmd)
259 {
260         struct usb_device *udev = es2->usb_dev;
261         struct urb *urb;
262         struct usb_ctrlrequest *dr;
263         u8 *buf;
264         int retval;
265
266         urb = usb_alloc_urb(0, GFP_ATOMIC);
267         if (!urb)
268                 return -ENOMEM;
269
270         dr = kmalloc(sizeof(*dr) + size, GFP_ATOMIC);
271         if (!dr) {
272                 usb_free_urb(urb);
273                 return -ENOMEM;
274         }
275
276         buf = (u8 *)dr + sizeof(*dr);
277         memcpy(buf, req, size);
278
279         dr->bRequest = cmd;
280         dr->bRequestType = USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE;
281         dr->wValue = 0;
282         dr->wIndex = 0;
283         dr->wLength = cpu_to_le16(size);
284
285         usb_fill_control_urb(urb, udev, usb_sndctrlpipe(udev, 0),
286                              (unsigned char *)dr, buf, size,
287                              ap_urb_complete, dr);
288         retval = usb_submit_urb(urb, GFP_ATOMIC);
289         if (retval) {
290                 usb_free_urb(urb);
291                 kfree(dr);
292         }
293         return retval;
294 }
295
296 static int output(struct gb_host_device *hd, void *req, u16 size, u8 cmd,
297                      bool async)
298 {
299         struct es2_ap_dev *es2 = hd_to_es2(hd);
300
301         if (async)
302                 return output_async(es2, req, size, cmd);
303
304         return output_sync(es2, req, size, cmd);
305 }
306
307 static int es2_cport_in_enable(struct es2_ap_dev *es2,
308                                 struct es2_cport_in *cport_in)
309 {
310         struct urb *urb;
311         int ret;
312         int i;
313
314         for (i = 0; i < NUM_CPORT_IN_URB; ++i) {
315                 urb = cport_in->urb[i];
316
317                 ret = usb_submit_urb(urb, GFP_KERNEL);
318                 if (ret) {
319                         dev_err(&es2->usb_dev->dev,
320                                         "failed to submit in-urb: %d\n", ret);
321                         goto err_kill_urbs;
322                 }
323         }
324
325         return 0;
326
327 err_kill_urbs:
328         for (--i; i >= 0; --i) {
329                 urb = cport_in->urb[i];
330                 usb_kill_urb(urb);
331         }
332
333         return ret;
334 }
335
336 static void es2_cport_in_disable(struct es2_ap_dev *es2,
337                                 struct es2_cport_in *cport_in)
338 {
339         struct urb *urb;
340         int i;
341
342         for (i = 0; i < NUM_CPORT_IN_URB; ++i) {
343                 urb = cport_in->urb[i];
344                 usb_kill_urb(urb);
345         }
346 }
347
348 static struct urb *next_free_urb(struct es2_ap_dev *es2, gfp_t gfp_mask)
349 {
350         struct urb *urb = NULL;
351         unsigned long flags;
352         int i;
353
354         spin_lock_irqsave(&es2->cport_out_urb_lock, flags);
355
356         /* Look in our pool of allocated urbs first, as that's the "fastest" */
357         for (i = 0; i < NUM_CPORT_OUT_URB; ++i) {
358                 if (es2->cport_out_urb_busy[i] == false &&
359                                 es2->cport_out_urb_cancelled[i] == false) {
360                         es2->cport_out_urb_busy[i] = true;
361                         urb = es2->cport_out_urb[i];
362                         break;
363                 }
364         }
365         spin_unlock_irqrestore(&es2->cport_out_urb_lock, flags);
366         if (urb)
367                 return urb;
368
369         /*
370          * Crap, pool is empty, complain to the syslog and go allocate one
371          * dynamically as we have to succeed.
372          */
373         dev_dbg(&es2->usb_dev->dev,
374                 "No free CPort OUT urbs, having to dynamically allocate one!\n");
375         return usb_alloc_urb(0, gfp_mask);
376 }
377
378 static void free_urb(struct es2_ap_dev *es2, struct urb *urb)
379 {
380         unsigned long flags;
381         int i;
382         /*
383          * See if this was an urb in our pool, if so mark it "free", otherwise
384          * we need to free it ourselves.
385          */
386         spin_lock_irqsave(&es2->cport_out_urb_lock, flags);
387         for (i = 0; i < NUM_CPORT_OUT_URB; ++i) {
388                 if (urb == es2->cport_out_urb[i]) {
389                         es2->cport_out_urb_busy[i] = false;
390                         urb = NULL;
391                         break;
392                 }
393         }
394         spin_unlock_irqrestore(&es2->cport_out_urb_lock, flags);
395
396         /* If urb is not NULL, then we need to free this urb */
397         usb_free_urb(urb);
398 }
399
400 /*
401  * We (ab)use the operation-message header pad bytes to transfer the
402  * cport id in order to minimise overhead.
403  */
404 static void
405 gb_message_cport_pack(struct gb_operation_msg_hdr *header, u16 cport_id)
406 {
407         header->pad[0] = cport_id;
408 }
409
410 /* Clear the pad bytes used for the CPort id */
411 static void gb_message_cport_clear(struct gb_operation_msg_hdr *header)
412 {
413         header->pad[0] = 0;
414 }
415
416 /* Extract the CPort id packed into the header, and clear it */
417 static u16 gb_message_cport_unpack(struct gb_operation_msg_hdr *header)
418 {
419         u16 cport_id = header->pad[0];
420
421         gb_message_cport_clear(header);
422
423         return cport_id;
424 }
425
426 /*
427  * Returns zero if the message was successfully queued, or a negative errno
428  * otherwise.
429  */
430 static int message_send(struct gb_host_device *hd, u16 cport_id,
431                         struct gb_message *message, gfp_t gfp_mask)
432 {
433         struct es2_ap_dev *es2 = hd_to_es2(hd);
434         struct usb_device *udev = es2->usb_dev;
435         size_t buffer_size;
436         int retval;
437         struct urb *urb;
438         int ep_pair;
439         unsigned long flags;
440
441         /*
442          * The data actually transferred will include an indication
443          * of where the data should be sent.  Do one last check of
444          * the target CPort id before filling it in.
445          */
446         if (!cport_id_valid(hd, cport_id)) {
447                 dev_err(&udev->dev, "invalid cport %u\n", cport_id);
448                 return -EINVAL;
449         }
450
451         /* Find a free urb */
452         urb = next_free_urb(es2, gfp_mask);
453         if (!urb)
454                 return -ENOMEM;
455
456         spin_lock_irqsave(&es2->cport_out_urb_lock, flags);
457         message->hcpriv = urb;
458         spin_unlock_irqrestore(&es2->cport_out_urb_lock, flags);
459
460         /* Pack the cport id into the message header */
461         gb_message_cport_pack(message->header, cport_id);
462
463         buffer_size = sizeof(*message->header) + message->payload_size;
464
465         ep_pair = cport_to_ep_pair(es2, cport_id);
466         usb_fill_bulk_urb(urb, udev,
467                           usb_sndbulkpipe(udev,
468                                           es2->cport_out[ep_pair].endpoint),
469                           message->buffer, buffer_size,
470                           cport_out_callback, message);
471         urb->transfer_flags |= URB_ZERO_PACKET;
472         trace_gb_host_device_send(hd, cport_id, buffer_size);
473         retval = usb_submit_urb(urb, gfp_mask);
474         if (retval) {
475                 dev_err(&udev->dev, "failed to submit out-urb: %d\n", retval);
476
477                 spin_lock_irqsave(&es2->cport_out_urb_lock, flags);
478                 message->hcpriv = NULL;
479                 spin_unlock_irqrestore(&es2->cport_out_urb_lock, flags);
480
481                 free_urb(es2, urb);
482                 gb_message_cport_clear(message->header);
483
484                 return retval;
485         }
486
487         return 0;
488 }
489
490 /*
491  * Can not be called in atomic context.
492  */
493 static void message_cancel(struct gb_message *message)
494 {
495         struct gb_host_device *hd = message->operation->connection->hd;
496         struct es2_ap_dev *es2 = hd_to_es2(hd);
497         struct urb *urb;
498         int i;
499
500         might_sleep();
501
502         spin_lock_irq(&es2->cport_out_urb_lock);
503         urb = message->hcpriv;
504
505         /* Prevent dynamically allocated urb from being deallocated. */
506         usb_get_urb(urb);
507
508         /* Prevent pre-allocated urb from being reused. */
509         for (i = 0; i < NUM_CPORT_OUT_URB; ++i) {
510                 if (urb == es2->cport_out_urb[i]) {
511                         es2->cport_out_urb_cancelled[i] = true;
512                         break;
513                 }
514         }
515         spin_unlock_irq(&es2->cport_out_urb_lock);
516
517         usb_kill_urb(urb);
518
519         if (i < NUM_CPORT_OUT_URB) {
520                 spin_lock_irq(&es2->cport_out_urb_lock);
521                 es2->cport_out_urb_cancelled[i] = false;
522                 spin_unlock_irq(&es2->cport_out_urb_lock);
523         }
524
525         usb_free_urb(urb);
526 }
527
528 static int cport_reset(struct gb_host_device *hd, u16 cport_id)
529 {
530         struct es2_ap_dev *es2 = hd_to_es2(hd);
531         struct usb_device *udev = es2->usb_dev;
532         int retval;
533
534         switch (cport_id) {
535         case GB_SVC_CPORT_ID:
536         case ES2_CPORT_CDSI0:
537         case ES2_CPORT_CDSI1:
538                 return 0;
539         }
540
541         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
542                                  GB_APB_REQUEST_RESET_CPORT,
543                                  USB_DIR_OUT | USB_TYPE_VENDOR |
544                                  USB_RECIP_INTERFACE, cport_id, 0,
545                                  NULL, 0, ES2_TIMEOUT);
546         if (retval < 0) {
547                 dev_err(&udev->dev, "failed to reset cport %u: %d\n", cport_id,
548                         retval);
549                 return retval;
550         }
551
552         return 0;
553 }
554
555 static int es2_cport_allocate(struct gb_host_device *hd, int cport_id,
556                                 unsigned long flags)
557 {
558         struct es2_ap_dev *es2 = hd_to_es2(hd);
559         struct ida *id_map = &hd->cport_id_map;
560         int ida_start, ida_end;
561
562         switch (cport_id) {
563         case ES2_CPORT_CDSI0:
564         case ES2_CPORT_CDSI1:
565                 dev_err(&hd->dev, "cport %d not available\n", cport_id);
566                 return -EBUSY;
567         }
568
569         if (flags & GB_CONNECTION_FLAG_OFFLOADED &&
570                         flags & GB_CONNECTION_FLAG_CDSI1) {
571                 if (es2->cdsi1_in_use) {
572                         dev_err(&hd->dev, "CDSI1 already in use\n");
573                         return -EBUSY;
574                 }
575
576                 es2->cdsi1_in_use = true;
577
578                 return ES2_CPORT_CDSI1;
579         }
580
581         if (cport_id < 0) {
582                 ida_start = 0;
583                 ida_end = hd->num_cports;
584         } else if (cport_id < hd->num_cports) {
585                 ida_start = cport_id;
586                 ida_end = cport_id + 1;
587         } else {
588                 dev_err(&hd->dev, "cport %d not available\n", cport_id);
589                 return -EINVAL;
590         }
591
592         return ida_simple_get(id_map, ida_start, ida_end, GFP_KERNEL);
593 }
594
595 static void es2_cport_release(struct gb_host_device *hd, u16 cport_id)
596 {
597         struct es2_ap_dev *es2 = hd_to_es2(hd);
598
599         switch (cport_id) {
600         case ES2_CPORT_CDSI1:
601                 es2->cdsi1_in_use = false;
602                 return;
603         }
604
605         ida_simple_remove(&hd->cport_id_map, cport_id);
606 }
607
608 static int cport_enable(struct gb_host_device *hd, u16 cport_id)
609 {
610         int retval;
611
612         retval = cport_reset(hd, cport_id);
613         if (retval)
614                 return retval;
615
616         return 0;
617 }
618
619 static int latency_tag_enable(struct gb_host_device *hd, u16 cport_id)
620 {
621         int retval;
622         struct es2_ap_dev *es2 = hd_to_es2(hd);
623         struct usb_device *udev = es2->usb_dev;
624
625         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
626                                  GB_APB_REQUEST_LATENCY_TAG_EN,
627                                  USB_DIR_OUT | USB_TYPE_VENDOR |
628                                  USB_RECIP_INTERFACE, cport_id, 0, NULL,
629                                  0, ES2_TIMEOUT);
630
631         if (retval < 0)
632                 dev_err(&udev->dev, "Cannot enable latency tag for cport %d\n",
633                         cport_id);
634         return retval;
635 }
636
637 static int latency_tag_disable(struct gb_host_device *hd, u16 cport_id)
638 {
639         int retval;
640         struct es2_ap_dev *es2 = hd_to_es2(hd);
641         struct usb_device *udev = es2->usb_dev;
642
643         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
644                                  GB_APB_REQUEST_LATENCY_TAG_DIS,
645                                  USB_DIR_OUT | USB_TYPE_VENDOR |
646                                  USB_RECIP_INTERFACE, cport_id, 0, NULL,
647                                  0, ES2_TIMEOUT);
648
649         if (retval < 0)
650                 dev_err(&udev->dev, "Cannot disable latency tag for cport %d\n",
651                         cport_id);
652         return retval;
653 }
654
655 static int cport_features_enable(struct gb_host_device *hd, u16 cport_id)
656 {
657         int retval;
658         struct es2_ap_dev *es2 = hd_to_es2(hd);
659         struct usb_device *udev = es2->usb_dev;
660
661         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
662                                  GB_APB_REQUEST_CPORT_FEAT_EN,
663                                  USB_DIR_OUT | USB_TYPE_VENDOR |
664                                  USB_RECIP_INTERFACE, cport_id, 0, NULL,
665                                  0, ES2_TIMEOUT);
666         if (retval < 0)
667                 dev_err(&udev->dev, "Cannot enable CPort features for cport %u: %d\n",
668                         cport_id, retval);
669         return retval;
670 }
671
672 static int cport_features_disable(struct gb_host_device *hd, u16 cport_id)
673 {
674         int retval;
675         struct es2_ap_dev *es2 = hd_to_es2(hd);
676         struct usb_device *udev = es2->usb_dev;
677
678         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
679                                  GB_APB_REQUEST_CPORT_FEAT_DIS,
680                                  USB_DIR_OUT | USB_TYPE_VENDOR |
681                                  USB_RECIP_INTERFACE, cport_id, 0, NULL,
682                                  0, ES2_TIMEOUT);
683         if (retval < 0)
684                 dev_err(&udev->dev,
685                         "Cannot disable CPort features for cport %u: %d\n",
686                         cport_id, retval);
687         return retval;
688 }
689
690 static int timesync_enable(struct gb_host_device *hd, u8 count,
691                            u64 frame_time, u32 strobe_delay, u32 refclk)
692 {
693         int retval;
694         struct es2_ap_dev *es2 = hd_to_es2(hd);
695         struct usb_device *udev = es2->usb_dev;
696         struct gb_control_timesync_enable_request *request;
697
698         request = kzalloc(sizeof(*request), GFP_KERNEL);
699         if (!request)
700                 return -ENOMEM;
701
702         request->count = count;
703         request->frame_time = cpu_to_le64(frame_time);
704         request->strobe_delay = cpu_to_le32(strobe_delay);
705         request->refclk = cpu_to_le32(refclk);
706         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
707                                  REQUEST_TIMESYNC_ENABLE,
708                                  USB_DIR_OUT | USB_TYPE_VENDOR |
709                                  USB_RECIP_INTERFACE, 0, 0, request,
710                                  sizeof(*request), ES2_TIMEOUT);
711         if (retval < 0)
712                 dev_err(&udev->dev, "Cannot enable timesync %d\n", retval);
713
714         kfree(request);
715         return retval;
716 }
717
718 static int timesync_disable(struct gb_host_device *hd)
719 {
720         int retval;
721         struct es2_ap_dev *es2 = hd_to_es2(hd);
722         struct usb_device *udev = es2->usb_dev;
723
724         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
725                                  REQUEST_TIMESYNC_DISABLE,
726                                  USB_DIR_OUT | USB_TYPE_VENDOR |
727                                  USB_RECIP_INTERFACE, 0, 0, NULL,
728                                  0, ES2_TIMEOUT);
729         if (retval < 0)
730                 dev_err(&udev->dev, "Cannot disable timesync %d\n", retval);
731
732         return retval;
733 }
734
735 static int timesync_authoritative(struct gb_host_device *hd, u64 *frame_time)
736 {
737         int retval, i;
738         struct es2_ap_dev *es2 = hd_to_es2(hd);
739         struct usb_device *udev = es2->usb_dev;
740         struct timesync_authoritative_request *request;
741
742         request = kzalloc(sizeof(*request), GFP_KERNEL);
743         if (!request)
744                 return -ENOMEM;
745
746         for (i = 0; i < GB_TIMESYNC_MAX_STROBES; i++)
747                 request->frame_time[i] = cpu_to_le64(frame_time[i]);
748
749         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
750                                  REQUEST_TIMESYNC_AUTHORITATIVE,
751                                  USB_DIR_OUT | USB_TYPE_VENDOR |
752                                  USB_RECIP_INTERFACE, 0, 0, request,
753                                  sizeof(*request), ES2_TIMEOUT);
754         if (retval < 0)
755                 dev_err(&udev->dev, "Cannot timesync authoritative out %d\n", retval);
756
757         kfree(request);
758         return retval;
759 }
760
761 static int timesync_get_last_event(struct gb_host_device *hd, u64 *frame_time)
762 {
763         int retval;
764         struct es2_ap_dev *es2 = hd_to_es2(hd);
765         struct usb_device *udev = es2->usb_dev;
766         __le64 *response_frame_time;
767
768         response_frame_time = kzalloc(sizeof(*response_frame_time), GFP_KERNEL);
769         if (!response_frame_time)
770                 return -ENOMEM;
771
772         retval = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
773                                  REQUEST_TIMESYNC_GET_LAST_EVENT,
774                                  USB_DIR_IN | USB_TYPE_VENDOR |
775                                  USB_RECIP_INTERFACE, 0, 0, response_frame_time,
776                                  sizeof(*response_frame_time), ES2_TIMEOUT);
777
778         if (retval != sizeof(*response_frame_time)) {
779                 dev_err(&udev->dev, "Cannot get last TimeSync event: %d\n",
780                         retval);
781
782                 if (retval >= 0)
783                         retval = -EIO;
784
785                 goto out;
786         }
787         *frame_time = le64_to_cpu(*response_frame_time);
788         retval = 0;
789 out:
790         kfree(response_frame_time);
791         return retval;
792 }
793
794 static struct gb_hd_driver es2_driver = {
795         .hd_priv_size                   = sizeof(struct es2_ap_dev),
796         .message_send                   = message_send,
797         .message_cancel                 = message_cancel,
798         .cport_allocate                 = es2_cport_allocate,
799         .cport_release                  = es2_cport_release,
800         .cport_enable                   = cport_enable,
801         .latency_tag_enable             = latency_tag_enable,
802         .latency_tag_disable            = latency_tag_disable,
803         .output                         = output,
804         .cport_features_enable          = cport_features_enable,
805         .cport_features_disable         = cport_features_disable,
806         .timesync_enable                = timesync_enable,
807         .timesync_disable               = timesync_disable,
808         .timesync_authoritative         = timesync_authoritative,
809         .timesync_get_last_event        = timesync_get_last_event,
810 };
811
812 /* Common function to report consistent warnings based on URB status */
813 static int check_urb_status(struct urb *urb)
814 {
815         struct device *dev = &urb->dev->dev;
816         int status = urb->status;
817
818         switch (status) {
819         case 0:
820                 return 0;
821
822         case -EOVERFLOW:
823                 dev_err(dev, "%s: overflow actual length is %d\n",
824                         __func__, urb->actual_length);
825         case -ECONNRESET:
826         case -ENOENT:
827         case -ESHUTDOWN:
828         case -EILSEQ:
829         case -EPROTO:
830                 /* device is gone, stop sending */
831                 return status;
832         }
833         dev_err(dev, "%s: unknown status %d\n", __func__, status);
834
835         return -EAGAIN;
836 }
837
838 static void es2_destroy(struct es2_ap_dev *es2)
839 {
840         struct usb_device *udev;
841         int bulk_in;
842         int i;
843
844         debugfs_remove(es2->apb_log_enable_dentry);
845         usb_log_disable(es2);
846
847         /* Tear down everything! */
848         for (i = 0; i < NUM_CPORT_OUT_URB; ++i) {
849                 struct urb *urb = es2->cport_out_urb[i];
850
851                 if (!urb)
852                         break;
853                 usb_kill_urb(urb);
854                 usb_free_urb(urb);
855                 es2->cport_out_urb[i] = NULL;
856                 es2->cport_out_urb_busy[i] = false;     /* just to be anal */
857         }
858
859         for (bulk_in = 0; bulk_in < NUM_BULKS; bulk_in++) {
860                 struct es2_cport_in *cport_in = &es2->cport_in[bulk_in];
861
862                 for (i = 0; i < NUM_CPORT_IN_URB; ++i) {
863                         struct urb *urb = cport_in->urb[i];
864
865                         if (!urb)
866                                 break;
867                         usb_free_urb(urb);
868                         kfree(cport_in->buffer[i]);
869                         cport_in->buffer[i] = NULL;
870                 }
871         }
872
873         kfree(es2->cport_to_ep);
874
875         udev = es2->usb_dev;
876         gb_hd_put(es2->hd);
877
878         usb_put_dev(udev);
879 }
880
881 static void cport_in_callback(struct urb *urb)
882 {
883         struct gb_host_device *hd = urb->context;
884         struct device *dev = &urb->dev->dev;
885         struct gb_operation_msg_hdr *header;
886         int status = check_urb_status(urb);
887         int retval;
888         u16 cport_id;
889
890         if (status) {
891                 if ((status == -EAGAIN) || (status == -EPROTO))
892                         goto exit;
893
894                 /* The urb is being unlinked */
895                 if (status == -ENOENT || status == -ESHUTDOWN)
896                         return;
897
898                 dev_err(dev, "urb cport in error %d (dropped)\n", status);
899                 return;
900         }
901
902         if (urb->actual_length < sizeof(*header)) {
903                 dev_err(dev, "short message received\n");
904                 goto exit;
905         }
906
907         /* Extract the CPort id, which is packed in the message header */
908         header = urb->transfer_buffer;
909         cport_id = gb_message_cport_unpack(header);
910
911         if (cport_id_valid(hd, cport_id)) {
912                 trace_gb_host_device_recv(hd, cport_id, urb->actual_length);
913                 greybus_data_rcvd(hd, cport_id, urb->transfer_buffer,
914                                                         urb->actual_length);
915         } else {
916                 dev_err(dev, "invalid cport id %u received\n", cport_id);
917         }
918 exit:
919         /* put our urb back in the request pool */
920         retval = usb_submit_urb(urb, GFP_ATOMIC);
921         if (retval)
922                 dev_err(dev, "failed to resubmit in-urb: %d\n", retval);
923 }
924
925 static void cport_out_callback(struct urb *urb)
926 {
927         struct gb_message *message = urb->context;
928         struct gb_host_device *hd = message->operation->connection->hd;
929         struct es2_ap_dev *es2 = hd_to_es2(hd);
930         int status = check_urb_status(urb);
931         unsigned long flags;
932
933         gb_message_cport_clear(message->header);
934
935         spin_lock_irqsave(&es2->cport_out_urb_lock, flags);
936         message->hcpriv = NULL;
937         spin_unlock_irqrestore(&es2->cport_out_urb_lock, flags);
938
939         /*
940          * Tell the submitter that the message send (attempt) is
941          * complete, and report the status.
942          */
943         greybus_message_sent(hd, message, status);
944
945         free_urb(es2, urb);
946 }
947
948 #define APB1_LOG_MSG_SIZE       64
949 static void apb_log_get(struct es2_ap_dev *es2, char *buf)
950 {
951         int retval;
952
953         /* SVC messages go down our control pipe */
954         do {
955                 retval = usb_control_msg(es2->usb_dev,
956                                         usb_rcvctrlpipe(es2->usb_dev, 0),
957                                         GB_APB_REQUEST_LOG,
958                                         USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
959                                         0x00, 0x00,
960                                         buf,
961                                         APB1_LOG_MSG_SIZE,
962                                         ES2_TIMEOUT);
963                 if (retval > 0)
964                         kfifo_in(&es2->apb_log_fifo, buf, retval);
965         } while (retval > 0);
966 }
967
968 static int apb_log_poll(void *data)
969 {
970         struct es2_ap_dev *es2 = data;
971         char *buf;
972
973         buf = kmalloc(APB1_LOG_MSG_SIZE, GFP_KERNEL);
974         if (!buf)
975                 return -ENOMEM;
976
977         while (!kthread_should_stop()) {
978                 msleep(1000);
979                 apb_log_get(es2, buf);
980         }
981
982         kfree(buf);
983
984         return 0;
985 }
986
987 static ssize_t apb_log_read(struct file *f, char __user *buf,
988                                 size_t count, loff_t *ppos)
989 {
990         struct es2_ap_dev *es2 = f->f_inode->i_private;
991         ssize_t ret;
992         size_t copied;
993         char *tmp_buf;
994
995         if (count > APB1_LOG_SIZE)
996                 count = APB1_LOG_SIZE;
997
998         tmp_buf = kmalloc(count, GFP_KERNEL);
999         if (!tmp_buf)
1000                 return -ENOMEM;
1001
1002         copied = kfifo_out(&es2->apb_log_fifo, tmp_buf, count);
1003         ret = simple_read_from_buffer(buf, count, ppos, tmp_buf, copied);
1004
1005         kfree(tmp_buf);
1006
1007         return ret;
1008 }
1009
1010 static const struct file_operations apb_log_fops = {
1011         .read   = apb_log_read,
1012 };
1013
1014 static void usb_log_enable(struct es2_ap_dev *es2)
1015 {
1016         if (!IS_ERR_OR_NULL(es2->apb_log_task))
1017                 return;
1018
1019         /* get log from APB1 */
1020         es2->apb_log_task = kthread_run(apb_log_poll, es2, "apb_log");
1021         if (IS_ERR(es2->apb_log_task))
1022                 return;
1023         /* XXX We will need to rename this per APB */
1024         es2->apb_log_dentry = debugfs_create_file("apb_log", S_IRUGO,
1025                                                 gb_debugfs_get(), es2,
1026                                                 &apb_log_fops);
1027 }
1028
1029 static void usb_log_disable(struct es2_ap_dev *es2)
1030 {
1031         if (IS_ERR_OR_NULL(es2->apb_log_task))
1032                 return;
1033
1034         debugfs_remove(es2->apb_log_dentry);
1035         es2->apb_log_dentry = NULL;
1036
1037         kthread_stop(es2->apb_log_task);
1038         es2->apb_log_task = NULL;
1039 }
1040
1041 static ssize_t apb_log_enable_read(struct file *f, char __user *buf,
1042                                 size_t count, loff_t *ppos)
1043 {
1044         struct es2_ap_dev *es2 = f->f_inode->i_private;
1045         int enable = !IS_ERR_OR_NULL(es2->apb_log_task);
1046         char tmp_buf[3];
1047
1048         sprintf(tmp_buf, "%d\n", enable);
1049         return simple_read_from_buffer(buf, count, ppos, tmp_buf, 3);
1050 }
1051
1052 static ssize_t apb_log_enable_write(struct file *f, const char __user *buf,
1053                                 size_t count, loff_t *ppos)
1054 {
1055         int enable;
1056         ssize_t retval;
1057         struct es2_ap_dev *es2 = f->f_inode->i_private;
1058
1059         retval = kstrtoint_from_user(buf, count, 10, &enable);
1060         if (retval)
1061                 return retval;
1062
1063         if (enable)
1064                 usb_log_enable(es2);
1065         else
1066                 usb_log_disable(es2);
1067
1068         return count;
1069 }
1070
1071 static const struct file_operations apb_log_enable_fops = {
1072         .read   = apb_log_enable_read,
1073         .write  = apb_log_enable_write,
1074 };
1075
1076 static int apb_get_cport_count(struct usb_device *udev)
1077 {
1078         int retval;
1079         __le16 *cport_count;
1080
1081         cport_count = kzalloc(sizeof(*cport_count), GFP_KERNEL);
1082         if (!cport_count)
1083                 return -ENOMEM;
1084
1085         retval = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
1086                                  GB_APB_REQUEST_CPORT_COUNT,
1087                                  USB_DIR_IN | USB_TYPE_VENDOR |
1088                                  USB_RECIP_INTERFACE, 0, 0, cport_count,
1089                                  sizeof(*cport_count), ES2_TIMEOUT);
1090         if (retval != sizeof(*cport_count)) {
1091                 dev_err(&udev->dev, "Cannot retrieve CPort count: %d\n",
1092                         retval);
1093
1094                 if (retval >= 0)
1095                         retval = -EIO;
1096
1097                 goto out;
1098         }
1099
1100         retval = le16_to_cpu(*cport_count);
1101
1102         /* We need to fit a CPort ID in one byte of a message header */
1103         if (retval > U8_MAX) {
1104                 retval = U8_MAX;
1105                 dev_warn(&udev->dev, "Limiting number of CPorts to U8_MAX\n");
1106         }
1107
1108 out:
1109         kfree(cport_count);
1110         return retval;
1111 }
1112
1113 /*
1114  * The ES2 USB Bridge device has 15 endpoints
1115  * 1 Control - usual USB stuff + AP -> APBridgeA messages
1116  * 7 Bulk IN - CPort data in
1117  * 7 Bulk OUT - CPort data out
1118  */
1119 static int ap_probe(struct usb_interface *interface,
1120                     const struct usb_device_id *id)
1121 {
1122         struct es2_ap_dev *es2;
1123         struct gb_host_device *hd;
1124         struct usb_device *udev;
1125         struct usb_host_interface *iface_desc;
1126         struct usb_endpoint_descriptor *endpoint;
1127         int bulk_in = 0;
1128         int bulk_out = 0;
1129         int retval;
1130         int i;
1131         int num_cports;
1132
1133         udev = usb_get_dev(interface_to_usbdev(interface));
1134
1135         num_cports = apb_get_cport_count(udev);
1136         if (num_cports < 0) {
1137                 usb_put_dev(udev);
1138                 dev_err(&udev->dev, "Cannot retrieve CPort count: %d\n",
1139                         num_cports);
1140                 return num_cports;
1141         }
1142
1143         hd = gb_hd_create(&es2_driver, &udev->dev, ES2_GBUF_MSG_SIZE_MAX,
1144                                 num_cports);
1145         if (IS_ERR(hd)) {
1146                 usb_put_dev(udev);
1147                 return PTR_ERR(hd);
1148         }
1149
1150         es2 = hd_to_es2(hd);
1151         es2->hd = hd;
1152         es2->usb_intf = interface;
1153         es2->usb_dev = udev;
1154         spin_lock_init(&es2->cport_out_urb_lock);
1155         INIT_KFIFO(es2->apb_log_fifo);
1156         usb_set_intfdata(interface, es2);
1157
1158         /*
1159          * Reserve the CDSI0 and CDSI1 CPorts so they won't be allocated
1160          * dynamically.
1161          */
1162         retval = gb_hd_cport_reserve(hd, ES2_CPORT_CDSI0);
1163         if (retval)
1164                 goto error;
1165         retval = gb_hd_cport_reserve(hd, ES2_CPORT_CDSI1);
1166         if (retval)
1167                 goto error;
1168
1169         es2->cport_to_ep = kcalloc(hd->num_cports, sizeof(*es2->cport_to_ep),
1170                                    GFP_KERNEL);
1171         if (!es2->cport_to_ep) {
1172                 retval = -ENOMEM;
1173                 goto error;
1174         }
1175
1176         /* find all bulk endpoints */
1177         iface_desc = interface->cur_altsetting;
1178         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
1179                 endpoint = &iface_desc->endpoint[i].desc;
1180
1181                 if (usb_endpoint_is_bulk_in(endpoint)) {
1182                         es2->cport_in[bulk_in++].endpoint =
1183                                 endpoint->bEndpointAddress;
1184                 } else if (usb_endpoint_is_bulk_out(endpoint)) {
1185                         es2->cport_out[bulk_out++].endpoint =
1186                                 endpoint->bEndpointAddress;
1187                 } else {
1188                         dev_err(&udev->dev,
1189                                 "Unknown endpoint type found, address 0x%02x\n",
1190                                 endpoint->bEndpointAddress);
1191                 }
1192         }
1193         if (bulk_in != NUM_BULKS || bulk_out != NUM_BULKS) {
1194                 dev_err(&udev->dev, "Not enough endpoints found in device, aborting!\n");
1195                 retval = -ENODEV;
1196                 goto error;
1197         }
1198
1199         /* Allocate buffers for our cport in messages */
1200         for (bulk_in = 0; bulk_in < NUM_BULKS; bulk_in++) {
1201                 struct es2_cport_in *cport_in = &es2->cport_in[bulk_in];
1202
1203                 for (i = 0; i < NUM_CPORT_IN_URB; ++i) {
1204                         struct urb *urb;
1205                         u8 *buffer;
1206
1207                         urb = usb_alloc_urb(0, GFP_KERNEL);
1208                         if (!urb) {
1209                                 retval = -ENOMEM;
1210                                 goto error;
1211                         }
1212                         buffer = kmalloc(ES2_GBUF_MSG_SIZE_MAX, GFP_KERNEL);
1213                         if (!buffer) {
1214                                 retval = -ENOMEM;
1215                                 goto error;
1216                         }
1217
1218                         usb_fill_bulk_urb(urb, udev,
1219                                           usb_rcvbulkpipe(udev,
1220                                                           cport_in->endpoint),
1221                                           buffer, ES2_GBUF_MSG_SIZE_MAX,
1222                                           cport_in_callback, hd);
1223                         cport_in->urb[i] = urb;
1224                         cport_in->buffer[i] = buffer;
1225                 }
1226         }
1227
1228         /* Allocate urbs for our CPort OUT messages */
1229         for (i = 0; i < NUM_CPORT_OUT_URB; ++i) {
1230                 struct urb *urb;
1231
1232                 urb = usb_alloc_urb(0, GFP_KERNEL);
1233                 if (!urb) {
1234                         retval = -ENOMEM;
1235                         goto error;
1236                 }
1237
1238                 es2->cport_out_urb[i] = urb;
1239                 es2->cport_out_urb_busy[i] = false;     /* just to be anal */
1240         }
1241
1242         /* XXX We will need to rename this per APB */
1243         es2->apb_log_enable_dentry = debugfs_create_file("apb_log_enable",
1244                                                         (S_IWUSR | S_IRUGO),
1245                                                         gb_debugfs_get(), es2,
1246                                                         &apb_log_enable_fops);
1247
1248         retval = gb_hd_add(hd);
1249         if (retval)
1250                 goto error;
1251
1252         for (i = 0; i < NUM_BULKS; ++i) {
1253                 retval = es2_cport_in_enable(es2, &es2->cport_in[i]);
1254                 if (retval)
1255                         goto err_disable_cport_in;
1256         }
1257
1258         return 0;
1259
1260 err_disable_cport_in:
1261         for (--i; i >= 0; --i)
1262                 es2_cport_in_disable(es2, &es2->cport_in[i]);
1263         gb_hd_del(hd);
1264 error:
1265         es2_destroy(es2);
1266
1267         return retval;
1268 }
1269
1270 static void ap_disconnect(struct usb_interface *interface)
1271 {
1272         struct es2_ap_dev *es2 = usb_get_intfdata(interface);
1273         int i;
1274
1275         gb_hd_del(es2->hd);
1276
1277         for (i = 0; i < NUM_BULKS; ++i)
1278                 es2_cport_in_disable(es2, &es2->cport_in[i]);
1279
1280         es2_destroy(es2);
1281 }
1282
1283 static struct usb_driver es2_ap_driver = {
1284         .name =         "es2_ap_driver",
1285         .probe =        ap_probe,
1286         .disconnect =   ap_disconnect,
1287         .id_table =     id_table,
1288         .soft_unbind =  1,
1289 };
1290
1291 module_usb_driver(es2_ap_driver);
1292
1293 MODULE_LICENSE("GPL v2");
1294 MODULE_AUTHOR("Greg Kroah-Hartman <gregkh@linuxfoundation.org>");