955b37d0c4c66e9a8261add25026b1a7a3195ac5
[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 <linux/list.h>
15 #include <asm/unaligned.h>
16
17 #include "arpc.h"
18 #include "greybus.h"
19 #include "greybus_trace.h"
20 #include "kernel_ver.h"
21 #include "connection.h"
22
23
24 /* Default timeout for USB vendor requests. */
25 #define ES2_USB_CTRL_TIMEOUT    500
26
27 /* Default timeout for ARPC CPort requests */
28 #define ES2_ARPC_CPORT_TIMEOUT  500
29
30 /* Fixed CPort numbers */
31 #define ES2_CPORT_CDSI0         16
32 #define ES2_CPORT_CDSI1         17
33
34 /* Memory sizes for the buffers sent to/from the ES2 controller */
35 #define ES2_GBUF_MSG_SIZE_MAX   2048
36
37 /* Memory sizes for the ARPC buffers */
38 #define ARPC_OUT_SIZE_MAX       U16_MAX
39 #define ARPC_IN_SIZE_MAX        128
40
41 static const struct usb_device_id id_table[] = {
42         { USB_DEVICE(0x18d1, 0x1eaf) },
43         { },
44 };
45 MODULE_DEVICE_TABLE(usb, id_table);
46
47 #define APB1_LOG_SIZE           SZ_16K
48
49 /* Number of bulk in and bulk out couple */
50 #define NUM_BULKS               7
51
52 /* Expected number of bulk out endpoints */
53 #define NUM_BULKS_OUT           NUM_BULKS
54
55 /* Expected number of bulk in endpoints (including ARPC endpoint) */
56 #define NUM_BULKS_IN            (NUM_BULKS + 1)
57
58 /*
59  * Number of CPort IN urbs in flight at any point in time.
60  * Adjust if we are having stalls in the USB buffer due to not enough urbs in
61  * flight.
62  */
63 #define NUM_CPORT_IN_URB        4
64
65 /* Number of CPort OUT urbs in flight at any point in time.
66  * Adjust if we get messages saying we are out of urbs in the system log.
67  */
68 #define NUM_CPORT_OUT_URB       (8 * NUM_BULKS)
69
70 /*
71  * Number of ARPC in urbs in flight at any point in time.
72  */
73 #define NUM_ARPC_IN_URB         2
74
75 /*
76  * @endpoint: bulk in endpoint for CPort data
77  * @urb: array of urbs for the CPort in messages
78  * @buffer: array of buffers for the @cport_in_urb urbs
79  */
80 struct es2_cport_in {
81         __u8 endpoint;
82         struct urb *urb[NUM_CPORT_IN_URB];
83         u8 *buffer[NUM_CPORT_IN_URB];
84 };
85
86 /*
87  * @endpoint: bulk out endpoint for CPort data
88  */
89 struct es2_cport_out {
90         __u8 endpoint;
91 };
92
93 /**
94  * es2_ap_dev - ES2 USB Bridge to AP structure
95  * @usb_dev: pointer to the USB device we are.
96  * @usb_intf: pointer to the USB interface we are bound to.
97  * @hd: pointer to our gb_host_device structure
98
99  * @cport_in: endpoint, urbs and buffer for cport in messages
100  * @cport_out: endpoint for for cport out messages
101  * @cport_out_urb: array of urbs for the CPort out messages
102  * @cport_out_urb_busy: array of flags to see if the @cport_out_urb is busy or
103  *                      not.
104  * @cport_out_urb_cancelled: array of flags indicating whether the
105  *                      corresponding @cport_out_urb is being cancelled
106  * @cport_out_urb_lock: locks the @cport_out_urb_busy "list"
107  *
108  * @apb_log_task: task pointer for logging thread
109  * @apb_log_dentry: file system entry for the log file interface
110  * @apb_log_enable_dentry: file system entry for enabling logging
111  * @apb_log_fifo: kernel FIFO to carry logged data
112  * @arpc_urb: array of urbs for the ARPC in messages
113  * @arpc_buffer: array of buffers for the @arpc_urb urbs
114  * @arpc_endpoint_in: bulk in endpoint for APBridgeA RPC
115  * @arpc_id_cycle: gives an unique id to ARPC
116  * @arpc_lock: locks ARPC list
117  * @arpcs: list of in progress ARPCs
118  */
119 struct es2_ap_dev {
120         struct usb_device *usb_dev;
121         struct usb_interface *usb_intf;
122         struct gb_host_device *hd;
123
124         struct es2_cport_in cport_in[NUM_BULKS];
125         struct es2_cport_out cport_out[NUM_BULKS];
126         struct urb *cport_out_urb[NUM_CPORT_OUT_URB];
127         bool cport_out_urb_busy[NUM_CPORT_OUT_URB];
128         bool cport_out_urb_cancelled[NUM_CPORT_OUT_URB];
129         spinlock_t cport_out_urb_lock;
130
131         bool cdsi1_in_use;
132
133         int *cport_to_ep;
134
135         struct task_struct *apb_log_task;
136         struct dentry *apb_log_dentry;
137         struct dentry *apb_log_enable_dentry;
138         DECLARE_KFIFO(apb_log_fifo, char, APB1_LOG_SIZE);
139
140         __u8 arpc_endpoint_in;
141         struct urb *arpc_urb[NUM_ARPC_IN_URB];
142         u8 *arpc_buffer[NUM_ARPC_IN_URB];
143
144         int arpc_id_cycle;
145         spinlock_t arpc_lock;
146         struct list_head arpcs;
147 };
148
149 /**
150  * cport_to_ep - information about cport to endpoints mapping
151  * @cport_id: the id of cport to map to endpoints
152  * @endpoint_in: the endpoint number to use for in transfer
153  * @endpoint_out: he endpoint number to use for out transfer
154  */
155 struct cport_to_ep {
156         __le16 cport_id;
157         __u8 endpoint_in;
158         __u8 endpoint_out;
159 };
160
161 /**
162  * timesync_enable_request - Enable timesync in an APBridge
163  * @count: number of TimeSync Pulses to expect
164  * @frame_time: the initial FrameTime at the first TimeSync Pulse
165  * @strobe_delay: the expected delay in microseconds between each TimeSync Pulse
166  * @refclk: The AP mandated reference clock to run FrameTime at
167  */
168 struct timesync_enable_request {
169         __u8    count;
170         __le64  frame_time;
171         __le32  strobe_delay;
172         __le32  refclk;
173 } __packed;
174
175 /**
176  * timesync_authoritative_request - Transmit authoritative FrameTime to APBridge
177  * @frame_time: An array of authoritative FrameTimes provided by the SVC
178  *              and relayed to the APBridge by the AP
179  */
180 struct timesync_authoritative_request {
181         __le64  frame_time[GB_TIMESYNC_MAX_STROBES];
182 } __packed;
183
184 struct arpc {
185         struct list_head list;
186         struct arpc_request_message *req;
187         struct arpc_response_message *resp;
188         struct completion response_received;
189         bool active;
190 };
191
192 static inline struct es2_ap_dev *hd_to_es2(struct gb_host_device *hd)
193 {
194         return (struct es2_ap_dev *)&hd->hd_priv;
195 }
196
197 static void cport_out_callback(struct urb *urb);
198 static void usb_log_enable(struct es2_ap_dev *es2);
199 static void usb_log_disable(struct es2_ap_dev *es2);
200 static int arpc_sync(struct es2_ap_dev *es2, u8 type, void *payload,
201                      size_t size, int *result, unsigned int timeout);
202
203 /* Get the endpoints pair mapped to the cport */
204 static int cport_to_ep_pair(struct es2_ap_dev *es2, u16 cport_id)
205 {
206         if (cport_id >= es2->hd->num_cports)
207                 return 0;
208         return es2->cport_to_ep[cport_id];
209 }
210
211 /* Disable for now until we work all of this out to keep a warning-free build */
212 #if 0
213 /* Test if the endpoints pair is already mapped to a cport */
214 static int ep_pair_in_use(struct es2_ap_dev *es2, int ep_pair)
215 {
216         int i;
217
218         for (i = 0; i < es2->hd->num_cports; i++) {
219                 if (es2->cport_to_ep[i] == ep_pair)
220                         return 1;
221         }
222         return 0;
223 }
224
225 /* Configure the endpoint mapping and send the request to APBridge */
226 static int map_cport_to_ep(struct es2_ap_dev *es2,
227                                 u16 cport_id, int ep_pair)
228 {
229         int retval;
230         struct cport_to_ep *cport_to_ep;
231
232         if (ep_pair < 0 || ep_pair >= NUM_BULKS)
233                 return -EINVAL;
234         if (cport_id >= es2->hd->num_cports)
235                 return -EINVAL;
236         if (ep_pair && ep_pair_in_use(es2, ep_pair))
237                 return -EINVAL;
238
239         cport_to_ep = kmalloc(sizeof(*cport_to_ep), GFP_KERNEL);
240         if (!cport_to_ep)
241                 return -ENOMEM;
242
243         es2->cport_to_ep[cport_id] = ep_pair;
244         cport_to_ep->cport_id = cpu_to_le16(cport_id);
245         cport_to_ep->endpoint_in = es2->cport_in[ep_pair].endpoint;
246         cport_to_ep->endpoint_out = es2->cport_out[ep_pair].endpoint;
247
248         retval = usb_control_msg(es2->usb_dev,
249                                  usb_sndctrlpipe(es2->usb_dev, 0),
250                                  GB_APB_REQUEST_EP_MAPPING,
251                                  USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
252                                  0x00, 0x00,
253                                  (char *)cport_to_ep,
254                                  sizeof(*cport_to_ep),
255                                  ES2_USB_CTRL_TIMEOUT);
256         if (retval == sizeof(*cport_to_ep))
257                 retval = 0;
258         kfree(cport_to_ep);
259
260         return retval;
261 }
262
263 /* Unmap a cport: use the muxed endpoints pair */
264 static int unmap_cport(struct es2_ap_dev *es2, u16 cport_id)
265 {
266         return map_cport_to_ep(es2, cport_id, 0);
267 }
268 #endif
269
270 static int output_sync(struct es2_ap_dev *es2, void *req, u16 size, u8 cmd)
271 {
272         struct usb_device *udev = es2->usb_dev;
273         u8 *data;
274         int retval;
275
276         data = kmalloc(size, GFP_KERNEL);
277         if (!data)
278                 return -ENOMEM;
279         memcpy(data, req, size);
280
281         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
282                                  cmd,
283                                  USB_DIR_OUT | USB_TYPE_VENDOR |
284                                  USB_RECIP_INTERFACE,
285                                  0, 0, data, size, ES2_USB_CTRL_TIMEOUT);
286         if (retval < 0)
287                 dev_err(&udev->dev, "%s: return error %d\n", __func__, retval);
288         else
289                 retval = 0;
290
291         kfree(data);
292         return retval;
293 }
294
295 static void ap_urb_complete(struct urb *urb)
296 {
297         struct usb_ctrlrequest *dr = urb->context;
298
299         kfree(dr);
300         usb_free_urb(urb);
301 }
302
303 static int output_async(struct es2_ap_dev *es2, void *req, u16 size, u8 cmd)
304 {
305         struct usb_device *udev = es2->usb_dev;
306         struct urb *urb;
307         struct usb_ctrlrequest *dr;
308         u8 *buf;
309         int retval;
310
311         urb = usb_alloc_urb(0, GFP_ATOMIC);
312         if (!urb)
313                 return -ENOMEM;
314
315         dr = kmalloc(sizeof(*dr) + size, GFP_ATOMIC);
316         if (!dr) {
317                 usb_free_urb(urb);
318                 return -ENOMEM;
319         }
320
321         buf = (u8 *)dr + sizeof(*dr);
322         memcpy(buf, req, size);
323
324         dr->bRequest = cmd;
325         dr->bRequestType = USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE;
326         dr->wValue = 0;
327         dr->wIndex = 0;
328         dr->wLength = cpu_to_le16(size);
329
330         usb_fill_control_urb(urb, udev, usb_sndctrlpipe(udev, 0),
331                              (unsigned char *)dr, buf, size,
332                              ap_urb_complete, dr);
333         retval = usb_submit_urb(urb, GFP_ATOMIC);
334         if (retval) {
335                 usb_free_urb(urb);
336                 kfree(dr);
337         }
338         return retval;
339 }
340
341 static int output(struct gb_host_device *hd, void *req, u16 size, u8 cmd,
342                      bool async)
343 {
344         struct es2_ap_dev *es2 = hd_to_es2(hd);
345
346         if (async)
347                 return output_async(es2, req, size, cmd);
348
349         return output_sync(es2, req, size, cmd);
350 }
351
352 static int es2_cport_in_enable(struct es2_ap_dev *es2,
353                                 struct es2_cport_in *cport_in)
354 {
355         struct urb *urb;
356         int ret;
357         int i;
358
359         for (i = 0; i < NUM_CPORT_IN_URB; ++i) {
360                 urb = cport_in->urb[i];
361
362                 ret = usb_submit_urb(urb, GFP_KERNEL);
363                 if (ret) {
364                         dev_err(&es2->usb_dev->dev,
365                                         "failed to submit in-urb: %d\n", ret);
366                         goto err_kill_urbs;
367                 }
368         }
369
370         return 0;
371
372 err_kill_urbs:
373         for (--i; i >= 0; --i) {
374                 urb = cport_in->urb[i];
375                 usb_kill_urb(urb);
376         }
377
378         return ret;
379 }
380
381 static void es2_cport_in_disable(struct es2_ap_dev *es2,
382                                 struct es2_cport_in *cport_in)
383 {
384         struct urb *urb;
385         int i;
386
387         for (i = 0; i < NUM_CPORT_IN_URB; ++i) {
388                 urb = cport_in->urb[i];
389                 usb_kill_urb(urb);
390         }
391 }
392
393 static int es2_arpc_in_enable(struct es2_ap_dev *es2)
394 {
395         struct urb *urb;
396         int ret;
397         int i;
398
399         for (i = 0; i < NUM_ARPC_IN_URB; ++i) {
400                 urb = es2->arpc_urb[i];
401
402                 ret = usb_submit_urb(urb, GFP_KERNEL);
403                 if (ret) {
404                         dev_err(&es2->usb_dev->dev,
405                                 "failed to submit arpc in-urb: %d\n", ret);
406                         goto err_kill_urbs;
407                 }
408         }
409
410         return 0;
411
412 err_kill_urbs:
413         for (--i; i >= 0; --i) {
414                 urb = es2->arpc_urb[i];
415                 usb_kill_urb(urb);
416         }
417
418         return ret;
419 }
420
421 static void es2_arpc_in_disable(struct es2_ap_dev *es2)
422 {
423         struct urb *urb;
424         int i;
425
426         for (i = 0; i < NUM_ARPC_IN_URB; ++i) {
427                 urb = es2->arpc_urb[i];
428                 usb_kill_urb(urb);
429         }
430 }
431
432 static struct urb *next_free_urb(struct es2_ap_dev *es2, gfp_t gfp_mask)
433 {
434         struct urb *urb = NULL;
435         unsigned long flags;
436         int i;
437
438         spin_lock_irqsave(&es2->cport_out_urb_lock, flags);
439
440         /* Look in our pool of allocated urbs first, as that's the "fastest" */
441         for (i = 0; i < NUM_CPORT_OUT_URB; ++i) {
442                 if (es2->cport_out_urb_busy[i] == false &&
443                                 es2->cport_out_urb_cancelled[i] == false) {
444                         es2->cport_out_urb_busy[i] = true;
445                         urb = es2->cport_out_urb[i];
446                         break;
447                 }
448         }
449         spin_unlock_irqrestore(&es2->cport_out_urb_lock, flags);
450         if (urb)
451                 return urb;
452
453         /*
454          * Crap, pool is empty, complain to the syslog and go allocate one
455          * dynamically as we have to succeed.
456          */
457         dev_dbg(&es2->usb_dev->dev,
458                 "No free CPort OUT urbs, having to dynamically allocate one!\n");
459         return usb_alloc_urb(0, gfp_mask);
460 }
461
462 static void free_urb(struct es2_ap_dev *es2, struct urb *urb)
463 {
464         unsigned long flags;
465         int i;
466         /*
467          * See if this was an urb in our pool, if so mark it "free", otherwise
468          * we need to free it ourselves.
469          */
470         spin_lock_irqsave(&es2->cport_out_urb_lock, flags);
471         for (i = 0; i < NUM_CPORT_OUT_URB; ++i) {
472                 if (urb == es2->cport_out_urb[i]) {
473                         es2->cport_out_urb_busy[i] = false;
474                         urb = NULL;
475                         break;
476                 }
477         }
478         spin_unlock_irqrestore(&es2->cport_out_urb_lock, flags);
479
480         /* If urb is not NULL, then we need to free this urb */
481         usb_free_urb(urb);
482 }
483
484 /*
485  * We (ab)use the operation-message header pad bytes to transfer the
486  * cport id in order to minimise overhead.
487  */
488 static void
489 gb_message_cport_pack(struct gb_operation_msg_hdr *header, u16 cport_id)
490 {
491         header->pad[0] = cport_id;
492 }
493
494 /* Clear the pad bytes used for the CPort id */
495 static void gb_message_cport_clear(struct gb_operation_msg_hdr *header)
496 {
497         header->pad[0] = 0;
498 }
499
500 /* Extract the CPort id packed into the header, and clear it */
501 static u16 gb_message_cport_unpack(struct gb_operation_msg_hdr *header)
502 {
503         u16 cport_id = header->pad[0];
504
505         gb_message_cport_clear(header);
506
507         return cport_id;
508 }
509
510 /*
511  * Returns zero if the message was successfully queued, or a negative errno
512  * otherwise.
513  */
514 static int message_send(struct gb_host_device *hd, u16 cport_id,
515                         struct gb_message *message, gfp_t gfp_mask)
516 {
517         struct es2_ap_dev *es2 = hd_to_es2(hd);
518         struct usb_device *udev = es2->usb_dev;
519         size_t buffer_size;
520         int retval;
521         struct urb *urb;
522         int ep_pair;
523         unsigned long flags;
524
525         /*
526          * The data actually transferred will include an indication
527          * of where the data should be sent.  Do one last check of
528          * the target CPort id before filling it in.
529          */
530         if (!cport_id_valid(hd, cport_id)) {
531                 dev_err(&udev->dev, "invalid cport %u\n", cport_id);
532                 return -EINVAL;
533         }
534
535         /* Find a free urb */
536         urb = next_free_urb(es2, gfp_mask);
537         if (!urb)
538                 return -ENOMEM;
539
540         spin_lock_irqsave(&es2->cport_out_urb_lock, flags);
541         message->hcpriv = urb;
542         spin_unlock_irqrestore(&es2->cport_out_urb_lock, flags);
543
544         /* Pack the cport id into the message header */
545         gb_message_cport_pack(message->header, cport_id);
546
547         buffer_size = sizeof(*message->header) + message->payload_size;
548
549         ep_pair = cport_to_ep_pair(es2, cport_id);
550         usb_fill_bulk_urb(urb, udev,
551                           usb_sndbulkpipe(udev,
552                                           es2->cport_out[ep_pair].endpoint),
553                           message->buffer, buffer_size,
554                           cport_out_callback, message);
555         urb->transfer_flags |= URB_ZERO_PACKET;
556
557         trace_gb_message_submit(message);
558
559         retval = usb_submit_urb(urb, gfp_mask);
560         if (retval) {
561                 dev_err(&udev->dev, "failed to submit out-urb: %d\n", retval);
562
563                 spin_lock_irqsave(&es2->cport_out_urb_lock, flags);
564                 message->hcpriv = NULL;
565                 spin_unlock_irqrestore(&es2->cport_out_urb_lock, flags);
566
567                 free_urb(es2, urb);
568                 gb_message_cport_clear(message->header);
569
570                 return retval;
571         }
572
573         return 0;
574 }
575
576 /*
577  * Can not be called in atomic context.
578  */
579 static void message_cancel(struct gb_message *message)
580 {
581         struct gb_host_device *hd = message->operation->connection->hd;
582         struct es2_ap_dev *es2 = hd_to_es2(hd);
583         struct urb *urb;
584         int i;
585
586         might_sleep();
587
588         spin_lock_irq(&es2->cport_out_urb_lock);
589         urb = message->hcpriv;
590
591         /* Prevent dynamically allocated urb from being deallocated. */
592         usb_get_urb(urb);
593
594         /* Prevent pre-allocated urb from being reused. */
595         for (i = 0; i < NUM_CPORT_OUT_URB; ++i) {
596                 if (urb == es2->cport_out_urb[i]) {
597                         es2->cport_out_urb_cancelled[i] = true;
598                         break;
599                 }
600         }
601         spin_unlock_irq(&es2->cport_out_urb_lock);
602
603         usb_kill_urb(urb);
604
605         if (i < NUM_CPORT_OUT_URB) {
606                 spin_lock_irq(&es2->cport_out_urb_lock);
607                 es2->cport_out_urb_cancelled[i] = false;
608                 spin_unlock_irq(&es2->cport_out_urb_lock);
609         }
610
611         usb_free_urb(urb);
612 }
613
614 static int cport_reset(struct gb_host_device *hd, u16 cport_id)
615 {
616         struct es2_ap_dev *es2 = hd_to_es2(hd);
617         struct usb_device *udev = es2->usb_dev;
618         struct arpc_cport_reset_req req;
619         int retval;
620         int result;
621
622         switch (cport_id) {
623         case GB_SVC_CPORT_ID:
624         case ES2_CPORT_CDSI0:
625         case ES2_CPORT_CDSI1:
626                 return 0;
627         }
628
629         req.cport_id = cpu_to_le16(cport_id);
630         retval = arpc_sync(es2, ARPC_TYPE_CPORT_RESET, &req, sizeof(req),
631                            &result, ES2_ARPC_CPORT_TIMEOUT);
632         if (retval == -EREMOTEIO) {
633                 dev_err(&udev->dev, "failed to reset cport %u: %d\n", cport_id,
634                         result);
635         }
636
637         return retval;
638 }
639
640 static int es2_cport_allocate(struct gb_host_device *hd, int cport_id,
641                                 unsigned long flags)
642 {
643         struct es2_ap_dev *es2 = hd_to_es2(hd);
644         struct ida *id_map = &hd->cport_id_map;
645         int ida_start, ida_end;
646
647         switch (cport_id) {
648         case ES2_CPORT_CDSI0:
649         case ES2_CPORT_CDSI1:
650                 dev_err(&hd->dev, "cport %d not available\n", cport_id);
651                 return -EBUSY;
652         }
653
654         if (flags & GB_CONNECTION_FLAG_OFFLOADED &&
655                         flags & GB_CONNECTION_FLAG_CDSI1) {
656                 if (es2->cdsi1_in_use) {
657                         dev_err(&hd->dev, "CDSI1 already in use\n");
658                         return -EBUSY;
659                 }
660
661                 es2->cdsi1_in_use = true;
662
663                 return ES2_CPORT_CDSI1;
664         }
665
666         if (cport_id < 0) {
667                 ida_start = 0;
668                 ida_end = hd->num_cports;
669         } else if (cport_id < hd->num_cports) {
670                 ida_start = cport_id;
671                 ida_end = cport_id + 1;
672         } else {
673                 dev_err(&hd->dev, "cport %d not available\n", cport_id);
674                 return -EINVAL;
675         }
676
677         return ida_simple_get(id_map, ida_start, ida_end, GFP_KERNEL);
678 }
679
680 static void es2_cport_release(struct gb_host_device *hd, u16 cport_id)
681 {
682         struct es2_ap_dev *es2 = hd_to_es2(hd);
683
684         switch (cport_id) {
685         case ES2_CPORT_CDSI1:
686                 es2->cdsi1_in_use = false;
687                 return;
688         }
689
690         ida_simple_remove(&hd->cport_id_map, cport_id);
691 }
692
693 static int cport_enable(struct gb_host_device *hd, u16 cport_id,
694                         unsigned long flags)
695 {
696         struct es2_ap_dev *es2 = hd_to_es2(hd);
697         struct usb_device *udev = es2->usb_dev;
698         struct gb_apb_request_cport_flags *req;
699         u32 connection_flags;
700         int ret;
701
702         req = kzalloc(sizeof(*req), GFP_KERNEL);
703         if (!req)
704                 return -ENOMEM;
705
706         connection_flags = 0;
707         if (flags & GB_CONNECTION_FLAG_CONTROL)
708                 connection_flags |= GB_APB_CPORT_FLAG_CONTROL;
709         if (flags & GB_CONNECTION_FLAG_HIGH_PRIO)
710                 connection_flags |= GB_APB_CPORT_FLAG_HIGH_PRIO;
711
712         req->flags = cpu_to_le32(connection_flags);
713
714         dev_dbg(&hd->dev, "%s - cport = %u, flags = %02x\n", __func__,
715                         cport_id, connection_flags);
716
717         ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
718                                 GB_APB_REQUEST_CPORT_FLAGS,
719                                 USB_DIR_OUT | USB_TYPE_VENDOR |
720                                 USB_RECIP_INTERFACE, cport_id, 0,
721                                 req, sizeof(*req), ES2_USB_CTRL_TIMEOUT);
722         if (ret != sizeof(*req)) {
723                 dev_err(&udev->dev, "failed to set cport flags for port %d\n",
724                                 cport_id);
725                 if (ret >= 0)
726                         ret = -EIO;
727
728                 goto out;
729         }
730
731         ret = 0;
732 out:
733         kfree(req);
734
735         return ret;
736 }
737
738 static int cport_disable(struct gb_host_device *hd, u16 cport_id)
739 {
740         int retval;
741
742         retval = cport_reset(hd, cport_id);
743         if (retval)
744                 return retval;
745
746         return 0;
747 }
748
749 static int latency_tag_enable(struct gb_host_device *hd, u16 cport_id)
750 {
751         int retval;
752         struct es2_ap_dev *es2 = hd_to_es2(hd);
753         struct usb_device *udev = es2->usb_dev;
754
755         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
756                                  GB_APB_REQUEST_LATENCY_TAG_EN,
757                                  USB_DIR_OUT | USB_TYPE_VENDOR |
758                                  USB_RECIP_INTERFACE, cport_id, 0, NULL,
759                                  0, ES2_USB_CTRL_TIMEOUT);
760
761         if (retval < 0)
762                 dev_err(&udev->dev, "Cannot enable latency tag for cport %d\n",
763                         cport_id);
764         return retval;
765 }
766
767 static int latency_tag_disable(struct gb_host_device *hd, u16 cport_id)
768 {
769         int retval;
770         struct es2_ap_dev *es2 = hd_to_es2(hd);
771         struct usb_device *udev = es2->usb_dev;
772
773         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
774                                  GB_APB_REQUEST_LATENCY_TAG_DIS,
775                                  USB_DIR_OUT | USB_TYPE_VENDOR |
776                                  USB_RECIP_INTERFACE, cport_id, 0, NULL,
777                                  0, ES2_USB_CTRL_TIMEOUT);
778
779         if (retval < 0)
780                 dev_err(&udev->dev, "Cannot disable latency tag for cport %d\n",
781                         cport_id);
782         return retval;
783 }
784
785 static int cport_features_enable(struct gb_host_device *hd, u16 cport_id)
786 {
787         int retval;
788         struct es2_ap_dev *es2 = hd_to_es2(hd);
789         struct usb_device *udev = es2->usb_dev;
790
791         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
792                                  GB_APB_REQUEST_CPORT_FEAT_EN,
793                                  USB_DIR_OUT | USB_TYPE_VENDOR |
794                                  USB_RECIP_INTERFACE, cport_id, 0, NULL,
795                                  0, ES2_USB_CTRL_TIMEOUT);
796         if (retval < 0)
797                 dev_err(&udev->dev, "Cannot enable CPort features for cport %u: %d\n",
798                         cport_id, retval);
799         return retval;
800 }
801
802 static int cport_features_disable(struct gb_host_device *hd, u16 cport_id)
803 {
804         int retval;
805         struct es2_ap_dev *es2 = hd_to_es2(hd);
806         struct usb_device *udev = es2->usb_dev;
807
808         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
809                                  GB_APB_REQUEST_CPORT_FEAT_DIS,
810                                  USB_DIR_OUT | USB_TYPE_VENDOR |
811                                  USB_RECIP_INTERFACE, cport_id, 0, NULL,
812                                  0, ES2_USB_CTRL_TIMEOUT);
813         if (retval < 0)
814                 dev_err(&udev->dev,
815                         "Cannot disable CPort features for cport %u: %d\n",
816                         cport_id, retval);
817         return retval;
818 }
819
820 static int timesync_enable(struct gb_host_device *hd, u8 count,
821                            u64 frame_time, u32 strobe_delay, u32 refclk)
822 {
823         int retval;
824         struct es2_ap_dev *es2 = hd_to_es2(hd);
825         struct usb_device *udev = es2->usb_dev;
826         struct gb_control_timesync_enable_request *request;
827
828         request = kzalloc(sizeof(*request), GFP_KERNEL);
829         if (!request)
830                 return -ENOMEM;
831
832         request->count = count;
833         request->frame_time = cpu_to_le64(frame_time);
834         request->strobe_delay = cpu_to_le32(strobe_delay);
835         request->refclk = cpu_to_le32(refclk);
836         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
837                                  GB_APB_REQUEST_TIMESYNC_ENABLE,
838                                  USB_DIR_OUT | USB_TYPE_VENDOR |
839                                  USB_RECIP_INTERFACE, 0, 0, request,
840                                  sizeof(*request), ES2_USB_CTRL_TIMEOUT);
841         if (retval < 0)
842                 dev_err(&udev->dev, "Cannot enable timesync %d\n", retval);
843
844         kfree(request);
845         return retval;
846 }
847
848 static int timesync_disable(struct gb_host_device *hd)
849 {
850         int retval;
851         struct es2_ap_dev *es2 = hd_to_es2(hd);
852         struct usb_device *udev = es2->usb_dev;
853
854         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
855                                  GB_APB_REQUEST_TIMESYNC_DISABLE,
856                                  USB_DIR_OUT | USB_TYPE_VENDOR |
857                                  USB_RECIP_INTERFACE, 0, 0, NULL,
858                                  0, ES2_USB_CTRL_TIMEOUT);
859         if (retval < 0)
860                 dev_err(&udev->dev, "Cannot disable timesync %d\n", retval);
861
862         return retval;
863 }
864
865 static int timesync_authoritative(struct gb_host_device *hd, u64 *frame_time)
866 {
867         int retval, i;
868         struct es2_ap_dev *es2 = hd_to_es2(hd);
869         struct usb_device *udev = es2->usb_dev;
870         struct timesync_authoritative_request *request;
871
872         request = kzalloc(sizeof(*request), GFP_KERNEL);
873         if (!request)
874                 return -ENOMEM;
875
876         for (i = 0; i < GB_TIMESYNC_MAX_STROBES; i++)
877                 request->frame_time[i] = cpu_to_le64(frame_time[i]);
878
879         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
880                                  GB_APB_REQUEST_TIMESYNC_AUTHORITATIVE,
881                                  USB_DIR_OUT | USB_TYPE_VENDOR |
882                                  USB_RECIP_INTERFACE, 0, 0, request,
883                                  sizeof(*request), ES2_USB_CTRL_TIMEOUT);
884         if (retval < 0)
885                 dev_err(&udev->dev, "Cannot timesync authoritative out %d\n", retval);
886
887         kfree(request);
888         return retval;
889 }
890
891 static int timesync_get_last_event(struct gb_host_device *hd, u64 *frame_time)
892 {
893         int retval;
894         struct es2_ap_dev *es2 = hd_to_es2(hd);
895         struct usb_device *udev = es2->usb_dev;
896         __le64 *response_frame_time;
897
898         response_frame_time = kzalloc(sizeof(*response_frame_time), GFP_KERNEL);
899         if (!response_frame_time)
900                 return -ENOMEM;
901
902         retval = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
903                                  GB_APB_REQUEST_TIMESYNC_GET_LAST_EVENT,
904                                  USB_DIR_IN | USB_TYPE_VENDOR |
905                                  USB_RECIP_INTERFACE, 0, 0, response_frame_time,
906                                  sizeof(*response_frame_time),
907                                  ES2_USB_CTRL_TIMEOUT);
908
909         if (retval != sizeof(*response_frame_time)) {
910                 dev_err(&udev->dev, "Cannot get last TimeSync event: %d\n",
911                         retval);
912
913                 if (retval >= 0)
914                         retval = -EIO;
915
916                 goto out;
917         }
918         *frame_time = le64_to_cpu(*response_frame_time);
919         retval = 0;
920 out:
921         kfree(response_frame_time);
922         return retval;
923 }
924
925 static struct gb_hd_driver es2_driver = {
926         .hd_priv_size                   = sizeof(struct es2_ap_dev),
927         .message_send                   = message_send,
928         .message_cancel                 = message_cancel,
929         .cport_allocate                 = es2_cport_allocate,
930         .cport_release                  = es2_cport_release,
931         .cport_enable                   = cport_enable,
932         .cport_disable                  = cport_disable,
933         .latency_tag_enable             = latency_tag_enable,
934         .latency_tag_disable            = latency_tag_disable,
935         .output                         = output,
936         .cport_features_enable          = cport_features_enable,
937         .cport_features_disable         = cport_features_disable,
938         .timesync_enable                = timesync_enable,
939         .timesync_disable               = timesync_disable,
940         .timesync_authoritative         = timesync_authoritative,
941         .timesync_get_last_event        = timesync_get_last_event,
942 };
943
944 /* Common function to report consistent warnings based on URB status */
945 static int check_urb_status(struct urb *urb)
946 {
947         struct device *dev = &urb->dev->dev;
948         int status = urb->status;
949
950         switch (status) {
951         case 0:
952                 return 0;
953
954         case -EOVERFLOW:
955                 dev_err(dev, "%s: overflow actual length is %d\n",
956                         __func__, urb->actual_length);
957         case -ECONNRESET:
958         case -ENOENT:
959         case -ESHUTDOWN:
960         case -EILSEQ:
961         case -EPROTO:
962                 /* device is gone, stop sending */
963                 return status;
964         }
965         dev_err(dev, "%s: unknown status %d\n", __func__, status);
966
967         return -EAGAIN;
968 }
969
970 static void es2_destroy(struct es2_ap_dev *es2)
971 {
972         struct usb_device *udev;
973         int bulk_in;
974         int i;
975
976         debugfs_remove(es2->apb_log_enable_dentry);
977         usb_log_disable(es2);
978
979         /* Tear down everything! */
980         for (i = 0; i < NUM_CPORT_OUT_URB; ++i) {
981                 struct urb *urb = es2->cport_out_urb[i];
982
983                 if (!urb)
984                         break;
985                 usb_kill_urb(urb);
986                 usb_free_urb(urb);
987                 es2->cport_out_urb[i] = NULL;
988                 es2->cport_out_urb_busy[i] = false;     /* just to be anal */
989         }
990
991         for (i = 0; i < NUM_ARPC_IN_URB; ++i) {
992                 struct urb *urb = es2->arpc_urb[i];
993
994                 if (!urb)
995                         break;
996                 usb_free_urb(urb);
997                 kfree(es2->arpc_buffer[i]);
998                 es2->arpc_buffer[i] = NULL;
999         }
1000
1001         for (bulk_in = 0; bulk_in < NUM_BULKS; bulk_in++) {
1002                 struct es2_cport_in *cport_in = &es2->cport_in[bulk_in];
1003
1004                 for (i = 0; i < NUM_CPORT_IN_URB; ++i) {
1005                         struct urb *urb = cport_in->urb[i];
1006
1007                         if (!urb)
1008                                 break;
1009                         usb_free_urb(urb);
1010                         kfree(cport_in->buffer[i]);
1011                         cport_in->buffer[i] = NULL;
1012                 }
1013         }
1014
1015         kfree(es2->cport_to_ep);
1016
1017         /* release reserved CDSI0 and CDSI1 cports */
1018         gb_hd_cport_release_reserved(es2->hd, ES2_CPORT_CDSI1);
1019         gb_hd_cport_release_reserved(es2->hd, ES2_CPORT_CDSI0);
1020
1021         udev = es2->usb_dev;
1022         gb_hd_put(es2->hd);
1023
1024         usb_put_dev(udev);
1025 }
1026
1027 static void cport_in_callback(struct urb *urb)
1028 {
1029         struct gb_host_device *hd = urb->context;
1030         struct device *dev = &urb->dev->dev;
1031         struct gb_operation_msg_hdr *header;
1032         int status = check_urb_status(urb);
1033         int retval;
1034         u16 cport_id;
1035
1036         if (status) {
1037                 if ((status == -EAGAIN) || (status == -EPROTO))
1038                         goto exit;
1039
1040                 /* The urb is being unlinked */
1041                 if (status == -ENOENT || status == -ESHUTDOWN)
1042                         return;
1043
1044                 dev_err(dev, "urb cport in error %d (dropped)\n", status);
1045                 return;
1046         }
1047
1048         if (urb->actual_length < sizeof(*header)) {
1049                 dev_err(dev, "short message received\n");
1050                 goto exit;
1051         }
1052
1053         /* Extract the CPort id, which is packed in the message header */
1054         header = urb->transfer_buffer;
1055         cport_id = gb_message_cport_unpack(header);
1056
1057         if (cport_id_valid(hd, cport_id)) {
1058                 greybus_data_rcvd(hd, cport_id, urb->transfer_buffer,
1059                                                         urb->actual_length);
1060         } else {
1061                 dev_err(dev, "invalid cport id %u received\n", cport_id);
1062         }
1063 exit:
1064         /* put our urb back in the request pool */
1065         retval = usb_submit_urb(urb, GFP_ATOMIC);
1066         if (retval)
1067                 dev_err(dev, "failed to resubmit in-urb: %d\n", retval);
1068 }
1069
1070 static void cport_out_callback(struct urb *urb)
1071 {
1072         struct gb_message *message = urb->context;
1073         struct gb_host_device *hd = message->operation->connection->hd;
1074         struct es2_ap_dev *es2 = hd_to_es2(hd);
1075         int status = check_urb_status(urb);
1076         unsigned long flags;
1077
1078         gb_message_cport_clear(message->header);
1079
1080         spin_lock_irqsave(&es2->cport_out_urb_lock, flags);
1081         message->hcpriv = NULL;
1082         spin_unlock_irqrestore(&es2->cport_out_urb_lock, flags);
1083
1084         /*
1085          * Tell the submitter that the message send (attempt) is
1086          * complete, and report the status.
1087          */
1088         greybus_message_sent(hd, message, status);
1089
1090         free_urb(es2, urb);
1091 }
1092
1093 static struct arpc *arpc_alloc(void *payload, u16 size, u8 type)
1094 {
1095         struct arpc *rpc;
1096
1097         if (size + sizeof(*rpc->req) > ARPC_OUT_SIZE_MAX)
1098                 return NULL;
1099
1100         rpc = kzalloc(sizeof(*rpc), GFP_KERNEL);
1101         if (!rpc)
1102                 return NULL;
1103
1104         INIT_LIST_HEAD(&rpc->list);
1105         rpc->req = kzalloc(sizeof(*rpc->req) + size, GFP_KERNEL);
1106         if (!rpc->req)
1107                 goto err_free_rpc;
1108
1109         rpc->resp = kzalloc(sizeof(*rpc->resp), GFP_KERNEL);
1110         if (!rpc->resp)
1111                 goto err_free_req;
1112
1113         rpc->req->type = type;
1114         rpc->req->size = cpu_to_le16(sizeof(rpc->req) + size);
1115         memcpy(rpc->req->data, payload, size);
1116
1117         init_completion(&rpc->response_received);
1118
1119         return rpc;
1120
1121 err_free_req:
1122         kfree(rpc->req);
1123 err_free_rpc:
1124         kfree(rpc);
1125
1126         return NULL;
1127 }
1128
1129 static void arpc_free(struct arpc *rpc)
1130 {
1131         kfree(rpc->req);
1132         kfree(rpc->resp);
1133         kfree(rpc);
1134 }
1135
1136 static struct arpc *arpc_find(struct es2_ap_dev *es2, __le16 id)
1137 {
1138         struct arpc *rpc;
1139
1140         list_for_each_entry(rpc, &es2->arpcs, list) {
1141                 if (rpc->req->id == id)
1142                         return rpc;
1143         }
1144
1145         return NULL;
1146 }
1147
1148 static void arpc_add(struct es2_ap_dev *es2, struct arpc *rpc)
1149 {
1150         rpc->active = true;
1151         rpc->req->id = cpu_to_le16(es2->arpc_id_cycle++);
1152         list_add_tail(&rpc->list, &es2->arpcs);
1153 }
1154
1155 static void arpc_del(struct es2_ap_dev *es2, struct arpc *rpc)
1156 {
1157         if (rpc->active) {
1158                 rpc->active = false;
1159                 list_del(&rpc->list);
1160         }
1161 }
1162
1163 static int arpc_send(struct es2_ap_dev *es2, struct arpc *rpc, int timeout)
1164 {
1165         struct usb_device *udev = es2->usb_dev;
1166         int retval;
1167
1168         retval = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
1169                                  GB_APB_REQUEST_ARPC_RUN,
1170                                  USB_DIR_OUT | USB_TYPE_VENDOR |
1171                                  USB_RECIP_INTERFACE,
1172                                  0, 0,
1173                                  rpc->req, le16_to_cpu(rpc->req->size),
1174                                  ES2_USB_CTRL_TIMEOUT);
1175         if (retval != le16_to_cpu(rpc->req->size)) {
1176                 dev_err(&udev->dev,
1177                         "failed to send ARPC request %d: %d\n",
1178                         rpc->req->type, retval);
1179                 if (retval > 0)
1180                         retval = -EIO;
1181                 return retval;
1182         }
1183
1184         return 0;
1185 }
1186
1187 static int arpc_sync(struct es2_ap_dev *es2, u8 type, void *payload,
1188                      size_t size, int *result, unsigned int timeout)
1189 {
1190         struct arpc *rpc;
1191         unsigned long flags;
1192         int retval;
1193
1194         if (result)
1195                 *result = 0;
1196
1197         rpc = arpc_alloc(payload, size, type);
1198         if (!rpc)
1199                 return -ENOMEM;
1200
1201         spin_lock_irqsave(&es2->arpc_lock, flags);
1202         arpc_add(es2, rpc);
1203         spin_unlock_irqrestore(&es2->arpc_lock, flags);
1204
1205         retval = arpc_send(es2, rpc, timeout);
1206         if (retval)
1207                 goto out_arpc_del;
1208
1209         retval = wait_for_completion_interruptible_timeout(
1210                                                 &rpc->response_received,
1211                                                 msecs_to_jiffies(timeout));
1212         if (retval <= 0) {
1213                 if (!retval)
1214                         retval = -ETIMEDOUT;
1215                 goto out_arpc_del;
1216         }
1217
1218         if (rpc->resp->result) {
1219                 retval = -EREMOTEIO;
1220                 if (result)
1221                         *result = rpc->resp->result;
1222         } else {
1223                 retval = 0;
1224         }
1225
1226 out_arpc_del:
1227         spin_lock_irqsave(&es2->arpc_lock, flags);
1228         arpc_del(es2, rpc);
1229         spin_unlock_irqrestore(&es2->arpc_lock, flags);
1230         arpc_free(rpc);
1231
1232         if (retval < 0 && retval != -EREMOTEIO) {
1233                 dev_err(&es2->usb_dev->dev,
1234                         "failed to execute ARPC: %d\n", retval);
1235         }
1236
1237         return retval;
1238 }
1239
1240 static void arpc_in_callback(struct urb *urb)
1241 {
1242         struct es2_ap_dev *es2 = urb->context;
1243         struct device *dev = &urb->dev->dev;
1244         int status = check_urb_status(urb);
1245         struct arpc *rpc;
1246         struct arpc_response_message *resp;
1247         unsigned long flags;
1248         int retval;
1249
1250         if (status) {
1251                 if ((status == -EAGAIN) || (status == -EPROTO))
1252                         goto exit;
1253
1254                 /* The urb is being unlinked */
1255                 if (status == -ENOENT || status == -ESHUTDOWN)
1256                         return;
1257
1258                 dev_err(dev, "arpc in-urb error %d (dropped)\n", status);
1259                 return;
1260         }
1261
1262         if (urb->actual_length < sizeof(*resp)) {
1263                 dev_err(dev, "short aprc response received\n");
1264                 goto exit;
1265         }
1266
1267         resp = urb->transfer_buffer;
1268         spin_lock_irqsave(&es2->arpc_lock, flags);
1269         rpc = arpc_find(es2, resp->id);
1270         if (!rpc) {
1271                 dev_err(dev, "invalid arpc response id received: %u\n",
1272                         le16_to_cpu(resp->id));
1273                 spin_unlock_irqrestore(&es2->arpc_lock, flags);
1274                 goto exit;
1275         }
1276
1277         arpc_del(es2, rpc);
1278         memcpy(rpc->resp, resp, sizeof(*resp));
1279         complete(&rpc->response_received);
1280         spin_unlock_irqrestore(&es2->arpc_lock, flags);
1281
1282 exit:
1283         /* put our urb back in the request pool */
1284         retval = usb_submit_urb(urb, GFP_ATOMIC);
1285         if (retval)
1286                 dev_err(dev, "failed to resubmit arpc in-urb: %d\n", retval);
1287 }
1288
1289 #define APB1_LOG_MSG_SIZE       64
1290 static void apb_log_get(struct es2_ap_dev *es2, char *buf)
1291 {
1292         int retval;
1293
1294         do {
1295                 retval = usb_control_msg(es2->usb_dev,
1296                                         usb_rcvctrlpipe(es2->usb_dev, 0),
1297                                         GB_APB_REQUEST_LOG,
1298                                         USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
1299                                         0x00, 0x00,
1300                                         buf,
1301                                         APB1_LOG_MSG_SIZE,
1302                                         ES2_USB_CTRL_TIMEOUT);
1303                 if (retval > 0)
1304                         kfifo_in(&es2->apb_log_fifo, buf, retval);
1305         } while (retval > 0);
1306 }
1307
1308 static int apb_log_poll(void *data)
1309 {
1310         struct es2_ap_dev *es2 = data;
1311         char *buf;
1312
1313         buf = kmalloc(APB1_LOG_MSG_SIZE, GFP_KERNEL);
1314         if (!buf)
1315                 return -ENOMEM;
1316
1317         while (!kthread_should_stop()) {
1318                 msleep(1000);
1319                 apb_log_get(es2, buf);
1320         }
1321
1322         kfree(buf);
1323
1324         return 0;
1325 }
1326
1327 static ssize_t apb_log_read(struct file *f, char __user *buf,
1328                                 size_t count, loff_t *ppos)
1329 {
1330         struct es2_ap_dev *es2 = f->f_inode->i_private;
1331         ssize_t ret;
1332         size_t copied;
1333         char *tmp_buf;
1334
1335         if (count > APB1_LOG_SIZE)
1336                 count = APB1_LOG_SIZE;
1337
1338         tmp_buf = kmalloc(count, GFP_KERNEL);
1339         if (!tmp_buf)
1340                 return -ENOMEM;
1341
1342         copied = kfifo_out(&es2->apb_log_fifo, tmp_buf, count);
1343         ret = simple_read_from_buffer(buf, count, ppos, tmp_buf, copied);
1344
1345         kfree(tmp_buf);
1346
1347         return ret;
1348 }
1349
1350 static const struct file_operations apb_log_fops = {
1351         .read   = apb_log_read,
1352 };
1353
1354 static void usb_log_enable(struct es2_ap_dev *es2)
1355 {
1356         if (!IS_ERR_OR_NULL(es2->apb_log_task))
1357                 return;
1358
1359         /* get log from APB1 */
1360         es2->apb_log_task = kthread_run(apb_log_poll, es2, "apb_log");
1361         if (IS_ERR(es2->apb_log_task))
1362                 return;
1363         /* XXX We will need to rename this per APB */
1364         es2->apb_log_dentry = debugfs_create_file("apb_log", S_IRUGO,
1365                                                 gb_debugfs_get(), es2,
1366                                                 &apb_log_fops);
1367 }
1368
1369 static void usb_log_disable(struct es2_ap_dev *es2)
1370 {
1371         if (IS_ERR_OR_NULL(es2->apb_log_task))
1372                 return;
1373
1374         debugfs_remove(es2->apb_log_dentry);
1375         es2->apb_log_dentry = NULL;
1376
1377         kthread_stop(es2->apb_log_task);
1378         es2->apb_log_task = NULL;
1379 }
1380
1381 static ssize_t apb_log_enable_read(struct file *f, char __user *buf,
1382                                 size_t count, loff_t *ppos)
1383 {
1384         struct es2_ap_dev *es2 = f->f_inode->i_private;
1385         int enable = !IS_ERR_OR_NULL(es2->apb_log_task);
1386         char tmp_buf[3];
1387
1388         sprintf(tmp_buf, "%d\n", enable);
1389         return simple_read_from_buffer(buf, count, ppos, tmp_buf, 3);
1390 }
1391
1392 static ssize_t apb_log_enable_write(struct file *f, const char __user *buf,
1393                                 size_t count, loff_t *ppos)
1394 {
1395         int enable;
1396         ssize_t retval;
1397         struct es2_ap_dev *es2 = f->f_inode->i_private;
1398
1399         retval = kstrtoint_from_user(buf, count, 10, &enable);
1400         if (retval)
1401                 return retval;
1402
1403         if (enable)
1404                 usb_log_enable(es2);
1405         else
1406                 usb_log_disable(es2);
1407
1408         return count;
1409 }
1410
1411 static const struct file_operations apb_log_enable_fops = {
1412         .read   = apb_log_enable_read,
1413         .write  = apb_log_enable_write,
1414 };
1415
1416 static int apb_get_cport_count(struct usb_device *udev)
1417 {
1418         int retval;
1419         __le16 *cport_count;
1420
1421         cport_count = kzalloc(sizeof(*cport_count), GFP_KERNEL);
1422         if (!cport_count)
1423                 return -ENOMEM;
1424
1425         retval = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
1426                                  GB_APB_REQUEST_CPORT_COUNT,
1427                                  USB_DIR_IN | USB_TYPE_VENDOR |
1428                                  USB_RECIP_INTERFACE, 0, 0, cport_count,
1429                                  sizeof(*cport_count), ES2_USB_CTRL_TIMEOUT);
1430         if (retval != sizeof(*cport_count)) {
1431                 dev_err(&udev->dev, "Cannot retrieve CPort count: %d\n",
1432                         retval);
1433
1434                 if (retval >= 0)
1435                         retval = -EIO;
1436
1437                 goto out;
1438         }
1439
1440         retval = le16_to_cpu(*cport_count);
1441
1442         /* We need to fit a CPort ID in one byte of a message header */
1443         if (retval > U8_MAX) {
1444                 retval = U8_MAX;
1445                 dev_warn(&udev->dev, "Limiting number of CPorts to U8_MAX\n");
1446         }
1447
1448 out:
1449         kfree(cport_count);
1450         return retval;
1451 }
1452
1453 /*
1454  * The ES2 USB Bridge device has 15 endpoints
1455  * 1 Control - usual USB stuff + AP -> APBridgeA messages
1456  * 7 Bulk IN - CPort data in
1457  * 7 Bulk OUT - CPort data out
1458  */
1459 static int ap_probe(struct usb_interface *interface,
1460                     const struct usb_device_id *id)
1461 {
1462         struct es2_ap_dev *es2;
1463         struct gb_host_device *hd;
1464         struct usb_device *udev;
1465         struct usb_host_interface *iface_desc;
1466         struct usb_endpoint_descriptor *endpoint;
1467         int bulk_in = 0;
1468         int bulk_out = 0;
1469         int retval;
1470         int i;
1471         int num_cports;
1472
1473         udev = usb_get_dev(interface_to_usbdev(interface));
1474
1475         num_cports = apb_get_cport_count(udev);
1476         if (num_cports < 0) {
1477                 usb_put_dev(udev);
1478                 dev_err(&udev->dev, "Cannot retrieve CPort count: %d\n",
1479                         num_cports);
1480                 return num_cports;
1481         }
1482
1483         hd = gb_hd_create(&es2_driver, &udev->dev, ES2_GBUF_MSG_SIZE_MAX,
1484                                 num_cports);
1485         if (IS_ERR(hd)) {
1486                 usb_put_dev(udev);
1487                 return PTR_ERR(hd);
1488         }
1489
1490         es2 = hd_to_es2(hd);
1491         es2->hd = hd;
1492         es2->usb_intf = interface;
1493         es2->usb_dev = udev;
1494         spin_lock_init(&es2->cport_out_urb_lock);
1495         INIT_KFIFO(es2->apb_log_fifo);
1496         usb_set_intfdata(interface, es2);
1497
1498         /*
1499          * Reserve the CDSI0 and CDSI1 CPorts so they won't be allocated
1500          * dynamically.
1501          */
1502         retval = gb_hd_cport_reserve(hd, ES2_CPORT_CDSI0);
1503         if (retval)
1504                 goto error;
1505         retval = gb_hd_cport_reserve(hd, ES2_CPORT_CDSI1);
1506         if (retval)
1507                 goto error;
1508
1509         es2->cport_to_ep = kcalloc(hd->num_cports, sizeof(*es2->cport_to_ep),
1510                                    GFP_KERNEL);
1511         if (!es2->cport_to_ep) {
1512                 retval = -ENOMEM;
1513                 goto error;
1514         }
1515
1516         /* find all bulk endpoints */
1517         iface_desc = interface->cur_altsetting;
1518         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
1519                 endpoint = &iface_desc->endpoint[i].desc;
1520
1521                 if (usb_endpoint_is_bulk_in(endpoint)) {
1522                         if (bulk_in < NUM_BULKS)
1523                                 es2->cport_in[bulk_in].endpoint =
1524                                         endpoint->bEndpointAddress;
1525                         else
1526                                 es2->arpc_endpoint_in =
1527                                         endpoint->bEndpointAddress;
1528                         bulk_in++;
1529                 } else if (usb_endpoint_is_bulk_out(endpoint)) {
1530                         es2->cport_out[bulk_out++].endpoint =
1531                                 endpoint->bEndpointAddress;
1532                 } else {
1533                         dev_err(&udev->dev,
1534                                 "Unknown endpoint type found, address 0x%02x\n",
1535                                 endpoint->bEndpointAddress);
1536                 }
1537         }
1538         if (bulk_in != NUM_BULKS_IN || bulk_out != NUM_BULKS_OUT) {
1539                 dev_err(&udev->dev, "Not enough endpoints found in device, aborting!\n");
1540                 retval = -ENODEV;
1541                 goto error;
1542         }
1543
1544         /* Allocate buffers for our cport in messages */
1545         for (bulk_in = 0; bulk_in < NUM_BULKS; bulk_in++) {
1546                 struct es2_cport_in *cport_in = &es2->cport_in[bulk_in];
1547
1548                 for (i = 0; i < NUM_CPORT_IN_URB; ++i) {
1549                         struct urb *urb;
1550                         u8 *buffer;
1551
1552                         urb = usb_alloc_urb(0, GFP_KERNEL);
1553                         if (!urb) {
1554                                 retval = -ENOMEM;
1555                                 goto error;
1556                         }
1557                         buffer = kmalloc(ES2_GBUF_MSG_SIZE_MAX, GFP_KERNEL);
1558                         if (!buffer) {
1559                                 retval = -ENOMEM;
1560                                 goto error;
1561                         }
1562
1563                         usb_fill_bulk_urb(urb, udev,
1564                                           usb_rcvbulkpipe(udev,
1565                                                           cport_in->endpoint),
1566                                           buffer, ES2_GBUF_MSG_SIZE_MAX,
1567                                           cport_in_callback, hd);
1568                         cport_in->urb[i] = urb;
1569                         cport_in->buffer[i] = buffer;
1570                 }
1571         }
1572
1573         /* Allocate buffers for ARPC in messages */
1574         for (i = 0; i < NUM_ARPC_IN_URB; ++i) {
1575                 struct urb *urb;
1576                 u8 *buffer;
1577
1578                 urb = usb_alloc_urb(0, GFP_KERNEL);
1579                 if (!urb) {
1580                         retval = -ENOMEM;
1581                         goto error;
1582                 }
1583                 buffer = kmalloc(ARPC_IN_SIZE_MAX, GFP_KERNEL);
1584                 if (!buffer) {
1585                         retval = -ENOMEM;
1586                         goto error;
1587                 }
1588
1589                 usb_fill_bulk_urb(urb, udev,
1590                                   usb_rcvbulkpipe(udev,
1591                                                   es2->arpc_endpoint_in),
1592                                   buffer, ARPC_IN_SIZE_MAX,
1593                                   arpc_in_callback, es2);
1594
1595                 es2->arpc_urb[i] = urb;
1596                 es2->arpc_buffer[i] = buffer;
1597         }
1598
1599         /* Allocate urbs for our CPort OUT messages */
1600         for (i = 0; i < NUM_CPORT_OUT_URB; ++i) {
1601                 struct urb *urb;
1602
1603                 urb = usb_alloc_urb(0, GFP_KERNEL);
1604                 if (!urb) {
1605                         retval = -ENOMEM;
1606                         goto error;
1607                 }
1608
1609                 es2->cport_out_urb[i] = urb;
1610                 es2->cport_out_urb_busy[i] = false;     /* just to be anal */
1611         }
1612
1613         /* XXX We will need to rename this per APB */
1614         es2->apb_log_enable_dentry = debugfs_create_file("apb_log_enable",
1615                                                         (S_IWUSR | S_IRUGO),
1616                                                         gb_debugfs_get(), es2,
1617                                                         &apb_log_enable_fops);
1618
1619         INIT_LIST_HEAD(&es2->arpcs);
1620         spin_lock_init(&es2->arpc_lock);
1621
1622         if (es2_arpc_in_enable(es2))
1623                 goto error;
1624
1625         retval = gb_hd_add(hd);
1626         if (retval)
1627                 goto err_disable_arpc_in;
1628
1629         for (i = 0; i < NUM_BULKS; ++i) {
1630                 retval = es2_cport_in_enable(es2, &es2->cport_in[i]);
1631                 if (retval)
1632                         goto err_disable_cport_in;
1633         }
1634
1635         return 0;
1636
1637 err_disable_cport_in:
1638         for (--i; i >= 0; --i)
1639                 es2_cport_in_disable(es2, &es2->cport_in[i]);
1640         gb_hd_del(hd);
1641 err_disable_arpc_in:
1642         es2_arpc_in_disable(es2);
1643 error:
1644         es2_destroy(es2);
1645
1646         return retval;
1647 }
1648
1649 static void ap_disconnect(struct usb_interface *interface)
1650 {
1651         struct es2_ap_dev *es2 = usb_get_intfdata(interface);
1652         int i;
1653
1654         gb_hd_del(es2->hd);
1655
1656         for (i = 0; i < NUM_BULKS; ++i)
1657                 es2_cport_in_disable(es2, &es2->cport_in[i]);
1658         es2_arpc_in_disable(es2);
1659
1660         es2_destroy(es2);
1661 }
1662
1663 static struct usb_driver es2_ap_driver = {
1664         .name =         "es2_ap_driver",
1665         .probe =        ap_probe,
1666         .disconnect =   ap_disconnect,
1667         .id_table =     id_table,
1668         .soft_unbind =  1,
1669 };
1670
1671 module_usb_driver(es2_ap_driver);
1672
1673 MODULE_LICENSE("GPL v2");
1674 MODULE_AUTHOR("Greg Kroah-Hartman <gregkh@linuxfoundation.org>");