linux/drivers/net/can/usb/peak_usb/pcan_usb.c
<<
>>
Prefs
   1/*
   2 * CAN driver for PEAK System PCAN-USB adapter
   3 * Derived from the PCAN project file driver/src/pcan_usb.c
   4 *
   5 * Copyright (C) 2003-2010 PEAK System-Technik GmbH
   6 * Copyright (C) 2011-2012 Stephane Grosjean <s.grosjean@peak-system.com>
   7 *
   8 * Many thanks to Klaus Hitschler <klaus.hitschler@gmx.de>
   9 *
  10 * This program is free software; you can redistribute it and/or modify it
  11 * under the terms of the GNU General Public License as published
  12 * by the Free Software Foundation; version 2 of the License.
  13 *
  14 * This program is distributed in the hope that it will be useful, but
  15 * WITHOUT ANY WARRANTY; without even the implied warranty of
  16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  17 * General Public License for more details.
  18 */
  19#include <linux/netdevice.h>
  20#include <linux/usb.h>
  21#include <linux/module.h>
  22
  23#include <linux/can.h>
  24#include <linux/can/dev.h>
  25#include <linux/can/error.h>
  26
  27#include "pcan_usb_core.h"
  28
  29MODULE_SUPPORTED_DEVICE("PEAK-System PCAN-USB adapter");
  30
  31/* PCAN-USB Endpoints */
  32#define PCAN_USB_EP_CMDOUT              1
  33#define PCAN_USB_EP_CMDIN               (PCAN_USB_EP_CMDOUT | USB_DIR_IN)
  34#define PCAN_USB_EP_MSGOUT              2
  35#define PCAN_USB_EP_MSGIN               (PCAN_USB_EP_MSGOUT | USB_DIR_IN)
  36
  37/* PCAN-USB command struct */
  38#define PCAN_USB_CMD_FUNC               0
  39#define PCAN_USB_CMD_NUM                1
  40#define PCAN_USB_CMD_ARGS               2
  41#define PCAN_USB_CMD_ARGS_LEN           14
  42#define PCAN_USB_CMD_LEN                (PCAN_USB_CMD_ARGS + \
  43                                         PCAN_USB_CMD_ARGS_LEN)
  44
  45/* PCAN-USB commands */
  46#define PCAN_USB_CMD_BITRATE    1
  47#define PCAN_USB_CMD_SET_BUS    3
  48#define PCAN_USB_CMD_DEVID      4
  49#define PCAN_USB_CMD_SN         6
  50#define PCAN_USB_CMD_REGISTER   9
  51#define PCAN_USB_CMD_EXT_VCC    10
  52#define PCAN_USB_CMD_ERR_FR     11
  53
  54/* PCAN_USB_CMD_SET_BUS number arg */
  55#define PCAN_USB_BUS_XCVER              2
  56#define PCAN_USB_BUS_SILENT_MODE        3
  57
  58/* PCAN_USB_CMD_xxx functions */
  59#define PCAN_USB_GET            1
  60#define PCAN_USB_SET            2
  61
  62/* PCAN-USB command timeout (ms.) */
  63#define PCAN_USB_COMMAND_TIMEOUT        1000
  64
  65/* PCAN-USB startup timeout (ms.) */
  66#define PCAN_USB_STARTUP_TIMEOUT        10
  67
  68/* PCAN-USB rx/tx buffers size */
  69#define PCAN_USB_RX_BUFFER_SIZE         64
  70#define PCAN_USB_TX_BUFFER_SIZE         64
  71
  72#define PCAN_USB_MSG_HEADER_LEN         2
  73
  74/* PCAN-USB adapter internal clock (MHz) */
  75#define PCAN_USB_CRYSTAL_HZ             16000000
  76
  77/* PCAN-USB USB message record status/len field */
  78#define PCAN_USB_STATUSLEN_TIMESTAMP    (1 << 7)
  79#define PCAN_USB_STATUSLEN_INTERNAL     (1 << 6)
  80#define PCAN_USB_STATUSLEN_EXT_ID       (1 << 5)
  81#define PCAN_USB_STATUSLEN_RTR          (1 << 4)
  82#define PCAN_USB_STATUSLEN_DLC          (0xf)
  83
  84/* PCAN-USB error flags */
  85#define PCAN_USB_ERROR_TXFULL           0x01
  86#define PCAN_USB_ERROR_RXQOVR           0x02
  87#define PCAN_USB_ERROR_BUS_LIGHT        0x04
  88#define PCAN_USB_ERROR_BUS_HEAVY        0x08
  89#define PCAN_USB_ERROR_BUS_OFF          0x10
  90#define PCAN_USB_ERROR_RXQEMPTY         0x20
  91#define PCAN_USB_ERROR_QOVR             0x40
  92#define PCAN_USB_ERROR_TXQFULL          0x80
  93
  94#define PCAN_USB_ERROR_BUS              (PCAN_USB_ERROR_BUS_LIGHT | \
  95                                         PCAN_USB_ERROR_BUS_HEAVY | \
  96                                         PCAN_USB_ERROR_BUS_OFF)
  97
  98/* SJA1000 modes */
  99#define SJA1000_MODE_NORMAL             0x00
 100#define SJA1000_MODE_INIT               0x01
 101
 102/*
 103 * tick duration = 42.666 us =>
 104 * (tick_number * 44739243) >> 20 ~ (tick_number * 42666) / 1000
 105 * accuracy = 10^-7
 106 */
 107#define PCAN_USB_TS_DIV_SHIFTER         20
 108#define PCAN_USB_TS_US_PER_TICK         44739243
 109
 110/* PCAN-USB messages record types */
 111#define PCAN_USB_REC_ERROR              1
 112#define PCAN_USB_REC_ANALOG             2
 113#define PCAN_USB_REC_BUSLOAD            3
 114#define PCAN_USB_REC_TS                 4
 115#define PCAN_USB_REC_BUSEVT             5
 116
 117/* CAN bus events notifications selection mask */
 118#define PCAN_USB_ERR_RXERR              0x02    /* ask for rxerr counter */
 119#define PCAN_USB_ERR_TXERR              0x04    /* ask for txerr counter */
 120
 121/* This mask generates an usb packet each time the state of the bus changes.
 122 * In other words, its interest is to know which side among rx and tx is
 123 * responsible of the change of the bus state.
 124 */
 125#define PCAN_USB_BERR_MASK      (PCAN_USB_ERR_RXERR | PCAN_USB_ERR_TXERR)
 126
 127/* identify bus event packets with rx/tx error counters */
 128#define PCAN_USB_ERR_CNT                0x80
 129
 130/* private to PCAN-USB adapter */
 131struct pcan_usb {
 132        struct peak_usb_device dev;
 133        struct peak_time_ref time_ref;
 134        struct timer_list restart_timer;
 135        struct can_berr_counter bec;
 136};
 137
 138/* incoming message context for decoding */
 139struct pcan_usb_msg_context {
 140        u16 ts16;
 141        u8 prev_ts8;
 142        u8 *ptr;
 143        u8 *end;
 144        u8 rec_cnt;
 145        u8 rec_idx;
 146        u8 rec_ts_idx;
 147        struct net_device *netdev;
 148        struct pcan_usb *pdev;
 149};
 150
 151/*
 152 * send a command
 153 */
 154static int pcan_usb_send_cmd(struct peak_usb_device *dev, u8 f, u8 n, u8 *p)
 155{
 156        int err;
 157        int actual_length;
 158
 159        /* usb device unregistered? */
 160        if (!(dev->state & PCAN_USB_STATE_CONNECTED))
 161                return 0;
 162
 163        dev->cmd_buf[PCAN_USB_CMD_FUNC] = f;
 164        dev->cmd_buf[PCAN_USB_CMD_NUM] = n;
 165
 166        if (p)
 167                memcpy(dev->cmd_buf + PCAN_USB_CMD_ARGS,
 168                        p, PCAN_USB_CMD_ARGS_LEN);
 169
 170        err = usb_bulk_msg(dev->udev,
 171                        usb_sndbulkpipe(dev->udev, PCAN_USB_EP_CMDOUT),
 172                        dev->cmd_buf, PCAN_USB_CMD_LEN, &actual_length,
 173                        PCAN_USB_COMMAND_TIMEOUT);
 174        if (err)
 175                netdev_err(dev->netdev,
 176                        "sending cmd f=0x%x n=0x%x failure: %d\n",
 177                        f, n, err);
 178        return err;
 179}
 180
 181/*
 182 * send a command then wait for its response
 183 */
 184static int pcan_usb_wait_rsp(struct peak_usb_device *dev, u8 f, u8 n, u8 *p)
 185{
 186        int err;
 187        int actual_length;
 188
 189        /* usb device unregistered? */
 190        if (!(dev->state & PCAN_USB_STATE_CONNECTED))
 191                return 0;
 192
 193        /* first, send command */
 194        err = pcan_usb_send_cmd(dev, f, n, NULL);
 195        if (err)
 196                return err;
 197
 198        err = usb_bulk_msg(dev->udev,
 199                usb_rcvbulkpipe(dev->udev, PCAN_USB_EP_CMDIN),
 200                dev->cmd_buf, PCAN_USB_CMD_LEN, &actual_length,
 201                PCAN_USB_COMMAND_TIMEOUT);
 202        if (err)
 203                netdev_err(dev->netdev,
 204                        "waiting rsp f=0x%x n=0x%x failure: %d\n", f, n, err);
 205        else if (p)
 206                memcpy(p, dev->cmd_buf + PCAN_USB_CMD_ARGS,
 207                        PCAN_USB_CMD_ARGS_LEN);
 208
 209        return err;
 210}
 211
 212static int pcan_usb_set_sja1000(struct peak_usb_device *dev, u8 mode)
 213{
 214        u8 args[PCAN_USB_CMD_ARGS_LEN] = {
 215                [1] = mode,
 216        };
 217
 218        return pcan_usb_send_cmd(dev, PCAN_USB_CMD_REGISTER, PCAN_USB_SET,
 219                                 args);
 220}
 221
 222static int pcan_usb_set_bus(struct peak_usb_device *dev, u8 onoff)
 223{
 224        u8 args[PCAN_USB_CMD_ARGS_LEN] = {
 225                [0] = !!onoff,
 226        };
 227
 228        return pcan_usb_send_cmd(dev, PCAN_USB_CMD_SET_BUS, PCAN_USB_BUS_XCVER,
 229                                 args);
 230}
 231
 232static int pcan_usb_set_silent(struct peak_usb_device *dev, u8 onoff)
 233{
 234        u8 args[PCAN_USB_CMD_ARGS_LEN] = {
 235                [0] = !!onoff,
 236        };
 237
 238        return pcan_usb_send_cmd(dev, PCAN_USB_CMD_SET_BUS,
 239                                 PCAN_USB_BUS_SILENT_MODE, args);
 240}
 241
 242/* send the cmd to be notified from bus errors */
 243static int pcan_usb_set_err_frame(struct peak_usb_device *dev, u8 err_mask)
 244{
 245        u8 args[PCAN_USB_CMD_ARGS_LEN] = {
 246                [0] = err_mask,
 247        };
 248
 249        return pcan_usb_send_cmd(dev, PCAN_USB_CMD_ERR_FR, PCAN_USB_SET, args);
 250}
 251
 252static int pcan_usb_set_ext_vcc(struct peak_usb_device *dev, u8 onoff)
 253{
 254        u8 args[PCAN_USB_CMD_ARGS_LEN] = {
 255                [0] = !!onoff,
 256        };
 257
 258        return pcan_usb_send_cmd(dev, PCAN_USB_CMD_EXT_VCC, PCAN_USB_SET, args);
 259}
 260
 261/*
 262 * set bittiming value to can
 263 */
 264static int pcan_usb_set_bittiming(struct peak_usb_device *dev,
 265                                  struct can_bittiming *bt)
 266{
 267        u8 args[PCAN_USB_CMD_ARGS_LEN];
 268        u8 btr0, btr1;
 269
 270        btr0 = ((bt->brp - 1) & 0x3f) | (((bt->sjw - 1) & 0x3) << 6);
 271        btr1 = ((bt->prop_seg + bt->phase_seg1 - 1) & 0xf) |
 272                (((bt->phase_seg2 - 1) & 0x7) << 4);
 273        if (dev->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
 274                btr1 |= 0x80;
 275
 276        netdev_info(dev->netdev, "setting BTR0=0x%02x BTR1=0x%02x\n",
 277                btr0, btr1);
 278
 279        args[0] = btr1;
 280        args[1] = btr0;
 281
 282        return pcan_usb_send_cmd(dev, PCAN_USB_CMD_BITRATE, PCAN_USB_SET, args);
 283}
 284
 285/*
 286 * init/reset can
 287 */
 288static int pcan_usb_write_mode(struct peak_usb_device *dev, u8 onoff)
 289{
 290        int err;
 291
 292        err = pcan_usb_set_bus(dev, onoff);
 293        if (err)
 294                return err;
 295
 296        if (!onoff) {
 297                err = pcan_usb_set_sja1000(dev, SJA1000_MODE_INIT);
 298        } else {
 299                /* the PCAN-USB needs time to init */
 300                set_current_state(TASK_INTERRUPTIBLE);
 301                schedule_timeout(msecs_to_jiffies(PCAN_USB_STARTUP_TIMEOUT));
 302        }
 303
 304        return err;
 305}
 306
 307/*
 308 * handle end of waiting for the device to reset
 309 */
 310static void pcan_usb_restart(struct timer_list *t)
 311{
 312        struct pcan_usb *pdev = from_timer(pdev, t, restart_timer);
 313        struct peak_usb_device *dev = &pdev->dev;
 314
 315        /* notify candev and netdev */
 316        peak_usb_restart_complete(dev);
 317}
 318
 319/*
 320 * handle the submission of the restart urb
 321 */
 322static void pcan_usb_restart_pending(struct urb *urb)
 323{
 324        struct pcan_usb *pdev = urb->context;
 325
 326        /* the PCAN-USB needs time to restart */
 327        mod_timer(&pdev->restart_timer,
 328                        jiffies + msecs_to_jiffies(PCAN_USB_STARTUP_TIMEOUT));
 329
 330        /* can delete usb resources */
 331        peak_usb_async_complete(urb);
 332}
 333
 334/*
 335 * handle asynchronous restart
 336 */
 337static int pcan_usb_restart_async(struct peak_usb_device *dev, struct urb *urb,
 338                                  u8 *buf)
 339{
 340        struct pcan_usb *pdev = container_of(dev, struct pcan_usb, dev);
 341
 342        if (timer_pending(&pdev->restart_timer))
 343                return -EBUSY;
 344
 345        /* set bus on */
 346        buf[PCAN_USB_CMD_FUNC] = 3;
 347        buf[PCAN_USB_CMD_NUM] = 2;
 348        buf[PCAN_USB_CMD_ARGS] = 1;
 349
 350        usb_fill_bulk_urb(urb, dev->udev,
 351                        usb_sndbulkpipe(dev->udev, PCAN_USB_EP_CMDOUT),
 352                        buf, PCAN_USB_CMD_LEN,
 353                        pcan_usb_restart_pending, pdev);
 354
 355        return usb_submit_urb(urb, GFP_ATOMIC);
 356}
 357
 358/*
 359 * read serial number from device
 360 */
 361static int pcan_usb_get_serial(struct peak_usb_device *dev, u32 *serial_number)
 362{
 363        u8 args[PCAN_USB_CMD_ARGS_LEN];
 364        int err;
 365
 366        err = pcan_usb_wait_rsp(dev, PCAN_USB_CMD_SN, PCAN_USB_GET, args);
 367        if (err) {
 368                netdev_err(dev->netdev, "getting serial failure: %d\n", err);
 369        } else if (serial_number) {
 370                __le32 tmp32;
 371
 372                memcpy(&tmp32, args, 4);
 373                *serial_number = le32_to_cpu(tmp32);
 374        }
 375
 376        return err;
 377}
 378
 379/*
 380 * read device id from device
 381 */
 382static int pcan_usb_get_device_id(struct peak_usb_device *dev, u32 *device_id)
 383{
 384        u8 args[PCAN_USB_CMD_ARGS_LEN];
 385        int err;
 386
 387        err = pcan_usb_wait_rsp(dev, PCAN_USB_CMD_DEVID, PCAN_USB_GET, args);
 388        if (err)
 389                netdev_err(dev->netdev, "getting device id failure: %d\n", err);
 390        else if (device_id)
 391                *device_id = args[0];
 392
 393        return err;
 394}
 395
 396/*
 397 * update current time ref with received timestamp
 398 */
 399static int pcan_usb_update_ts(struct pcan_usb_msg_context *mc)
 400{
 401        __le16 tmp16;
 402
 403        if ((mc->ptr+2) > mc->end)
 404                return -EINVAL;
 405
 406        memcpy(&tmp16, mc->ptr, 2);
 407
 408        mc->ts16 = le16_to_cpu(tmp16);
 409
 410        if (mc->rec_idx > 0)
 411                peak_usb_update_ts_now(&mc->pdev->time_ref, mc->ts16);
 412        else
 413                peak_usb_set_ts_now(&mc->pdev->time_ref, mc->ts16);
 414
 415        return 0;
 416}
 417
 418/*
 419 * decode received timestamp
 420 */
 421static int pcan_usb_decode_ts(struct pcan_usb_msg_context *mc, u8 first_packet)
 422{
 423        /* only 1st packet supplies a word timestamp */
 424        if (first_packet) {
 425                __le16 tmp16;
 426
 427                if ((mc->ptr + 2) > mc->end)
 428                        return -EINVAL;
 429
 430                memcpy(&tmp16, mc->ptr, 2);
 431                mc->ptr += 2;
 432
 433                mc->ts16 = le16_to_cpu(tmp16);
 434                mc->prev_ts8 = mc->ts16 & 0x00ff;
 435        } else {
 436                u8 ts8;
 437
 438                if ((mc->ptr + 1) > mc->end)
 439                        return -EINVAL;
 440
 441                ts8 = *mc->ptr++;
 442
 443                if (ts8 < mc->prev_ts8)
 444                        mc->ts16 += 0x100;
 445
 446                mc->ts16 &= 0xff00;
 447                mc->ts16 |= ts8;
 448                mc->prev_ts8 = ts8;
 449        }
 450
 451        return 0;
 452}
 453
 454static int pcan_usb_decode_error(struct pcan_usb_msg_context *mc, u8 n,
 455                                 u8 status_len)
 456{
 457        struct sk_buff *skb;
 458        struct can_frame *cf;
 459        enum can_state new_state;
 460
 461        /* ignore this error until 1st ts received */
 462        if (n == PCAN_USB_ERROR_QOVR)
 463                if (!mc->pdev->time_ref.tick_count)
 464                        return 0;
 465
 466        new_state = mc->pdev->dev.can.state;
 467
 468        switch (mc->pdev->dev.can.state) {
 469        case CAN_STATE_ERROR_ACTIVE:
 470                if (n & PCAN_USB_ERROR_BUS_LIGHT) {
 471                        new_state = CAN_STATE_ERROR_WARNING;
 472                        break;
 473                }
 474                /* fall through */
 475
 476        case CAN_STATE_ERROR_WARNING:
 477                if (n & PCAN_USB_ERROR_BUS_HEAVY) {
 478                        new_state = CAN_STATE_ERROR_PASSIVE;
 479                        break;
 480                }
 481                if (n & PCAN_USB_ERROR_BUS_OFF) {
 482                        new_state = CAN_STATE_BUS_OFF;
 483                        break;
 484                }
 485                if (n & ~PCAN_USB_ERROR_BUS) {
 486                        /*
 487                         * trick to bypass next comparison and process other
 488                         * errors
 489                         */
 490                        new_state = CAN_STATE_MAX;
 491                        break;
 492                }
 493                if ((n & PCAN_USB_ERROR_BUS_LIGHT) == 0) {
 494                        /* no error (back to active state) */
 495                        new_state = CAN_STATE_ERROR_ACTIVE;
 496                        break;
 497                }
 498                break;
 499
 500        case CAN_STATE_ERROR_PASSIVE:
 501                if (n & PCAN_USB_ERROR_BUS_OFF) {
 502                        new_state = CAN_STATE_BUS_OFF;
 503                        break;
 504                }
 505                if (n & PCAN_USB_ERROR_BUS_LIGHT) {
 506                        new_state = CAN_STATE_ERROR_WARNING;
 507                        break;
 508                }
 509                if (n & ~PCAN_USB_ERROR_BUS) {
 510                        /*
 511                         * trick to bypass next comparison and process other
 512                         * errors
 513                         */
 514                        new_state = CAN_STATE_MAX;
 515                        break;
 516                }
 517
 518                if ((n & PCAN_USB_ERROR_BUS_HEAVY) == 0) {
 519                        /* no error (back to warning state) */
 520                        new_state = CAN_STATE_ERROR_WARNING;
 521                        break;
 522                }
 523                break;
 524
 525        default:
 526                /* do nothing waiting for restart */
 527                return 0;
 528        }
 529
 530        /* donot post any error if current state didn't change */
 531        if (mc->pdev->dev.can.state == new_state)
 532                return 0;
 533
 534        /* allocate an skb to store the error frame */
 535        skb = alloc_can_err_skb(mc->netdev, &cf);
 536        if (!skb)
 537                return -ENOMEM;
 538
 539        switch (new_state) {
 540        case CAN_STATE_BUS_OFF:
 541                cf->can_id |= CAN_ERR_BUSOFF;
 542                mc->pdev->dev.can.can_stats.bus_off++;
 543                can_bus_off(mc->netdev);
 544                break;
 545
 546        case CAN_STATE_ERROR_PASSIVE:
 547                cf->can_id |= CAN_ERR_CRTL;
 548                cf->data[1] = (mc->pdev->bec.txerr > mc->pdev->bec.rxerr) ?
 549                                CAN_ERR_CRTL_TX_PASSIVE :
 550                                CAN_ERR_CRTL_RX_PASSIVE;
 551                cf->data[6] = mc->pdev->bec.txerr;
 552                cf->data[7] = mc->pdev->bec.rxerr;
 553
 554                mc->pdev->dev.can.can_stats.error_passive++;
 555                break;
 556
 557        case CAN_STATE_ERROR_WARNING:
 558                cf->can_id |= CAN_ERR_CRTL;
 559                cf->data[1] = (mc->pdev->bec.txerr > mc->pdev->bec.rxerr) ?
 560                                CAN_ERR_CRTL_TX_WARNING :
 561                                CAN_ERR_CRTL_RX_WARNING;
 562                cf->data[6] = mc->pdev->bec.txerr;
 563                cf->data[7] = mc->pdev->bec.rxerr;
 564
 565                mc->pdev->dev.can.can_stats.error_warning++;
 566                break;
 567
 568        case CAN_STATE_ERROR_ACTIVE:
 569                cf->can_id |= CAN_ERR_CRTL;
 570                cf->data[1] = CAN_ERR_CRTL_ACTIVE;
 571
 572                /* sync local copies of rxerr/txerr counters */
 573                mc->pdev->bec.txerr = 0;
 574                mc->pdev->bec.rxerr = 0;
 575                break;
 576
 577        default:
 578                /* CAN_STATE_MAX (trick to handle other errors) */
 579                if (n & PCAN_USB_ERROR_TXQFULL)
 580                        netdev_dbg(mc->netdev, "device Tx queue full)\n");
 581
 582                if (n & PCAN_USB_ERROR_RXQOVR) {
 583                        netdev_dbg(mc->netdev, "data overrun interrupt\n");
 584                        cf->can_id |= CAN_ERR_CRTL;
 585                        cf->data[1] |= CAN_ERR_CRTL_RX_OVERFLOW;
 586                        mc->netdev->stats.rx_over_errors++;
 587                        mc->netdev->stats.rx_errors++;
 588                }
 589
 590                cf->data[6] = mc->pdev->bec.txerr;
 591                cf->data[7] = mc->pdev->bec.rxerr;
 592
 593                new_state = mc->pdev->dev.can.state;
 594                break;
 595        }
 596
 597        mc->pdev->dev.can.state = new_state;
 598
 599        if (status_len & PCAN_USB_STATUSLEN_TIMESTAMP) {
 600                struct skb_shared_hwtstamps *hwts = skb_hwtstamps(skb);
 601
 602                peak_usb_get_ts_time(&mc->pdev->time_ref, mc->ts16,
 603                                     &hwts->hwtstamp);
 604        }
 605
 606        mc->netdev->stats.rx_packets++;
 607        mc->netdev->stats.rx_bytes += cf->can_dlc;
 608        netif_rx(skb);
 609
 610        return 0;
 611}
 612
 613/* decode bus event usb packet: first byte contains rxerr while 2nd one contains
 614 * txerr.
 615 */
 616static int pcan_usb_handle_bus_evt(struct pcan_usb_msg_context *mc, u8 ir)
 617{
 618        struct pcan_usb *pdev = mc->pdev;
 619
 620        /* acccording to the content of the packet */
 621        switch (ir) {
 622        case PCAN_USB_ERR_CNT:
 623
 624                /* save rx/tx error counters from in the device context */
 625                pdev->bec.rxerr = mc->ptr[0];
 626                pdev->bec.txerr = mc->ptr[1];
 627                break;
 628
 629        default:
 630                /* reserved */
 631                break;
 632        }
 633
 634        return 0;
 635}
 636
 637/*
 638 * decode non-data usb message
 639 */
 640static int pcan_usb_decode_status(struct pcan_usb_msg_context *mc,
 641                                  u8 status_len)
 642{
 643        u8 rec_len = status_len & PCAN_USB_STATUSLEN_DLC;
 644        u8 f, n;
 645        int err;
 646
 647        /* check whether function and number can be read */
 648        if ((mc->ptr + 2) > mc->end)
 649                return -EINVAL;
 650
 651        f = mc->ptr[PCAN_USB_CMD_FUNC];
 652        n = mc->ptr[PCAN_USB_CMD_NUM];
 653        mc->ptr += PCAN_USB_CMD_ARGS;
 654
 655        if (status_len & PCAN_USB_STATUSLEN_TIMESTAMP) {
 656                int err = pcan_usb_decode_ts(mc, !mc->rec_ts_idx);
 657
 658                if (err)
 659                        return err;
 660
 661                /* Next packet in the buffer will have a timestamp on a single
 662                 * byte
 663                 */
 664                mc->rec_ts_idx++;
 665        }
 666
 667        switch (f) {
 668        case PCAN_USB_REC_ERROR:
 669                err = pcan_usb_decode_error(mc, n, status_len);
 670                if (err)
 671                        return err;
 672                break;
 673
 674        case PCAN_USB_REC_ANALOG:
 675                /* analog values (ignored) */
 676                rec_len = 2;
 677                break;
 678
 679        case PCAN_USB_REC_BUSLOAD:
 680                /* bus load (ignored) */
 681                rec_len = 1;
 682                break;
 683
 684        case PCAN_USB_REC_TS:
 685                /* only timestamp */
 686                if (pcan_usb_update_ts(mc))
 687                        return -EINVAL;
 688                break;
 689
 690        case PCAN_USB_REC_BUSEVT:
 691                /* bus event notifications (get rxerr/txerr) */
 692                err = pcan_usb_handle_bus_evt(mc, n);
 693                if (err)
 694                        return err;
 695                break;
 696        default:
 697                netdev_err(mc->netdev, "unexpected function %u\n", f);
 698                break;
 699        }
 700
 701        if ((mc->ptr + rec_len) > mc->end)
 702                return -EINVAL;
 703
 704        mc->ptr += rec_len;
 705
 706        return 0;
 707}
 708
 709/*
 710 * decode data usb message
 711 */
 712static int pcan_usb_decode_data(struct pcan_usb_msg_context *mc, u8 status_len)
 713{
 714        u8 rec_len = status_len & PCAN_USB_STATUSLEN_DLC;
 715        struct sk_buff *skb;
 716        struct can_frame *cf;
 717        struct skb_shared_hwtstamps *hwts;
 718
 719        skb = alloc_can_skb(mc->netdev, &cf);
 720        if (!skb)
 721                return -ENOMEM;
 722
 723        if (status_len & PCAN_USB_STATUSLEN_EXT_ID) {
 724                __le32 tmp32;
 725
 726                if ((mc->ptr + 4) > mc->end)
 727                        goto decode_failed;
 728
 729                memcpy(&tmp32, mc->ptr, 4);
 730                mc->ptr += 4;
 731
 732                cf->can_id = (le32_to_cpu(tmp32) >> 3) | CAN_EFF_FLAG;
 733        } else {
 734                __le16 tmp16;
 735
 736                if ((mc->ptr + 2) > mc->end)
 737                        goto decode_failed;
 738
 739                memcpy(&tmp16, mc->ptr, 2);
 740                mc->ptr += 2;
 741
 742                cf->can_id = le16_to_cpu(tmp16) >> 5;
 743        }
 744
 745        cf->can_dlc = get_can_dlc(rec_len);
 746
 747        /* Only first packet timestamp is a word */
 748        if (pcan_usb_decode_ts(mc, !mc->rec_ts_idx))
 749                goto decode_failed;
 750
 751        /* Next packet in the buffer will have a timestamp on a single byte */
 752        mc->rec_ts_idx++;
 753
 754        /* read data */
 755        memset(cf->data, 0x0, sizeof(cf->data));
 756        if (status_len & PCAN_USB_STATUSLEN_RTR) {
 757                cf->can_id |= CAN_RTR_FLAG;
 758        } else {
 759                if ((mc->ptr + rec_len) > mc->end)
 760                        goto decode_failed;
 761
 762                memcpy(cf->data, mc->ptr, cf->can_dlc);
 763                mc->ptr += rec_len;
 764        }
 765
 766        /* convert timestamp into kernel time */
 767        hwts = skb_hwtstamps(skb);
 768        peak_usb_get_ts_time(&mc->pdev->time_ref, mc->ts16, &hwts->hwtstamp);
 769
 770        /* update statistics */
 771        mc->netdev->stats.rx_packets++;
 772        mc->netdev->stats.rx_bytes += cf->can_dlc;
 773        /* push the skb */
 774        netif_rx(skb);
 775
 776        return 0;
 777
 778decode_failed:
 779        dev_kfree_skb(skb);
 780        return -EINVAL;
 781}
 782
 783/*
 784 * process incoming message
 785 */
 786static int pcan_usb_decode_msg(struct peak_usb_device *dev, u8 *ibuf, u32 lbuf)
 787{
 788        struct pcan_usb_msg_context mc = {
 789                .rec_cnt = ibuf[1],
 790                .ptr = ibuf + PCAN_USB_MSG_HEADER_LEN,
 791                .end = ibuf + lbuf,
 792                .netdev = dev->netdev,
 793                .pdev = container_of(dev, struct pcan_usb, dev),
 794        };
 795        int err;
 796
 797        for (err = 0; mc.rec_idx < mc.rec_cnt && !err; mc.rec_idx++) {
 798                u8 sl = *mc.ptr++;
 799
 800                /* handle status and error frames here */
 801                if (sl & PCAN_USB_STATUSLEN_INTERNAL) {
 802                        err = pcan_usb_decode_status(&mc, sl);
 803                /* handle normal can frames here */
 804                } else {
 805                        err = pcan_usb_decode_data(&mc, sl);
 806                }
 807        }
 808
 809        return err;
 810}
 811
 812/*
 813 * process any incoming buffer
 814 */
 815static int pcan_usb_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 816{
 817        int err = 0;
 818
 819        if (urb->actual_length > PCAN_USB_MSG_HEADER_LEN) {
 820                err = pcan_usb_decode_msg(dev, urb->transfer_buffer,
 821                        urb->actual_length);
 822
 823        } else if (urb->actual_length > 0) {
 824                netdev_err(dev->netdev, "usb message length error (%u)\n",
 825                        urb->actual_length);
 826                err = -EINVAL;
 827        }
 828
 829        return err;
 830}
 831
 832/*
 833 * process outgoing packet
 834 */
 835static int pcan_usb_encode_msg(struct peak_usb_device *dev, struct sk_buff *skb,
 836                               u8 *obuf, size_t *size)
 837{
 838        struct net_device *netdev = dev->netdev;
 839        struct net_device_stats *stats = &netdev->stats;
 840        struct can_frame *cf = (struct can_frame *)skb->data;
 841        u8 *pc;
 842
 843        obuf[0] = 2;
 844        obuf[1] = 1;
 845
 846        pc = obuf + PCAN_USB_MSG_HEADER_LEN;
 847
 848        /* status/len byte */
 849        *pc = cf->can_dlc;
 850        if (cf->can_id & CAN_RTR_FLAG)
 851                *pc |= PCAN_USB_STATUSLEN_RTR;
 852
 853        /* can id */
 854        if (cf->can_id & CAN_EFF_FLAG) {
 855                __le32 tmp32 = cpu_to_le32((cf->can_id & CAN_ERR_MASK) << 3);
 856
 857                *pc |= PCAN_USB_STATUSLEN_EXT_ID;
 858                memcpy(++pc, &tmp32, 4);
 859                pc += 4;
 860        } else {
 861                __le16 tmp16 = cpu_to_le16((cf->can_id & CAN_ERR_MASK) << 5);
 862
 863                memcpy(++pc, &tmp16, 2);
 864                pc += 2;
 865        }
 866
 867        /* can data */
 868        if (!(cf->can_id & CAN_RTR_FLAG)) {
 869                memcpy(pc, cf->data, cf->can_dlc);
 870                pc += cf->can_dlc;
 871        }
 872
 873        obuf[(*size)-1] = (u8)(stats->tx_packets & 0xff);
 874
 875        return 0;
 876}
 877
 878/* socket callback used to copy berr counters values received through USB */
 879static int pcan_usb_get_berr_counter(const struct net_device *netdev,
 880                                     struct can_berr_counter *bec)
 881{
 882        struct peak_usb_device *dev = netdev_priv(netdev);
 883        struct pcan_usb *pdev = container_of(dev, struct pcan_usb, dev);
 884
 885        *bec = pdev->bec;
 886
 887        /* must return 0 */
 888        return 0;
 889}
 890
 891/*
 892 * start interface
 893 */
 894static int pcan_usb_start(struct peak_usb_device *dev)
 895{
 896        struct pcan_usb *pdev = container_of(dev, struct pcan_usb, dev);
 897        int err;
 898
 899        /* number of bits used in timestamps read from adapter struct */
 900        peak_usb_init_time_ref(&pdev->time_ref, &pcan_usb);
 901
 902        pdev->bec.rxerr = 0;
 903        pdev->bec.txerr = 0;
 904
 905        /* be notified on error counter changes (if requested by user) */
 906        if (dev->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING) {
 907                err = pcan_usb_set_err_frame(dev, PCAN_USB_BERR_MASK);
 908                if (err)
 909                        netdev_warn(dev->netdev,
 910                                    "Asking for BERR reporting error %u\n",
 911                                    err);
 912        }
 913
 914        /* if revision greater than 3, can put silent mode on/off */
 915        if (dev->device_rev > 3) {
 916                err = pcan_usb_set_silent(dev,
 917                                dev->can.ctrlmode & CAN_CTRLMODE_LISTENONLY);
 918                if (err)
 919                        return err;
 920        }
 921
 922        return pcan_usb_set_ext_vcc(dev, 0);
 923}
 924
 925static int pcan_usb_init(struct peak_usb_device *dev)
 926{
 927        struct pcan_usb *pdev = container_of(dev, struct pcan_usb, dev);
 928        u32 serial_number;
 929        int err;
 930
 931        /* initialize a timer needed to wait for hardware restart */
 932        timer_setup(&pdev->restart_timer, pcan_usb_restart, 0);
 933
 934        /*
 935         * explicit use of dev_xxx() instead of netdev_xxx() here:
 936         * information displayed are related to the device itself, not
 937         * to the canx netdevice.
 938         */
 939        err = pcan_usb_get_serial(dev, &serial_number);
 940        if (err) {
 941                dev_err(dev->netdev->dev.parent,
 942                        "unable to read %s serial number (err %d)\n",
 943                        pcan_usb.name, err);
 944                return err;
 945        }
 946
 947        dev_info(dev->netdev->dev.parent,
 948                 "PEAK-System %s adapter hwrev %u serial %08X (%u channel)\n",
 949                 pcan_usb.name, dev->device_rev, serial_number,
 950                 pcan_usb.ctrl_count);
 951
 952        return 0;
 953}
 954
 955/*
 956 * probe function for new PCAN-USB usb interface
 957 */
 958static int pcan_usb_probe(struct usb_interface *intf)
 959{
 960        struct usb_host_interface *if_desc;
 961        int i;
 962
 963        if_desc = intf->altsetting;
 964
 965        /* check interface endpoint addresses */
 966        for (i = 0; i < if_desc->desc.bNumEndpoints; i++) {
 967                struct usb_endpoint_descriptor *ep = &if_desc->endpoint[i].desc;
 968
 969                switch (ep->bEndpointAddress) {
 970                case PCAN_USB_EP_CMDOUT:
 971                case PCAN_USB_EP_CMDIN:
 972                case PCAN_USB_EP_MSGOUT:
 973                case PCAN_USB_EP_MSGIN:
 974                        break;
 975                default:
 976                        return -ENODEV;
 977                }
 978        }
 979
 980        return 0;
 981}
 982
 983/*
 984 * describe the PCAN-USB adapter
 985 */
 986static const struct can_bittiming_const pcan_usb_const = {
 987        .name = "pcan_usb",
 988        .tseg1_min = 1,
 989        .tseg1_max = 16,
 990        .tseg2_min = 1,
 991        .tseg2_max = 8,
 992        .sjw_max = 4,
 993        .brp_min = 1,
 994        .brp_max = 64,
 995        .brp_inc = 1,
 996};
 997
 998const struct peak_usb_adapter pcan_usb = {
 999        .name = "PCAN-USB",
1000        .device_id = PCAN_USB_PRODUCT_ID,
1001        .ctrl_count = 1,
1002        .ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES | CAN_CTRLMODE_LISTENONLY |
1003                              CAN_CTRLMODE_BERR_REPORTING,
1004        .clock = {
1005                .freq = PCAN_USB_CRYSTAL_HZ / 2 ,
1006        },
1007        .bittiming_const = &pcan_usb_const,
1008
1009        /* size of device private data */
1010        .sizeof_dev_private = sizeof(struct pcan_usb),
1011
1012        /* timestamps usage */
1013        .ts_used_bits = 16,
1014        .ts_period = 24575, /* calibration period in ts. */
1015        .us_per_ts_scale = PCAN_USB_TS_US_PER_TICK, /* us=(ts*scale) */
1016        .us_per_ts_shift = PCAN_USB_TS_DIV_SHIFTER, /*  >> shift     */
1017
1018        /* give here messages in/out endpoints */
1019        .ep_msg_in = PCAN_USB_EP_MSGIN,
1020        .ep_msg_out = {PCAN_USB_EP_MSGOUT},
1021
1022        /* size of rx/tx usb buffers */
1023        .rx_buffer_size = PCAN_USB_RX_BUFFER_SIZE,
1024        .tx_buffer_size = PCAN_USB_TX_BUFFER_SIZE,
1025
1026        /* device callbacks */
1027        .intf_probe = pcan_usb_probe,
1028        .dev_init = pcan_usb_init,
1029        .dev_set_bus = pcan_usb_write_mode,
1030        .dev_set_bittiming = pcan_usb_set_bittiming,
1031        .dev_get_device_id = pcan_usb_get_device_id,
1032        .dev_decode_buf = pcan_usb_decode_buf,
1033        .dev_encode_msg = pcan_usb_encode_msg,
1034        .dev_start = pcan_usb_start,
1035        .dev_restart_async = pcan_usb_restart_async,
1036        .do_get_berr_counter = pcan_usb_get_berr_counter,
1037};
1038