File Index
Files and directories
Sign in
FILE

ca8210.c

File preview with syntax highlighting.

linux-6.19.14/drivers/net/ieee802154/ca8210.c C
   1/*
   2 * http://www.cascoda.com/products/ca-821x/
   3 * Copyright (c) 2016, Cascoda, Ltd.
   4 * All rights reserved.
   5 *
   6 * This code is dual-licensed under both GPLv2 and 3-clause BSD. What follows is
   7 * the license notice for both respectively.
   8 *
   9 *******************************************************************************
  10 *
  11 * This program is free software; you can redistribute it and/or
  12 * modify it under the terms of the GNU General Public License
  13 * as published by the Free Software Foundation; either version 2
  14 * of the License, or (at your option) any later version.
  15 *
  16 * This program is distributed in the hope that it will be useful,
  17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19 * GNU General Public License for more details.
  20 *
  21 *******************************************************************************
  22 *
  23 * Redistribution and use in source and binary forms, with or without
  24 * modification, are permitted provided that the following conditions are met:
  25 *
  26 * 1. Redistributions of source code must retain the above copyright notice,
  27 * this list of conditions and the following disclaimer.
  28 *
  29 * 2. Redistributions in binary form must reproduce the above copyright notice,
  30 * this list of conditions and the following disclaimer in the documentation
  31 * and/or other materials provided with the distribution.
  32 *
  33 * 3. Neither the name of the copyright holder nor the names of its contributors
  34 * may be used to endorse or promote products derived from this software without
  35 * specific prior written permission.
  36 *
  37 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  38 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  40 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
  41 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  42 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  43 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  44 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  45 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  46 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  47 * POSSIBILITY OF SUCH DAMAGE.
  48 */
  49
  50#include <linux/cdev.h>
  51#include <linux/clk-provider.h>
  52#include <linux/debugfs.h>
  53#include <linux/delay.h>
  54#include <linux/gpio/consumer.h>
  55#include <linux/ieee802154.h>
  56#include <linux/io.h>
  57#include <linux/kfifo.h>
  58#include <linux/of.h>
  59#include <linux/module.h>
  60#include <linux/mutex.h>
  61#include <linux/poll.h>
  62#include <linux/skbuff.h>
  63#include <linux/slab.h>
  64#include <linux/spi/spi.h>
  65#include <linux/spinlock.h>
  66#include <linux/string.h>
  67#include <linux/workqueue.h>
  68#include <linux/interrupt.h>
  69
  70#include <net/ieee802154_netdev.h>
  71#include <net/mac802154.h>
  72
  73#define DRIVER_NAME "ca8210"
  74
  75/* external clock frequencies */
  76#define ONE_MHZ      1000000
  77#define TWO_MHZ      (2 * ONE_MHZ)
  78#define FOUR_MHZ     (4 * ONE_MHZ)
  79#define EIGHT_MHZ    (8 * ONE_MHZ)
  80#define SIXTEEN_MHZ  (16 * ONE_MHZ)
  81
  82/* spi constants */
  83#define CA8210_SPI_BUF_SIZE 256
  84#define CA8210_SYNC_TIMEOUT 1000     /* Timeout for synchronous commands [ms] */
  85
  86/* test interface constants */
  87#define CA8210_TEST_INT_FILE_NAME "ca8210_test"
  88#define CA8210_TEST_INT_FIFO_SIZE 256
  89
  90/* HWME attribute IDs */
  91#define HWME_EDTHRESHOLD       (0x04)
  92#define HWME_EDVALUE           (0x06)
  93#define HWME_SYSCLKOUT         (0x0F)
  94#define HWME_LQILIMIT          (0x11)
  95
  96/* TDME attribute IDs */
  97#define TDME_CHANNEL          (0x00)
  98#define TDME_ATM_CONFIG       (0x06)
  99
 100#define MAX_HWME_ATTRIBUTE_SIZE  16
 101#define MAX_TDME_ATTRIBUTE_SIZE  2
 102
 103/* PHY/MAC PIB Attribute Enumerations */
 104#define PHY_CURRENT_CHANNEL               (0x00)
 105#define PHY_TRANSMIT_POWER                (0x02)
 106#define PHY_CCA_MODE                      (0x03)
 107#define MAC_ASSOCIATION_PERMIT            (0x41)
 108#define MAC_AUTO_REQUEST                  (0x42)
 109#define MAC_BATT_LIFE_EXT                 (0x43)
 110#define MAC_BATT_LIFE_EXT_PERIODS         (0x44)
 111#define MAC_BEACON_PAYLOAD                (0x45)
 112#define MAC_BEACON_PAYLOAD_LENGTH         (0x46)
 113#define MAC_BEACON_ORDER                  (0x47)
 114#define MAC_GTS_PERMIT                    (0x4d)
 115#define MAC_MAX_CSMA_BACKOFFS             (0x4e)
 116#define MAC_MIN_BE                        (0x4f)
 117#define MAC_PAN_ID                        (0x50)
 118#define MAC_PROMISCUOUS_MODE              (0x51)
 119#define MAC_RX_ON_WHEN_IDLE               (0x52)
 120#define MAC_SHORT_ADDRESS                 (0x53)
 121#define MAC_SUPERFRAME_ORDER              (0x54)
 122#define MAC_ASSOCIATED_PAN_COORD          (0x56)
 123#define MAC_MAX_BE                        (0x57)
 124#define MAC_MAX_FRAME_RETRIES             (0x59)
 125#define MAC_RESPONSE_WAIT_TIME            (0x5A)
 126#define MAC_SECURITY_ENABLED              (0x5D)
 127
 128#define MAC_AUTO_REQUEST_SECURITY_LEVEL   (0x78)
 129#define MAC_AUTO_REQUEST_KEY_ID_MODE      (0x79)
 130
 131#define NS_IEEE_ADDRESS                   (0xFF) /* Non-standard IEEE address */
 132
 133/* MAC Address Mode Definitions */
 134#define MAC_MODE_NO_ADDR                (0x00)
 135#define MAC_MODE_SHORT_ADDR             (0x02)
 136#define MAC_MODE_LONG_ADDR              (0x03)
 137
 138/* MAC constants */
 139#define MAX_BEACON_OVERHEAD        (75)
 140#define MAX_BEACON_PAYLOAD_LENGTH  (IEEE802154_MTU - MAX_BEACON_OVERHEAD)
 141
 142#define MAX_ATTRIBUTE_SIZE              (122)
 143#define MAX_DATA_SIZE                   (114)
 144
 145#define CA8210_VALID_CHANNELS                 (0x07FFF800)
 146
 147/* MAC workarounds for V1.1 and MPW silicon (V0.x) */
 148#define CA8210_MAC_WORKAROUNDS (0)
 149#define CA8210_MAC_MPW         (0)
 150
 151/* memory manipulation macros */
 152#define LS_BYTE(x)     ((u8)((x) & 0xFF))
 153#define MS_BYTE(x)     ((u8)(((x) >> 8) & 0xFF))
 154
 155/* message ID codes in SPI commands */
 156/* downstream */
 157#define MCPS_DATA_REQUEST                     (0x00)
 158#define MLME_ASSOCIATE_REQUEST                (0x02)
 159#define MLME_ASSOCIATE_RESPONSE               (0x03)
 160#define MLME_DISASSOCIATE_REQUEST             (0x04)
 161#define MLME_GET_REQUEST                      (0x05)
 162#define MLME_ORPHAN_RESPONSE                  (0x06)
 163#define MLME_RESET_REQUEST                    (0x07)
 164#define MLME_RX_ENABLE_REQUEST                (0x08)
 165#define MLME_SCAN_REQUEST                     (0x09)
 166#define MLME_SET_REQUEST                      (0x0A)
 167#define MLME_START_REQUEST                    (0x0B)
 168#define MLME_POLL_REQUEST                     (0x0D)
 169#define HWME_SET_REQUEST                      (0x0E)
 170#define HWME_GET_REQUEST                      (0x0F)
 171#define TDME_SETSFR_REQUEST                   (0x11)
 172#define TDME_GETSFR_REQUEST                   (0x12)
 173#define TDME_SET_REQUEST                      (0x14)
 174/* upstream */
 175#define MCPS_DATA_INDICATION                  (0x00)
 176#define MCPS_DATA_CONFIRM                     (0x01)
 177#define MLME_RESET_CONFIRM                    (0x0A)
 178#define MLME_SET_CONFIRM                      (0x0E)
 179#define MLME_START_CONFIRM                    (0x0F)
 180#define HWME_SET_CONFIRM                      (0x12)
 181#define HWME_GET_CONFIRM                      (0x13)
 182#define HWME_WAKEUP_INDICATION		      (0x15)
 183#define TDME_SETSFR_CONFIRM                   (0x17)
 184
 185/* SPI command IDs */
 186/* bit indicating a confirm or indication from slave to master */
 187#define SPI_S2M                            (0x20)
 188/* bit indicating a synchronous message */
 189#define SPI_SYN                            (0x40)
 190
 191/* SPI command definitions */
 192#define SPI_IDLE                           (0xFF)
 193#define SPI_NACK                           (0xF0)
 194
 195#define SPI_MCPS_DATA_REQUEST          (MCPS_DATA_REQUEST)
 196#define SPI_MCPS_DATA_INDICATION       (MCPS_DATA_INDICATION + SPI_S2M)
 197#define SPI_MCPS_DATA_CONFIRM          (MCPS_DATA_CONFIRM + SPI_S2M)
 198
 199#define SPI_MLME_ASSOCIATE_REQUEST     (MLME_ASSOCIATE_REQUEST)
 200#define SPI_MLME_RESET_REQUEST         (MLME_RESET_REQUEST + SPI_SYN)
 201#define SPI_MLME_SET_REQUEST           (MLME_SET_REQUEST + SPI_SYN)
 202#define SPI_MLME_START_REQUEST         (MLME_START_REQUEST + SPI_SYN)
 203#define SPI_MLME_RESET_CONFIRM         (MLME_RESET_CONFIRM + SPI_S2M + SPI_SYN)
 204#define SPI_MLME_SET_CONFIRM           (MLME_SET_CONFIRM + SPI_S2M + SPI_SYN)
 205#define SPI_MLME_START_CONFIRM         (MLME_START_CONFIRM + SPI_S2M + SPI_SYN)
 206
 207#define SPI_HWME_SET_REQUEST           (HWME_SET_REQUEST + SPI_SYN)
 208#define SPI_HWME_GET_REQUEST           (HWME_GET_REQUEST + SPI_SYN)
 209#define SPI_HWME_SET_CONFIRM           (HWME_SET_CONFIRM + SPI_S2M + SPI_SYN)
 210#define SPI_HWME_GET_CONFIRM           (HWME_GET_CONFIRM + SPI_S2M + SPI_SYN)
 211#define SPI_HWME_WAKEUP_INDICATION     (HWME_WAKEUP_INDICATION + SPI_S2M)
 212
 213#define SPI_TDME_SETSFR_REQUEST        (TDME_SETSFR_REQUEST + SPI_SYN)
 214#define SPI_TDME_SET_REQUEST           (TDME_SET_REQUEST + SPI_SYN)
 215#define SPI_TDME_SETSFR_CONFIRM        (TDME_SETSFR_CONFIRM + SPI_S2M + SPI_SYN)
 216
 217/* TDME SFR addresses */
 218/* Page 0 */
 219#define CA8210_SFR_PACFG                   (0xB1)
 220#define CA8210_SFR_MACCON                  (0xD8)
 221#define CA8210_SFR_PACFGIB                 (0xFE)
 222/* Page 1 */
 223#define CA8210_SFR_LOTXCAL                 (0xBF)
 224#define CA8210_SFR_PTHRH                   (0xD1)
 225#define CA8210_SFR_PRECFG                  (0xD3)
 226#define CA8210_SFR_LNAGX40                 (0xE1)
 227#define CA8210_SFR_LNAGX41                 (0xE2)
 228#define CA8210_SFR_LNAGX42                 (0xE3)
 229#define CA8210_SFR_LNAGX43                 (0xE4)
 230#define CA8210_SFR_LNAGX44                 (0xE5)
 231#define CA8210_SFR_LNAGX45                 (0xE6)
 232#define CA8210_SFR_LNAGX46                 (0xE7)
 233#define CA8210_SFR_LNAGX47                 (0xE9)
 234
 235#define PACFGIB_DEFAULT_CURRENT            (0x3F)
 236#define PTHRH_DEFAULT_THRESHOLD            (0x5A)
 237#define LNAGX40_DEFAULT_GAIN               (0x29) /* 10dB */
 238#define LNAGX41_DEFAULT_GAIN               (0x54) /* 21dB */
 239#define LNAGX42_DEFAULT_GAIN               (0x6C) /* 27dB */
 240#define LNAGX43_DEFAULT_GAIN               (0x7A) /* 30dB */
 241#define LNAGX44_DEFAULT_GAIN               (0x84) /* 33dB */
 242#define LNAGX45_DEFAULT_GAIN               (0x8B) /* 34dB */
 243#define LNAGX46_DEFAULT_GAIN               (0x92) /* 36dB */
 244#define LNAGX47_DEFAULT_GAIN               (0x96) /* 37dB */
 245
 246#define CA8210_IOCTL_HARD_RESET            (0x00)
 247
 248/* Structs/Enums */
 249
 250/**
 251 * struct cas_control - spi transfer structure
 252 * @msg:                  spi_message for each exchange
 253 * @transfer:             spi_transfer for each exchange
 254 * @tx_buf:               source array for transmission
 255 * @tx_in_buf:            array storing bytes received during transmission
 256 * @priv:                 pointer to private data
 257 *
 258 * This structure stores all the necessary data passed around during a single
 259 * spi exchange.
 260 */
 261struct cas_control {
 262	struct spi_message msg;
 263	struct spi_transfer transfer;
 264
 265	u8 tx_buf[CA8210_SPI_BUF_SIZE];
 266	u8 tx_in_buf[CA8210_SPI_BUF_SIZE];
 267
 268	struct ca8210_priv *priv;
 269};
 270
 271/**
 272 * struct ca8210_test - ca8210 test interface structure
 273 * @ca8210_dfs_spi_int: pointer to the entry in the debug fs for this device
 274 * @up_fifo:            fifo for upstream messages
 275 * @readq:              read wait queue
 276 *
 277 * This structure stores all the data pertaining to the debug interface
 278 */
 279struct ca8210_test {
 280	struct dentry *ca8210_dfs_spi_int;
 281	struct kfifo up_fifo;
 282	wait_queue_head_t readq;
 283};
 284
 285/**
 286 * struct ca8210_priv - ca8210 private data structure
 287 * @spi:                    pointer to the ca8210 spi device object
 288 * @hw:                     pointer to the ca8210 ieee802154_hw object
 289 * @hw_registered:          true if hw has been registered with ieee802154
 290 * @lock:                   spinlock protecting the private data area
 291 * @mlme_workqueue:           workqueue for triggering MLME Reset
 292 * @irq_workqueue:          workqueue for irq processing
 293 * @tx_skb:                 current socket buffer to transmit
 294 * @nextmsduhandle:         msdu handle to pass to the 15.4 MAC layer for the
 295 *                           next transmission
 296 * @clk:                    external clock provided by the ca8210
 297 * @last_dsn:               sequence number of last data packet received, for
 298 *                           resend detection
 299 * @test:                   test interface data section for this instance
 300 * @async_tx_pending:       true if an asynchronous transmission was started and
 301 *                           is not complete
 302 * @sync_command_response:  pointer to buffer to fill with sync response
 303 * @ca8210_is_awake:        nonzero if ca8210 is initialised, ready for comms
 304 * @sync_down:              counts number of downstream synchronous commands
 305 * @sync_up:                counts number of upstream synchronous commands
 306 * @spi_transfer_complete:  completion object for a single spi_transfer
 307 * @sync_exchange_complete: completion object for a complete synchronous API
 308 *                          exchange
 309 * @promiscuous:            whether the ca8210 is in promiscuous mode or not
 310 * @retries:                records how many times the current pending spi
 311 *                          transfer has been retried
 312 */
 313struct ca8210_priv {
 314	struct spi_device *spi;
 315	struct ieee802154_hw *hw;
 316	bool hw_registered;
 317	spinlock_t lock;
 318	struct workqueue_struct *mlme_workqueue;
 319	struct workqueue_struct *irq_workqueue;
 320	struct sk_buff *tx_skb;
 321	u8 nextmsduhandle;
 322	struct clk *clk;
 323	int last_dsn;
 324	struct ca8210_test test;
 325	bool async_tx_pending;
 326	u8 *sync_command_response;
 327	struct completion ca8210_is_awake;
 328	int sync_down, sync_up;
 329	struct completion spi_transfer_complete, sync_exchange_complete;
 330	bool promiscuous;
 331	int retries;
 332};
 333
 334/**
 335 * struct work_priv_container - link between a work object and the relevant
 336 *                              device's private data
 337 * @work: work object being executed
 338 * @priv: device's private data section
 339 *
 340 */
 341struct work_priv_container {
 342	struct work_struct work;
 343	struct ca8210_priv *priv;
 344};
 345
 346/**
 347 * struct ca8210_platform_data - ca8210 platform data structure
 348 * @extclockenable: true if the external clock is to be enabled
 349 * @extclockfreq:   frequency of the external clock
 350 * @extclockgpio:   ca8210 output gpio of the external clock
 351 * @reset_gpio:     ca8210 reset GPIO descriptor
 352 * @irq_gpio:       ca8210 interrupt GPIO descriptor
 353 * @irq_id:         identifier for the ca8210 irq
 354 *
 355 */
 356struct ca8210_platform_data {
 357	bool extclockenable;
 358	unsigned int extclockfreq;
 359	unsigned int extclockgpio;
 360	struct gpio_desc *reset_gpio;
 361	struct gpio_desc *irq_gpio;
 362	int irq_id;
 363};
 364
 365/**
 366 * struct fulladdr - full MAC addressing information structure
 367 * @mode:    address mode (none, short, extended)
 368 * @pan_id:  16-bit LE pan id
 369 * @address: LE address, variable length as specified by mode
 370 *
 371 */
 372struct fulladdr {
 373	u8         mode;
 374	u8         pan_id[2];
 375	u8         address[8];
 376};
 377
 378/**
 379 * union macaddr: generic MAC address container
 380 * @short_address: 16-bit short address
 381 * @ieee_address:  64-bit extended address as LE byte array
 382 *
 383 */
 384union macaddr {
 385	u16        short_address;
 386	u8         ieee_address[8];
 387};
 388
 389/**
 390 * struct secspec: security specification for SAP commands
 391 * @security_level: 0-7, controls level of authentication & encryption
 392 * @key_id_mode:    0-3, specifies how to obtain key
 393 * @key_source:     extended key retrieval data
 394 * @key_index:      single-byte key identifier
 395 *
 396 */
 397struct secspec {
 398	u8         security_level;
 399	u8         key_id_mode;
 400	u8         key_source[8];
 401	u8         key_index;
 402};
 403
 404/* downlink functions parameter set definitions */
 405struct mcps_data_request_pset {
 406	u8              src_addr_mode;
 407	struct fulladdr dst;
 408	u8              msdu_length;
 409	u8              msdu_handle;
 410	u8              tx_options;
 411	u8              msdu[MAX_DATA_SIZE];
 412};
 413
 414struct mlme_set_request_pset {
 415	u8         pib_attribute;
 416	u8         pib_attribute_index;
 417	u8         pib_attribute_length;
 418	u8         pib_attribute_value[MAX_ATTRIBUTE_SIZE];
 419};
 420
 421struct hwme_set_request_pset {
 422	u8         hw_attribute;
 423	u8         hw_attribute_length;
 424	u8         hw_attribute_value[MAX_HWME_ATTRIBUTE_SIZE];
 425};
 426
 427struct hwme_get_request_pset {
 428	u8         hw_attribute;
 429};
 430
 431struct tdme_setsfr_request_pset {
 432	u8         sfr_page;
 433	u8         sfr_address;
 434	u8         sfr_value;
 435};
 436
 437/* uplink functions parameter set definitions */
 438struct hwme_set_confirm_pset {
 439	u8         status;
 440	u8         hw_attribute;
 441};
 442
 443struct hwme_get_confirm_pset {
 444	u8         status;
 445	u8         hw_attribute;
 446	u8         hw_attribute_length;
 447	u8         hw_attribute_value[MAX_HWME_ATTRIBUTE_SIZE];
 448};
 449
 450struct tdme_setsfr_confirm_pset {
 451	u8         status;
 452	u8         sfr_page;
 453	u8         sfr_address;
 454};
 455
 456struct mac_message {
 457	u8      command_id;
 458	u8      length;
 459	union {
 460		struct mcps_data_request_pset       data_req;
 461		struct mlme_set_request_pset        set_req;
 462		struct hwme_set_request_pset        hwme_set_req;
 463		struct hwme_get_request_pset        hwme_get_req;
 464		struct tdme_setsfr_request_pset     tdme_set_sfr_req;
 465		struct hwme_set_confirm_pset        hwme_set_cnf;
 466		struct hwme_get_confirm_pset        hwme_get_cnf;
 467		struct tdme_setsfr_confirm_pset     tdme_set_sfr_cnf;
 468		u8                                  u8param;
 469		u8                                  status;
 470		u8                                  payload[148];
 471	} pdata;
 472};
 473
 474union pa_cfg_sfr {
 475	struct {
 476		u8 bias_current_trim     : 3;
 477		u8 /* reserved */        : 1;
 478		u8 buffer_capacitor_trim : 3;
 479		u8 boost                 : 1;
 480	};
 481	u8 paib;
 482};
 483
 484struct preamble_cfg_sfr {
 485	u8 timeout_symbols      : 3;
 486	u8 acquisition_symbols  : 3;
 487	u8 search_symbols       : 2;
 488};
 489
 490static int (*cascoda_api_upstream)(
 491	const u8 *buf,
 492	size_t len,
 493	void *device_ref
 494);
 495
 496/**
 497 * link_to_linux_err() - Translates an 802.15.4 return code into the closest
 498 *                       linux error
 499 * @link_status:  802.15.4 status code
 500 *
 501 * Return: 0 or Linux error code
 502 */
 503static int link_to_linux_err(int link_status)
 504{
 505	if (link_status < 0) {
 506		/* status is already a Linux code */
 507		return link_status;
 508	}
 509	switch (link_status) {
 510	case IEEE802154_SUCCESS:
 511	case IEEE802154_REALIGNMENT:
 512		return 0;
 513	case IEEE802154_IMPROPER_KEY_TYPE:
 514		return -EKEYREJECTED;
 515	case IEEE802154_IMPROPER_SECURITY_LEVEL:
 516	case IEEE802154_UNSUPPORTED_LEGACY:
 517	case IEEE802154_DENIED:
 518		return -EACCES;
 519	case IEEE802154_BEACON_LOST:
 520	case IEEE802154_NO_ACK:
 521	case IEEE802154_NO_BEACON:
 522		return -ENETUNREACH;
 523	case IEEE802154_CHANNEL_ACCESS_FAILURE:
 524	case IEEE802154_TX_ACTIVE:
 525	case IEEE802154_SCAN_IN_PROGRESS:
 526		return -EBUSY;
 527	case IEEE802154_DISABLE_TRX_FAILURE:
 528	case IEEE802154_OUT_OF_CAP:
 529		return -EAGAIN;
 530	case IEEE802154_FRAME_TOO_LONG:
 531		return -EMSGSIZE;
 532	case IEEE802154_INVALID_GTS:
 533	case IEEE802154_PAST_TIME:
 534		return -EBADSLT;
 535	case IEEE802154_INVALID_HANDLE:
 536		return -EBADMSG;
 537	case IEEE802154_INVALID_PARAMETER:
 538	case IEEE802154_UNSUPPORTED_ATTRIBUTE:
 539	case IEEE802154_ON_TIME_TOO_LONG:
 540	case IEEE802154_INVALID_INDEX:
 541		return -EINVAL;
 542	case IEEE802154_NO_DATA:
 543		return -ENODATA;
 544	case IEEE802154_NO_SHORT_ADDRESS:
 545		return -EFAULT;
 546	case IEEE802154_PAN_ID_CONFLICT:
 547		return -EADDRINUSE;
 548	case IEEE802154_TRANSACTION_EXPIRED:
 549		return -ETIME;
 550	case IEEE802154_TRANSACTION_OVERFLOW:
 551		return -ENOBUFS;
 552	case IEEE802154_UNAVAILABLE_KEY:
 553		return -ENOKEY;
 554	case IEEE802154_INVALID_ADDRESS:
 555		return -ENXIO;
 556	case IEEE802154_TRACKING_OFF:
 557	case IEEE802154_SUPERFRAME_OVERLAP:
 558		return -EREMOTEIO;
 559	case IEEE802154_LIMIT_REACHED:
 560		return -EDQUOT;
 561	case IEEE802154_READ_ONLY:
 562		return -EROFS;
 563	default:
 564		return -EPROTO;
 565	}
 566}
 567
 568/**
 569 * ca8210_test_int_driver_write() - Writes a message to the test interface to be
 570 *                                  read by the userspace
 571 * @buf:  Buffer containing upstream message
 572 * @len:  length of message to write
 573 * @spi:  SPI device of message originator
 574 *
 575 * Return: 0 or linux error code
 576 */
 577static int ca8210_test_int_driver_write(
 578	const u8       *buf,
 579	size_t          len,
 580	void           *spi
 581)
 582{
 583	struct ca8210_priv *priv = spi_get_drvdata(spi);
 584	struct ca8210_test *test = &priv->test;
 585	char *fifo_buffer;
 586	int i;
 587
 588	dev_dbg(
 589		&priv->spi->dev,
 590		"test_interface: Buffering upstream message:\n"
 591	);
 592	for (i = 0; i < len; i++)
 593		dev_dbg(&priv->spi->dev, "%#03x\n", buf[i]);
 594
 595	fifo_buffer = kmemdup(buf, len, GFP_KERNEL);
 596	if (!fifo_buffer)
 597		return -ENOMEM;
 598	kfifo_in(&test->up_fifo, &fifo_buffer, 4);
 599	wake_up_interruptible(&priv->test.readq);
 600
 601	return 0;
 602}
 603
 604/* SPI Operation */
 605
 606static int ca8210_net_rx(
 607	struct ieee802154_hw  *hw,
 608	u8                    *command,
 609	size_t                 len
 610);
 611static u8 mlme_reset_request_sync(
 612	u8       set_default_pib,
 613	void    *device_ref
 614);
 615static int ca8210_spi_transfer(
 616	struct spi_device *spi,
 617	const u8          *buf,
 618	size_t             len
 619);
 620
 621/**
 622 * ca8210_reset_send() - Hard resets the ca8210 for a given time
 623 * @spi:  Pointer to target ca8210 spi device
 624 * @ms:   Milliseconds to hold the reset line low for
 625 */
 626static void ca8210_reset_send(struct spi_device *spi, unsigned int ms)
 627{
 628	struct device *dev = &spi->dev;
 629	struct ca8210_platform_data *pdata = dev_get_platdata(dev);
 630	struct ca8210_priv *priv = spi_get_drvdata(spi);
 631	long status;
 632
 633	gpiod_set_value(pdata->reset_gpio, 1);
 634	reinit_completion(&priv->ca8210_is_awake);
 635	msleep(ms);
 636	gpiod_set_value(pdata->reset_gpio, 0);
 637	priv->promiscuous = false;
 638
 639	/* Wait until wakeup indication seen */
 640	status = wait_for_completion_interruptible_timeout(
 641		&priv->ca8210_is_awake,
 642		msecs_to_jiffies(CA8210_SYNC_TIMEOUT)
 643	);
 644	if (status == 0) {
 645		dev_crit(
 646			&spi->dev,
 647			"Fatal: No wakeup from ca8210 after reset!\n"
 648		);
 649	}
 650
 651	dev_dbg(&spi->dev, "Reset the device\n");
 652}
 653
 654/**
 655 * ca8210_mlme_reset_worker() - Resets the MLME, Called when the MAC OVERFLOW
 656 *                              condition happens.
 657 * @work:  Pointer to work being executed
 658 */
 659static void ca8210_mlme_reset_worker(struct work_struct *work)
 660{
 661	struct work_priv_container *wpc = container_of(
 662		work,
 663		struct work_priv_container,
 664		work
 665	);
 666	struct ca8210_priv *priv = wpc->priv;
 667
 668	mlme_reset_request_sync(0, priv->spi);
 669	kfree(wpc);
 670}
 671
 672/**
 673 * ca8210_rx_done() - Calls various message dispatches responding to a received
 674 *                    command
 675 * @cas_ctl: Pointer to the cas_control object for the relevant spi transfer
 676 *
 677 * Presents a received SAP command from the ca8210 to the Cascoda EVBME, test
 678 * interface and network driver.
 679 */
 680static void ca8210_rx_done(struct cas_control *cas_ctl)
 681{
 682	u8 *buf;
 683	unsigned int len;
 684	struct work_priv_container *mlme_reset_wpc;
 685	struct ca8210_priv *priv = cas_ctl->priv;
 686
 687	buf = cas_ctl->tx_in_buf;
 688	len = buf[1] + 2;
 689	if (len > CA8210_SPI_BUF_SIZE) {
 690		dev_crit(
 691			&priv->spi->dev,
 692			"Received packet len (%u) erroneously long\n",
 693			len
 694		);
 695		goto finish;
 696	}
 697
 698	if (buf[0] & SPI_SYN) {
 699		if (priv->sync_command_response) {
 700			memcpy(priv->sync_command_response, buf, len);
 701			complete(&priv->sync_exchange_complete);
 702		} else {
 703			if (cascoda_api_upstream)
 704				cascoda_api_upstream(buf, len, priv->spi);
 705			priv->sync_up++;
 706		}
 707	} else {
 708		if (cascoda_api_upstream)
 709			cascoda_api_upstream(buf, len, priv->spi);
 710	}
 711
 712	ca8210_net_rx(priv->hw, buf, len);
 713	if (buf[0] == SPI_MCPS_DATA_CONFIRM) {
 714		if (buf[3] == IEEE802154_TRANSACTION_OVERFLOW) {
 715			dev_info(
 716				&priv->spi->dev,
 717				"Waiting for transaction overflow to stabilise...\n");
 718			msleep(2000);
 719			dev_info(
 720				&priv->spi->dev,
 721				"Resetting MAC...\n");
 722
 723			mlme_reset_wpc = kmalloc(sizeof(*mlme_reset_wpc),
 724						 GFP_KERNEL);
 725			if (!mlme_reset_wpc)
 726				goto finish;
 727			INIT_WORK(
 728				&mlme_reset_wpc->work,
 729				ca8210_mlme_reset_worker
 730			);
 731			mlme_reset_wpc->priv = priv;
 732			queue_work(priv->mlme_workqueue, &mlme_reset_wpc->work);
 733		}
 734	} else if (buf[0] == SPI_HWME_WAKEUP_INDICATION) {
 735		dev_notice(
 736			&priv->spi->dev,
 737			"Wakeup indication received, reason:\n"
 738		);
 739		switch (buf[2]) {
 740		case 0:
 741			dev_notice(
 742				&priv->spi->dev,
 743				"Transceiver woken up from Power Up / System Reset\n"
 744			);
 745			break;
 746		case 1:
 747			dev_notice(
 748				&priv->spi->dev,
 749				"Watchdog Timer Time-Out\n"
 750			);
 751			break;
 752		case 2:
 753			dev_notice(
 754				&priv->spi->dev,
 755				"Transceiver woken up from Power-Off by Sleep Timer Time-Out\n");
 756			break;
 757		case 3:
 758			dev_notice(
 759				&priv->spi->dev,
 760				"Transceiver woken up from Power-Off by GPIO Activity\n"
 761			);
 762			break;
 763		case 4:
 764			dev_notice(
 765				&priv->spi->dev,
 766				"Transceiver woken up from Standby by Sleep Timer Time-Out\n"
 767			);
 768			break;
 769		case 5:
 770			dev_notice(
 771				&priv->spi->dev,
 772				"Transceiver woken up from Standby by GPIO Activity\n"
 773			);
 774			break;
 775		case 6:
 776			dev_notice(
 777				&priv->spi->dev,
 778				"Sleep-Timer Time-Out in Active Mode\n"
 779			);
 780			break;
 781		default:
 782			dev_warn(&priv->spi->dev, "Wakeup reason unknown\n");
 783			break;
 784		}
 785		complete(&priv->ca8210_is_awake);
 786	}
 787
 788finish:;
 789}
 790
 791static void ca8210_remove(struct spi_device *spi_device);
 792
 793/**
 794 * ca8210_spi_transfer_complete() - Called when a single spi transfer has
 795 *                                  completed
 796 * @context:  Pointer to the cas_control object for the finished transfer
 797 */
 798static void ca8210_spi_transfer_complete(void *context)
 799{
 800	struct cas_control *cas_ctl = context;
 801	struct ca8210_priv *priv = cas_ctl->priv;
 802	bool duplex_rx = false;
 803	int i;
 804	u8 retry_buffer[CA8210_SPI_BUF_SIZE];
 805
 806	if (
 807		cas_ctl->tx_in_buf[0] == SPI_NACK ||
 808		(cas_ctl->tx_in_buf[0] == SPI_IDLE &&
 809		cas_ctl->tx_in_buf[1] == SPI_NACK)
 810	) {
 811		/* ca8210 is busy */
 812		dev_info(&priv->spi->dev, "ca8210 was busy during attempted write\n");
 813		if (cas_ctl->tx_buf[0] == SPI_IDLE) {
 814			dev_warn(
 815				&priv->spi->dev,
 816				"IRQ servicing NACKd, dropping transfer\n"
 817			);
 818			kfree(cas_ctl);
 819			return;
 820		}
 821		if (priv->retries > 3) {
 822			dev_err(&priv->spi->dev, "too many retries!\n");
 823			kfree(cas_ctl);
 824			ca8210_remove(priv->spi);
 825			return;
 826		}
 827		memcpy(retry_buffer, cas_ctl->tx_buf, CA8210_SPI_BUF_SIZE);
 828		kfree(cas_ctl);
 829		ca8210_spi_transfer(
 830			priv->spi,
 831			retry_buffer,
 832			CA8210_SPI_BUF_SIZE
 833		);
 834		priv->retries++;
 835		dev_info(&priv->spi->dev, "retried spi write\n");
 836		return;
 837	} else if (
 838			cas_ctl->tx_in_buf[0] != SPI_IDLE &&
 839			cas_ctl->tx_in_buf[0] != SPI_NACK
 840		) {
 841		duplex_rx = true;
 842	}
 843
 844	if (duplex_rx) {
 845		dev_dbg(&priv->spi->dev, "READ CMD DURING TX\n");
 846		for (i = 0; i < cas_ctl->tx_in_buf[1] + 2; i++)
 847			dev_dbg(
 848				&priv->spi->dev,
 849				"%#03x\n",
 850				cas_ctl->tx_in_buf[i]
 851			);
 852		ca8210_rx_done(cas_ctl);
 853	}
 854	complete(&priv->spi_transfer_complete);
 855	kfree(cas_ctl);
 856	priv->retries = 0;
 857}
 858
 859/**
 860 * ca8210_spi_transfer() - Initiate duplex spi transfer with ca8210
 861 * @spi: Pointer to spi device for transfer
 862 * @buf: Octet array to send
 863 * @len: length of the buffer being sent
 864 *
 865 * Return: 0 or linux error code
 866 */
 867static int ca8210_spi_transfer(
 868	struct spi_device  *spi,
 869	const u8           *buf,
 870	size_t              len
 871)
 872{
 873	int i, status = 0;
 874	struct ca8210_priv *priv;
 875	struct cas_control *cas_ctl;
 876
 877	if (!spi) {
 878		pr_crit("NULL spi device passed to %s\n", __func__);
 879		return -ENODEV;
 880	}
 881
 882	priv = spi_get_drvdata(spi);
 883	reinit_completion(&priv->spi_transfer_complete);
 884
 885	dev_dbg(&spi->dev, "%s called\n", __func__);
 886
 887	cas_ctl = kzalloc(sizeof(*cas_ctl), GFP_ATOMIC);
 888	if (!cas_ctl)
 889		return -ENOMEM;
 890
 891	cas_ctl->priv = priv;
 892	memset(cas_ctl->tx_buf, SPI_IDLE, CA8210_SPI_BUF_SIZE);
 893	memset(cas_ctl->tx_in_buf, SPI_IDLE, CA8210_SPI_BUF_SIZE);
 894	memcpy(cas_ctl->tx_buf, buf, len);
 895
 896	for (i = 0; i < len; i++)
 897		dev_dbg(&spi->dev, "%#03x\n", cas_ctl->tx_buf[i]);
 898
 899	spi_message_init(&cas_ctl->msg);
 900
 901	cas_ctl->transfer.tx_nbits = 1; /* 1 MOSI line */
 902	cas_ctl->transfer.rx_nbits = 1; /* 1 MISO line */
 903	cas_ctl->transfer.speed_hz = 0; /* Use device setting */
 904	cas_ctl->transfer.bits_per_word = 0; /* Use device setting */
 905	cas_ctl->transfer.tx_buf = cas_ctl->tx_buf;
 906	cas_ctl->transfer.rx_buf = cas_ctl->tx_in_buf;
 907	cas_ctl->transfer.delay.value = 0;
 908	cas_ctl->transfer.delay.unit = SPI_DELAY_UNIT_USECS;
 909	cas_ctl->transfer.cs_change = 0;
 910	cas_ctl->transfer.len = sizeof(struct mac_message);
 911	cas_ctl->msg.complete = ca8210_spi_transfer_complete;
 912	cas_ctl->msg.context = cas_ctl;
 913
 914	spi_message_add_tail(
 915		&cas_ctl->transfer,
 916		&cas_ctl->msg
 917	);
 918
 919	status = spi_async(spi, &cas_ctl->msg);
 920	if (status < 0) {
 921		dev_crit(
 922			&spi->dev,
 923			"status %d from spi_sync in write\n",
 924			status
 925		);
 926	}
 927
 928	return status;
 929}
 930
 931/**
 932 * ca8210_spi_exchange() - Exchange API/SAP commands with the radio
 933 * @buf:         Octet array of command being sent downstream
 934 * @len:         length of buf
 935 * @response:    buffer for storing synchronous response
 936 * @device_ref:  spi_device pointer for ca8210
 937 *
 938 * Effectively calls ca8210_spi_transfer to write buf[] to the spi, then for
 939 * synchronous commands waits for the corresponding response to be read from
 940 * the spi before returning. The response is written to the response parameter.
 941 *
 942 * Return: 0 or linux error code
 943 */
 944static int ca8210_spi_exchange(
 945	const u8 *buf,
 946	size_t len,
 947	u8 *response,
 948	void *device_ref
 949)
 950{
 951	int status = 0;
 952	struct spi_device *spi = device_ref;
 953	struct ca8210_priv *priv = spi->dev.driver_data;
 954	long wait_remaining;
 955
 956	if ((buf[0] & SPI_SYN) && response) { /* if sync wait for confirm */
 957		reinit_completion(&priv->sync_exchange_complete);
 958		priv->sync_command_response = response;
 959	}
 960
 961	do {
 962		reinit_completion(&priv->spi_transfer_complete);
 963		status = ca8210_spi_transfer(priv->spi, buf, len);
 964		if (status) {
 965			dev_warn(
 966				&spi->dev,
 967				"spi write failed, returned %d\n",
 968				status
 969			);
 970			if (status == -EBUSY)
 971				continue;
 972			if (((buf[0] & SPI_SYN) && response))
 973				complete(&priv->sync_exchange_complete);
 974			goto cleanup;
 975		}
 976
 977		wait_remaining = wait_for_completion_interruptible_timeout(
 978			&priv->spi_transfer_complete,
 979			msecs_to_jiffies(1000)
 980		);
 981		if (wait_remaining == -ERESTARTSYS) {
 982			status = -ERESTARTSYS;
 983		} else if (wait_remaining == 0) {
 984			dev_err(
 985				&spi->dev,
 986				"SPI downstream transfer timed out!\n"
 987			);
 988			status = -ETIME;
 989			goto cleanup;
 990		}
 991	} while (status < 0);
 992
 993	if (!((buf[0] & SPI_SYN) && response))
 994		goto cleanup;
 995
 996	wait_remaining = wait_for_completion_interruptible_timeout(
 997		&priv->sync_exchange_complete,
 998		msecs_to_jiffies(CA8210_SYNC_TIMEOUT)
 999	);
1000	if (wait_remaining == -ERESTARTSYS) {
1001		status = -ERESTARTSYS;
1002	} else if (wait_remaining == 0) {
1003		dev_err(
1004			&spi->dev,
1005			"Synchronous confirm timeout\n"
1006		);
1007		status = -ETIME;
1008	}
1009
1010cleanup:
1011	priv->sync_command_response = NULL;
1012	return status;
1013}
1014
1015/**
1016 * ca8210_interrupt_handler() - Called when an irq is received from the ca8210
1017 * @irq:     Id of the irq being handled
1018 * @dev_id:  Pointer passed by the system, pointing to the ca8210's private data
1019 *
1020 * This function is called when the irq line from the ca8210 is asserted,
1021 * signifying that the ca8210 has a message to send upstream to us. Starts the
1022 * asynchronous spi read.
1023 *
1024 * Return: irq return code
1025 */
1026static irqreturn_t ca8210_interrupt_handler(int irq, void *dev_id)
1027{
1028	struct ca8210_priv *priv = dev_id;
1029	int status;
1030
1031	dev_dbg(&priv->spi->dev, "irq: Interrupt occurred\n");
1032	do {
1033		status = ca8210_spi_transfer(priv->spi, NULL, 0);
1034		if (status && (status != -EBUSY)) {
1035			dev_warn(
1036				&priv->spi->dev,
1037				"spi read failed, returned %d\n",
1038				status
1039			);
1040		}
1041	} while (status == -EBUSY);
1042	return IRQ_HANDLED;
1043}
1044
1045static int (*cascoda_api_downstream)(
1046	const u8 *buf,
1047	size_t len,
1048	u8 *response,
1049	void *device_ref
1050) = ca8210_spi_exchange;
1051
1052/* Cascoda API / 15.4 SAP Primitives */
1053
1054/**
1055 * tdme_setsfr_request_sync() - TDME_SETSFR_request/confirm according to API
1056 * @sfr_page:    SFR Page
1057 * @sfr_address: SFR Address
1058 * @sfr_value:   SFR Value
1059 * @device_ref:  Nondescript pointer to target device
1060 *
1061 * Return: 802.15.4 status code of TDME-SETSFR.confirm
1062 */
1063static u8 tdme_setsfr_request_sync(
1064	u8            sfr_page,
1065	u8            sfr_address,
1066	u8            sfr_value,
1067	void         *device_ref
1068)
1069{
1070	int ret;
1071	struct mac_message command, response;
1072	struct spi_device *spi = device_ref;
1073
1074	command.command_id = SPI_TDME_SETSFR_REQUEST;
1075	command.length = 3;
1076	command.pdata.tdme_set_sfr_req.sfr_page    = sfr_page;
1077	command.pdata.tdme_set_sfr_req.sfr_address = sfr_address;
1078	command.pdata.tdme_set_sfr_req.sfr_value   = sfr_value;
1079	response.command_id = SPI_IDLE;
1080	ret = cascoda_api_downstream(
1081		&command.command_id,
1082		command.length + 2,
1083		&response.command_id,
1084		device_ref
1085	);
1086	if (ret) {
1087		dev_crit(&spi->dev, "cascoda_api_downstream returned %d", ret);
1088		return IEEE802154_SYSTEM_ERROR;
1089	}
1090
1091	if (response.command_id != SPI_TDME_SETSFR_CONFIRM) {
1092		dev_crit(
1093			&spi->dev,
1094			"sync response to SPI_TDME_SETSFR_REQUEST was not SPI_TDME_SETSFR_CONFIRM, it was %d\n",
1095			response.command_id
1096		);
1097		return IEEE802154_SYSTEM_ERROR;
1098	}
1099
1100	return response.pdata.tdme_set_sfr_cnf.status;
1101}
1102
1103/**
1104 * tdme_chipinit() - TDME Chip Register Default Initialisation Macro
1105 * @device_ref: Nondescript pointer to target device
1106 *
1107 * Return: 802.15.4 status code of API calls
1108 */
1109static u8 tdme_chipinit(void *device_ref)
1110{
1111	u8 status = IEEE802154_SUCCESS;
1112	u8 sfr_address;
1113	struct spi_device *spi = device_ref;
1114	struct preamble_cfg_sfr pre_cfg_value = {
1115		.timeout_symbols     = 3,
1116		.acquisition_symbols = 3,
1117		.search_symbols      = 1,
1118	};
1119	/* LNA Gain Settings */
1120	status = tdme_setsfr_request_sync(
1121		1, (sfr_address = CA8210_SFR_LNAGX40),
1122		LNAGX40_DEFAULT_GAIN, device_ref);
1123	if (status)
1124		goto finish;
1125	status = tdme_setsfr_request_sync(
1126		1, (sfr_address = CA8210_SFR_LNAGX41),
1127		LNAGX41_DEFAULT_GAIN, device_ref);
1128	if (status)
1129		goto finish;
1130	status = tdme_setsfr_request_sync(
1131		1, (sfr_address = CA8210_SFR_LNAGX42),
1132		LNAGX42_DEFAULT_GAIN, device_ref);
1133	if (status)
1134		goto finish;
1135	status = tdme_setsfr_request_sync(
1136		1, (sfr_address = CA8210_SFR_LNAGX43),
1137		LNAGX43_DEFAULT_GAIN, device_ref);
1138	if (status)
1139		goto finish;
1140	status = tdme_setsfr_request_sync(
1141		1, (sfr_address = CA8210_SFR_LNAGX44),
1142		LNAGX44_DEFAULT_GAIN, device_ref);
1143	if (status)
1144		goto finish;
1145	status = tdme_setsfr_request_sync(
1146		1, (sfr_address = CA8210_SFR_LNAGX45),
1147		LNAGX45_DEFAULT_GAIN, device_ref);
1148	if (status)
1149		goto finish;
1150	status = tdme_setsfr_request_sync(
1151		1, (sfr_address = CA8210_SFR_LNAGX46),
1152		LNAGX46_DEFAULT_GAIN, device_ref);
1153	if (status)
1154		goto finish;
1155	status = tdme_setsfr_request_sync(
1156		1, (sfr_address = CA8210_SFR_LNAGX47),
1157		LNAGX47_DEFAULT_GAIN, device_ref);
1158	if (status)
1159		goto finish;
1160	/* Preamble Timing Config */
1161	status = tdme_setsfr_request_sync(
1162		1, (sfr_address = CA8210_SFR_PRECFG),
1163		*((u8 *)&pre_cfg_value), device_ref);
1164	if (status)
1165		goto finish;
1166	/* Preamble Threshold High */
1167	status = tdme_setsfr_request_sync(
1168		1, (sfr_address = CA8210_SFR_PTHRH),
1169		PTHRH_DEFAULT_THRESHOLD, device_ref);
1170	if (status)
1171		goto finish;
1172	/* Tx Output Power 8 dBm */
1173	status = tdme_setsfr_request_sync(
1174		0, (sfr_address = CA8210_SFR_PACFGIB),
1175		PACFGIB_DEFAULT_CURRENT, device_ref);
1176	if (status)
1177		goto finish;
1178
1179finish:
1180	if (status != IEEE802154_SUCCESS) {
1181		dev_err(
1182			&spi->dev,
1183			"failed to set sfr at %#03x, status = %#03x\n",
1184			sfr_address,
1185			status
1186		);
1187	}
1188	return status;
1189}
1190
1191/**
1192 * tdme_channelinit() - TDME Channel Register Default Initialisation Macro (Tx)
1193 * @channel:    802.15.4 channel to initialise chip for
1194 * @device_ref: Nondescript pointer to target device
1195 *
1196 * Return: 802.15.4 status code of API calls
1197 */
1198static u8 tdme_channelinit(u8 channel, void *device_ref)
1199{
1200	/* Transceiver front-end local oscillator tx two-point calibration
1201	 * value. Tuned for the hardware.
1202	 */
1203	u8 txcalval;
1204
1205	if (channel >= 25)
1206		txcalval = 0xA7;
1207	else if (channel >= 23)
1208		txcalval = 0xA8;
1209	else if (channel >= 22)
1210		txcalval = 0xA9;
1211	else if (channel >= 20)
1212		txcalval = 0xAA;
1213	else if (channel >= 17)
1214		txcalval = 0xAB;
1215	else if (channel >= 16)
1216		txcalval = 0xAC;
1217	else if (channel >= 14)
1218		txcalval = 0xAD;
1219	else if (channel >= 12)
1220		txcalval = 0xAE;
1221	else
1222		txcalval = 0xAF;
1223
1224	return tdme_setsfr_request_sync(
1225		1,
1226		CA8210_SFR_LOTXCAL,
1227		txcalval,
1228		device_ref
1229	);  /* LO Tx Cal */
1230}
1231
1232/**
1233 * tdme_checkpibattribute() - Checks Attribute Values that are not checked in
1234 *                            MAC
1235 * @pib_attribute:        Attribute Number
1236 * @pib_attribute_length: Attribute length
1237 * @pib_attribute_value:  Pointer to Attribute Value
1238 *
1239 * Return: 802.15.4 status code of checks
1240 */
1241static u8 tdme_checkpibattribute(
1242	u8            pib_attribute,
1243	u8            pib_attribute_length,
1244	const void   *pib_attribute_value
1245)
1246{
1247	u8 status = IEEE802154_SUCCESS;
1248	u8 value;
1249
1250	value  = *((u8 *)pib_attribute_value);
1251
1252	switch (pib_attribute) {
1253	/* PHY */
1254	case PHY_TRANSMIT_POWER:
1255		if (value > 0x3F)
1256			status = IEEE802154_INVALID_PARAMETER;
1257		break;
1258	case PHY_CCA_MODE:
1259		if (value > 0x03)
1260			status = IEEE802154_INVALID_PARAMETER;
1261		break;
1262	/* MAC */
1263	case MAC_BATT_LIFE_EXT_PERIODS:
1264		if (value < 6 || value > 41)
1265			status = IEEE802154_INVALID_PARAMETER;
1266		break;
1267	case MAC_BEACON_PAYLOAD:
1268		if (pib_attribute_length > MAX_BEACON_PAYLOAD_LENGTH)
1269			status = IEEE802154_INVALID_PARAMETER;
1270		break;
1271	case MAC_BEACON_PAYLOAD_LENGTH:
1272		if (value > MAX_BEACON_PAYLOAD_LENGTH)
1273			status = IEEE802154_INVALID_PARAMETER;
1274		break;
1275	case MAC_BEACON_ORDER:
1276		if (value > 15)
1277			status = IEEE802154_INVALID_PARAMETER;
1278		break;
1279	case MAC_MAX_BE:
1280		if (value < 3 || value > 8)
1281			status = IEEE802154_INVALID_PARAMETER;
1282		break;
1283	case MAC_MAX_CSMA_BACKOFFS:
1284		if (value > 5)
1285			status = IEEE802154_INVALID_PARAMETER;
1286		break;
1287	case MAC_MAX_FRAME_RETRIES:
1288		if (value > 7)
1289			status = IEEE802154_INVALID_PARAMETER;
1290		break;
1291	case MAC_MIN_BE:
1292		if (value > 8)
1293			status = IEEE802154_INVALID_PARAMETER;
1294		break;
1295	case MAC_RESPONSE_WAIT_TIME:
1296		if (value < 2 || value > 64)
1297			status = IEEE802154_INVALID_PARAMETER;
1298		break;
1299	case MAC_SUPERFRAME_ORDER:
1300		if (value > 15)
1301			status = IEEE802154_INVALID_PARAMETER;
1302		break;
1303	/* boolean */
1304	case MAC_ASSOCIATED_PAN_COORD:
1305	case MAC_ASSOCIATION_PERMIT:
1306	case MAC_AUTO_REQUEST:
1307	case MAC_BATT_LIFE_EXT:
1308	case MAC_GTS_PERMIT:
1309	case MAC_PROMISCUOUS_MODE:
1310	case MAC_RX_ON_WHEN_IDLE:
1311	case MAC_SECURITY_ENABLED:
1312		if (value > 1)
1313			status = IEEE802154_INVALID_PARAMETER;
1314		break;
1315	/* MAC SEC */
1316	case MAC_AUTO_REQUEST_SECURITY_LEVEL:
1317		if (value > 7)
1318			status = IEEE802154_INVALID_PARAMETER;
1319		break;
1320	case MAC_AUTO_REQUEST_KEY_ID_MODE:
1321		if (value > 3)
1322			status = IEEE802154_INVALID_PARAMETER;
1323		break;
1324	default:
1325		break;
1326	}
1327
1328	return status;
1329}
1330
1331/**
1332 * tdme_settxpower() - Sets the tx power for MLME_SET phyTransmitPower
1333 * @txp:        Transmit Power
1334 * @device_ref: Nondescript pointer to target device
1335 *
1336 * Normalised to 802.15.4 Definition (6-bit, signed):
1337 * Bit 7-6: not used
1338 * Bit 5-0: tx power (-32 - +31 dB)
1339 *
1340 * Return: 802.15.4 status code of api calls
1341 */
1342static u8 tdme_settxpower(u8 txp, void *device_ref)
1343{
1344	u8 status;
1345	s8 txp_val;
1346	u8 txp_ext;
1347	union pa_cfg_sfr pa_cfg_val;
1348
1349	/* extend from 6 to 8 bit */
1350	txp_ext = 0x3F & txp;
1351	if (txp_ext & 0x20)
1352		txp_ext += 0xC0;
1353	txp_val = (s8)txp_ext;
1354
1355	if (CA8210_MAC_MPW) {
1356		if (txp_val > 0) {
1357			/* 8 dBm: ptrim = 5, itrim = +3 => +4 dBm */
1358			pa_cfg_val.bias_current_trim     = 3;
1359			pa_cfg_val.buffer_capacitor_trim = 5;
1360			pa_cfg_val.boost                 = 1;
1361		} else {
1362			/* 0 dBm: ptrim = 7, itrim = +3 => -6 dBm */
1363			pa_cfg_val.bias_current_trim     = 3;
1364			pa_cfg_val.buffer_capacitor_trim = 7;
1365			pa_cfg_val.boost                 = 0;
1366		}
1367		/* write PACFG */
1368		status = tdme_setsfr_request_sync(
1369			0,
1370			CA8210_SFR_PACFG,
1371			pa_cfg_val.paib,
1372			device_ref
1373		);
1374	} else {
1375		/* Look-Up Table for Setting Current and Frequency Trim values
1376		 * for desired Output Power
1377		 */
1378		if (txp_val > 8) {
1379			pa_cfg_val.paib = 0x3F;
1380		} else if (txp_val == 8) {
1381			pa_cfg_val.paib = 0x32;
1382		} else if (txp_val == 7) {
1383			pa_cfg_val.paib = 0x22;
1384		} else if (txp_val == 6) {
1385			pa_cfg_val.paib = 0x18;
1386		} else if (txp_val == 5) {
1387			pa_cfg_val.paib = 0x10;
1388		} else if (txp_val == 4) {
1389			pa_cfg_val.paib = 0x0C;
1390		} else if (txp_val == 3) {
1391			pa_cfg_val.paib = 0x08;
1392		} else if (txp_val == 2) {
1393			pa_cfg_val.paib = 0x05;
1394		} else if (txp_val == 1) {
1395			pa_cfg_val.paib = 0x03;
1396		} else if (txp_val == 0) {
1397			pa_cfg_val.paib = 0x01;
1398		} else { /* < 0 */
1399			pa_cfg_val.paib = 0x00;
1400		}
1401		/* write PACFGIB */
1402		status = tdme_setsfr_request_sync(
1403			0,
1404			CA8210_SFR_PACFGIB,
1405			pa_cfg_val.paib,
1406			device_ref
1407		);
1408	}
1409
1410	return status;
1411}
1412
1413/**
1414 * mcps_data_request() - mcps_data_request (Send Data) according to API Spec
1415 * @src_addr_mode:    Source Addressing Mode
1416 * @dst_address_mode: Destination Addressing Mode
1417 * @dst_pan_id:       Destination PAN ID
1418 * @dst_addr:         Pointer to Destination Address
1419 * @msdu_length:      length of Data
1420 * @msdu:             Pointer to Data
1421 * @msdu_handle:      Handle of Data
1422 * @tx_options:       Tx Options Bit Field
1423 * @security:         Pointer to Security Structure or NULL
1424 * @device_ref:       Nondescript pointer to target device
1425 *
1426 * Return: 802.15.4 status code of action
1427 */
1428static u8 mcps_data_request(
1429	u8               src_addr_mode,
1430	u8               dst_address_mode,
1431	u16              dst_pan_id,
1432	union macaddr   *dst_addr,
1433	u8               msdu_length,
1434	u8              *msdu,
1435	u8               msdu_handle,
1436	u8               tx_options,
1437	struct secspec  *security,
1438	void            *device_ref
1439)
1440{
1441	struct secspec *psec;
1442	struct mac_message command;
1443
1444	command.command_id = SPI_MCPS_DATA_REQUEST;
1445	command.pdata.data_req.src_addr_mode = src_addr_mode;
1446	command.pdata.data_req.dst.mode = dst_address_mode;
1447	if (dst_address_mode != MAC_MODE_NO_ADDR) {
1448		put_unaligned_le16(dst_pan_id, command.pdata.data_req.dst.pan_id);
1449		if (dst_address_mode == MAC_MODE_SHORT_ADDR) {
1450			command.pdata.data_req.dst.address[0] = LS_BYTE(
1451				dst_addr->short_address
1452			);
1453			command.pdata.data_req.dst.address[1] = MS_BYTE(
1454				dst_addr->short_address
1455			);
1456		} else {   /* MAC_MODE_LONG_ADDR*/
1457			memcpy(
1458				command.pdata.data_req.dst.address,
1459				dst_addr->ieee_address,
1460				8
1461			);
1462		}
1463	}
1464	command.pdata.data_req.msdu_length = msdu_length;
1465	command.pdata.data_req.msdu_handle = msdu_handle;
1466	command.pdata.data_req.tx_options = tx_options;
1467	memcpy(command.pdata.data_req.msdu, msdu, msdu_length);
1468	psec = (struct secspec *)(command.pdata.data_req.msdu + msdu_length);
1469	command.length = sizeof(struct mcps_data_request_pset) -
1470		MAX_DATA_SIZE + msdu_length;
1471	if (!security || security->security_level == 0) {
1472		psec->security_level = 0;
1473		command.length += 1;
1474	} else {
1475		*psec = *security;
1476		command.length += sizeof(struct secspec);
1477	}
1478
1479	if (ca8210_spi_transfer(device_ref, &command.command_id,
1480				command.length + 2))
1481		return IEEE802154_SYSTEM_ERROR;
1482
1483	return IEEE802154_SUCCESS;
1484}
1485
1486/**
1487 * mlme_reset_request_sync() - MLME_RESET_request/confirm according to API Spec
1488 * @set_default_pib: Set defaults in PIB
1489 * @device_ref:      Nondescript pointer to target device
1490 *
1491 * Return: 802.15.4 status code of MLME-RESET.confirm
1492 */
1493static u8 mlme_reset_request_sync(
1494	u8    set_default_pib,
1495	void *device_ref
1496)
1497{
1498	u8 status;
1499	struct mac_message command, response;
1500	struct spi_device *spi = device_ref;
1501
1502	command.command_id = SPI_MLME_RESET_REQUEST;
1503	command.length = 1;
1504	command.pdata.u8param = set_default_pib;
1505
1506	if (cascoda_api_downstream(
1507		&command.command_id,
1508		command.length + 2,
1509		&response.command_id,
1510		device_ref)) {
1511		dev_err(&spi->dev, "cascoda_api_downstream failed\n");
1512		return IEEE802154_SYSTEM_ERROR;
1513	}
1514
1515	if (response.command_id != SPI_MLME_RESET_CONFIRM)
1516		return IEEE802154_SYSTEM_ERROR;
1517
1518	status = response.pdata.status;
1519
1520	/* reset COORD Bit for Channel Filtering as Coordinator */
1521	if (CA8210_MAC_WORKAROUNDS && set_default_pib && !status) {
1522		status = tdme_setsfr_request_sync(
1523			0,
1524			CA8210_SFR_MACCON,
1525			0,
1526			device_ref
1527		);
1528	}
1529
1530	return status;
1531}
1532
1533/**
1534 * mlme_set_request_sync() - MLME_SET_request/confirm according to API Spec
1535 * @pib_attribute:        Attribute Number
1536 * @pib_attribute_index:  Index within Attribute if an Array
1537 * @pib_attribute_length: Attribute length
1538 * @pib_attribute_value:  Pointer to Attribute Value
1539 * @device_ref:           Nondescript pointer to target device
1540 *
1541 * Return: 802.15.4 status code of MLME-SET.confirm
1542 */
1543static u8 mlme_set_request_sync(
1544	u8            pib_attribute,
1545	u8            pib_attribute_index,
1546	u8            pib_attribute_length,
1547	const void   *pib_attribute_value,
1548	void         *device_ref
1549)
1550{
1551	u8 status;
1552	struct mac_message command, response;
1553
1554	/* pre-check the validity of pib_attribute values that are not checked
1555	 * in MAC
1556	 */
1557	if (tdme_checkpibattribute(
1558		pib_attribute, pib_attribute_length, pib_attribute_value)) {
1559		return IEEE802154_INVALID_PARAMETER;
1560	}
1561
1562	if (pib_attribute == PHY_CURRENT_CHANNEL) {
1563		status = tdme_channelinit(
1564			*((u8 *)pib_attribute_value),
1565			device_ref
1566		);
1567		if (status)
1568			return status;
1569	}
1570
1571	if (pib_attribute == PHY_TRANSMIT_POWER) {
1572		return tdme_settxpower(
1573			*((u8 *)pib_attribute_value),
1574			device_ref
1575		);
1576	}
1577
1578	command.command_id = SPI_MLME_SET_REQUEST;
1579	command.length = sizeof(struct mlme_set_request_pset) -
1580		MAX_ATTRIBUTE_SIZE + pib_attribute_length;
1581	command.pdata.set_req.pib_attribute = pib_attribute;
1582	command.pdata.set_req.pib_attribute_index = pib_attribute_index;
1583	command.pdata.set_req.pib_attribute_length = pib_attribute_length;
1584	memcpy(
1585		command.pdata.set_req.pib_attribute_value,
1586		pib_attribute_value,
1587		pib_attribute_length
1588	);
1589
1590	if (cascoda_api_downstream(
1591		&command.command_id,
1592		command.length + 2,
1593		&response.command_id,
1594		device_ref)) {
1595		return IEEE802154_SYSTEM_ERROR;
1596	}
1597
1598	if (response.command_id != SPI_MLME_SET_CONFIRM)
1599		return IEEE802154_SYSTEM_ERROR;
1600
1601	return response.pdata.status;
1602}
1603
1604/**
1605 * hwme_set_request_sync() - HWME_SET_request/confirm according to API Spec
1606 * @hw_attribute:        Attribute Number
1607 * @hw_attribute_length: Attribute length
1608 * @hw_attribute_value:  Pointer to Attribute Value
1609 * @device_ref:          Nondescript pointer to target device
1610 *
1611 * Return: 802.15.4 status code of HWME-SET.confirm
1612 */
1613static u8 hwme_set_request_sync(
1614	u8           hw_attribute,
1615	u8           hw_attribute_length,
1616	u8          *hw_attribute_value,
1617	void        *device_ref
1618)
1619{
1620	struct mac_message command, response;
1621
1622	command.command_id = SPI_HWME_SET_REQUEST;
1623	command.length = 2 + hw_attribute_length;
1624	command.pdata.hwme_set_req.hw_attribute = hw_attribute;
1625	command.pdata.hwme_set_req.hw_attribute_length = hw_attribute_length;
1626	memcpy(
1627		command.pdata.hwme_set_req.hw_attribute_value,
1628		hw_attribute_value,
1629		hw_attribute_length
1630	);
1631
1632	if (cascoda_api_downstream(
1633		&command.command_id,
1634		command.length + 2,
1635		&response.command_id,
1636		device_ref)) {
1637		return IEEE802154_SYSTEM_ERROR;
1638	}
1639
1640	if (response.command_id != SPI_HWME_SET_CONFIRM)
1641		return IEEE802154_SYSTEM_ERROR;
1642
1643	return response.pdata.hwme_set_cnf.status;
1644}
1645
1646/**
1647 * hwme_get_request_sync() - HWME_GET_request/confirm according to API Spec
1648 * @hw_attribute:        Attribute Number
1649 * @hw_attribute_length: Attribute length
1650 * @hw_attribute_value:  Pointer to Attribute Value
1651 * @device_ref:          Nondescript pointer to target device
1652 *
1653 * Return: 802.15.4 status code of HWME-GET.confirm
1654 */
1655static u8 hwme_get_request_sync(
1656	u8           hw_attribute,
1657	u8          *hw_attribute_length,
1658	u8          *hw_attribute_value,
1659	void        *device_ref
1660)
1661{
1662	struct mac_message command, response;
1663
1664	command.command_id = SPI_HWME_GET_REQUEST;
1665	command.length = 1;
1666	command.pdata.hwme_get_req.hw_attribute = hw_attribute;
1667
1668	if (cascoda_api_downstream(
1669		&command.command_id,
1670		command.length + 2,
1671		&response.command_id,
1672		device_ref)) {
1673		return IEEE802154_SYSTEM_ERROR;
1674	}
1675
1676	if (response.command_id != SPI_HWME_GET_CONFIRM)
1677		return IEEE802154_SYSTEM_ERROR;
1678
1679	if (response.pdata.hwme_get_cnf.status == IEEE802154_SUCCESS) {
1680		*hw_attribute_length =
1681			response.pdata.hwme_get_cnf.hw_attribute_length;
1682		memcpy(
1683			hw_attribute_value,
1684			response.pdata.hwme_get_cnf.hw_attribute_value,
1685			*hw_attribute_length
1686		);
1687	}
1688
1689	return response.pdata.hwme_get_cnf.status;
1690}
1691
1692/* Network driver operation */
1693
1694/**
1695 * ca8210_async_xmit_complete() - Called to announce that an asynchronous
1696 *                                transmission has finished
1697 * @hw:          ieee802154_hw of ca8210 that has finished exchange
1698 * @msduhandle:  Identifier of transmission that has completed
1699 * @status:      Returned 802.15.4 status code of the transmission
1700 *
1701 * Return: 0 or linux error code
1702 */
1703static int ca8210_async_xmit_complete(
1704	struct ieee802154_hw  *hw,
1705	u8                     msduhandle,
1706	u8                     status)
1707{
1708	struct ca8210_priv *priv = hw->priv;
1709
1710	if (priv->nextmsduhandle != msduhandle) {
1711		dev_err(
1712			&priv->spi->dev,
1713			"Unexpected msdu_handle on data confirm, Expected %d, got %d\n",
1714			priv->nextmsduhandle,
1715			msduhandle
1716		);
1717		return -EIO;
1718	}
1719
1720	priv->async_tx_pending = false;
1721	priv->nextmsduhandle++;
1722
1723	if (status) {
1724		dev_err(
1725			&priv->spi->dev,
1726			"Link transmission unsuccessful, status = %d\n",
1727			status
1728		);
1729		if (status != IEEE802154_TRANSACTION_OVERFLOW) {
1730			ieee802154_xmit_error(priv->hw, priv->tx_skb, status);
1731			return 0;
1732		}
1733	}
1734	ieee802154_xmit_complete(priv->hw, priv->tx_skb, true);
1735
1736	return 0;
1737}
1738
1739/**
1740 * ca8210_skb_rx() - Contructs a properly framed socket buffer from a received
1741 *                   MCPS_DATA_indication
1742 * @hw:        ieee802154_hw that MCPS_DATA_indication was received by
1743 * @len:       length of MCPS_DATA_indication
1744 * @data_ind:  Octet array of MCPS_DATA_indication
1745 *
1746 * Called by the spi driver whenever a SAP command is received, this function
1747 * will ascertain whether the command is of interest to the network driver and
1748 * take necessary action.
1749 *
1750 * Return: 0 or linux error code
1751 */
1752static int ca8210_skb_rx(
1753	struct ieee802154_hw  *hw,
1754	size_t                 len,
1755	u8                    *data_ind
1756)
1757{
1758	struct ieee802154_hdr hdr;
1759	int msdulen;
1760	int hlen;
1761	u8 mpdulinkquality = data_ind[23];
1762	struct sk_buff *skb;
1763	struct ca8210_priv *priv = hw->priv;
1764
1765	/* Allocate mtu size buffer for every rx packet */
1766	skb = dev_alloc_skb(IEEE802154_MTU + sizeof(hdr));
1767	if (!skb)
1768		return -ENOMEM;
1769
1770	skb_reserve(skb, sizeof(hdr));
1771
1772	msdulen = data_ind[22]; /* msdu_length */
1773	if (msdulen > IEEE802154_MTU) {
1774		dev_err(
1775			&priv->spi->dev,
1776			"received erroneously large msdu length!\n"
1777		);
1778		kfree_skb(skb);
1779		return -EMSGSIZE;
1780	}
1781	dev_dbg(&priv->spi->dev, "skb buffer length = %d\n", msdulen);
1782
1783	if (priv->promiscuous)
1784		goto copy_payload;
1785
1786	/* Populate hdr */
1787	hdr.sec.level = data_ind[29 + msdulen];
1788	dev_dbg(&priv->spi->dev, "security level: %#03x\n", hdr.sec.level);
1789	if (hdr.sec.level > 0) {
1790		hdr.sec.key_id_mode = data_ind[30 + msdulen];
1791		memcpy(&hdr.sec.extended_src, &data_ind[31 + msdulen], 8);
1792		hdr.sec.key_id = data_ind[39 + msdulen];
1793	}
1794	hdr.source.mode = data_ind[0];
1795	dev_dbg(&priv->spi->dev, "srcAddrMode: %#03x\n", hdr.source.mode);
1796	hdr.source.pan_id = cpu_to_le16(get_unaligned_le16(&data_ind[1]));
1797	dev_dbg(&priv->spi->dev, "srcPanId: %#06x\n", hdr.source.pan_id);
1798	memcpy(&hdr.source.extended_addr, &data_ind[3], 8);
1799	hdr.dest.mode = data_ind[11];
1800	dev_dbg(&priv->spi->dev, "dstAddrMode: %#03x\n", hdr.dest.mode);
1801	hdr.dest.pan_id = cpu_to_le16(get_unaligned_le16(&data_ind[12]));
1802	dev_dbg(&priv->spi->dev, "dstPanId: %#06x\n", hdr.dest.pan_id);
1803	memcpy(&hdr.dest.extended_addr, &data_ind[14], 8);
1804
1805	/* Fill in FC implicitly */
1806	hdr.fc.type = 1; /* Data frame */
1807	if (hdr.sec.level)
1808		hdr.fc.security_enabled = 1;
1809	else
1810		hdr.fc.security_enabled = 0;
1811	if (data_ind[1] != data_ind[12] || data_ind[2] != data_ind[13])
1812		hdr.fc.intra_pan = 1;
1813	else
1814		hdr.fc.intra_pan = 0;
1815	hdr.fc.dest_addr_mode = hdr.dest.mode;
1816	hdr.fc.source_addr_mode = hdr.source.mode;
1817
1818	/* Add hdr to front of buffer */
1819	hlen = ieee802154_hdr_push(skb, &hdr);
1820
1821	if (hlen < 0) {
1822		dev_crit(&priv->spi->dev, "failed to push mac hdr onto skb!\n");
1823		kfree_skb(skb);
1824		return hlen;
1825	}
1826
1827	skb_reset_mac_header(skb);
1828	skb->mac_len = hlen;
1829
1830copy_payload:
1831	/* Add <msdulen> bytes of space to the back of the buffer */
1832	/* Copy msdu to skb */
1833	skb_put_data(skb, &data_ind[29], msdulen);
1834
1835	ieee802154_rx_irqsafe(hw, skb, mpdulinkquality);
1836	return 0;
1837}
1838
1839/**
1840 * ca8210_net_rx() - Acts upon received SAP commands relevant to the network
1841 *                   driver
1842 * @hw:       ieee802154_hw that command was received by
1843 * @command:  Octet array of received command
1844 * @len:      length of the received command
1845 *
1846 * Called by the spi driver whenever a SAP command is received, this function
1847 * will ascertain whether the command is of interest to the network driver and
1848 * take necessary action.
1849 *
1850 * Return: 0 or linux error code
1851 */
1852static int ca8210_net_rx(struct ieee802154_hw *hw, u8 *command, size_t len)
1853{
1854	struct ca8210_priv *priv = hw->priv;
1855	unsigned long flags;
1856	u8 status;
1857
1858	dev_dbg(&priv->spi->dev, "%s: CmdID = %d\n", __func__, command[0]);
1859
1860	if (command[0] == SPI_MCPS_DATA_INDICATION) {
1861		/* Received data */
1862		spin_lock_irqsave(&priv->lock, flags);
1863		if (command[26] == priv->last_dsn) {
1864			dev_dbg(
1865				&priv->spi->dev,
1866				"DSN %d resend received, ignoring...\n",
1867				command[26]
1868			);
1869			spin_unlock_irqrestore(&priv->lock, flags);
1870			return 0;
1871		}
1872		priv->last_dsn = command[26];
1873		spin_unlock_irqrestore(&priv->lock, flags);
1874		return ca8210_skb_rx(hw, len - 2, command + 2);
1875	} else if (command[0] == SPI_MCPS_DATA_CONFIRM) {
1876		status = command[3];
1877		if (priv->async_tx_pending) {
1878			return ca8210_async_xmit_complete(
1879				hw,
1880				command[2],
1881				status
1882			);
1883		}
1884	}
1885
1886	return 0;
1887}
1888
1889/**
1890 * ca8210_skb_tx() - Transmits a given socket buffer using the ca8210
1891 * @skb:         Socket buffer to transmit
1892 * @msduhandle:  Data identifier to pass to the 802.15.4 MAC
1893 * @priv:        Pointer to private data section of target ca8210
1894 *
1895 * Return: 0 or linux error code
1896 */
1897static int ca8210_skb_tx(
1898	struct sk_buff      *skb,
1899	u8                   msduhandle,
1900	struct ca8210_priv  *priv
1901)
1902{
1903	struct ieee802154_hdr header = { };
1904	struct secspec secspec;
1905	int mac_len, status;
1906
1907	dev_dbg(&priv->spi->dev, "%s called\n", __func__);
1908
1909	/* Get addressing info from skb - ieee802154 layer creates a full
1910	 * packet
1911	 */
1912	mac_len = ieee802154_hdr_peek_addrs(skb, &header);
1913	if (mac_len < 0)
1914		return mac_len;
1915
1916	secspec.security_level = header.sec.level;
1917	secspec.key_id_mode = header.sec.key_id_mode;
1918	if (secspec.key_id_mode == 2)
1919		memcpy(secspec.key_source, &header.sec.short_src, 4);
1920	else if (secspec.key_id_mode == 3)
1921		memcpy(secspec.key_source, &header.sec.extended_src, 8);
1922	secspec.key_index = header.sec.key_id;
1923
1924	/* Pass to Cascoda API */
1925	status =  mcps_data_request(
1926		header.source.mode,
1927		header.dest.mode,
1928		le16_to_cpu(header.dest.pan_id),
1929		(union macaddr *)&header.dest.extended_addr,
1930		skb->len - mac_len,
1931		&skb->data[mac_len],
1932		msduhandle,
1933		header.fc.ack_request,
1934		&secspec,
1935		priv->spi
1936	);
1937	return link_to_linux_err(status);
1938}
1939
1940/**
1941 * ca8210_start() - Starts the network driver
1942 * @hw:  ieee802154_hw of ca8210 being started
1943 *
1944 * Return: 0 or linux error code
1945 */
1946static int ca8210_start(struct ieee802154_hw *hw)
1947{
1948	int status;
1949	u8 rx_on_when_idle;
1950	u8 lqi_threshold = 0;
1951	struct ca8210_priv *priv = hw->priv;
1952
1953	priv->last_dsn = -1;
1954	/* Turn receiver on when idle for now just to test rx */
1955	rx_on_when_idle = 1;
1956	status = mlme_set_request_sync(
1957		MAC_RX_ON_WHEN_IDLE,
1958		0,
1959		1,
1960		&rx_on_when_idle,
1961		priv->spi
1962	);
1963	if (status) {
1964		dev_crit(
1965			&priv->spi->dev,
1966			"Setting rx_on_when_idle failed, status = %d\n",
1967			status
1968		);
1969		return link_to_linux_err(status);
1970	}
1971	status = hwme_set_request_sync(
1972		HWME_LQILIMIT,
1973		1,
1974		&lqi_threshold,
1975		priv->spi
1976	);
1977	if (status) {
1978		dev_crit(
1979			&priv->spi->dev,
1980			"Setting lqilimit failed, status = %d\n",
1981			status
1982		);
1983		return link_to_linux_err(status);
1984	}
1985
1986	return 0;
1987}
1988
1989/**
1990 * ca8210_stop() - Stops the network driver
1991 * @hw:  ieee802154_hw of ca8210 being stopped
1992 *
1993 * Return: 0 or linux error code
1994 */
1995static void ca8210_stop(struct ieee802154_hw *hw)
1996{
1997}
1998
1999/**
2000 * ca8210_xmit_async() - Asynchronously transmits a given socket buffer using
2001 *                       the ca8210
2002 * @hw:   ieee802154_hw of ca8210 to transmit from
2003 * @skb:  Socket buffer to transmit
2004 *
2005 * Return: 0 or linux error code
2006 */
2007static int ca8210_xmit_async(struct ieee802154_hw *hw, struct sk_buff *skb)
2008{
2009	struct ca8210_priv *priv = hw->priv;
2010	int status;
2011
2012	dev_dbg(&priv->spi->dev, "calling %s\n", __func__);
2013
2014	priv->tx_skb = skb;
2015	priv->async_tx_pending = true;
2016	status = ca8210_skb_tx(skb, priv->nextmsduhandle, priv);
2017	return status;
2018}
2019
2020/**
2021 * ca8210_get_ed() - Returns the measured energy on the current channel at this
2022 *                   instant in time
2023 * @hw:     ieee802154_hw of target ca8210
2024 * @level:  Measured Energy Detect level
2025 *
2026 * Return: 0 or linux error code
2027 */
2028static int ca8210_get_ed(struct ieee802154_hw *hw, u8 *level)
2029{
2030	u8 lenvar;
2031	struct ca8210_priv *priv = hw->priv;
2032
2033	return link_to_linux_err(
2034		hwme_get_request_sync(HWME_EDVALUE, &lenvar, level, priv->spi)
2035	);
2036}
2037
2038/**
2039 * ca8210_set_channel() - Sets the current operating 802.15.4 channel of the
2040 *                        ca8210
2041 * @hw:       ieee802154_hw of target ca8210
2042 * @page:     Channel page to set
2043 * @channel:  Channel number to set
2044 *
2045 * Return: 0 or linux error code
2046 */
2047static int ca8210_set_channel(
2048	struct ieee802154_hw  *hw,
2049	u8                     page,
2050	u8                     channel
2051)
2052{
2053	u8 status;
2054	struct ca8210_priv *priv = hw->priv;
2055
2056	status = mlme_set_request_sync(
2057		PHY_CURRENT_CHANNEL,
2058		0,
2059		1,
2060		&channel,
2061		priv->spi
2062	);
2063	if (status) {
2064		dev_err(
2065			&priv->spi->dev,
2066			"error setting channel, MLME-SET.confirm status = %d\n",
2067			status
2068		);
2069	}
2070	return link_to_linux_err(status);
2071}
2072
2073/**
2074 * ca8210_set_hw_addr_filt() - Sets the address filtering parameters of the
2075 *                             ca8210
2076 * @hw:       ieee802154_hw of target ca8210
2077 * @filt:     Filtering parameters
2078 * @changed:  Bitmap representing which parameters to change
2079 *
2080 * Effectively just sets the actual addressing information identifying this node
2081 * as all filtering is performed by the ca8210 as detailed in the IEEE 802.15.4
2082 * 2006 specification.
2083 *
2084 * Return: 0 or linux error code
2085 */
2086static int ca8210_set_hw_addr_filt(
2087	struct ieee802154_hw            *hw,
2088	struct ieee802154_hw_addr_filt  *filt,
2089	unsigned long                    changed
2090)
2091{
2092	u8 status = 0;
2093	struct ca8210_priv *priv = hw->priv;
2094
2095	if (changed & IEEE802154_AFILT_PANID_CHANGED) {
2096		status = mlme_set_request_sync(
2097			MAC_PAN_ID,
2098			0,
2099			2,
2100			&filt->pan_id, priv->spi
2101		);
2102		if (status) {
2103			dev_err(
2104				&priv->spi->dev,
2105				"error setting pan id, MLME-SET.confirm status = %d",
2106				status
2107			);
2108			return link_to_linux_err(status);
2109		}
2110	}
2111	if (changed & IEEE802154_AFILT_SADDR_CHANGED) {
2112		status = mlme_set_request_sync(
2113			MAC_SHORT_ADDRESS,
2114			0,
2115			2,
2116			&filt->short_addr, priv->spi
2117		);
2118		if (status) {
2119			dev_err(
2120				&priv->spi->dev,
2121				"error setting short address, MLME-SET.confirm status = %d",
2122				status
2123			);
2124			return link_to_linux_err(status);
2125		}
2126	}
2127	if (changed & IEEE802154_AFILT_IEEEADDR_CHANGED) {
2128		status = mlme_set_request_sync(
2129			NS_IEEE_ADDRESS,
2130			0,
2131			8,
2132			&filt->ieee_addr,
2133			priv->spi
2134		);
2135		if (status) {
2136			dev_err(
2137				&priv->spi->dev,
2138				"error setting ieee address, MLME-SET.confirm status = %d",
2139				status
2140			);
2141			return link_to_linux_err(status);
2142		}
2143	}
2144	/* TODO: Should use MLME_START to set coord bit? */
2145	return 0;
2146}
2147
2148/**
2149 * ca8210_set_tx_power() - Sets the transmit power of the ca8210
2150 * @hw:   ieee802154_hw of target ca8210
2151 * @mbm:  Transmit power in mBm (dBm*100)
2152 *
2153 * Return: 0 or linux error code
2154 */
2155static int ca8210_set_tx_power(struct ieee802154_hw *hw, s32 mbm)
2156{
2157	struct ca8210_priv *priv = hw->priv;
2158
2159	mbm /= 100;
2160	return link_to_linux_err(
2161		mlme_set_request_sync(PHY_TRANSMIT_POWER, 0, 1, &mbm, priv->spi)
2162	);
2163}
2164
2165/**
2166 * ca8210_set_cca_mode() - Sets the clear channel assessment mode of the ca8210
2167 * @hw:   ieee802154_hw of target ca8210
2168 * @cca:  CCA mode to set
2169 *
2170 * Return: 0 or linux error code
2171 */
2172static int ca8210_set_cca_mode(
2173	struct ieee802154_hw       *hw,
2174	const struct wpan_phy_cca  *cca
2175)
2176{
2177	u8 status;
2178	u8 cca_mode;
2179	struct ca8210_priv *priv = hw->priv;
2180
2181	cca_mode = cca->mode & 3;
2182	if (cca_mode == 3 && cca->opt == NL802154_CCA_OPT_ENERGY_CARRIER_OR) {
2183		/* cca_mode 0 == CS OR ED, 3 == CS AND ED */
2184		cca_mode = 0;
2185	}
2186	status = mlme_set_request_sync(
2187		PHY_CCA_MODE,
2188		0,
2189		1,
2190		&cca_mode,
2191		priv->spi
2192	);
2193	if (status) {
2194		dev_err(
2195			&priv->spi->dev,
2196			"error setting cca mode, MLME-SET.confirm status = %d",
2197			status
2198		);
2199	}
2200	return link_to_linux_err(status);
2201}
2202
2203/**
2204 * ca8210_set_cca_ed_level() - Sets the CCA ED level of the ca8210
2205 * @hw:     ieee802154_hw of target ca8210
2206 * @level:  ED level to set (in mbm)
2207 *
2208 * Sets the minimum threshold of measured energy above which the ca8210 will
2209 * back off and retry a transmission.
2210 *
2211 * Return: 0 or linux error code
2212 */
2213static int ca8210_set_cca_ed_level(struct ieee802154_hw *hw, s32 level)
2214{
2215	u8 status;
2216	u8 ed_threshold = (level / 100) * 2 + 256;
2217	struct ca8210_priv *priv = hw->priv;
2218
2219	status = hwme_set_request_sync(
2220		HWME_EDTHRESHOLD,
2221		1,
2222		&ed_threshold,
2223		priv->spi
2224	);
2225	if (status) {
2226		dev_err(
2227			&priv->spi->dev,
2228			"error setting ed threshold, HWME-SET.confirm status = %d",
2229			status
2230		);
2231	}
2232	return link_to_linux_err(status);
2233}
2234
2235/**
2236 * ca8210_set_csma_params() - Sets the CSMA parameters of the ca8210
2237 * @hw:       ieee802154_hw of target ca8210
2238 * @min_be:   Minimum backoff exponent when backing off a transmission
2239 * @max_be:   Maximum backoff exponent when backing off a transmission
2240 * @retries:  Number of times to retry after backing off
2241 *
2242 * Return: 0 or linux error code
2243 */
2244static int ca8210_set_csma_params(
2245	struct ieee802154_hw  *hw,
2246	u8                     min_be,
2247	u8                     max_be,
2248	u8                     retries
2249)
2250{
2251	u8 status;
2252	struct ca8210_priv *priv = hw->priv;
2253
2254	status = mlme_set_request_sync(MAC_MIN_BE, 0, 1, &min_be, priv->spi);
2255	if (status) {
2256		dev_err(
2257			&priv->spi->dev,
2258			"error setting min be, MLME-SET.confirm status = %d",
2259			status
2260		);
2261		return link_to_linux_err(status);
2262	}
2263	status = mlme_set_request_sync(MAC_MAX_BE, 0, 1, &max_be, priv->spi);
2264	if (status) {
2265		dev_err(
2266			&priv->spi->dev,
2267			"error setting max be, MLME-SET.confirm status = %d",
2268			status
2269		);
2270		return link_to_linux_err(status);
2271	}
2272	status = mlme_set_request_sync(
2273		MAC_MAX_CSMA_BACKOFFS,
2274		0,
2275		1,
2276		&retries,
2277		priv->spi
2278	);
2279	if (status) {
2280		dev_err(
2281			&priv->spi->dev,
2282			"error setting max csma backoffs, MLME-SET.confirm status = %d",
2283			status
2284		);
2285	}
2286	return link_to_linux_err(status);
2287}
2288
2289/**
2290 * ca8210_set_frame_retries() - Sets the maximum frame retries of the ca8210
2291 * @hw:       ieee802154_hw of target ca8210
2292 * @retries:  Number of retries
2293 *
2294 * Sets the number of times to retry a transmission if no acknowledgment was
2295 * received from the other end when one was requested.
2296 *
2297 * Return: 0 or linux error code
2298 */
2299static int ca8210_set_frame_retries(struct ieee802154_hw *hw, s8 retries)
2300{
2301	u8 status;
2302	struct ca8210_priv *priv = hw->priv;
2303
2304	status = mlme_set_request_sync(
2305		MAC_MAX_FRAME_RETRIES,
2306		0,
2307		1,
2308		&retries,
2309		priv->spi
2310	);
2311	if (status) {
2312		dev_err(
2313			&priv->spi->dev,
2314			"error setting frame retries, MLME-SET.confirm status = %d",
2315			status
2316		);
2317	}
2318	return link_to_linux_err(status);
2319}
2320
2321static int ca8210_set_promiscuous_mode(struct ieee802154_hw *hw, const bool on)
2322{
2323	u8 status;
2324	struct ca8210_priv *priv = hw->priv;
2325
2326	status = mlme_set_request_sync(
2327		MAC_PROMISCUOUS_MODE,
2328		0,
2329		1,
2330		(const void *)&on,
2331		priv->spi
2332	);
2333	if (status) {
2334		dev_err(
2335			&priv->spi->dev,
2336			"error setting promiscuous mode, MLME-SET.confirm status = %d",
2337			status
2338		);
2339	} else {
2340		priv->promiscuous = on;
2341	}
2342	return link_to_linux_err(status);
2343}
2344
2345static const struct ieee802154_ops ca8210_phy_ops = {
2346	.start = ca8210_start,
2347	.stop = ca8210_stop,
2348	.xmit_async = ca8210_xmit_async,
2349	.ed = ca8210_get_ed,
2350	.set_channel = ca8210_set_channel,
2351	.set_hw_addr_filt = ca8210_set_hw_addr_filt,
2352	.set_txpower = ca8210_set_tx_power,
2353	.set_cca_mode = ca8210_set_cca_mode,
2354	.set_cca_ed_level = ca8210_set_cca_ed_level,
2355	.set_csma_params = ca8210_set_csma_params,
2356	.set_frame_retries = ca8210_set_frame_retries,
2357	.set_promiscuous_mode = ca8210_set_promiscuous_mode
2358};
2359
2360/* Test/EVBME Interface */
2361
2362/**
2363 * ca8210_test_int_open() - Opens the test interface to the userspace
2364 * @inodp:  inode representation of file interface
2365 * @filp:   file interface
2366 *
2367 * Return: 0 or linux error code
2368 */
2369static int ca8210_test_int_open(struct inode *inodp, struct file *filp)
2370{
2371	struct ca8210_priv *priv = inodp->i_private;
2372
2373	filp->private_data = priv;
2374	return 0;
2375}
2376
2377/**
2378 * ca8210_test_check_upstream() - Checks a command received from the upstream
2379 *                                testing interface for required action
2380 * @buf:        Buffer containing command to check
2381 * @device_ref: Nondescript pointer to target device
2382 *
2383 * Return: 0 or linux error code
2384 */
2385static int ca8210_test_check_upstream(u8 *buf, void *device_ref)
2386{
2387	int ret;
2388	u8 response[CA8210_SPI_BUF_SIZE];
2389
2390	if (buf[0] == SPI_MLME_SET_REQUEST) {
2391		ret = tdme_checkpibattribute(buf[2], buf[4], buf + 5);
2392		if (ret) {
2393			response[0]  = SPI_MLME_SET_CONFIRM;
2394			response[1] = 3;
2395			response[2] = IEEE802154_INVALID_PARAMETER;
2396			response[3] = buf[2];
2397			response[4] = buf[3];
2398			if (cascoda_api_upstream)
2399				cascoda_api_upstream(response, 5, device_ref);
2400			return ret;
2401		}
2402	}
2403	if (buf[0] == SPI_MLME_ASSOCIATE_REQUEST) {
2404		return tdme_channelinit(buf[2], device_ref);
2405	} else if (buf[0] == SPI_MLME_START_REQUEST) {
2406		return tdme_channelinit(buf[4], device_ref);
2407	} else if (
2408		(buf[0] == SPI_MLME_SET_REQUEST) &&
2409		(buf[2] == PHY_CURRENT_CHANNEL)
2410	) {
2411		return tdme_channelinit(buf[5], device_ref);
2412	} else if (
2413		(buf[0] == SPI_TDME_SET_REQUEST) &&
2414		(buf[2] == TDME_CHANNEL)
2415	) {
2416		return tdme_channelinit(buf[4], device_ref);
2417	} else if (
2418		(CA8210_MAC_WORKAROUNDS) &&
2419		(buf[0] == SPI_MLME_RESET_REQUEST) &&
2420		(buf[2] == 1)
2421	) {
2422		/* reset COORD Bit for Channel Filtering as Coordinator */
2423		return tdme_setsfr_request_sync(
2424			0,
2425			CA8210_SFR_MACCON,
2426			0,
2427			device_ref
2428		);
2429	}
2430	return 0;
2431} /* End of EVBMECheckSerialCommand() */
2432
2433/**
2434 * ca8210_test_int_user_write() - Called by a process in userspace to send a
2435 *                                message to the ca8210 drivers
2436 * @filp:    file interface
2437 * @in_buf:  Buffer containing message to write
2438 * @len:     length of message
2439 * @off:     file offset
2440 *
2441 * Return: 0 or linux error code
2442 */
2443static ssize_t ca8210_test_int_user_write(
2444	struct file        *filp,
2445	const char __user  *in_buf,
2446	size_t              len,
2447	loff_t             *off
2448)
2449{
2450	int ret;
2451	struct ca8210_priv *priv = filp->private_data;
2452	u8 command[CA8210_SPI_BUF_SIZE];
2453
2454	memset(command, SPI_IDLE, 6);
2455	if (len > CA8210_SPI_BUF_SIZE || len < 2) {
2456		dev_warn(
2457			&priv->spi->dev,
2458			"userspace requested erroneous write length (%zu)\n",
2459			len
2460		);
2461		return -EBADE;
2462	}
2463
2464	ret = copy_from_user(command, in_buf, len);
2465	if (ret) {
2466		dev_err(
2467			&priv->spi->dev,
2468			"%d bytes could not be copied from userspace\n",
2469			ret
2470		);
2471		return -EIO;
2472	}
2473	if (len != command[1] + 2) {
2474		dev_err(
2475			&priv->spi->dev,
2476			"write len does not match packet length field\n"
2477		);
2478		return -EBADE;
2479	}
2480
2481	ret = ca8210_test_check_upstream(command, priv->spi);
2482	if (ret == 0) {
2483		ret = ca8210_spi_exchange(
2484			command,
2485			command[1] + 2,
2486			NULL,
2487			priv->spi
2488		);
2489		if (ret < 0) {
2490			/* effectively 0 bytes were written successfully */
2491			dev_err(
2492				&priv->spi->dev,
2493				"spi exchange failed\n"
2494			);
2495			return ret;
2496		}
2497		if (command[0] & SPI_SYN)
2498			priv->sync_down++;
2499	}
2500
2501	return len;
2502}
2503
2504/**
2505 * ca8210_test_int_user_read() - Called by a process in userspace to read a
2506 *                               message from the ca8210 drivers
2507 * @filp:  file interface
2508 * @buf:   Buffer to write message to
2509 * @len:   length of message to read (ignored)
2510 * @offp:  file offset
2511 *
2512 * If the O_NONBLOCK flag was set when opening the file then this function will
2513 * not block, i.e. it will return if the fifo is empty. Otherwise the function
2514 * will block, i.e. wait until new data arrives.
2515 *
2516 * Return: number of bytes read
2517 */
2518static ssize_t ca8210_test_int_user_read(
2519	struct file  *filp,
2520	char __user  *buf,
2521	size_t        len,
2522	loff_t       *offp
2523)
2524{
2525	int i, cmdlen;
2526	struct ca8210_priv *priv = filp->private_data;
2527	unsigned char *fifo_buffer;
2528	unsigned long bytes_not_copied;
2529
2530	if (filp->f_flags & O_NONBLOCK) {
2531		/* Non-blocking mode */
2532		if (kfifo_is_empty(&priv->test.up_fifo))
2533			return 0;
2534	} else {
2535		/* Blocking mode */
2536		wait_event_interruptible(
2537			priv->test.readq,
2538			!kfifo_is_empty(&priv->test.up_fifo)
2539		);
2540	}
2541
2542	if (kfifo_out(&priv->test.up_fifo, &fifo_buffer, 4) != 4) {
2543		dev_err(
2544			&priv->spi->dev,
2545			"test_interface: Wrong number of elements popped from upstream fifo\n"
2546		);
2547		return 0;
2548	}
2549	cmdlen = fifo_buffer[1];
2550	bytes_not_copied = cmdlen + 2;
2551
2552	bytes_not_copied = copy_to_user(buf, fifo_buffer, bytes_not_copied);
2553	if (bytes_not_copied > 0) {
2554		dev_err(
2555			&priv->spi->dev,
2556			"%lu bytes could not be copied to user space!\n",
2557			bytes_not_copied
2558		);
2559	}
2560
2561	dev_dbg(&priv->spi->dev, "test_interface: Cmd len = %d\n", cmdlen);
2562
2563	dev_dbg(&priv->spi->dev, "test_interface: Read\n");
2564	for (i = 0; i < cmdlen + 2; i++)
2565		dev_dbg(&priv->spi->dev, "%#03x\n", fifo_buffer[i]);
2566
2567	kfree(fifo_buffer);
2568
2569	return cmdlen + 2;
2570}
2571
2572/**
2573 * ca8210_test_int_ioctl() - Called by a process in userspace to enact an
2574 *                           arbitrary action
2575 * @filp:        file interface
2576 * @ioctl_num:   which action to enact
2577 * @ioctl_param: arbitrary parameter for the action
2578 *
2579 * Return: status
2580 */
2581static long ca8210_test_int_ioctl(
2582	struct file *filp,
2583	unsigned int ioctl_num,
2584	unsigned long ioctl_param
2585)
2586{
2587	struct ca8210_priv *priv = filp->private_data;
2588
2589	switch (ioctl_num) {
2590	case CA8210_IOCTL_HARD_RESET:
2591		ca8210_reset_send(priv->spi, ioctl_param);
2592		break;
2593	default:
2594		break;
2595	}
2596	return 0;
2597}
2598
2599/**
2600 * ca8210_test_int_poll() - Called by a process in userspace to determine which
2601 *                          actions are currently possible for the file
2602 * @filp:   file interface
2603 * @ptable: poll table
2604 *
2605 * Return: set of poll return flags
2606 */
2607static __poll_t ca8210_test_int_poll(
2608	struct file *filp,
2609	struct poll_table_struct *ptable
2610)
2611{
2612	__poll_t return_flags = 0;
2613	struct ca8210_priv *priv = filp->private_data;
2614
2615	poll_wait(filp, &priv->test.readq, ptable);
2616	if (!kfifo_is_empty(&priv->test.up_fifo))
2617		return_flags |= (EPOLLIN | EPOLLRDNORM);
2618	if (wait_event_interruptible(
2619		priv->test.readq,
2620		!kfifo_is_empty(&priv->test.up_fifo))) {
2621		return EPOLLERR;
2622	}
2623	return return_flags;
2624}
2625
2626static const struct file_operations test_int_fops = {
2627	.read =           ca8210_test_int_user_read,
2628	.write =          ca8210_test_int_user_write,
2629	.open =           ca8210_test_int_open,
2630	.release =        NULL,
2631	.unlocked_ioctl = ca8210_test_int_ioctl,
2632	.poll =           ca8210_test_int_poll
2633};
2634
2635/* Init/Deinit */
2636
2637/**
2638 * ca8210_get_platform_data() - Populate a ca8210_platform_data object
2639 * @spi_device:  Pointer to ca8210 spi device object to get data for
2640 * @pdata:       Pointer to ca8210_platform_data object to populate
2641 *
2642 * Return: 0 or linux error code
2643 */
2644static int ca8210_get_platform_data(
2645	struct spi_device *spi_device,
2646	struct ca8210_platform_data *pdata
2647)
2648{
2649	int ret = 0;
2650
2651	if (!spi_device->dev.of_node)
2652		return -EINVAL;
2653
2654	pdata->extclockenable = of_property_read_bool(
2655		spi_device->dev.of_node,
2656		"extclock-enable"
2657	);
2658	if (pdata->extclockenable) {
2659		ret = of_property_read_u32(
2660			spi_device->dev.of_node,
2661			"extclock-freq",
2662			&pdata->extclockfreq
2663		);
2664		if (ret < 0)
2665			return ret;
2666
2667		ret = of_property_read_u32(
2668			spi_device->dev.of_node,
2669			"extclock-gpio",
2670			&pdata->extclockgpio
2671		);
2672	}
2673
2674	return ret;
2675}
2676
2677/**
2678 * ca8210_config_extern_clk() - Configure the external clock provided by the
2679 *                              ca8210
2680 * @pdata:  Pointer to ca8210_platform_data containing clock parameters
2681 * @spi:    Pointer to target ca8210 spi device
2682 * @on:	    True to turn the clock on, false to turn off
2683 *
2684 * The external clock is configured with a frequency and output pin taken from
2685 * the platform data.
2686 *
2687 * Return: 0 or linux error code
2688 */
2689static int ca8210_config_extern_clk(
2690	struct ca8210_platform_data *pdata,
2691	struct spi_device *spi,
2692	bool on
2693)
2694{
2695	u8 clkparam[2];
2696
2697	if (on) {
2698		dev_info(&spi->dev, "Switching external clock on\n");
2699		switch (pdata->extclockfreq) {
2700		case SIXTEEN_MHZ:
2701			clkparam[0] = 1;
2702			break;
2703		case EIGHT_MHZ:
2704			clkparam[0] = 2;
2705			break;
2706		case FOUR_MHZ:
2707			clkparam[0] = 3;
2708			break;
2709		case TWO_MHZ:
2710			clkparam[0] = 4;
2711			break;
2712		case ONE_MHZ:
2713			clkparam[0] = 5;
2714			break;
2715		default:
2716			dev_crit(&spi->dev, "Invalid extclock-freq\n");
2717			return -EINVAL;
2718		}
2719		clkparam[1] = pdata->extclockgpio;
2720	} else {
2721		dev_info(&spi->dev, "Switching external clock off\n");
2722		clkparam[0] = 0; /* off */
2723		clkparam[1] = 0;
2724	}
2725	return link_to_linux_err(
2726		hwme_set_request_sync(HWME_SYSCLKOUT, 2, clkparam, spi)
2727	);
2728}
2729
2730/**
2731 * ca8210_register_ext_clock() - Register ca8210's external clock with kernel
2732 * @spi:  Pointer to target ca8210 spi device
2733 *
2734 * Return: 0 or linux error code
2735 */
2736static int ca8210_register_ext_clock(struct spi_device *spi)
2737{
2738	struct device *dev = &spi->dev;
2739	struct ca8210_platform_data *pdata = dev_get_platdata(dev);
2740	struct device_node *np = spi->dev.of_node;
2741	struct ca8210_priv *priv = spi_get_drvdata(spi);
2742
2743	if (!np)
2744		return -EFAULT;
2745
2746	priv->clk = clk_register_fixed_rate(
2747		&spi->dev,
2748		np->name,
2749		NULL,
2750		0,
2751		pdata->extclockfreq
2752	);
2753
2754	if (IS_ERR(priv->clk)) {
2755		dev_crit(&spi->dev, "Failed to register external clk\n");
2756		return PTR_ERR(priv->clk);
2757	}
2758
2759	return of_clk_add_provider(np, of_clk_src_simple_get, priv->clk);
2760}
2761
2762/**
2763 * ca8210_unregister_ext_clock() - Unregister ca8210's external clock with
2764 *                                 kernel
2765 * @spi:  Pointer to target ca8210 spi device
2766 */
2767static void ca8210_unregister_ext_clock(struct spi_device *spi)
2768{
2769	struct ca8210_priv *priv = spi_get_drvdata(spi);
2770
2771	if (IS_ERR_OR_NULL(priv->clk))
2772		return;
2773
2774	of_clk_del_provider(spi->dev.of_node);
2775	clk_unregister(priv->clk);
2776	dev_info(&spi->dev, "External clock unregistered\n");
2777}
2778
2779/**
2780 * ca8210_reset_init() - Initialise the reset input to the ca8210
2781 * @spi:  Pointer to target ca8210 spi device
2782 *
2783 * Return: 0 or linux error code
2784 */
2785static int ca8210_reset_init(struct spi_device *spi)
2786{
2787	struct device *dev = &spi->dev;
2788	struct ca8210_platform_data *pdata = dev_get_platdata(dev);
2789
2790	pdata->reset_gpio = devm_gpiod_get(dev, "reset", GPIOD_OUT_LOW);
2791	if (IS_ERR(pdata->reset_gpio)) {
2792		dev_crit(dev, "Reset GPIO did not set to output mode\n");
2793		return PTR_ERR(pdata->reset_gpio);
2794	}
2795
2796	return 0;
2797}
2798
2799/**
2800 * ca8210_interrupt_init() - Initialise the irq output from the ca8210
2801 * @spi:  Pointer to target ca8210 spi device
2802 *
2803 * Return: 0 or linux error code
2804 */
2805static int ca8210_interrupt_init(struct spi_device *spi)
2806{
2807	struct device *dev = &spi->dev;
2808	struct ca8210_platform_data *pdata = dev_get_platdata(dev);
2809	int ret;
2810
2811	pdata->irq_gpio = devm_gpiod_get(dev, "irq", GPIOD_IN);
2812	if (IS_ERR(pdata->irq_gpio)) {
2813		dev_crit(dev, "Could not retrieve IRQ GPIO\n");
2814		return PTR_ERR(pdata->irq_gpio);
2815	}
2816
2817	pdata->irq_id = gpiod_to_irq(pdata->irq_gpio);
2818	if (pdata->irq_id < 0) {
2819		dev_crit(dev, "Could not get irq for IRQ GPIO\n");
2820		return pdata->irq_id;
2821	}
2822
2823	ret = request_irq(
2824		pdata->irq_id,
2825		ca8210_interrupt_handler,
2826		IRQF_TRIGGER_FALLING,
2827		"ca8210-irq",
2828		spi_get_drvdata(spi)
2829	);
2830	if (ret)
2831		dev_crit(&spi->dev, "request_irq %d failed\n", pdata->irq_id);
2832
2833	return ret;
2834}
2835
2836/**
2837 * ca8210_dev_com_init() - Initialise the spi communication component
2838 * @priv:  Pointer to private data structure
2839 *
2840 * Return: 0 or linux error code
2841 */
2842static int ca8210_dev_com_init(struct ca8210_priv *priv)
2843{
2844	priv->mlme_workqueue = alloc_ordered_workqueue("MLME work queue", 0);
2845	if (!priv->mlme_workqueue) {
2846		dev_crit(&priv->spi->dev, "alloc of mlme_workqueue failed!\n");
2847		return -ENOMEM;
2848	}
2849
2850	priv->irq_workqueue = alloc_ordered_workqueue("ca8210 irq worker", 0);
2851	if (!priv->irq_workqueue) {
2852		dev_crit(&priv->spi->dev, "alloc of irq_workqueue failed!\n");
2853		destroy_workqueue(priv->mlme_workqueue);
2854		return -ENOMEM;
2855	}
2856
2857	return 0;
2858}
2859
2860/**
2861 * ca8210_dev_com_clear() - Deinitialise the spi communication component
2862 * @priv:  Pointer to private data structure
2863 */
2864static void ca8210_dev_com_clear(struct ca8210_priv *priv)
2865{
2866	destroy_workqueue(priv->mlme_workqueue);
2867	destroy_workqueue(priv->irq_workqueue);
2868}
2869
2870#define CA8210_MAX_TX_POWERS (9)
2871static const s32 ca8210_tx_powers[CA8210_MAX_TX_POWERS] = {
2872	800, 700, 600, 500, 400, 300, 200, 100, 0
2873};
2874
2875#define CA8210_MAX_ED_LEVELS (21)
2876static const s32 ca8210_ed_levels[CA8210_MAX_ED_LEVELS] = {
2877	-10300, -10250, -10200, -10150, -10100, -10050, -10000, -9950, -9900,
2878	-9850, -9800, -9750, -9700, -9650, -9600, -9550, -9500, -9450, -9400,
2879	-9350, -9300
2880};
2881
2882/**
2883 * ca8210_hw_setup() - Populate the ieee802154_hw phy attributes with the
2884 *                     ca8210's defaults
2885 * @ca8210_hw:  Pointer to ieee802154_hw to populate
2886 */
2887static void ca8210_hw_setup(struct ieee802154_hw *ca8210_hw)
2888{
2889	/* Support channels 11-26 */
2890	ca8210_hw->phy->supported.channels[0] = CA8210_VALID_CHANNELS;
2891	ca8210_hw->phy->supported.tx_powers_size = CA8210_MAX_TX_POWERS;
2892	ca8210_hw->phy->supported.tx_powers = ca8210_tx_powers;
2893	ca8210_hw->phy->supported.cca_ed_levels_size = CA8210_MAX_ED_LEVELS;
2894	ca8210_hw->phy->supported.cca_ed_levels = ca8210_ed_levels;
2895	ca8210_hw->phy->current_channel = 18;
2896	ca8210_hw->phy->current_page = 0;
2897	ca8210_hw->phy->transmit_power = 800;
2898	ca8210_hw->phy->cca.mode = NL802154_CCA_ENERGY_CARRIER;
2899	ca8210_hw->phy->cca.opt = NL802154_CCA_OPT_ENERGY_CARRIER_AND;
2900	ca8210_hw->phy->cca_ed_level = -9800;
2901	ca8210_hw->phy->symbol_duration = 16;
2902	ca8210_hw->phy->lifs_period = 40 * ca8210_hw->phy->symbol_duration;
2903	ca8210_hw->phy->sifs_period = 12 * ca8210_hw->phy->symbol_duration;
2904	ca8210_hw->flags =
2905		IEEE802154_HW_AFILT |
2906		IEEE802154_HW_OMIT_CKSUM |
2907		IEEE802154_HW_FRAME_RETRIES |
2908		IEEE802154_HW_PROMISCUOUS |
2909		IEEE802154_HW_CSMA_PARAMS;
2910	ca8210_hw->phy->flags =
2911		WPAN_PHY_FLAG_TXPOWER |
2912		WPAN_PHY_FLAG_CCA_ED_LEVEL |
2913		WPAN_PHY_FLAG_CCA_MODE |
2914		WPAN_PHY_FLAG_DATAGRAMS_ONLY;
2915}
2916
2917/**
2918 * ca8210_test_interface_init() - Initialise the test file interface
2919 * @priv:  Pointer to private data structure
2920 *
2921 * Provided as an alternative to the standard linux network interface, the test
2922 * interface exposes a file in the filesystem (ca8210_test) that allows
2923 * 802.15.4 SAP Commands and Cascoda EVBME commands to be sent directly to
2924 * the stack.
2925 *
2926 * Return: 0 or linux error code
2927 */
2928static int ca8210_test_interface_init(struct ca8210_priv *priv)
2929{
2930	struct ca8210_test *test = &priv->test;
2931	char node_name[32];
2932
2933	snprintf(
2934		node_name,
2935		sizeof(node_name),
2936		"ca8210@%d_%d",
2937		priv->spi->controller->bus_num,
2938		spi_get_chipselect(priv->spi, 0)
2939	);
2940
2941	test->ca8210_dfs_spi_int = debugfs_create_file(
2942		node_name,
2943		0600, /* S_IRUSR | S_IWUSR */
2944		NULL,
2945		priv,
2946		&test_int_fops
2947	);
2948
2949	debugfs_create_symlink("ca8210", NULL, node_name);
2950	init_waitqueue_head(&test->readq);
2951	return kfifo_alloc(
2952		&test->up_fifo,
2953		CA8210_TEST_INT_FIFO_SIZE,
2954		GFP_KERNEL
2955	);
2956}
2957
2958/**
2959 * ca8210_test_interface_clear() - Deinitialise the test file interface
2960 * @priv:  Pointer to private data structure
2961 */
2962static void ca8210_test_interface_clear(struct ca8210_priv *priv)
2963{
2964	struct ca8210_test *test = &priv->test;
2965
2966	debugfs_remove(test->ca8210_dfs_spi_int);
2967	kfifo_free(&test->up_fifo);
2968	dev_info(&priv->spi->dev, "Test interface removed\n");
2969}
2970
2971/**
2972 * ca8210_remove() - Shut down a ca8210 upon being disconnected
2973 * @spi_device:  Pointer to spi device data structure
2974 *
2975 * Return: 0 or linux error code
2976 */
2977static void ca8210_remove(struct spi_device *spi_device)
2978{
2979	struct ca8210_priv *priv;
2980	struct ca8210_platform_data *pdata;
2981
2982	dev_info(&spi_device->dev, "Removing ca8210\n");
2983
2984	pdata = spi_device->dev.platform_data;
2985	if (pdata) {
2986		if (pdata->extclockenable) {
2987			ca8210_unregister_ext_clock(spi_device);
2988			ca8210_config_extern_clk(pdata, spi_device, 0);
2989		}
2990		free_irq(pdata->irq_id, spi_device->dev.driver_data);
2991		kfree(pdata);
2992		spi_device->dev.platform_data = NULL;
2993	}
2994	/* get spi_device private data */
2995	priv = spi_get_drvdata(spi_device);
2996	if (priv) {
2997		dev_info(
2998			&spi_device->dev,
2999			"sync_down = %d, sync_up = %d\n",
3000			priv->sync_down,
3001			priv->sync_up
3002		);
3003		ca8210_dev_com_clear(spi_device->dev.driver_data);
3004		if (priv->hw) {
3005			if (priv->hw_registered)
3006				ieee802154_unregister_hw(priv->hw);
3007			ieee802154_free_hw(priv->hw);
3008			priv->hw = NULL;
3009			dev_info(
3010				&spi_device->dev,
3011				"Unregistered & freed ieee802154_hw.\n"
3012			);
3013		}
3014		if (IS_ENABLED(CONFIG_IEEE802154_CA8210_DEBUGFS))
3015			ca8210_test_interface_clear(priv);
3016	}
3017}
3018
3019/**
3020 * ca8210_probe() - Set up a connected ca8210 upon being detected by the system
3021 * @spi_device:  Pointer to spi device data structure
3022 *
3023 * Return: 0 or linux error code
3024 */
3025static int ca8210_probe(struct spi_device *spi_device)
3026{
3027	struct ca8210_priv *priv;
3028	struct ieee802154_hw *hw;
3029	struct ca8210_platform_data *pdata;
3030	int ret;
3031
3032	dev_info(&spi_device->dev, "Inserting ca8210\n");
3033
3034	/* allocate ieee802154_hw and private data */
3035	hw = ieee802154_alloc_hw(sizeof(struct ca8210_priv), &ca8210_phy_ops);
3036	if (!hw) {
3037		dev_crit(&spi_device->dev, "ieee802154_alloc_hw failed\n");
3038		ret = -ENOMEM;
3039		goto error;
3040	}
3041
3042	priv = hw->priv;
3043	priv->hw = hw;
3044	priv->spi = spi_device;
3045	hw->parent = &spi_device->dev;
3046	spin_lock_init(&priv->lock);
3047	priv->async_tx_pending = false;
3048	priv->hw_registered = false;
3049	priv->sync_up = 0;
3050	priv->sync_down = 0;
3051	priv->promiscuous = false;
3052	priv->retries = 0;
3053	init_completion(&priv->ca8210_is_awake);
3054	init_completion(&priv->spi_transfer_complete);
3055	init_completion(&priv->sync_exchange_complete);
3056	spi_set_drvdata(priv->spi, priv);
3057	if (IS_ENABLED(CONFIG_IEEE802154_CA8210_DEBUGFS)) {
3058		cascoda_api_upstream = ca8210_test_int_driver_write;
3059		ret = ca8210_test_interface_init(priv);
3060		if (ret) {
3061			dev_crit(&spi_device->dev, "ca8210_test_interface_init failed\n");
3062			goto error;
3063		}
3064	} else {
3065		cascoda_api_upstream = NULL;
3066	}
3067	ca8210_hw_setup(hw);
3068	ieee802154_random_extended_addr(&hw->phy->perm_extended_addr);
3069
3070	pdata = kmalloc(sizeof(*pdata), GFP_KERNEL);
3071	if (!pdata) {
3072		ret = -ENOMEM;
3073		goto error;
3074	}
3075
3076	priv->spi->dev.platform_data = pdata;
3077	ret = ca8210_get_platform_data(priv->spi, pdata);
3078	if (ret) {
3079		dev_crit(&spi_device->dev, "ca8210_get_platform_data failed\n");
3080		goto error;
3081	}
3082
3083	ret = ca8210_dev_com_init(priv);
3084	if (ret) {
3085		dev_crit(&spi_device->dev, "ca8210_dev_com_init failed\n");
3086		goto error;
3087	}
3088	ret = ca8210_reset_init(priv->spi);
3089	if (ret) {
3090		dev_crit(&spi_device->dev, "ca8210_reset_init failed\n");
3091		goto error;
3092	}
3093
3094	ret = ca8210_interrupt_init(priv->spi);
3095	if (ret) {
3096		dev_crit(&spi_device->dev, "ca8210_interrupt_init failed\n");
3097		goto error;
3098	}
3099
3100	msleep(100);
3101
3102	ca8210_reset_send(priv->spi, 1);
3103
3104	ret = tdme_chipinit(priv->spi);
3105	if (ret) {
3106		dev_crit(&spi_device->dev, "tdme_chipinit failed\n");
3107		goto error;
3108	}
3109
3110	if (pdata->extclockenable) {
3111		ret = ca8210_config_extern_clk(pdata, priv->spi, 1);
3112		if (ret) {
3113			dev_crit(
3114				&spi_device->dev,
3115				"ca8210_config_extern_clk failed\n"
3116			);
3117			goto error;
3118		}
3119		ret = ca8210_register_ext_clock(priv->spi);
3120		if (ret) {
3121			dev_crit(
3122				&spi_device->dev,
3123				"ca8210_register_ext_clock failed\n"
3124			);
3125			goto error;
3126		}
3127	}
3128
3129	ret = ieee802154_register_hw(hw);
3130	if (ret) {
3131		dev_crit(&spi_device->dev, "ieee802154_register_hw failed\n");
3132		goto error;
3133	}
3134	priv->hw_registered = true;
3135
3136	return 0;
3137error:
3138	msleep(100); /* wait for pending spi transfers to complete */
3139	ca8210_remove(spi_device);
3140	return link_to_linux_err(ret);
3141}
3142
3143static const struct of_device_id ca8210_of_ids[] = {
3144	{.compatible = "cascoda,ca8210", },
3145	{},
3146};
3147MODULE_DEVICE_TABLE(of, ca8210_of_ids);
3148
3149static struct spi_driver ca8210_spi_driver = {
3150	.driver = {
3151		.name =                 DRIVER_NAME,
3152		.of_match_table =       ca8210_of_ids,
3153	},
3154	.probe  =                       ca8210_probe,
3155	.remove =                       ca8210_remove
3156};
3157
3158module_spi_driver(ca8210_spi_driver);
3159
3160MODULE_AUTHOR("Harry Morris <h.morris@cascoda.com>");
3161MODULE_DESCRIPTION("CA-8210 SoftMAC driver");
3162MODULE_LICENSE("Dual BSD/GPL");
3163MODULE_VERSION("1.0");
~/ Read-only file preview.