OSDN Git Service

staging: most: remove header include path to drivers/staging
[tomoyo/tomoyo-test1.git] / drivers / staging / most / usb / usb.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * usb.c - Hardware dependent module for USB
4  *
5  * Copyright (C) 2013-2015 Microchip Technology Germany II GmbH & Co. KG
6  */
7
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9 #include <linux/module.h>
10 #include <linux/fs.h>
11 #include <linux/usb.h>
12 #include <linux/slab.h>
13 #include <linux/init.h>
14 #include <linux/cdev.h>
15 #include <linux/device.h>
16 #include <linux/list.h>
17 #include <linux/completion.h>
18 #include <linux/mutex.h>
19 #include <linux/spinlock.h>
20 #include <linux/interrupt.h>
21 #include <linux/workqueue.h>
22 #include <linux/sysfs.h>
23 #include <linux/dma-mapping.h>
24 #include <linux/etherdevice.h>
25 #include <linux/uaccess.h>
26
27 #include "../most.h"
28
29 #define USB_MTU                 512
30 #define NO_ISOCHRONOUS_URB      0
31 #define AV_PACKETS_PER_XACT     2
32 #define BUF_CHAIN_SIZE          0xFFFF
33 #define MAX_NUM_ENDPOINTS       30
34 #define MAX_SUFFIX_LEN          10
35 #define MAX_STRING_LEN          80
36 #define MAX_BUF_SIZE            0xFFFF
37
38 #define USB_VENDOR_ID_SMSC      0x0424  /* VID: SMSC */
39 #define USB_DEV_ID_BRDG         0xC001  /* PID: USB Bridge */
40 #define USB_DEV_ID_OS81118      0xCF18  /* PID: USB OS81118 */
41 #define USB_DEV_ID_OS81119      0xCF19  /* PID: USB OS81119 */
42 #define USB_DEV_ID_OS81210      0xCF30  /* PID: USB OS81210 */
43 /* DRCI Addresses */
44 #define DRCI_REG_NI_STATE       0x0100
45 #define DRCI_REG_PACKET_BW      0x0101
46 #define DRCI_REG_NODE_ADDR      0x0102
47 #define DRCI_REG_NODE_POS       0x0103
48 #define DRCI_REG_MEP_FILTER     0x0140
49 #define DRCI_REG_HASH_TBL0      0x0141
50 #define DRCI_REG_HASH_TBL1      0x0142
51 #define DRCI_REG_HASH_TBL2      0x0143
52 #define DRCI_REG_HASH_TBL3      0x0144
53 #define DRCI_REG_HW_ADDR_HI     0x0145
54 #define DRCI_REG_HW_ADDR_MI     0x0146
55 #define DRCI_REG_HW_ADDR_LO     0x0147
56 #define DRCI_REG_BASE           0x1100
57 #define DRCI_COMMAND            0x02
58 #define DRCI_READ_REQ           0xA0
59 #define DRCI_WRITE_REQ          0xA1
60
61 /**
62  * struct most_dci_obj - Direct Communication Interface
63  * @kobj:position in sysfs
64  * @usb_device: pointer to the usb device
65  * @reg_addr: register address for arbitrary DCI access
66  */
67 struct most_dci_obj {
68         struct device dev;
69         struct usb_device *usb_device;
70         u16 reg_addr;
71 };
72
73 #define to_dci_obj(p) container_of(p, struct most_dci_obj, dev)
74
75 struct most_dev;
76
77 struct clear_hold_work {
78         struct work_struct ws;
79         struct most_dev *mdev;
80         unsigned int channel;
81         int pipe;
82 };
83
84 #define to_clear_hold_work(w) container_of(w, struct clear_hold_work, ws)
85
86 /**
87  * struct most_dev - holds all usb interface specific stuff
88  * @usb_device: pointer to usb device
89  * @iface: hardware interface
90  * @cap: channel capabilities
91  * @conf: channel configuration
92  * @dci: direct communication interface of hardware
93  * @ep_address: endpoint address table
94  * @description: device description
95  * @suffix: suffix for channel name
96  * @channel_lock: synchronize channel access
97  * @padding_active: indicates channel uses padding
98  * @is_channel_healthy: health status table of each channel
99  * @busy_urbs: list of anchored items
100  * @io_mutex: synchronize I/O with disconnect
101  * @link_stat_timer: timer for link status reports
102  * @poll_work_obj: work for polling link status
103  */
104 struct most_dev {
105         struct usb_device *usb_device;
106         struct most_interface iface;
107         struct most_channel_capability *cap;
108         struct most_channel_config *conf;
109         struct most_dci_obj *dci;
110         u8 *ep_address;
111         char description[MAX_STRING_LEN];
112         char suffix[MAX_NUM_ENDPOINTS][MAX_SUFFIX_LEN];
113         spinlock_t channel_lock[MAX_NUM_ENDPOINTS]; /* sync channel access */
114         bool padding_active[MAX_NUM_ENDPOINTS];
115         bool is_channel_healthy[MAX_NUM_ENDPOINTS];
116         struct clear_hold_work clear_work[MAX_NUM_ENDPOINTS];
117         struct usb_anchor *busy_urbs;
118         struct mutex io_mutex;
119         struct timer_list link_stat_timer;
120         struct work_struct poll_work_obj;
121         void (*on_netinfo)(struct most_interface *most_iface,
122                            unsigned char link_state, unsigned char *addrs);
123 };
124
125 #define to_mdev(d) container_of(d, struct most_dev, iface)
126 #define to_mdev_from_work(w) container_of(w, struct most_dev, poll_work_obj)
127
128 static void wq_clear_halt(struct work_struct *wq_obj);
129 static void wq_netinfo(struct work_struct *wq_obj);
130
131 /**
132  * drci_rd_reg - read a DCI register
133  * @dev: usb device
134  * @reg: register address
135  * @buf: buffer to store data
136  *
137  * This is reads data from INIC's direct register communication interface
138  */
139 static inline int drci_rd_reg(struct usb_device *dev, u16 reg, u16 *buf)
140 {
141         int retval;
142         __le16 *dma_buf = kzalloc(sizeof(*dma_buf), GFP_KERNEL);
143         u8 req_type = USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE;
144
145         if (!dma_buf)
146                 return -ENOMEM;
147
148         retval = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
149                                  DRCI_READ_REQ, req_type,
150                                  0x0000,
151                                  reg, dma_buf, sizeof(*dma_buf), 5 * HZ);
152         *buf = le16_to_cpu(*dma_buf);
153         kfree(dma_buf);
154
155         return retval;
156 }
157
158 /**
159  * drci_wr_reg - write a DCI register
160  * @dev: usb device
161  * @reg: register address
162  * @data: data to write
163  *
164  * This is writes data to INIC's direct register communication interface
165  */
166 static inline int drci_wr_reg(struct usb_device *dev, u16 reg, u16 data)
167 {
168         return usb_control_msg(dev,
169                                usb_sndctrlpipe(dev, 0),
170                                DRCI_WRITE_REQ,
171                                USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
172                                data,
173                                reg,
174                                NULL,
175                                0,
176                                5 * HZ);
177 }
178
179 static inline int start_sync_ep(struct usb_device *usb_dev, u16 ep)
180 {
181         return drci_wr_reg(usb_dev, DRCI_REG_BASE + DRCI_COMMAND + ep * 16, 1);
182 }
183
184 /**
185  * get_stream_frame_size - calculate frame size of current configuration
186  * @cfg: channel configuration
187  */
188 static unsigned int get_stream_frame_size(struct most_channel_config *cfg)
189 {
190         unsigned int frame_size = 0;
191         unsigned int sub_size = cfg->subbuffer_size;
192
193         if (!sub_size) {
194                 pr_warn("Misconfig: Subbuffer size zero.\n");
195                 return frame_size;
196         }
197         switch (cfg->data_type) {
198         case MOST_CH_ISOC:
199                 frame_size = AV_PACKETS_PER_XACT * sub_size;
200                 break;
201         case MOST_CH_SYNC:
202                 if (cfg->packets_per_xact == 0) {
203                         pr_warn("Misconfig: Packets per XACT zero\n");
204                         frame_size = 0;
205                 } else if (cfg->packets_per_xact == 0xFF) {
206                         frame_size = (USB_MTU / sub_size) * sub_size;
207                 } else {
208                         frame_size = cfg->packets_per_xact * sub_size;
209                 }
210                 break;
211         default:
212                 pr_warn("Query frame size of non-streaming channel\n");
213                 break;
214         }
215         return frame_size;
216 }
217
218 /**
219  * hdm_poison_channel - mark buffers of this channel as invalid
220  * @iface: pointer to the interface
221  * @channel: channel ID
222  *
223  * This unlinks all URBs submitted to the HCD,
224  * calls the associated completion function of the core and removes
225  * them from the list.
226  *
227  * Returns 0 on success or error code otherwise.
228  */
229 static int hdm_poison_channel(struct most_interface *iface, int channel)
230 {
231         struct most_dev *mdev = to_mdev(iface);
232         unsigned long flags;
233         spinlock_t *lock; /* temp. lock */
234
235         if (unlikely(!iface)) {
236                 dev_warn(&mdev->usb_device->dev, "Poison: Bad interface.\n");
237                 return -EIO;
238         }
239         if (unlikely(channel < 0 || channel >= iface->num_channels)) {
240                 dev_warn(&mdev->usb_device->dev, "Channel ID out of range.\n");
241                 return -ECHRNG;
242         }
243
244         lock = mdev->channel_lock + channel;
245         spin_lock_irqsave(lock, flags);
246         mdev->is_channel_healthy[channel] = false;
247         spin_unlock_irqrestore(lock, flags);
248
249         cancel_work_sync(&mdev->clear_work[channel].ws);
250
251         mutex_lock(&mdev->io_mutex);
252         usb_kill_anchored_urbs(&mdev->busy_urbs[channel]);
253         if (mdev->padding_active[channel])
254                 mdev->padding_active[channel] = false;
255
256         if (mdev->conf[channel].data_type == MOST_CH_ASYNC) {
257                 del_timer_sync(&mdev->link_stat_timer);
258                 cancel_work_sync(&mdev->poll_work_obj);
259         }
260         mutex_unlock(&mdev->io_mutex);
261         return 0;
262 }
263
264 /**
265  * hdm_add_padding - add padding bytes
266  * @mdev: most device
267  * @channel: channel ID
268  * @mbo: buffer object
269  *
270  * This inserts the INIC hardware specific padding bytes into a streaming
271  * channel's buffer
272  */
273 static int hdm_add_padding(struct most_dev *mdev, int channel, struct mbo *mbo)
274 {
275         struct most_channel_config *conf = &mdev->conf[channel];
276         unsigned int frame_size = get_stream_frame_size(conf);
277         unsigned int j, num_frames;
278
279         if (!frame_size)
280                 return -EIO;
281         num_frames = mbo->buffer_length / frame_size;
282
283         if (num_frames < 1) {
284                 dev_err(&mdev->usb_device->dev,
285                         "Missed minimal transfer unit.\n");
286                 return -EIO;
287         }
288
289         for (j = num_frames - 1; j > 0; j--)
290                 memmove(mbo->virt_address + j * USB_MTU,
291                         mbo->virt_address + j * frame_size,
292                         frame_size);
293         mbo->buffer_length = num_frames * USB_MTU;
294         return 0;
295 }
296
297 /**
298  * hdm_remove_padding - remove padding bytes
299  * @mdev: most device
300  * @channel: channel ID
301  * @mbo: buffer object
302  *
303  * This takes the INIC hardware specific padding bytes off a streaming
304  * channel's buffer.
305  */
306 static int hdm_remove_padding(struct most_dev *mdev, int channel,
307                               struct mbo *mbo)
308 {
309         struct most_channel_config *const conf = &mdev->conf[channel];
310         unsigned int frame_size = get_stream_frame_size(conf);
311         unsigned int j, num_frames;
312
313         if (!frame_size)
314                 return -EIO;
315         num_frames = mbo->processed_length / USB_MTU;
316
317         for (j = 1; j < num_frames; j++)
318                 memmove(mbo->virt_address + frame_size * j,
319                         mbo->virt_address + USB_MTU * j,
320                         frame_size);
321
322         mbo->processed_length = frame_size * num_frames;
323         return 0;
324 }
325
326 /**
327  * hdm_write_completion - completion function for submitted Tx URBs
328  * @urb: the URB that has been completed
329  *
330  * This checks the status of the completed URB. In case the URB has been
331  * unlinked before, it is immediately freed. On any other error the MBO
332  * transfer flag is set. On success it frees allocated resources and calls
333  * the completion function.
334  *
335  * Context: interrupt!
336  */
337 static void hdm_write_completion(struct urb *urb)
338 {
339         struct mbo *mbo = urb->context;
340         struct most_dev *mdev = to_mdev(mbo->ifp);
341         unsigned int channel = mbo->hdm_channel_id;
342         spinlock_t *lock = mdev->channel_lock + channel;
343         unsigned long flags;
344
345         spin_lock_irqsave(lock, flags);
346
347         mbo->processed_length = 0;
348         mbo->status = MBO_E_INVAL;
349         if (likely(mdev->is_channel_healthy[channel])) {
350                 switch (urb->status) {
351                 case 0:
352                 case -ESHUTDOWN:
353                         mbo->processed_length = urb->actual_length;
354                         mbo->status = MBO_SUCCESS;
355                         break;
356                 case -EPIPE:
357                         dev_warn(&mdev->usb_device->dev,
358                                  "Broken pipe on ep%02x\n",
359                                  mdev->ep_address[channel]);
360                         mdev->is_channel_healthy[channel] = false;
361                         mdev->clear_work[channel].pipe = urb->pipe;
362                         schedule_work(&mdev->clear_work[channel].ws);
363                         break;
364                 case -ENODEV:
365                 case -EPROTO:
366                         mbo->status = MBO_E_CLOSE;
367                         break;
368                 }
369         }
370
371         spin_unlock_irqrestore(lock, flags);
372
373         if (likely(mbo->complete))
374                 mbo->complete(mbo);
375         usb_free_urb(urb);
376 }
377
378 /**
379  * hdm_read_completion - completion function for submitted Rx URBs
380  * @urb: the URB that has been completed
381  *
382  * This checks the status of the completed URB. In case the URB has been
383  * unlinked before it is immediately freed. On any other error the MBO transfer
384  * flag is set. On success it frees allocated resources, removes
385  * padding bytes -if necessary- and calls the completion function.
386  *
387  * Context: interrupt!
388  *
389  * **************************************************************************
390  *                   Error codes returned by in urb->status
391  *                   or in iso_frame_desc[n].status (for ISO)
392  * *************************************************************************
393  *
394  * USB device drivers may only test urb status values in completion handlers.
395  * This is because otherwise there would be a race between HCDs updating
396  * these values on one CPU, and device drivers testing them on another CPU.
397  *
398  * A transfer's actual_length may be positive even when an error has been
399  * reported.  That's because transfers often involve several packets, so that
400  * one or more packets could finish before an error stops further endpoint I/O.
401  *
402  * For isochronous URBs, the urb status value is non-zero only if the URB is
403  * unlinked, the device is removed, the host controller is disabled or the total
404  * transferred length is less than the requested length and the URB_SHORT_NOT_OK
405  * flag is set.  Completion handlers for isochronous URBs should only see
406  * urb->status set to zero, -ENOENT, -ECONNRESET, -ESHUTDOWN, or -EREMOTEIO.
407  * Individual frame descriptor status fields may report more status codes.
408  *
409  *
410  * 0                    Transfer completed successfully
411  *
412  * -ENOENT              URB was synchronously unlinked by usb_unlink_urb
413  *
414  * -EINPROGRESS         URB still pending, no results yet
415  *                      (That is, if drivers see this it's a bug.)
416  *
417  * -EPROTO (*, **)      a) bitstuff error
418  *                      b) no response packet received within the
419  *                         prescribed bus turn-around time
420  *                      c) unknown USB error
421  *
422  * -EILSEQ (*, **)      a) CRC mismatch
423  *                      b) no response packet received within the
424  *                         prescribed bus turn-around time
425  *                      c) unknown USB error
426  *
427  *                      Note that often the controller hardware does not
428  *                      distinguish among cases a), b), and c), so a
429  *                      driver cannot tell whether there was a protocol
430  *                      error, a failure to respond (often caused by
431  *                      device disconnect), or some other fault.
432  *
433  * -ETIME (**)          No response packet received within the prescribed
434  *                      bus turn-around time.  This error may instead be
435  *                      reported as -EPROTO or -EILSEQ.
436  *
437  * -ETIMEDOUT           Synchronous USB message functions use this code
438  *                      to indicate timeout expired before the transfer
439  *                      completed, and no other error was reported by HC.
440  *
441  * -EPIPE (**)          Endpoint stalled.  For non-control endpoints,
442  *                      reset this status with usb_clear_halt().
443  *
444  * -ECOMM               During an IN transfer, the host controller
445  *                      received data from an endpoint faster than it
446  *                      could be written to system memory
447  *
448  * -ENOSR               During an OUT transfer, the host controller
449  *                      could not retrieve data from system memory fast
450  *                      enough to keep up with the USB data rate
451  *
452  * -EOVERFLOW (*)       The amount of data returned by the endpoint was
453  *                      greater than either the max packet size of the
454  *                      endpoint or the remaining buffer size.  "Babble".
455  *
456  * -EREMOTEIO           The data read from the endpoint did not fill the
457  *                      specified buffer, and URB_SHORT_NOT_OK was set in
458  *                      urb->transfer_flags.
459  *
460  * -ENODEV              Device was removed.  Often preceded by a burst of
461  *                      other errors, since the hub driver doesn't detect
462  *                      device removal events immediately.
463  *
464  * -EXDEV               ISO transfer only partially completed
465  *                      (only set in iso_frame_desc[n].status, not urb->status)
466  *
467  * -EINVAL              ISO madness, if this happens: Log off and go home
468  *
469  * -ECONNRESET          URB was asynchronously unlinked by usb_unlink_urb
470  *
471  * -ESHUTDOWN           The device or host controller has been disabled due
472  *                      to some problem that could not be worked around,
473  *                      such as a physical disconnect.
474  *
475  *
476  * (*) Error codes like -EPROTO, -EILSEQ and -EOVERFLOW normally indicate
477  * hardware problems such as bad devices (including firmware) or cables.
478  *
479  * (**) This is also one of several codes that different kinds of host
480  * controller use to indicate a transfer has failed because of device
481  * disconnect.  In the interval before the hub driver starts disconnect
482  * processing, devices may receive such fault reports for every request.
483  *
484  * See <https://www.kernel.org/doc/Documentation/driver-api/usb/error-codes.rst>
485  */
486 static void hdm_read_completion(struct urb *urb)
487 {
488         struct mbo *mbo = urb->context;
489         struct most_dev *mdev = to_mdev(mbo->ifp);
490         unsigned int channel = mbo->hdm_channel_id;
491         struct device *dev = &mdev->usb_device->dev;
492         spinlock_t *lock = mdev->channel_lock + channel;
493         unsigned long flags;
494
495         spin_lock_irqsave(lock, flags);
496
497         mbo->processed_length = 0;
498         mbo->status = MBO_E_INVAL;
499         if (likely(mdev->is_channel_healthy[channel])) {
500                 switch (urb->status) {
501                 case 0:
502                 case -ESHUTDOWN:
503                         mbo->processed_length = urb->actual_length;
504                         mbo->status = MBO_SUCCESS;
505                         if (mdev->padding_active[channel] &&
506                             hdm_remove_padding(mdev, channel, mbo)) {
507                                 mbo->processed_length = 0;
508                                 mbo->status = MBO_E_INVAL;
509                         }
510                         break;
511                 case -EPIPE:
512                         dev_warn(dev, "Broken pipe on ep%02x\n",
513                                  mdev->ep_address[channel]);
514                         mdev->is_channel_healthy[channel] = false;
515                         mdev->clear_work[channel].pipe = urb->pipe;
516                         schedule_work(&mdev->clear_work[channel].ws);
517                         break;
518                 case -ENODEV:
519                 case -EPROTO:
520                         mbo->status = MBO_E_CLOSE;
521                         break;
522                 case -EOVERFLOW:
523                         dev_warn(dev, "Babble on ep%02x\n",
524                                  mdev->ep_address[channel]);
525                         break;
526                 }
527         }
528
529         spin_unlock_irqrestore(lock, flags);
530
531         if (likely(mbo->complete))
532                 mbo->complete(mbo);
533         usb_free_urb(urb);
534 }
535
536 /**
537  * hdm_enqueue - receive a buffer to be used for data transfer
538  * @iface: interface to enqueue to
539  * @channel: ID of the channel
540  * @mbo: pointer to the buffer object
541  *
542  * This allocates a new URB and fills it according to the channel
543  * that is being used for transmission of data. Before the URB is
544  * submitted it is stored in the private anchor list.
545  *
546  * Returns 0 on success. On any error the URB is freed and a error code
547  * is returned.
548  *
549  * Context: Could in _some_ cases be interrupt!
550  */
551 static int hdm_enqueue(struct most_interface *iface, int channel,
552                        struct mbo *mbo)
553 {
554         struct most_dev *mdev;
555         struct most_channel_config *conf;
556         int retval = 0;
557         struct urb *urb;
558         unsigned long length;
559         void *virt_address;
560
561         if (unlikely(!iface || !mbo))
562                 return -EIO;
563         if (unlikely(iface->num_channels <= channel || channel < 0))
564                 return -ECHRNG;
565
566         mdev = to_mdev(iface);
567         conf = &mdev->conf[channel];
568
569         mutex_lock(&mdev->io_mutex);
570         if (!mdev->usb_device) {
571                 retval = -ENODEV;
572                 goto unlock_io_mutex;
573         }
574
575         urb = usb_alloc_urb(NO_ISOCHRONOUS_URB, GFP_ATOMIC);
576         if (!urb) {
577                 retval = -ENOMEM;
578                 goto unlock_io_mutex;
579         }
580
581         if ((conf->direction & MOST_CH_TX) && mdev->padding_active[channel] &&
582             hdm_add_padding(mdev, channel, mbo)) {
583                 retval = -EIO;
584                 goto err_free_urb;
585         }
586
587         urb->transfer_dma = mbo->bus_address;
588         virt_address = mbo->virt_address;
589         length = mbo->buffer_length;
590
591         if (conf->direction & MOST_CH_TX) {
592                 usb_fill_bulk_urb(urb, mdev->usb_device,
593                                   usb_sndbulkpipe(mdev->usb_device,
594                                                   mdev->ep_address[channel]),
595                                   virt_address,
596                                   length,
597                                   hdm_write_completion,
598                                   mbo);
599                 if (conf->data_type != MOST_CH_ISOC &&
600                     conf->data_type != MOST_CH_SYNC)
601                         urb->transfer_flags |= URB_ZERO_PACKET;
602         } else {
603                 usb_fill_bulk_urb(urb, mdev->usb_device,
604                                   usb_rcvbulkpipe(mdev->usb_device,
605                                                   mdev->ep_address[channel]),
606                                   virt_address,
607                                   length + conf->extra_len,
608                                   hdm_read_completion,
609                                   mbo);
610         }
611         urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
612
613         usb_anchor_urb(urb, &mdev->busy_urbs[channel]);
614
615         retval = usb_submit_urb(urb, GFP_KERNEL);
616         if (retval) {
617                 dev_err(&mdev->usb_device->dev,
618                         "URB submit failed with error %d.\n", retval);
619                 goto err_unanchor_urb;
620         }
621         goto unlock_io_mutex;
622
623 err_unanchor_urb:
624         usb_unanchor_urb(urb);
625 err_free_urb:
626         usb_free_urb(urb);
627 unlock_io_mutex:
628         mutex_unlock(&mdev->io_mutex);
629         return retval;
630 }
631
632 static void *hdm_dma_alloc(struct mbo *mbo, u32 size)
633 {
634         struct most_dev *mdev = to_mdev(mbo->ifp);
635
636         return usb_alloc_coherent(mdev->usb_device, size, GFP_KERNEL,
637                                   &mbo->bus_address);
638 }
639
640 static void hdm_dma_free(struct mbo *mbo, u32 size)
641 {
642         struct most_dev *mdev = to_mdev(mbo->ifp);
643
644         usb_free_coherent(mdev->usb_device, size, mbo->virt_address,
645                           mbo->bus_address);
646 }
647
648 /**
649  * hdm_configure_channel - receive channel configuration from core
650  * @iface: interface
651  * @channel: channel ID
652  * @conf: structure that holds the configuration information
653  *
654  * The attached network interface controller (NIC) supports a padding mode
655  * to avoid short packets on USB, hence increasing the performance due to a
656  * lower interrupt load. This mode is default for synchronous data and can
657  * be switched on for isochronous data. In case padding is active the
658  * driver needs to know the frame size of the payload in order to calculate
659  * the number of bytes it needs to pad when transmitting or to cut off when
660  * receiving data.
661  *
662  */
663 static int hdm_configure_channel(struct most_interface *iface, int channel,
664                                  struct most_channel_config *conf)
665 {
666         unsigned int num_frames;
667         unsigned int frame_size;
668         struct most_dev *mdev = to_mdev(iface);
669         struct device *dev = &mdev->usb_device->dev;
670
671         mdev->is_channel_healthy[channel] = true;
672         mdev->clear_work[channel].channel = channel;
673         mdev->clear_work[channel].mdev = mdev;
674         INIT_WORK(&mdev->clear_work[channel].ws, wq_clear_halt);
675
676         if (unlikely(!iface || !conf)) {
677                 dev_err(dev, "Bad interface or config pointer.\n");
678                 return -EINVAL;
679         }
680         if (unlikely(channel < 0 || channel >= iface->num_channels)) {
681                 dev_err(dev, "Channel ID out of range.\n");
682                 return -EINVAL;
683         }
684         if (!conf->num_buffers || !conf->buffer_size) {
685                 dev_err(dev, "Misconfig: buffer size or #buffers zero.\n");
686                 return -EINVAL;
687         }
688
689         if (conf->data_type != MOST_CH_SYNC &&
690             !(conf->data_type == MOST_CH_ISOC &&
691               conf->packets_per_xact != 0xFF)) {
692                 mdev->padding_active[channel] = false;
693                 /*
694                  * Since the NIC's padding mode is not going to be
695                  * used, we can skip the frame size calculations and
696                  * move directly on to exit.
697                  */
698                 goto exit;
699         }
700
701         mdev->padding_active[channel] = true;
702
703         frame_size = get_stream_frame_size(conf);
704         if (frame_size == 0 || frame_size > USB_MTU) {
705                 dev_warn(dev, "Misconfig: frame size wrong\n");
706                 return -EINVAL;
707         }
708
709         num_frames = conf->buffer_size / frame_size;
710
711         if (conf->buffer_size % frame_size) {
712                 u16 old_size = conf->buffer_size;
713
714                 conf->buffer_size = num_frames * frame_size;
715                 dev_warn(dev, "%s: fixed buffer size (%d -> %d)\n",
716                          mdev->suffix[channel], old_size, conf->buffer_size);
717         }
718
719         /* calculate extra length to comply w/ HW padding */
720         conf->extra_len = num_frames * (USB_MTU - frame_size);
721
722 exit:
723         mdev->conf[channel] = *conf;
724         if (conf->data_type == MOST_CH_ASYNC) {
725                 u16 ep = mdev->ep_address[channel];
726
727                 if (start_sync_ep(mdev->usb_device, ep) < 0)
728                         dev_warn(dev, "sync for ep%02x failed", ep);
729         }
730         return 0;
731 }
732
733 /**
734  * hdm_request_netinfo - request network information
735  * @iface: pointer to interface
736  * @channel: channel ID
737  *
738  * This is used as trigger to set up the link status timer that
739  * polls for the NI state of the INIC every 2 seconds.
740  *
741  */
742 static void hdm_request_netinfo(struct most_interface *iface, int channel,
743                                 void (*on_netinfo)(struct most_interface *,
744                                                    unsigned char,
745                                                    unsigned char *))
746 {
747         struct most_dev *mdev;
748
749         BUG_ON(!iface);
750         mdev = to_mdev(iface);
751         mdev->on_netinfo = on_netinfo;
752         if (!on_netinfo)
753                 return;
754
755         mdev->link_stat_timer.expires = jiffies + HZ;
756         mod_timer(&mdev->link_stat_timer, mdev->link_stat_timer.expires);
757 }
758
759 /**
760  * link_stat_timer_handler - schedule work obtaining mac address and link status
761  * @data: pointer to USB device instance
762  *
763  * The handler runs in interrupt context. That's why we need to defer the
764  * tasks to a work queue.
765  */
766 static void link_stat_timer_handler(struct timer_list *t)
767 {
768         struct most_dev *mdev = from_timer(mdev, t, link_stat_timer);
769
770         schedule_work(&mdev->poll_work_obj);
771         mdev->link_stat_timer.expires = jiffies + (2 * HZ);
772         add_timer(&mdev->link_stat_timer);
773 }
774
775 /**
776  * wq_netinfo - work queue function to deliver latest networking information
777  * @wq_obj: object that holds data for our deferred work to do
778  *
779  * This retrieves the network interface status of the USB INIC
780  */
781 static void wq_netinfo(struct work_struct *wq_obj)
782 {
783         struct most_dev *mdev = to_mdev_from_work(wq_obj);
784         struct usb_device *usb_device = mdev->usb_device;
785         struct device *dev = &usb_device->dev;
786         u16 hi, mi, lo, link;
787         u8 hw_addr[6];
788
789         if (drci_rd_reg(usb_device, DRCI_REG_HW_ADDR_HI, &hi) < 0) {
790                 dev_err(dev, "Vendor request 'hw_addr_hi' failed\n");
791                 return;
792         }
793
794         if (drci_rd_reg(usb_device, DRCI_REG_HW_ADDR_MI, &mi) < 0) {
795                 dev_err(dev, "Vendor request 'hw_addr_mid' failed\n");
796                 return;
797         }
798
799         if (drci_rd_reg(usb_device, DRCI_REG_HW_ADDR_LO, &lo) < 0) {
800                 dev_err(dev, "Vendor request 'hw_addr_low' failed\n");
801                 return;
802         }
803
804         if (drci_rd_reg(usb_device, DRCI_REG_NI_STATE, &link) < 0) {
805                 dev_err(dev, "Vendor request 'link status' failed\n");
806                 return;
807         }
808
809         hw_addr[0] = hi >> 8;
810         hw_addr[1] = hi;
811         hw_addr[2] = mi >> 8;
812         hw_addr[3] = mi;
813         hw_addr[4] = lo >> 8;
814         hw_addr[5] = lo;
815
816         if (mdev->on_netinfo)
817                 mdev->on_netinfo(&mdev->iface, link, hw_addr);
818 }
819
820 /**
821  * wq_clear_halt - work queue function
822  * @wq_obj: work_struct object to execute
823  *
824  * This sends a clear_halt to the given USB pipe.
825  */
826 static void wq_clear_halt(struct work_struct *wq_obj)
827 {
828         struct clear_hold_work *clear_work = to_clear_hold_work(wq_obj);
829         struct most_dev *mdev = clear_work->mdev;
830         unsigned int channel = clear_work->channel;
831         int pipe = clear_work->pipe;
832
833         mutex_lock(&mdev->io_mutex);
834         most_stop_enqueue(&mdev->iface, channel);
835         usb_kill_anchored_urbs(&mdev->busy_urbs[channel]);
836         if (usb_clear_halt(mdev->usb_device, pipe))
837                 dev_warn(&mdev->usb_device->dev, "Failed to reset endpoint.\n");
838
839         /* If the functional Stall condition has been set on an
840          * asynchronous rx channel, we need to clear the tx channel
841          * too, since the hardware runs its clean-up sequence on both
842          * channels, as they are physically one on the network.
843          *
844          * The USB interface that exposes the asynchronous channels
845          * contains always two endpoints, and two only.
846          */
847         if (mdev->conf[channel].data_type == MOST_CH_ASYNC &&
848             mdev->conf[channel].direction == MOST_CH_RX) {
849                 int peer = 1 - channel;
850                 int snd_pipe = usb_sndbulkpipe(mdev->usb_device,
851                                                mdev->ep_address[peer]);
852                 usb_clear_halt(mdev->usb_device, snd_pipe);
853         }
854         mdev->is_channel_healthy[channel] = true;
855         most_resume_enqueue(&mdev->iface, channel);
856         mutex_unlock(&mdev->io_mutex);
857 }
858
859 /**
860  * hdm_usb_fops - file operation table for USB driver
861  */
862 static const struct file_operations hdm_usb_fops = {
863         .owner = THIS_MODULE,
864 };
865
866 /**
867  * usb_device_id - ID table for HCD device probing
868  */
869 static const struct usb_device_id usbid[] = {
870         { USB_DEVICE(USB_VENDOR_ID_SMSC, USB_DEV_ID_BRDG), },
871         { USB_DEVICE(USB_VENDOR_ID_SMSC, USB_DEV_ID_OS81118), },
872         { USB_DEVICE(USB_VENDOR_ID_SMSC, USB_DEV_ID_OS81119), },
873         { USB_DEVICE(USB_VENDOR_ID_SMSC, USB_DEV_ID_OS81210), },
874         { } /* Terminating entry */
875 };
876
877 struct regs {
878         const char *name;
879         u16 reg;
880 };
881
882 static const struct regs ro_regs[] = {
883         { "ni_state", DRCI_REG_NI_STATE },
884         { "packet_bandwidth", DRCI_REG_PACKET_BW },
885         { "node_address", DRCI_REG_NODE_ADDR },
886         { "node_position", DRCI_REG_NODE_POS },
887 };
888
889 static const struct regs rw_regs[] = {
890         { "mep_filter", DRCI_REG_MEP_FILTER },
891         { "mep_hash0", DRCI_REG_HASH_TBL0 },
892         { "mep_hash1", DRCI_REG_HASH_TBL1 },
893         { "mep_hash2", DRCI_REG_HASH_TBL2 },
894         { "mep_hash3", DRCI_REG_HASH_TBL3 },
895         { "mep_eui48_hi", DRCI_REG_HW_ADDR_HI },
896         { "mep_eui48_mi", DRCI_REG_HW_ADDR_MI },
897         { "mep_eui48_lo", DRCI_REG_HW_ADDR_LO },
898 };
899
900 static int get_stat_reg_addr(const struct regs *regs, int size,
901                              const char *name, u16 *reg_addr)
902 {
903         int i;
904
905         for (i = 0; i < size; i++) {
906                 if (!strcmp(name, regs[i].name)) {
907                         *reg_addr = regs[i].reg;
908                         return 0;
909                 }
910         }
911         return -EFAULT;
912 }
913
914 #define get_static_reg_addr(regs, name, reg_addr) \
915         get_stat_reg_addr(regs, ARRAY_SIZE(regs), name, reg_addr)
916
917 static ssize_t value_show(struct device *dev, struct device_attribute *attr,
918                           char *buf)
919 {
920         const char *name = attr->attr.name;
921         struct most_dci_obj *dci_obj = to_dci_obj(dev);
922         u16 val;
923         u16 reg_addr;
924         int err;
925
926         if (!strcmp(name, "arb_address"))
927                 return snprintf(buf, PAGE_SIZE, "%04x\n", dci_obj->reg_addr);
928
929         if (!strcmp(name, "arb_value"))
930                 reg_addr = dci_obj->reg_addr;
931         else if (get_static_reg_addr(ro_regs, name, &reg_addr) &&
932                  get_static_reg_addr(rw_regs, name, &reg_addr))
933                 return -EFAULT;
934
935         err = drci_rd_reg(dci_obj->usb_device, reg_addr, &val);
936         if (err < 0)
937                 return err;
938
939         return snprintf(buf, PAGE_SIZE, "%04x\n", val);
940 }
941
942 static ssize_t value_store(struct device *dev, struct device_attribute *attr,
943                            const char *buf, size_t count)
944 {
945         u16 val;
946         u16 reg_addr;
947         const char *name = attr->attr.name;
948         struct most_dci_obj *dci_obj = to_dci_obj(dev);
949         struct usb_device *usb_dev = dci_obj->usb_device;
950         int err = kstrtou16(buf, 16, &val);
951
952         if (err)
953                 return err;
954
955         if (!strcmp(name, "arb_address")) {
956                 dci_obj->reg_addr = val;
957                 return count;
958         }
959
960         if (!strcmp(name, "arb_value"))
961                 err = drci_wr_reg(usb_dev, dci_obj->reg_addr, val);
962         else if (!strcmp(name, "sync_ep"))
963                 err = start_sync_ep(usb_dev, val);
964         else if (!get_static_reg_addr(rw_regs, name, &reg_addr))
965                 err = drci_wr_reg(usb_dev, reg_addr, val);
966         else
967                 return -EFAULT;
968
969         if (err < 0)
970                 return err;
971
972         return count;
973 }
974
975 static DEVICE_ATTR(ni_state, 0444, value_show, NULL);
976 static DEVICE_ATTR(packet_bandwidth, 0444, value_show, NULL);
977 static DEVICE_ATTR(node_address, 0444, value_show, NULL);
978 static DEVICE_ATTR(node_position, 0444, value_show, NULL);
979 static DEVICE_ATTR(sync_ep, 0200, NULL, value_store);
980 static DEVICE_ATTR(mep_filter, 0644, value_show, value_store);
981 static DEVICE_ATTR(mep_hash0, 0644, value_show, value_store);
982 static DEVICE_ATTR(mep_hash1, 0644, value_show, value_store);
983 static DEVICE_ATTR(mep_hash2, 0644, value_show, value_store);
984 static DEVICE_ATTR(mep_hash3, 0644, value_show, value_store);
985 static DEVICE_ATTR(mep_eui48_hi, 0644, value_show, value_store);
986 static DEVICE_ATTR(mep_eui48_mi, 0644, value_show, value_store);
987 static DEVICE_ATTR(mep_eui48_lo, 0644, value_show, value_store);
988 static DEVICE_ATTR(arb_address, 0644, value_show, value_store);
989 static DEVICE_ATTR(arb_value, 0644, value_show, value_store);
990
991 static struct attribute *dci_attrs[] = {
992         &dev_attr_ni_state.attr,
993         &dev_attr_packet_bandwidth.attr,
994         &dev_attr_node_address.attr,
995         &dev_attr_node_position.attr,
996         &dev_attr_sync_ep.attr,
997         &dev_attr_mep_filter.attr,
998         &dev_attr_mep_hash0.attr,
999         &dev_attr_mep_hash1.attr,
1000         &dev_attr_mep_hash2.attr,
1001         &dev_attr_mep_hash3.attr,
1002         &dev_attr_mep_eui48_hi.attr,
1003         &dev_attr_mep_eui48_mi.attr,
1004         &dev_attr_mep_eui48_lo.attr,
1005         &dev_attr_arb_address.attr,
1006         &dev_attr_arb_value.attr,
1007         NULL,
1008 };
1009
1010 static struct attribute_group dci_attr_group = {
1011         .attrs = dci_attrs,
1012 };
1013
1014 static const struct attribute_group *dci_attr_groups[] = {
1015         &dci_attr_group,
1016         NULL,
1017 };
1018
1019 static void release_dci(struct device *dev)
1020 {
1021         struct most_dci_obj *dci = to_dci_obj(dev);
1022
1023         kfree(dci);
1024 }
1025
1026 /**
1027  * hdm_probe - probe function of USB device driver
1028  * @interface: Interface of the attached USB device
1029  * @id: Pointer to the USB ID table.
1030  *
1031  * This allocates and initializes the device instance, adds the new
1032  * entry to the internal list, scans the USB descriptors and registers
1033  * the interface with the core.
1034  * Additionally, the DCI objects are created and the hardware is sync'd.
1035  *
1036  * Return 0 on success. In case of an error a negative number is returned.
1037  */
1038 static int
1039 hdm_probe(struct usb_interface *interface, const struct usb_device_id *id)
1040 {
1041         struct usb_host_interface *usb_iface_desc = interface->cur_altsetting;
1042         struct usb_device *usb_dev = interface_to_usbdev(interface);
1043         struct device *dev = &usb_dev->dev;
1044         struct most_dev *mdev = kzalloc(sizeof(*mdev), GFP_KERNEL);
1045         unsigned int i;
1046         unsigned int num_endpoints;
1047         struct most_channel_capability *tmp_cap;
1048         struct usb_endpoint_descriptor *ep_desc;
1049         int ret = 0;
1050
1051         if (!mdev)
1052                 goto err_out_of_memory;
1053
1054         usb_set_intfdata(interface, mdev);
1055         num_endpoints = usb_iface_desc->desc.bNumEndpoints;
1056         mutex_init(&mdev->io_mutex);
1057         INIT_WORK(&mdev->poll_work_obj, wq_netinfo);
1058         timer_setup(&mdev->link_stat_timer, link_stat_timer_handler, 0);
1059
1060         mdev->usb_device = usb_dev;
1061         mdev->link_stat_timer.expires = jiffies + (2 * HZ);
1062
1063         mdev->iface.mod = hdm_usb_fops.owner;
1064         mdev->iface.driver_dev = &interface->dev;
1065         mdev->iface.interface = ITYPE_USB;
1066         mdev->iface.configure = hdm_configure_channel;
1067         mdev->iface.request_netinfo = hdm_request_netinfo;
1068         mdev->iface.enqueue = hdm_enqueue;
1069         mdev->iface.poison_channel = hdm_poison_channel;
1070         mdev->iface.dma_alloc = hdm_dma_alloc;
1071         mdev->iface.dma_free = hdm_dma_free;
1072         mdev->iface.description = mdev->description;
1073         mdev->iface.num_channels = num_endpoints;
1074
1075         snprintf(mdev->description, sizeof(mdev->description),
1076                  "%d-%s:%d.%d",
1077                  usb_dev->bus->busnum,
1078                  usb_dev->devpath,
1079                  usb_dev->config->desc.bConfigurationValue,
1080                  usb_iface_desc->desc.bInterfaceNumber);
1081
1082         mdev->conf = kcalloc(num_endpoints, sizeof(*mdev->conf), GFP_KERNEL);
1083         if (!mdev->conf)
1084                 goto err_free_mdev;
1085
1086         mdev->cap = kcalloc(num_endpoints, sizeof(*mdev->cap), GFP_KERNEL);
1087         if (!mdev->cap)
1088                 goto err_free_conf;
1089
1090         mdev->iface.channel_vector = mdev->cap;
1091         mdev->ep_address =
1092                 kcalloc(num_endpoints, sizeof(*mdev->ep_address), GFP_KERNEL);
1093         if (!mdev->ep_address)
1094                 goto err_free_cap;
1095
1096         mdev->busy_urbs =
1097                 kcalloc(num_endpoints, sizeof(*mdev->busy_urbs), GFP_KERNEL);
1098         if (!mdev->busy_urbs)
1099                 goto err_free_ep_address;
1100
1101         tmp_cap = mdev->cap;
1102         for (i = 0; i < num_endpoints; i++) {
1103                 ep_desc = &usb_iface_desc->endpoint[i].desc;
1104                 mdev->ep_address[i] = ep_desc->bEndpointAddress;
1105                 mdev->padding_active[i] = false;
1106                 mdev->is_channel_healthy[i] = true;
1107
1108                 snprintf(&mdev->suffix[i][0], MAX_SUFFIX_LEN, "ep%02x",
1109                          mdev->ep_address[i]);
1110
1111                 tmp_cap->name_suffix = &mdev->suffix[i][0];
1112                 tmp_cap->buffer_size_packet = MAX_BUF_SIZE;
1113                 tmp_cap->buffer_size_streaming = MAX_BUF_SIZE;
1114                 tmp_cap->num_buffers_packet = BUF_CHAIN_SIZE;
1115                 tmp_cap->num_buffers_streaming = BUF_CHAIN_SIZE;
1116                 tmp_cap->data_type = MOST_CH_CONTROL | MOST_CH_ASYNC |
1117                                      MOST_CH_ISOC | MOST_CH_SYNC;
1118                 if (usb_endpoint_dir_in(ep_desc))
1119                         tmp_cap->direction = MOST_CH_RX;
1120                 else
1121                         tmp_cap->direction = MOST_CH_TX;
1122                 tmp_cap++;
1123                 init_usb_anchor(&mdev->busy_urbs[i]);
1124                 spin_lock_init(&mdev->channel_lock[i]);
1125         }
1126         dev_notice(dev, "claimed gadget: Vendor=%4.4x ProdID=%4.4x Bus=%02x Device=%02x\n",
1127                    le16_to_cpu(usb_dev->descriptor.idVendor),
1128                    le16_to_cpu(usb_dev->descriptor.idProduct),
1129                    usb_dev->bus->busnum,
1130                    usb_dev->devnum);
1131
1132         dev_notice(dev, "device path: /sys/bus/usb/devices/%d-%s:%d.%d\n",
1133                    usb_dev->bus->busnum,
1134                    usb_dev->devpath,
1135                    usb_dev->config->desc.bConfigurationValue,
1136                    usb_iface_desc->desc.bInterfaceNumber);
1137
1138         ret = most_register_interface(&mdev->iface);
1139         if (ret)
1140                 goto err_free_busy_urbs;
1141
1142         mutex_lock(&mdev->io_mutex);
1143         if (le16_to_cpu(usb_dev->descriptor.idProduct) == USB_DEV_ID_OS81118 ||
1144             le16_to_cpu(usb_dev->descriptor.idProduct) == USB_DEV_ID_OS81119 ||
1145             le16_to_cpu(usb_dev->descriptor.idProduct) == USB_DEV_ID_OS81210) {
1146                 mdev->dci = kzalloc(sizeof(*mdev->dci), GFP_KERNEL);
1147                 if (!mdev->dci) {
1148                         mutex_unlock(&mdev->io_mutex);
1149                         most_deregister_interface(&mdev->iface);
1150                         ret = -ENOMEM;
1151                         goto err_free_busy_urbs;
1152                 }
1153
1154                 mdev->dci->dev.init_name = "dci";
1155                 mdev->dci->dev.parent = &mdev->iface.dev;
1156                 mdev->dci->dev.groups = dci_attr_groups;
1157                 mdev->dci->dev.release = release_dci;
1158                 if (device_register(&mdev->dci->dev)) {
1159                         mutex_unlock(&mdev->io_mutex);
1160                         most_deregister_interface(&mdev->iface);
1161                         ret = -ENOMEM;
1162                         goto err_free_dci;
1163                 }
1164                 mdev->dci->usb_device = mdev->usb_device;
1165         }
1166         mutex_unlock(&mdev->io_mutex);
1167         return 0;
1168 err_free_dci:
1169         kfree(mdev->dci);
1170 err_free_busy_urbs:
1171         kfree(mdev->busy_urbs);
1172 err_free_ep_address:
1173         kfree(mdev->ep_address);
1174 err_free_cap:
1175         kfree(mdev->cap);
1176 err_free_conf:
1177         kfree(mdev->conf);
1178 err_free_mdev:
1179         kfree(mdev);
1180 err_out_of_memory:
1181         if (ret == 0 || ret == -ENOMEM) {
1182                 ret = -ENOMEM;
1183                 dev_err(dev, "out of memory\n");
1184         }
1185         return ret;
1186 }
1187
1188 /**
1189  * hdm_disconnect - disconnect function of USB device driver
1190  * @interface: Interface of the attached USB device
1191  *
1192  * This deregisters the interface with the core, removes the kernel timer
1193  * and frees resources.
1194  *
1195  * Context: hub kernel thread
1196  */
1197 static void hdm_disconnect(struct usb_interface *interface)
1198 {
1199         struct most_dev *mdev = usb_get_intfdata(interface);
1200
1201         mutex_lock(&mdev->io_mutex);
1202         usb_set_intfdata(interface, NULL);
1203         mdev->usb_device = NULL;
1204         mutex_unlock(&mdev->io_mutex);
1205
1206         del_timer_sync(&mdev->link_stat_timer);
1207         cancel_work_sync(&mdev->poll_work_obj);
1208
1209         device_unregister(&mdev->dci->dev);
1210         most_deregister_interface(&mdev->iface);
1211
1212         kfree(mdev->busy_urbs);
1213         kfree(mdev->cap);
1214         kfree(mdev->conf);
1215         kfree(mdev->ep_address);
1216         kfree(mdev);
1217 }
1218
1219 static struct usb_driver hdm_usb = {
1220         .name = "hdm_usb",
1221         .id_table = usbid,
1222         .probe = hdm_probe,
1223         .disconnect = hdm_disconnect,
1224 };
1225
1226 module_usb_driver(hdm_usb);
1227 MODULE_LICENSE("GPL");
1228 MODULE_AUTHOR("Christian Gromm <christian.gromm@microchip.com>");
1229 MODULE_DESCRIPTION("HDM_4_USB");