xref: /linux/drivers/net/ieee802154/ca8210.c (revision 32a92f8c89326985e05dce8b22d3f0aa07a3e1bd)
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  */
261 struct 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  */
279 struct 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  */
313 struct 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  */
341 struct 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  */
356 struct 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  */
372 struct 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  */
384 union 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  */
397 struct 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 */
405 struct 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 
414 struct 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 
421 struct hwme_set_request_pset {
422 	u8         hw_attribute;
423 	u8         hw_attribute_length;
424 	u8         hw_attribute_value[MAX_HWME_ATTRIBUTE_SIZE];
425 };
426 
427 struct hwme_get_request_pset {
428 	u8         hw_attribute;
429 };
430 
431 struct tdme_setsfr_request_pset {
432 	u8         sfr_page;
433 	u8         sfr_address;
434 	u8         sfr_value;
435 };
436 
437 /* uplink functions parameter set definitions */
438 struct hwme_set_confirm_pset {
439 	u8         status;
440 	u8         hw_attribute;
441 };
442 
443 struct 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 
450 struct tdme_setsfr_confirm_pset {
451 	u8         status;
452 	u8         sfr_page;
453 	u8         sfr_address;
454 };
455 
456 struct 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 
474 union 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 
484 struct preamble_cfg_sfr {
485 	u8 timeout_symbols      : 3;
486 	u8 acquisition_symbols  : 3;
487 	u8 search_symbols       : 2;
488 };
489 
490 static 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  */
link_to_linux_err(int link_status)503 static 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  */
ca8210_test_int_driver_write(const u8 * buf,size_t len,void * spi)577 static 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 
606 static int ca8210_net_rx(
607 	struct ieee802154_hw  *hw,
608 	u8                    *command,
609 	size_t                 len
610 );
611 static u8 mlme_reset_request_sync(
612 	u8       set_default_pib,
613 	void    *device_ref
614 );
615 static 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  */
ca8210_reset_send(struct spi_device * spi,unsigned int ms)626 static 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  */
ca8210_mlme_reset_worker(struct work_struct * work)659 static 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  */
ca8210_rx_done(struct cas_control * cas_ctl)680 static 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_obj(*mlme_reset_wpc);
724 			if (!mlme_reset_wpc)
725 				goto finish;
726 			INIT_WORK(
727 				&mlme_reset_wpc->work,
728 				ca8210_mlme_reset_worker
729 			);
730 			mlme_reset_wpc->priv = priv;
731 			queue_work(priv->mlme_workqueue, &mlme_reset_wpc->work);
732 		}
733 	} else if (buf[0] == SPI_HWME_WAKEUP_INDICATION) {
734 		dev_notice(
735 			&priv->spi->dev,
736 			"Wakeup indication received, reason:\n"
737 		);
738 		switch (buf[2]) {
739 		case 0:
740 			dev_notice(
741 				&priv->spi->dev,
742 				"Transceiver woken up from Power Up / System Reset\n"
743 			);
744 			break;
745 		case 1:
746 			dev_notice(
747 				&priv->spi->dev,
748 				"Watchdog Timer Time-Out\n"
749 			);
750 			break;
751 		case 2:
752 			dev_notice(
753 				&priv->spi->dev,
754 				"Transceiver woken up from Power-Off by Sleep Timer Time-Out\n");
755 			break;
756 		case 3:
757 			dev_notice(
758 				&priv->spi->dev,
759 				"Transceiver woken up from Power-Off by GPIO Activity\n"
760 			);
761 			break;
762 		case 4:
763 			dev_notice(
764 				&priv->spi->dev,
765 				"Transceiver woken up from Standby by Sleep Timer Time-Out\n"
766 			);
767 			break;
768 		case 5:
769 			dev_notice(
770 				&priv->spi->dev,
771 				"Transceiver woken up from Standby by GPIO Activity\n"
772 			);
773 			break;
774 		case 6:
775 			dev_notice(
776 				&priv->spi->dev,
777 				"Sleep-Timer Time-Out in Active Mode\n"
778 			);
779 			break;
780 		default:
781 			dev_warn(&priv->spi->dev, "Wakeup reason unknown\n");
782 			break;
783 		}
784 		complete(&priv->ca8210_is_awake);
785 	}
786 
787 finish:;
788 }
789 
790 static void ca8210_remove(struct spi_device *spi_device);
791 
792 /**
793  * ca8210_spi_transfer_complete() - Called when a single spi transfer has
794  *                                  completed
795  * @context:  Pointer to the cas_control object for the finished transfer
796  */
ca8210_spi_transfer_complete(void * context)797 static void ca8210_spi_transfer_complete(void *context)
798 {
799 	struct cas_control *cas_ctl = context;
800 	struct ca8210_priv *priv = cas_ctl->priv;
801 	bool duplex_rx = false;
802 	int i;
803 	u8 retry_buffer[CA8210_SPI_BUF_SIZE];
804 
805 	if (
806 		cas_ctl->tx_in_buf[0] == SPI_NACK ||
807 		(cas_ctl->tx_in_buf[0] == SPI_IDLE &&
808 		cas_ctl->tx_in_buf[1] == SPI_NACK)
809 	) {
810 		/* ca8210 is busy */
811 		dev_info(&priv->spi->dev, "ca8210 was busy during attempted write\n");
812 		if (cas_ctl->tx_buf[0] == SPI_IDLE) {
813 			dev_warn(
814 				&priv->spi->dev,
815 				"IRQ servicing NACKd, dropping transfer\n"
816 			);
817 			kfree(cas_ctl);
818 			return;
819 		}
820 		if (priv->retries > 3) {
821 			dev_err(&priv->spi->dev, "too many retries!\n");
822 			kfree(cas_ctl);
823 			ca8210_remove(priv->spi);
824 			return;
825 		}
826 		memcpy(retry_buffer, cas_ctl->tx_buf, CA8210_SPI_BUF_SIZE);
827 		kfree(cas_ctl);
828 		ca8210_spi_transfer(
829 			priv->spi,
830 			retry_buffer,
831 			CA8210_SPI_BUF_SIZE
832 		);
833 		priv->retries++;
834 		dev_info(&priv->spi->dev, "retried spi write\n");
835 		return;
836 	} else if (
837 			cas_ctl->tx_in_buf[0] != SPI_IDLE &&
838 			cas_ctl->tx_in_buf[0] != SPI_NACK
839 		) {
840 		duplex_rx = true;
841 	}
842 
843 	if (duplex_rx) {
844 		dev_dbg(&priv->spi->dev, "READ CMD DURING TX\n");
845 		for (i = 0; i < cas_ctl->tx_in_buf[1] + 2; i++)
846 			dev_dbg(
847 				&priv->spi->dev,
848 				"%#03x\n",
849 				cas_ctl->tx_in_buf[i]
850 			);
851 		ca8210_rx_done(cas_ctl);
852 	}
853 	complete(&priv->spi_transfer_complete);
854 	kfree(cas_ctl);
855 	priv->retries = 0;
856 }
857 
858 /**
859  * ca8210_spi_transfer() - Initiate duplex spi transfer with ca8210
860  * @spi: Pointer to spi device for transfer
861  * @buf: Octet array to send
862  * @len: length of the buffer being sent
863  *
864  * Return: 0 or linux error code
865  */
ca8210_spi_transfer(struct spi_device * spi,const u8 * buf,size_t len)866 static int ca8210_spi_transfer(
867 	struct spi_device  *spi,
868 	const u8           *buf,
869 	size_t              len
870 )
871 {
872 	int i, status = 0;
873 	struct ca8210_priv *priv;
874 	struct cas_control *cas_ctl;
875 
876 	if (!spi) {
877 		pr_crit("NULL spi device passed to %s\n", __func__);
878 		return -ENODEV;
879 	}
880 
881 	priv = spi_get_drvdata(spi);
882 	reinit_completion(&priv->spi_transfer_complete);
883 
884 	dev_dbg(&spi->dev, "%s called\n", __func__);
885 
886 	cas_ctl = kzalloc_obj(*cas_ctl, GFP_ATOMIC);
887 	if (!cas_ctl)
888 		return -ENOMEM;
889 
890 	cas_ctl->priv = priv;
891 	memset(cas_ctl->tx_buf, SPI_IDLE, CA8210_SPI_BUF_SIZE);
892 	memset(cas_ctl->tx_in_buf, SPI_IDLE, CA8210_SPI_BUF_SIZE);
893 	memcpy(cas_ctl->tx_buf, buf, len);
894 
895 	for (i = 0; i < len; i++)
896 		dev_dbg(&spi->dev, "%#03x\n", cas_ctl->tx_buf[i]);
897 
898 	spi_message_init(&cas_ctl->msg);
899 
900 	cas_ctl->transfer.tx_nbits = 1; /* 1 MOSI line */
901 	cas_ctl->transfer.rx_nbits = 1; /* 1 MISO line */
902 	cas_ctl->transfer.speed_hz = 0; /* Use device setting */
903 	cas_ctl->transfer.bits_per_word = 0; /* Use device setting */
904 	cas_ctl->transfer.tx_buf = cas_ctl->tx_buf;
905 	cas_ctl->transfer.rx_buf = cas_ctl->tx_in_buf;
906 	cas_ctl->transfer.delay.value = 0;
907 	cas_ctl->transfer.delay.unit = SPI_DELAY_UNIT_USECS;
908 	cas_ctl->transfer.cs_change = 0;
909 	cas_ctl->transfer.len = sizeof(struct mac_message);
910 	cas_ctl->msg.complete = ca8210_spi_transfer_complete;
911 	cas_ctl->msg.context = cas_ctl;
912 
913 	spi_message_add_tail(
914 		&cas_ctl->transfer,
915 		&cas_ctl->msg
916 	);
917 
918 	status = spi_async(spi, &cas_ctl->msg);
919 	if (status < 0) {
920 		dev_crit(
921 			&spi->dev,
922 			"status %d from spi_sync in write\n",
923 			status
924 		);
925 	}
926 
927 	return status;
928 }
929 
930 /**
931  * ca8210_spi_exchange() - Exchange API/SAP commands with the radio
932  * @buf:         Octet array of command being sent downstream
933  * @len:         length of buf
934  * @response:    buffer for storing synchronous response
935  * @device_ref:  spi_device pointer for ca8210
936  *
937  * Effectively calls ca8210_spi_transfer to write buf[] to the spi, then for
938  * synchronous commands waits for the corresponding response to be read from
939  * the spi before returning. The response is written to the response parameter.
940  *
941  * Return: 0 or linux error code
942  */
ca8210_spi_exchange(const u8 * buf,size_t len,u8 * response,void * device_ref)943 static int ca8210_spi_exchange(
944 	const u8 *buf,
945 	size_t len,
946 	u8 *response,
947 	void *device_ref
948 )
949 {
950 	int status = 0;
951 	struct spi_device *spi = device_ref;
952 	struct ca8210_priv *priv = spi->dev.driver_data;
953 	long wait_remaining;
954 
955 	if ((buf[0] & SPI_SYN) && response) { /* if sync wait for confirm */
956 		reinit_completion(&priv->sync_exchange_complete);
957 		priv->sync_command_response = response;
958 	}
959 
960 	do {
961 		reinit_completion(&priv->spi_transfer_complete);
962 		status = ca8210_spi_transfer(priv->spi, buf, len);
963 		if (status) {
964 			dev_warn(
965 				&spi->dev,
966 				"spi write failed, returned %d\n",
967 				status
968 			);
969 			if (status == -EBUSY)
970 				continue;
971 			if (((buf[0] & SPI_SYN) && response))
972 				complete(&priv->sync_exchange_complete);
973 			goto cleanup;
974 		}
975 
976 		wait_remaining = wait_for_completion_interruptible_timeout(
977 			&priv->spi_transfer_complete,
978 			msecs_to_jiffies(1000)
979 		);
980 		if (wait_remaining == -ERESTARTSYS) {
981 			status = -ERESTARTSYS;
982 		} else if (wait_remaining == 0) {
983 			dev_err(
984 				&spi->dev,
985 				"SPI downstream transfer timed out!\n"
986 			);
987 			status = -ETIME;
988 			goto cleanup;
989 		}
990 	} while (status < 0);
991 
992 	if (!((buf[0] & SPI_SYN) && response))
993 		goto cleanup;
994 
995 	wait_remaining = wait_for_completion_interruptible_timeout(
996 		&priv->sync_exchange_complete,
997 		msecs_to_jiffies(CA8210_SYNC_TIMEOUT)
998 	);
999 	if (wait_remaining == -ERESTARTSYS) {
1000 		status = -ERESTARTSYS;
1001 	} else if (wait_remaining == 0) {
1002 		dev_err(
1003 			&spi->dev,
1004 			"Synchronous confirm timeout\n"
1005 		);
1006 		status = -ETIME;
1007 	}
1008 
1009 cleanup:
1010 	priv->sync_command_response = NULL;
1011 	return status;
1012 }
1013 
1014 /**
1015  * ca8210_interrupt_handler() - Called when an irq is received from the ca8210
1016  * @irq:     Id of the irq being handled
1017  * @dev_id:  Pointer passed by the system, pointing to the ca8210's private data
1018  *
1019  * This function is called when the irq line from the ca8210 is asserted,
1020  * signifying that the ca8210 has a message to send upstream to us. Starts the
1021  * asynchronous spi read.
1022  *
1023  * Return: irq return code
1024  */
ca8210_interrupt_handler(int irq,void * dev_id)1025 static irqreturn_t ca8210_interrupt_handler(int irq, void *dev_id)
1026 {
1027 	struct ca8210_priv *priv = dev_id;
1028 	int status;
1029 
1030 	dev_dbg(&priv->spi->dev, "irq: Interrupt occurred\n");
1031 	do {
1032 		status = ca8210_spi_transfer(priv->spi, NULL, 0);
1033 		if (status && (status != -EBUSY)) {
1034 			dev_warn(
1035 				&priv->spi->dev,
1036 				"spi read failed, returned %d\n",
1037 				status
1038 			);
1039 		}
1040 	} while (status == -EBUSY);
1041 	return IRQ_HANDLED;
1042 }
1043 
1044 static int (*cascoda_api_downstream)(
1045 	const u8 *buf,
1046 	size_t len,
1047 	u8 *response,
1048 	void *device_ref
1049 ) = ca8210_spi_exchange;
1050 
1051 /* Cascoda API / 15.4 SAP Primitives */
1052 
1053 /**
1054  * tdme_setsfr_request_sync() - TDME_SETSFR_request/confirm according to API
1055  * @sfr_page:    SFR Page
1056  * @sfr_address: SFR Address
1057  * @sfr_value:   SFR Value
1058  * @device_ref:  Nondescript pointer to target device
1059  *
1060  * Return: 802.15.4 status code of TDME-SETSFR.confirm
1061  */
tdme_setsfr_request_sync(u8 sfr_page,u8 sfr_address,u8 sfr_value,void * device_ref)1062 static u8 tdme_setsfr_request_sync(
1063 	u8            sfr_page,
1064 	u8            sfr_address,
1065 	u8            sfr_value,
1066 	void         *device_ref
1067 )
1068 {
1069 	int ret;
1070 	struct mac_message command, response;
1071 	struct spi_device *spi = device_ref;
1072 
1073 	command.command_id = SPI_TDME_SETSFR_REQUEST;
1074 	command.length = 3;
1075 	command.pdata.tdme_set_sfr_req.sfr_page    = sfr_page;
1076 	command.pdata.tdme_set_sfr_req.sfr_address = sfr_address;
1077 	command.pdata.tdme_set_sfr_req.sfr_value   = sfr_value;
1078 	response.command_id = SPI_IDLE;
1079 	ret = cascoda_api_downstream(
1080 		&command.command_id,
1081 		command.length + 2,
1082 		&response.command_id,
1083 		device_ref
1084 	);
1085 	if (ret) {
1086 		dev_crit(&spi->dev, "cascoda_api_downstream returned %d", ret);
1087 		return IEEE802154_SYSTEM_ERROR;
1088 	}
1089 
1090 	if (response.command_id != SPI_TDME_SETSFR_CONFIRM) {
1091 		dev_crit(
1092 			&spi->dev,
1093 			"sync response to SPI_TDME_SETSFR_REQUEST was not SPI_TDME_SETSFR_CONFIRM, it was %d\n",
1094 			response.command_id
1095 		);
1096 		return IEEE802154_SYSTEM_ERROR;
1097 	}
1098 
1099 	return response.pdata.tdme_set_sfr_cnf.status;
1100 }
1101 
1102 /**
1103  * tdme_chipinit() - TDME Chip Register Default Initialisation Macro
1104  * @device_ref: Nondescript pointer to target device
1105  *
1106  * Return: 802.15.4 status code of API calls
1107  */
tdme_chipinit(void * device_ref)1108 static u8 tdme_chipinit(void *device_ref)
1109 {
1110 	u8 status = IEEE802154_SUCCESS;
1111 	u8 sfr_address;
1112 	struct spi_device *spi = device_ref;
1113 	struct preamble_cfg_sfr pre_cfg_value = {
1114 		.timeout_symbols     = 3,
1115 		.acquisition_symbols = 3,
1116 		.search_symbols      = 1,
1117 	};
1118 	/* LNA Gain Settings */
1119 	status = tdme_setsfr_request_sync(
1120 		1, (sfr_address = CA8210_SFR_LNAGX40),
1121 		LNAGX40_DEFAULT_GAIN, device_ref);
1122 	if (status)
1123 		goto finish;
1124 	status = tdme_setsfr_request_sync(
1125 		1, (sfr_address = CA8210_SFR_LNAGX41),
1126 		LNAGX41_DEFAULT_GAIN, device_ref);
1127 	if (status)
1128 		goto finish;
1129 	status = tdme_setsfr_request_sync(
1130 		1, (sfr_address = CA8210_SFR_LNAGX42),
1131 		LNAGX42_DEFAULT_GAIN, device_ref);
1132 	if (status)
1133 		goto finish;
1134 	status = tdme_setsfr_request_sync(
1135 		1, (sfr_address = CA8210_SFR_LNAGX43),
1136 		LNAGX43_DEFAULT_GAIN, device_ref);
1137 	if (status)
1138 		goto finish;
1139 	status = tdme_setsfr_request_sync(
1140 		1, (sfr_address = CA8210_SFR_LNAGX44),
1141 		LNAGX44_DEFAULT_GAIN, device_ref);
1142 	if (status)
1143 		goto finish;
1144 	status = tdme_setsfr_request_sync(
1145 		1, (sfr_address = CA8210_SFR_LNAGX45),
1146 		LNAGX45_DEFAULT_GAIN, device_ref);
1147 	if (status)
1148 		goto finish;
1149 	status = tdme_setsfr_request_sync(
1150 		1, (sfr_address = CA8210_SFR_LNAGX46),
1151 		LNAGX46_DEFAULT_GAIN, device_ref);
1152 	if (status)
1153 		goto finish;
1154 	status = tdme_setsfr_request_sync(
1155 		1, (sfr_address = CA8210_SFR_LNAGX47),
1156 		LNAGX47_DEFAULT_GAIN, device_ref);
1157 	if (status)
1158 		goto finish;
1159 	/* Preamble Timing Config */
1160 	status = tdme_setsfr_request_sync(
1161 		1, (sfr_address = CA8210_SFR_PRECFG),
1162 		*((u8 *)&pre_cfg_value), device_ref);
1163 	if (status)
1164 		goto finish;
1165 	/* Preamble Threshold High */
1166 	status = tdme_setsfr_request_sync(
1167 		1, (sfr_address = CA8210_SFR_PTHRH),
1168 		PTHRH_DEFAULT_THRESHOLD, device_ref);
1169 	if (status)
1170 		goto finish;
1171 	/* Tx Output Power 8 dBm */
1172 	status = tdme_setsfr_request_sync(
1173 		0, (sfr_address = CA8210_SFR_PACFGIB),
1174 		PACFGIB_DEFAULT_CURRENT, device_ref);
1175 	if (status)
1176 		goto finish;
1177 
1178 finish:
1179 	if (status != IEEE802154_SUCCESS) {
1180 		dev_err(
1181 			&spi->dev,
1182 			"failed to set sfr at %#03x, status = %#03x\n",
1183 			sfr_address,
1184 			status
1185 		);
1186 	}
1187 	return status;
1188 }
1189 
1190 /**
1191  * tdme_channelinit() - TDME Channel Register Default Initialisation Macro (Tx)
1192  * @channel:    802.15.4 channel to initialise chip for
1193  * @device_ref: Nondescript pointer to target device
1194  *
1195  * Return: 802.15.4 status code of API calls
1196  */
tdme_channelinit(u8 channel,void * device_ref)1197 static u8 tdme_channelinit(u8 channel, void *device_ref)
1198 {
1199 	/* Transceiver front-end local oscillator tx two-point calibration
1200 	 * value. Tuned for the hardware.
1201 	 */
1202 	u8 txcalval;
1203 
1204 	if (channel >= 25)
1205 		txcalval = 0xA7;
1206 	else if (channel >= 23)
1207 		txcalval = 0xA8;
1208 	else if (channel >= 22)
1209 		txcalval = 0xA9;
1210 	else if (channel >= 20)
1211 		txcalval = 0xAA;
1212 	else if (channel >= 17)
1213 		txcalval = 0xAB;
1214 	else if (channel >= 16)
1215 		txcalval = 0xAC;
1216 	else if (channel >= 14)
1217 		txcalval = 0xAD;
1218 	else if (channel >= 12)
1219 		txcalval = 0xAE;
1220 	else
1221 		txcalval = 0xAF;
1222 
1223 	return tdme_setsfr_request_sync(
1224 		1,
1225 		CA8210_SFR_LOTXCAL,
1226 		txcalval,
1227 		device_ref
1228 	);  /* LO Tx Cal */
1229 }
1230 
1231 /**
1232  * tdme_checkpibattribute() - Checks Attribute Values that are not checked in
1233  *                            MAC
1234  * @pib_attribute:        Attribute Number
1235  * @pib_attribute_length: Attribute length
1236  * @pib_attribute_value:  Pointer to Attribute Value
1237  *
1238  * Return: 802.15.4 status code of checks
1239  */
tdme_checkpibattribute(u8 pib_attribute,u8 pib_attribute_length,const void * pib_attribute_value)1240 static u8 tdme_checkpibattribute(
1241 	u8            pib_attribute,
1242 	u8            pib_attribute_length,
1243 	const void   *pib_attribute_value
1244 )
1245 {
1246 	u8 status = IEEE802154_SUCCESS;
1247 	u8 value;
1248 
1249 	value  = *((u8 *)pib_attribute_value);
1250 
1251 	switch (pib_attribute) {
1252 	/* PHY */
1253 	case PHY_TRANSMIT_POWER:
1254 		if (value > 0x3F)
1255 			status = IEEE802154_INVALID_PARAMETER;
1256 		break;
1257 	case PHY_CCA_MODE:
1258 		if (value > 0x03)
1259 			status = IEEE802154_INVALID_PARAMETER;
1260 		break;
1261 	/* MAC */
1262 	case MAC_BATT_LIFE_EXT_PERIODS:
1263 		if (value < 6 || value > 41)
1264 			status = IEEE802154_INVALID_PARAMETER;
1265 		break;
1266 	case MAC_BEACON_PAYLOAD:
1267 		if (pib_attribute_length > MAX_BEACON_PAYLOAD_LENGTH)
1268 			status = IEEE802154_INVALID_PARAMETER;
1269 		break;
1270 	case MAC_BEACON_PAYLOAD_LENGTH:
1271 		if (value > MAX_BEACON_PAYLOAD_LENGTH)
1272 			status = IEEE802154_INVALID_PARAMETER;
1273 		break;
1274 	case MAC_BEACON_ORDER:
1275 		if (value > 15)
1276 			status = IEEE802154_INVALID_PARAMETER;
1277 		break;
1278 	case MAC_MAX_BE:
1279 		if (value < 3 || value > 8)
1280 			status = IEEE802154_INVALID_PARAMETER;
1281 		break;
1282 	case MAC_MAX_CSMA_BACKOFFS:
1283 		if (value > 5)
1284 			status = IEEE802154_INVALID_PARAMETER;
1285 		break;
1286 	case MAC_MAX_FRAME_RETRIES:
1287 		if (value > 7)
1288 			status = IEEE802154_INVALID_PARAMETER;
1289 		break;
1290 	case MAC_MIN_BE:
1291 		if (value > 8)
1292 			status = IEEE802154_INVALID_PARAMETER;
1293 		break;
1294 	case MAC_RESPONSE_WAIT_TIME:
1295 		if (value < 2 || value > 64)
1296 			status = IEEE802154_INVALID_PARAMETER;
1297 		break;
1298 	case MAC_SUPERFRAME_ORDER:
1299 		if (value > 15)
1300 			status = IEEE802154_INVALID_PARAMETER;
1301 		break;
1302 	/* boolean */
1303 	case MAC_ASSOCIATED_PAN_COORD:
1304 	case MAC_ASSOCIATION_PERMIT:
1305 	case MAC_AUTO_REQUEST:
1306 	case MAC_BATT_LIFE_EXT:
1307 	case MAC_GTS_PERMIT:
1308 	case MAC_PROMISCUOUS_MODE:
1309 	case MAC_RX_ON_WHEN_IDLE:
1310 	case MAC_SECURITY_ENABLED:
1311 		if (value > 1)
1312 			status = IEEE802154_INVALID_PARAMETER;
1313 		break;
1314 	/* MAC SEC */
1315 	case MAC_AUTO_REQUEST_SECURITY_LEVEL:
1316 		if (value > 7)
1317 			status = IEEE802154_INVALID_PARAMETER;
1318 		break;
1319 	case MAC_AUTO_REQUEST_KEY_ID_MODE:
1320 		if (value > 3)
1321 			status = IEEE802154_INVALID_PARAMETER;
1322 		break;
1323 	default:
1324 		break;
1325 	}
1326 
1327 	return status;
1328 }
1329 
1330 /**
1331  * tdme_settxpower() - Sets the tx power for MLME_SET phyTransmitPower
1332  * @txp:        Transmit Power
1333  * @device_ref: Nondescript pointer to target device
1334  *
1335  * Normalised to 802.15.4 Definition (6-bit, signed):
1336  * Bit 7-6: not used
1337  * Bit 5-0: tx power (-32 - +31 dB)
1338  *
1339  * Return: 802.15.4 status code of api calls
1340  */
tdme_settxpower(u8 txp,void * device_ref)1341 static u8 tdme_settxpower(u8 txp, void *device_ref)
1342 {
1343 	u8 status;
1344 	s8 txp_val;
1345 	u8 txp_ext;
1346 	union pa_cfg_sfr pa_cfg_val;
1347 
1348 	/* extend from 6 to 8 bit */
1349 	txp_ext = 0x3F & txp;
1350 	if (txp_ext & 0x20)
1351 		txp_ext += 0xC0;
1352 	txp_val = (s8)txp_ext;
1353 
1354 	if (CA8210_MAC_MPW) {
1355 		if (txp_val > 0) {
1356 			/* 8 dBm: ptrim = 5, itrim = +3 => +4 dBm */
1357 			pa_cfg_val.bias_current_trim     = 3;
1358 			pa_cfg_val.buffer_capacitor_trim = 5;
1359 			pa_cfg_val.boost                 = 1;
1360 		} else {
1361 			/* 0 dBm: ptrim = 7, itrim = +3 => -6 dBm */
1362 			pa_cfg_val.bias_current_trim     = 3;
1363 			pa_cfg_val.buffer_capacitor_trim = 7;
1364 			pa_cfg_val.boost                 = 0;
1365 		}
1366 		/* write PACFG */
1367 		status = tdme_setsfr_request_sync(
1368 			0,
1369 			CA8210_SFR_PACFG,
1370 			pa_cfg_val.paib,
1371 			device_ref
1372 		);
1373 	} else {
1374 		/* Look-Up Table for Setting Current and Frequency Trim values
1375 		 * for desired Output Power
1376 		 */
1377 		if (txp_val > 8) {
1378 			pa_cfg_val.paib = 0x3F;
1379 		} else if (txp_val == 8) {
1380 			pa_cfg_val.paib = 0x32;
1381 		} else if (txp_val == 7) {
1382 			pa_cfg_val.paib = 0x22;
1383 		} else if (txp_val == 6) {
1384 			pa_cfg_val.paib = 0x18;
1385 		} else if (txp_val == 5) {
1386 			pa_cfg_val.paib = 0x10;
1387 		} else if (txp_val == 4) {
1388 			pa_cfg_val.paib = 0x0C;
1389 		} else if (txp_val == 3) {
1390 			pa_cfg_val.paib = 0x08;
1391 		} else if (txp_val == 2) {
1392 			pa_cfg_val.paib = 0x05;
1393 		} else if (txp_val == 1) {
1394 			pa_cfg_val.paib = 0x03;
1395 		} else if (txp_val == 0) {
1396 			pa_cfg_val.paib = 0x01;
1397 		} else { /* < 0 */
1398 			pa_cfg_val.paib = 0x00;
1399 		}
1400 		/* write PACFGIB */
1401 		status = tdme_setsfr_request_sync(
1402 			0,
1403 			CA8210_SFR_PACFGIB,
1404 			pa_cfg_val.paib,
1405 			device_ref
1406 		);
1407 	}
1408 
1409 	return status;
1410 }
1411 
1412 /**
1413  * mcps_data_request() - mcps_data_request (Send Data) according to API Spec
1414  * @src_addr_mode:    Source Addressing Mode
1415  * @dst_address_mode: Destination Addressing Mode
1416  * @dst_pan_id:       Destination PAN ID
1417  * @dst_addr:         Pointer to Destination Address
1418  * @msdu_length:      length of Data
1419  * @msdu:             Pointer to Data
1420  * @msdu_handle:      Handle of Data
1421  * @tx_options:       Tx Options Bit Field
1422  * @security:         Pointer to Security Structure or NULL
1423  * @device_ref:       Nondescript pointer to target device
1424  *
1425  * Return: 802.15.4 status code of action
1426  */
mcps_data_request(u8 src_addr_mode,u8 dst_address_mode,u16 dst_pan_id,union macaddr * dst_addr,u8 msdu_length,u8 * msdu,u8 msdu_handle,u8 tx_options,struct secspec * security,void * device_ref)1427 static u8 mcps_data_request(
1428 	u8               src_addr_mode,
1429 	u8               dst_address_mode,
1430 	u16              dst_pan_id,
1431 	union macaddr   *dst_addr,
1432 	u8               msdu_length,
1433 	u8              *msdu,
1434 	u8               msdu_handle,
1435 	u8               tx_options,
1436 	struct secspec  *security,
1437 	void            *device_ref
1438 )
1439 {
1440 	struct secspec *psec;
1441 	struct mac_message command;
1442 
1443 	command.command_id = SPI_MCPS_DATA_REQUEST;
1444 	command.pdata.data_req.src_addr_mode = src_addr_mode;
1445 	command.pdata.data_req.dst.mode = dst_address_mode;
1446 	if (dst_address_mode != MAC_MODE_NO_ADDR) {
1447 		put_unaligned_le16(dst_pan_id, command.pdata.data_req.dst.pan_id);
1448 		if (dst_address_mode == MAC_MODE_SHORT_ADDR) {
1449 			command.pdata.data_req.dst.address[0] = LS_BYTE(
1450 				dst_addr->short_address
1451 			);
1452 			command.pdata.data_req.dst.address[1] = MS_BYTE(
1453 				dst_addr->short_address
1454 			);
1455 		} else {   /* MAC_MODE_LONG_ADDR*/
1456 			memcpy(
1457 				command.pdata.data_req.dst.address,
1458 				dst_addr->ieee_address,
1459 				8
1460 			);
1461 		}
1462 	}
1463 	command.pdata.data_req.msdu_length = msdu_length;
1464 	command.pdata.data_req.msdu_handle = msdu_handle;
1465 	command.pdata.data_req.tx_options = tx_options;
1466 	memcpy(command.pdata.data_req.msdu, msdu, msdu_length);
1467 	psec = (struct secspec *)(command.pdata.data_req.msdu + msdu_length);
1468 	command.length = sizeof(struct mcps_data_request_pset) -
1469 		MAX_DATA_SIZE + msdu_length;
1470 	if (!security || security->security_level == 0) {
1471 		psec->security_level = 0;
1472 		command.length += 1;
1473 	} else {
1474 		*psec = *security;
1475 		command.length += sizeof(struct secspec);
1476 	}
1477 
1478 	if (ca8210_spi_transfer(device_ref, &command.command_id,
1479 				command.length + 2))
1480 		return IEEE802154_SYSTEM_ERROR;
1481 
1482 	return IEEE802154_SUCCESS;
1483 }
1484 
1485 /**
1486  * mlme_reset_request_sync() - MLME_RESET_request/confirm according to API Spec
1487  * @set_default_pib: Set defaults in PIB
1488  * @device_ref:      Nondescript pointer to target device
1489  *
1490  * Return: 802.15.4 status code of MLME-RESET.confirm
1491  */
mlme_reset_request_sync(u8 set_default_pib,void * device_ref)1492 static u8 mlme_reset_request_sync(
1493 	u8    set_default_pib,
1494 	void *device_ref
1495 )
1496 {
1497 	u8 status;
1498 	struct mac_message command, response;
1499 	struct spi_device *spi = device_ref;
1500 
1501 	command.command_id = SPI_MLME_RESET_REQUEST;
1502 	command.length = 1;
1503 	command.pdata.u8param = set_default_pib;
1504 
1505 	if (cascoda_api_downstream(
1506 		&command.command_id,
1507 		command.length + 2,
1508 		&response.command_id,
1509 		device_ref)) {
1510 		dev_err(&spi->dev, "cascoda_api_downstream failed\n");
1511 		return IEEE802154_SYSTEM_ERROR;
1512 	}
1513 
1514 	if (response.command_id != SPI_MLME_RESET_CONFIRM)
1515 		return IEEE802154_SYSTEM_ERROR;
1516 
1517 	status = response.pdata.status;
1518 
1519 	/* reset COORD Bit for Channel Filtering as Coordinator */
1520 	if (CA8210_MAC_WORKAROUNDS && set_default_pib && !status) {
1521 		status = tdme_setsfr_request_sync(
1522 			0,
1523 			CA8210_SFR_MACCON,
1524 			0,
1525 			device_ref
1526 		);
1527 	}
1528 
1529 	return status;
1530 }
1531 
1532 /**
1533  * mlme_set_request_sync() - MLME_SET_request/confirm according to API Spec
1534  * @pib_attribute:        Attribute Number
1535  * @pib_attribute_index:  Index within Attribute if an Array
1536  * @pib_attribute_length: Attribute length
1537  * @pib_attribute_value:  Pointer to Attribute Value
1538  * @device_ref:           Nondescript pointer to target device
1539  *
1540  * Return: 802.15.4 status code of MLME-SET.confirm
1541  */
mlme_set_request_sync(u8 pib_attribute,u8 pib_attribute_index,u8 pib_attribute_length,const void * pib_attribute_value,void * device_ref)1542 static u8 mlme_set_request_sync(
1543 	u8            pib_attribute,
1544 	u8            pib_attribute_index,
1545 	u8            pib_attribute_length,
1546 	const void   *pib_attribute_value,
1547 	void         *device_ref
1548 )
1549 {
1550 	u8 status;
1551 	struct mac_message command, response;
1552 
1553 	/* pre-check the validity of pib_attribute values that are not checked
1554 	 * in MAC
1555 	 */
1556 	if (tdme_checkpibattribute(
1557 		pib_attribute, pib_attribute_length, pib_attribute_value)) {
1558 		return IEEE802154_INVALID_PARAMETER;
1559 	}
1560 
1561 	if (pib_attribute == PHY_CURRENT_CHANNEL) {
1562 		status = tdme_channelinit(
1563 			*((u8 *)pib_attribute_value),
1564 			device_ref
1565 		);
1566 		if (status)
1567 			return status;
1568 	}
1569 
1570 	if (pib_attribute == PHY_TRANSMIT_POWER) {
1571 		return tdme_settxpower(
1572 			*((u8 *)pib_attribute_value),
1573 			device_ref
1574 		);
1575 	}
1576 
1577 	command.command_id = SPI_MLME_SET_REQUEST;
1578 	command.length = sizeof(struct mlme_set_request_pset) -
1579 		MAX_ATTRIBUTE_SIZE + pib_attribute_length;
1580 	command.pdata.set_req.pib_attribute = pib_attribute;
1581 	command.pdata.set_req.pib_attribute_index = pib_attribute_index;
1582 	command.pdata.set_req.pib_attribute_length = pib_attribute_length;
1583 	memcpy(
1584 		command.pdata.set_req.pib_attribute_value,
1585 		pib_attribute_value,
1586 		pib_attribute_length
1587 	);
1588 
1589 	if (cascoda_api_downstream(
1590 		&command.command_id,
1591 		command.length + 2,
1592 		&response.command_id,
1593 		device_ref)) {
1594 		return IEEE802154_SYSTEM_ERROR;
1595 	}
1596 
1597 	if (response.command_id != SPI_MLME_SET_CONFIRM)
1598 		return IEEE802154_SYSTEM_ERROR;
1599 
1600 	return response.pdata.status;
1601 }
1602 
1603 /**
1604  * hwme_set_request_sync() - HWME_SET_request/confirm according to API Spec
1605  * @hw_attribute:        Attribute Number
1606  * @hw_attribute_length: Attribute length
1607  * @hw_attribute_value:  Pointer to Attribute Value
1608  * @device_ref:          Nondescript pointer to target device
1609  *
1610  * Return: 802.15.4 status code of HWME-SET.confirm
1611  */
hwme_set_request_sync(u8 hw_attribute,u8 hw_attribute_length,u8 * hw_attribute_value,void * device_ref)1612 static u8 hwme_set_request_sync(
1613 	u8           hw_attribute,
1614 	u8           hw_attribute_length,
1615 	u8          *hw_attribute_value,
1616 	void        *device_ref
1617 )
1618 {
1619 	struct mac_message command, response;
1620 
1621 	command.command_id = SPI_HWME_SET_REQUEST;
1622 	command.length = 2 + hw_attribute_length;
1623 	command.pdata.hwme_set_req.hw_attribute = hw_attribute;
1624 	command.pdata.hwme_set_req.hw_attribute_length = hw_attribute_length;
1625 	memcpy(
1626 		command.pdata.hwme_set_req.hw_attribute_value,
1627 		hw_attribute_value,
1628 		hw_attribute_length
1629 	);
1630 
1631 	if (cascoda_api_downstream(
1632 		&command.command_id,
1633 		command.length + 2,
1634 		&response.command_id,
1635 		device_ref)) {
1636 		return IEEE802154_SYSTEM_ERROR;
1637 	}
1638 
1639 	if (response.command_id != SPI_HWME_SET_CONFIRM)
1640 		return IEEE802154_SYSTEM_ERROR;
1641 
1642 	return response.pdata.hwme_set_cnf.status;
1643 }
1644 
1645 /**
1646  * hwme_get_request_sync() - HWME_GET_request/confirm according to API Spec
1647  * @hw_attribute:        Attribute Number
1648  * @hw_attribute_length: Attribute length
1649  * @hw_attribute_value:  Pointer to Attribute Value
1650  * @device_ref:          Nondescript pointer to target device
1651  *
1652  * Return: 802.15.4 status code of HWME-GET.confirm
1653  */
hwme_get_request_sync(u8 hw_attribute,u8 * hw_attribute_length,u8 * hw_attribute_value,void * device_ref)1654 static u8 hwme_get_request_sync(
1655 	u8           hw_attribute,
1656 	u8          *hw_attribute_length,
1657 	u8          *hw_attribute_value,
1658 	void        *device_ref
1659 )
1660 {
1661 	struct mac_message command, response;
1662 
1663 	command.command_id = SPI_HWME_GET_REQUEST;
1664 	command.length = 1;
1665 	command.pdata.hwme_get_req.hw_attribute = hw_attribute;
1666 
1667 	if (cascoda_api_downstream(
1668 		&command.command_id,
1669 		command.length + 2,
1670 		&response.command_id,
1671 		device_ref)) {
1672 		return IEEE802154_SYSTEM_ERROR;
1673 	}
1674 
1675 	if (response.command_id != SPI_HWME_GET_CONFIRM)
1676 		return IEEE802154_SYSTEM_ERROR;
1677 
1678 	if (response.pdata.hwme_get_cnf.status == IEEE802154_SUCCESS) {
1679 		*hw_attribute_length =
1680 			response.pdata.hwme_get_cnf.hw_attribute_length;
1681 		memcpy(
1682 			hw_attribute_value,
1683 			response.pdata.hwme_get_cnf.hw_attribute_value,
1684 			*hw_attribute_length
1685 		);
1686 	}
1687 
1688 	return response.pdata.hwme_get_cnf.status;
1689 }
1690 
1691 /* Network driver operation */
1692 
1693 /**
1694  * ca8210_async_xmit_complete() - Called to announce that an asynchronous
1695  *                                transmission has finished
1696  * @hw:          ieee802154_hw of ca8210 that has finished exchange
1697  * @msduhandle:  Identifier of transmission that has completed
1698  * @status:      Returned 802.15.4 status code of the transmission
1699  *
1700  * Return: 0 or linux error code
1701  */
ca8210_async_xmit_complete(struct ieee802154_hw * hw,u8 msduhandle,u8 status)1702 static int ca8210_async_xmit_complete(
1703 	struct ieee802154_hw  *hw,
1704 	u8                     msduhandle,
1705 	u8                     status)
1706 {
1707 	struct ca8210_priv *priv = hw->priv;
1708 
1709 	if (priv->nextmsduhandle != msduhandle) {
1710 		dev_err(
1711 			&priv->spi->dev,
1712 			"Unexpected msdu_handle on data confirm, Expected %d, got %d\n",
1713 			priv->nextmsduhandle,
1714 			msduhandle
1715 		);
1716 		return -EIO;
1717 	}
1718 
1719 	priv->async_tx_pending = false;
1720 	priv->nextmsduhandle++;
1721 
1722 	if (status) {
1723 		dev_err(
1724 			&priv->spi->dev,
1725 			"Link transmission unsuccessful, status = %d\n",
1726 			status
1727 		);
1728 		if (status != IEEE802154_TRANSACTION_OVERFLOW) {
1729 			ieee802154_xmit_error(priv->hw, priv->tx_skb, status);
1730 			return 0;
1731 		}
1732 	}
1733 	ieee802154_xmit_complete(priv->hw, priv->tx_skb, true);
1734 
1735 	return 0;
1736 }
1737 
1738 /**
1739  * ca8210_skb_rx() - Contructs a properly framed socket buffer from a received
1740  *                   MCPS_DATA_indication
1741  * @hw:        ieee802154_hw that MCPS_DATA_indication was received by
1742  * @len:       length of MCPS_DATA_indication
1743  * @data_ind:  Octet array of MCPS_DATA_indication
1744  *
1745  * Called by the spi driver whenever a SAP command is received, this function
1746  * will ascertain whether the command is of interest to the network driver and
1747  * take necessary action.
1748  *
1749  * Return: 0 or linux error code
1750  */
ca8210_skb_rx(struct ieee802154_hw * hw,size_t len,u8 * data_ind)1751 static int ca8210_skb_rx(
1752 	struct ieee802154_hw  *hw,
1753 	size_t                 len,
1754 	u8                    *data_ind
1755 )
1756 {
1757 	struct ieee802154_hdr hdr;
1758 	int msdulen;
1759 	int hlen;
1760 	u8 mpdulinkquality = data_ind[23];
1761 	struct sk_buff *skb;
1762 	struct ca8210_priv *priv = hw->priv;
1763 
1764 	/* Allocate mtu size buffer for every rx packet */
1765 	skb = dev_alloc_skb(IEEE802154_MTU + sizeof(hdr));
1766 	if (!skb)
1767 		return -ENOMEM;
1768 
1769 	skb_reserve(skb, sizeof(hdr));
1770 
1771 	msdulen = data_ind[22]; /* msdu_length */
1772 	if (msdulen > IEEE802154_MTU) {
1773 		dev_err(
1774 			&priv->spi->dev,
1775 			"received erroneously large msdu length!\n"
1776 		);
1777 		kfree_skb(skb);
1778 		return -EMSGSIZE;
1779 	}
1780 	dev_dbg(&priv->spi->dev, "skb buffer length = %d\n", msdulen);
1781 
1782 	if (priv->promiscuous)
1783 		goto copy_payload;
1784 
1785 	/* Populate hdr */
1786 	hdr.sec.level = data_ind[29 + msdulen];
1787 	dev_dbg(&priv->spi->dev, "security level: %#03x\n", hdr.sec.level);
1788 	if (hdr.sec.level > 0) {
1789 		hdr.sec.key_id_mode = data_ind[30 + msdulen];
1790 		memcpy(&hdr.sec.extended_src, &data_ind[31 + msdulen], 8);
1791 		hdr.sec.key_id = data_ind[39 + msdulen];
1792 	}
1793 	hdr.source.mode = data_ind[0];
1794 	dev_dbg(&priv->spi->dev, "srcAddrMode: %#03x\n", hdr.source.mode);
1795 	hdr.source.pan_id = cpu_to_le16(get_unaligned_le16(&data_ind[1]));
1796 	dev_dbg(&priv->spi->dev, "srcPanId: %#06x\n", hdr.source.pan_id);
1797 	memcpy(&hdr.source.extended_addr, &data_ind[3], 8);
1798 	hdr.dest.mode = data_ind[11];
1799 	dev_dbg(&priv->spi->dev, "dstAddrMode: %#03x\n", hdr.dest.mode);
1800 	hdr.dest.pan_id = cpu_to_le16(get_unaligned_le16(&data_ind[12]));
1801 	dev_dbg(&priv->spi->dev, "dstPanId: %#06x\n", hdr.dest.pan_id);
1802 	memcpy(&hdr.dest.extended_addr, &data_ind[14], 8);
1803 
1804 	/* Fill in FC implicitly */
1805 	hdr.fc.type = 1; /* Data frame */
1806 	if (hdr.sec.level)
1807 		hdr.fc.security_enabled = 1;
1808 	else
1809 		hdr.fc.security_enabled = 0;
1810 	if (data_ind[1] != data_ind[12] || data_ind[2] != data_ind[13])
1811 		hdr.fc.intra_pan = 1;
1812 	else
1813 		hdr.fc.intra_pan = 0;
1814 	hdr.fc.dest_addr_mode = hdr.dest.mode;
1815 	hdr.fc.source_addr_mode = hdr.source.mode;
1816 
1817 	/* Add hdr to front of buffer */
1818 	hlen = ieee802154_hdr_push(skb, &hdr);
1819 
1820 	if (hlen < 0) {
1821 		dev_crit(&priv->spi->dev, "failed to push mac hdr onto skb!\n");
1822 		kfree_skb(skb);
1823 		return hlen;
1824 	}
1825 
1826 	skb_reset_mac_header(skb);
1827 	skb->mac_len = hlen;
1828 
1829 copy_payload:
1830 	/* Add <msdulen> bytes of space to the back of the buffer */
1831 	/* Copy msdu to skb */
1832 	skb_put_data(skb, &data_ind[29], msdulen);
1833 
1834 	ieee802154_rx_irqsafe(hw, skb, mpdulinkquality);
1835 	return 0;
1836 }
1837 
1838 /**
1839  * ca8210_net_rx() - Acts upon received SAP commands relevant to the network
1840  *                   driver
1841  * @hw:       ieee802154_hw that command was received by
1842  * @command:  Octet array of received command
1843  * @len:      length of the received command
1844  *
1845  * Called by the spi driver whenever a SAP command is received, this function
1846  * will ascertain whether the command is of interest to the network driver and
1847  * take necessary action.
1848  *
1849  * Return: 0 or linux error code
1850  */
ca8210_net_rx(struct ieee802154_hw * hw,u8 * command,size_t len)1851 static int ca8210_net_rx(struct ieee802154_hw *hw, u8 *command, size_t len)
1852 {
1853 	struct ca8210_priv *priv = hw->priv;
1854 	unsigned long flags;
1855 	u8 status;
1856 
1857 	dev_dbg(&priv->spi->dev, "%s: CmdID = %d\n", __func__, command[0]);
1858 
1859 	if (command[0] == SPI_MCPS_DATA_INDICATION) {
1860 		/* Received data */
1861 		spin_lock_irqsave(&priv->lock, flags);
1862 		if (command[26] == priv->last_dsn) {
1863 			dev_dbg(
1864 				&priv->spi->dev,
1865 				"DSN %d resend received, ignoring...\n",
1866 				command[26]
1867 			);
1868 			spin_unlock_irqrestore(&priv->lock, flags);
1869 			return 0;
1870 		}
1871 		priv->last_dsn = command[26];
1872 		spin_unlock_irqrestore(&priv->lock, flags);
1873 		return ca8210_skb_rx(hw, len - 2, command + 2);
1874 	} else if (command[0] == SPI_MCPS_DATA_CONFIRM) {
1875 		status = command[3];
1876 		if (priv->async_tx_pending) {
1877 			return ca8210_async_xmit_complete(
1878 				hw,
1879 				command[2],
1880 				status
1881 			);
1882 		}
1883 	}
1884 
1885 	return 0;
1886 }
1887 
1888 /**
1889  * ca8210_skb_tx() - Transmits a given socket buffer using the ca8210
1890  * @skb:         Socket buffer to transmit
1891  * @msduhandle:  Data identifier to pass to the 802.15.4 MAC
1892  * @priv:        Pointer to private data section of target ca8210
1893  *
1894  * Return: 0 or linux error code
1895  */
ca8210_skb_tx(struct sk_buff * skb,u8 msduhandle,struct ca8210_priv * priv)1896 static int ca8210_skb_tx(
1897 	struct sk_buff      *skb,
1898 	u8                   msduhandle,
1899 	struct ca8210_priv  *priv
1900 )
1901 {
1902 	struct ieee802154_hdr header = { };
1903 	struct secspec secspec;
1904 	int mac_len, status;
1905 
1906 	dev_dbg(&priv->spi->dev, "%s called\n", __func__);
1907 
1908 	/* Get addressing info from skb - ieee802154 layer creates a full
1909 	 * packet
1910 	 */
1911 	mac_len = ieee802154_hdr_peek_addrs(skb, &header);
1912 	if (mac_len < 0)
1913 		return mac_len;
1914 
1915 	secspec.security_level = header.sec.level;
1916 	secspec.key_id_mode = header.sec.key_id_mode;
1917 	if (secspec.key_id_mode == 2)
1918 		memcpy(secspec.key_source, &header.sec.short_src, 4);
1919 	else if (secspec.key_id_mode == 3)
1920 		memcpy(secspec.key_source, &header.sec.extended_src, 8);
1921 	secspec.key_index = header.sec.key_id;
1922 
1923 	/* Pass to Cascoda API */
1924 	status =  mcps_data_request(
1925 		header.source.mode,
1926 		header.dest.mode,
1927 		le16_to_cpu(header.dest.pan_id),
1928 		(union macaddr *)&header.dest.extended_addr,
1929 		skb->len - mac_len,
1930 		&skb->data[mac_len],
1931 		msduhandle,
1932 		header.fc.ack_request,
1933 		&secspec,
1934 		priv->spi
1935 	);
1936 	return link_to_linux_err(status);
1937 }
1938 
1939 /**
1940  * ca8210_start() - Starts the network driver
1941  * @hw:  ieee802154_hw of ca8210 being started
1942  *
1943  * Return: 0 or linux error code
1944  */
ca8210_start(struct ieee802154_hw * hw)1945 static int ca8210_start(struct ieee802154_hw *hw)
1946 {
1947 	int status;
1948 	u8 rx_on_when_idle;
1949 	u8 lqi_threshold = 0;
1950 	struct ca8210_priv *priv = hw->priv;
1951 
1952 	priv->last_dsn = -1;
1953 	/* Turn receiver on when idle for now just to test rx */
1954 	rx_on_when_idle = 1;
1955 	status = mlme_set_request_sync(
1956 		MAC_RX_ON_WHEN_IDLE,
1957 		0,
1958 		1,
1959 		&rx_on_when_idle,
1960 		priv->spi
1961 	);
1962 	if (status) {
1963 		dev_crit(
1964 			&priv->spi->dev,
1965 			"Setting rx_on_when_idle failed, status = %d\n",
1966 			status
1967 		);
1968 		return link_to_linux_err(status);
1969 	}
1970 	status = hwme_set_request_sync(
1971 		HWME_LQILIMIT,
1972 		1,
1973 		&lqi_threshold,
1974 		priv->spi
1975 	);
1976 	if (status) {
1977 		dev_crit(
1978 			&priv->spi->dev,
1979 			"Setting lqilimit failed, status = %d\n",
1980 			status
1981 		);
1982 		return link_to_linux_err(status);
1983 	}
1984 
1985 	return 0;
1986 }
1987 
1988 /**
1989  * ca8210_stop() - Stops the network driver
1990  * @hw:  ieee802154_hw of ca8210 being stopped
1991  *
1992  * Return: 0 or linux error code
1993  */
ca8210_stop(struct ieee802154_hw * hw)1994 static void ca8210_stop(struct ieee802154_hw *hw)
1995 {
1996 }
1997 
1998 /**
1999  * ca8210_xmit_async() - Asynchronously transmits a given socket buffer using
2000  *                       the ca8210
2001  * @hw:   ieee802154_hw of ca8210 to transmit from
2002  * @skb:  Socket buffer to transmit
2003  *
2004  * Return: 0 or linux error code
2005  */
ca8210_xmit_async(struct ieee802154_hw * hw,struct sk_buff * skb)2006 static int ca8210_xmit_async(struct ieee802154_hw *hw, struct sk_buff *skb)
2007 {
2008 	struct ca8210_priv *priv = hw->priv;
2009 	int status;
2010 
2011 	dev_dbg(&priv->spi->dev, "calling %s\n", __func__);
2012 
2013 	priv->tx_skb = skb;
2014 	priv->async_tx_pending = true;
2015 	status = ca8210_skb_tx(skb, priv->nextmsduhandle, priv);
2016 	return status;
2017 }
2018 
2019 /**
2020  * ca8210_get_ed() - Returns the measured energy on the current channel at this
2021  *                   instant in time
2022  * @hw:     ieee802154_hw of target ca8210
2023  * @level:  Measured Energy Detect level
2024  *
2025  * Return: 0 or linux error code
2026  */
ca8210_get_ed(struct ieee802154_hw * hw,u8 * level)2027 static int ca8210_get_ed(struct ieee802154_hw *hw, u8 *level)
2028 {
2029 	u8 lenvar;
2030 	struct ca8210_priv *priv = hw->priv;
2031 
2032 	return link_to_linux_err(
2033 		hwme_get_request_sync(HWME_EDVALUE, &lenvar, level, priv->spi)
2034 	);
2035 }
2036 
2037 /**
2038  * ca8210_set_channel() - Sets the current operating 802.15.4 channel of the
2039  *                        ca8210
2040  * @hw:       ieee802154_hw of target ca8210
2041  * @page:     Channel page to set
2042  * @channel:  Channel number to set
2043  *
2044  * Return: 0 or linux error code
2045  */
ca8210_set_channel(struct ieee802154_hw * hw,u8 page,u8 channel)2046 static int ca8210_set_channel(
2047 	struct ieee802154_hw  *hw,
2048 	u8                     page,
2049 	u8                     channel
2050 )
2051 {
2052 	u8 status;
2053 	struct ca8210_priv *priv = hw->priv;
2054 
2055 	status = mlme_set_request_sync(
2056 		PHY_CURRENT_CHANNEL,
2057 		0,
2058 		1,
2059 		&channel,
2060 		priv->spi
2061 	);
2062 	if (status) {
2063 		dev_err(
2064 			&priv->spi->dev,
2065 			"error setting channel, MLME-SET.confirm status = %d\n",
2066 			status
2067 		);
2068 	}
2069 	return link_to_linux_err(status);
2070 }
2071 
2072 /**
2073  * ca8210_set_hw_addr_filt() - Sets the address filtering parameters of the
2074  *                             ca8210
2075  * @hw:       ieee802154_hw of target ca8210
2076  * @filt:     Filtering parameters
2077  * @changed:  Bitmap representing which parameters to change
2078  *
2079  * Effectively just sets the actual addressing information identifying this node
2080  * as all filtering is performed by the ca8210 as detailed in the IEEE 802.15.4
2081  * 2006 specification.
2082  *
2083  * Return: 0 or linux error code
2084  */
ca8210_set_hw_addr_filt(struct ieee802154_hw * hw,struct ieee802154_hw_addr_filt * filt,unsigned long changed)2085 static int ca8210_set_hw_addr_filt(
2086 	struct ieee802154_hw            *hw,
2087 	struct ieee802154_hw_addr_filt  *filt,
2088 	unsigned long                    changed
2089 )
2090 {
2091 	u8 status = 0;
2092 	struct ca8210_priv *priv = hw->priv;
2093 
2094 	if (changed & IEEE802154_AFILT_PANID_CHANGED) {
2095 		status = mlme_set_request_sync(
2096 			MAC_PAN_ID,
2097 			0,
2098 			2,
2099 			&filt->pan_id, priv->spi
2100 		);
2101 		if (status) {
2102 			dev_err(
2103 				&priv->spi->dev,
2104 				"error setting pan id, MLME-SET.confirm status = %d",
2105 				status
2106 			);
2107 			return link_to_linux_err(status);
2108 		}
2109 	}
2110 	if (changed & IEEE802154_AFILT_SADDR_CHANGED) {
2111 		status = mlme_set_request_sync(
2112 			MAC_SHORT_ADDRESS,
2113 			0,
2114 			2,
2115 			&filt->short_addr, priv->spi
2116 		);
2117 		if (status) {
2118 			dev_err(
2119 				&priv->spi->dev,
2120 				"error setting short address, MLME-SET.confirm status = %d",
2121 				status
2122 			);
2123 			return link_to_linux_err(status);
2124 		}
2125 	}
2126 	if (changed & IEEE802154_AFILT_IEEEADDR_CHANGED) {
2127 		status = mlme_set_request_sync(
2128 			NS_IEEE_ADDRESS,
2129 			0,
2130 			8,
2131 			&filt->ieee_addr,
2132 			priv->spi
2133 		);
2134 		if (status) {
2135 			dev_err(
2136 				&priv->spi->dev,
2137 				"error setting ieee address, MLME-SET.confirm status = %d",
2138 				status
2139 			);
2140 			return link_to_linux_err(status);
2141 		}
2142 	}
2143 	/* TODO: Should use MLME_START to set coord bit? */
2144 	return 0;
2145 }
2146 
2147 /**
2148  * ca8210_set_tx_power() - Sets the transmit power of the ca8210
2149  * @hw:   ieee802154_hw of target ca8210
2150  * @mbm:  Transmit power in mBm (dBm*100)
2151  *
2152  * Return: 0 or linux error code
2153  */
ca8210_set_tx_power(struct ieee802154_hw * hw,s32 mbm)2154 static int ca8210_set_tx_power(struct ieee802154_hw *hw, s32 mbm)
2155 {
2156 	struct ca8210_priv *priv = hw->priv;
2157 
2158 	mbm /= 100;
2159 	return link_to_linux_err(
2160 		mlme_set_request_sync(PHY_TRANSMIT_POWER, 0, 1, &mbm, priv->spi)
2161 	);
2162 }
2163 
2164 /**
2165  * ca8210_set_cca_mode() - Sets the clear channel assessment mode of the ca8210
2166  * @hw:   ieee802154_hw of target ca8210
2167  * @cca:  CCA mode to set
2168  *
2169  * Return: 0 or linux error code
2170  */
ca8210_set_cca_mode(struct ieee802154_hw * hw,const struct wpan_phy_cca * cca)2171 static int ca8210_set_cca_mode(
2172 	struct ieee802154_hw       *hw,
2173 	const struct wpan_phy_cca  *cca
2174 )
2175 {
2176 	u8 status;
2177 	u8 cca_mode;
2178 	struct ca8210_priv *priv = hw->priv;
2179 
2180 	cca_mode = cca->mode & 3;
2181 	if (cca_mode == 3 && cca->opt == NL802154_CCA_OPT_ENERGY_CARRIER_OR) {
2182 		/* cca_mode 0 == CS OR ED, 3 == CS AND ED */
2183 		cca_mode = 0;
2184 	}
2185 	status = mlme_set_request_sync(
2186 		PHY_CCA_MODE,
2187 		0,
2188 		1,
2189 		&cca_mode,
2190 		priv->spi
2191 	);
2192 	if (status) {
2193 		dev_err(
2194 			&priv->spi->dev,
2195 			"error setting cca mode, MLME-SET.confirm status = %d",
2196 			status
2197 		);
2198 	}
2199 	return link_to_linux_err(status);
2200 }
2201 
2202 /**
2203  * ca8210_set_cca_ed_level() - Sets the CCA ED level of the ca8210
2204  * @hw:     ieee802154_hw of target ca8210
2205  * @level:  ED level to set (in mbm)
2206  *
2207  * Sets the minimum threshold of measured energy above which the ca8210 will
2208  * back off and retry a transmission.
2209  *
2210  * Return: 0 or linux error code
2211  */
ca8210_set_cca_ed_level(struct ieee802154_hw * hw,s32 level)2212 static int ca8210_set_cca_ed_level(struct ieee802154_hw *hw, s32 level)
2213 {
2214 	u8 status;
2215 	u8 ed_threshold = (level / 100) * 2 + 256;
2216 	struct ca8210_priv *priv = hw->priv;
2217 
2218 	status = hwme_set_request_sync(
2219 		HWME_EDTHRESHOLD,
2220 		1,
2221 		&ed_threshold,
2222 		priv->spi
2223 	);
2224 	if (status) {
2225 		dev_err(
2226 			&priv->spi->dev,
2227 			"error setting ed threshold, HWME-SET.confirm status = %d",
2228 			status
2229 		);
2230 	}
2231 	return link_to_linux_err(status);
2232 }
2233 
2234 /**
2235  * ca8210_set_csma_params() - Sets the CSMA parameters of the ca8210
2236  * @hw:       ieee802154_hw of target ca8210
2237  * @min_be:   Minimum backoff exponent when backing off a transmission
2238  * @max_be:   Maximum backoff exponent when backing off a transmission
2239  * @retries:  Number of times to retry after backing off
2240  *
2241  * Return: 0 or linux error code
2242  */
ca8210_set_csma_params(struct ieee802154_hw * hw,u8 min_be,u8 max_be,u8 retries)2243 static int ca8210_set_csma_params(
2244 	struct ieee802154_hw  *hw,
2245 	u8                     min_be,
2246 	u8                     max_be,
2247 	u8                     retries
2248 )
2249 {
2250 	u8 status;
2251 	struct ca8210_priv *priv = hw->priv;
2252 
2253 	status = mlme_set_request_sync(MAC_MIN_BE, 0, 1, &min_be, priv->spi);
2254 	if (status) {
2255 		dev_err(
2256 			&priv->spi->dev,
2257 			"error setting min be, MLME-SET.confirm status = %d",
2258 			status
2259 		);
2260 		return link_to_linux_err(status);
2261 	}
2262 	status = mlme_set_request_sync(MAC_MAX_BE, 0, 1, &max_be, priv->spi);
2263 	if (status) {
2264 		dev_err(
2265 			&priv->spi->dev,
2266 			"error setting max be, MLME-SET.confirm status = %d",
2267 			status
2268 		);
2269 		return link_to_linux_err(status);
2270 	}
2271 	status = mlme_set_request_sync(
2272 		MAC_MAX_CSMA_BACKOFFS,
2273 		0,
2274 		1,
2275 		&retries,
2276 		priv->spi
2277 	);
2278 	if (status) {
2279 		dev_err(
2280 			&priv->spi->dev,
2281 			"error setting max csma backoffs, MLME-SET.confirm status = %d",
2282 			status
2283 		);
2284 	}
2285 	return link_to_linux_err(status);
2286 }
2287 
2288 /**
2289  * ca8210_set_frame_retries() - Sets the maximum frame retries of the ca8210
2290  * @hw:       ieee802154_hw of target ca8210
2291  * @retries:  Number of retries
2292  *
2293  * Sets the number of times to retry a transmission if no acknowledgment was
2294  * received from the other end when one was requested.
2295  *
2296  * Return: 0 or linux error code
2297  */
ca8210_set_frame_retries(struct ieee802154_hw * hw,s8 retries)2298 static int ca8210_set_frame_retries(struct ieee802154_hw *hw, s8 retries)
2299 {
2300 	u8 status;
2301 	struct ca8210_priv *priv = hw->priv;
2302 
2303 	status = mlme_set_request_sync(
2304 		MAC_MAX_FRAME_RETRIES,
2305 		0,
2306 		1,
2307 		&retries,
2308 		priv->spi
2309 	);
2310 	if (status) {
2311 		dev_err(
2312 			&priv->spi->dev,
2313 			"error setting frame retries, MLME-SET.confirm status = %d",
2314 			status
2315 		);
2316 	}
2317 	return link_to_linux_err(status);
2318 }
2319 
ca8210_set_promiscuous_mode(struct ieee802154_hw * hw,const bool on)2320 static int ca8210_set_promiscuous_mode(struct ieee802154_hw *hw, const bool on)
2321 {
2322 	u8 status;
2323 	struct ca8210_priv *priv = hw->priv;
2324 
2325 	status = mlme_set_request_sync(
2326 		MAC_PROMISCUOUS_MODE,
2327 		0,
2328 		1,
2329 		(const void *)&on,
2330 		priv->spi
2331 	);
2332 	if (status) {
2333 		dev_err(
2334 			&priv->spi->dev,
2335 			"error setting promiscuous mode, MLME-SET.confirm status = %d",
2336 			status
2337 		);
2338 	} else {
2339 		priv->promiscuous = on;
2340 	}
2341 	return link_to_linux_err(status);
2342 }
2343 
2344 static const struct ieee802154_ops ca8210_phy_ops = {
2345 	.start = ca8210_start,
2346 	.stop = ca8210_stop,
2347 	.xmit_async = ca8210_xmit_async,
2348 	.ed = ca8210_get_ed,
2349 	.set_channel = ca8210_set_channel,
2350 	.set_hw_addr_filt = ca8210_set_hw_addr_filt,
2351 	.set_txpower = ca8210_set_tx_power,
2352 	.set_cca_mode = ca8210_set_cca_mode,
2353 	.set_cca_ed_level = ca8210_set_cca_ed_level,
2354 	.set_csma_params = ca8210_set_csma_params,
2355 	.set_frame_retries = ca8210_set_frame_retries,
2356 	.set_promiscuous_mode = ca8210_set_promiscuous_mode
2357 };
2358 
2359 /* Test/EVBME Interface */
2360 
2361 /**
2362  * ca8210_test_int_open() - Opens the test interface to the userspace
2363  * @inodp:  inode representation of file interface
2364  * @filp:   file interface
2365  *
2366  * Return: 0 or linux error code
2367  */
ca8210_test_int_open(struct inode * inodp,struct file * filp)2368 static int ca8210_test_int_open(struct inode *inodp, struct file *filp)
2369 {
2370 	struct ca8210_priv *priv = inodp->i_private;
2371 
2372 	filp->private_data = priv;
2373 	return 0;
2374 }
2375 
2376 /**
2377  * ca8210_test_check_upstream() - Checks a command received from the upstream
2378  *                                testing interface for required action
2379  * @buf:        Buffer containing command to check
2380  * @device_ref: Nondescript pointer to target device
2381  *
2382  * Return: 0 or linux error code
2383  */
ca8210_test_check_upstream(u8 * buf,void * device_ref)2384 static int ca8210_test_check_upstream(u8 *buf, void *device_ref)
2385 {
2386 	int ret;
2387 	u8 response[CA8210_SPI_BUF_SIZE];
2388 
2389 	if (buf[0] == SPI_MLME_SET_REQUEST) {
2390 		ret = tdme_checkpibattribute(buf[2], buf[4], buf + 5);
2391 		if (ret) {
2392 			response[0]  = SPI_MLME_SET_CONFIRM;
2393 			response[1] = 3;
2394 			response[2] = IEEE802154_INVALID_PARAMETER;
2395 			response[3] = buf[2];
2396 			response[4] = buf[3];
2397 			if (cascoda_api_upstream)
2398 				cascoda_api_upstream(response, 5, device_ref);
2399 			return ret;
2400 		}
2401 	}
2402 	if (buf[0] == SPI_MLME_ASSOCIATE_REQUEST) {
2403 		return tdme_channelinit(buf[2], device_ref);
2404 	} else if (buf[0] == SPI_MLME_START_REQUEST) {
2405 		return tdme_channelinit(buf[4], device_ref);
2406 	} else if (
2407 		(buf[0] == SPI_MLME_SET_REQUEST) &&
2408 		(buf[2] == PHY_CURRENT_CHANNEL)
2409 	) {
2410 		return tdme_channelinit(buf[5], device_ref);
2411 	} else if (
2412 		(buf[0] == SPI_TDME_SET_REQUEST) &&
2413 		(buf[2] == TDME_CHANNEL)
2414 	) {
2415 		return tdme_channelinit(buf[4], device_ref);
2416 	} else if (
2417 		(CA8210_MAC_WORKAROUNDS) &&
2418 		(buf[0] == SPI_MLME_RESET_REQUEST) &&
2419 		(buf[2] == 1)
2420 	) {
2421 		/* reset COORD Bit for Channel Filtering as Coordinator */
2422 		return tdme_setsfr_request_sync(
2423 			0,
2424 			CA8210_SFR_MACCON,
2425 			0,
2426 			device_ref
2427 		);
2428 	}
2429 	return 0;
2430 } /* End of EVBMECheckSerialCommand() */
2431 
2432 /**
2433  * ca8210_test_int_user_write() - Called by a process in userspace to send a
2434  *                                message to the ca8210 drivers
2435  * @filp:    file interface
2436  * @in_buf:  Buffer containing message to write
2437  * @len:     length of message
2438  * @off:     file offset
2439  *
2440  * Return: 0 or linux error code
2441  */
ca8210_test_int_user_write(struct file * filp,const char __user * in_buf,size_t len,loff_t * off)2442 static ssize_t ca8210_test_int_user_write(
2443 	struct file        *filp,
2444 	const char __user  *in_buf,
2445 	size_t              len,
2446 	loff_t             *off
2447 )
2448 {
2449 	int ret;
2450 	struct ca8210_priv *priv = filp->private_data;
2451 	u8 command[CA8210_SPI_BUF_SIZE];
2452 
2453 	memset(command, SPI_IDLE, 6);
2454 	if (len > CA8210_SPI_BUF_SIZE || len < 2) {
2455 		dev_warn(
2456 			&priv->spi->dev,
2457 			"userspace requested erroneous write length (%zu)\n",
2458 			len
2459 		);
2460 		return -EBADE;
2461 	}
2462 
2463 	ret = copy_from_user(command, in_buf, len);
2464 	if (ret) {
2465 		dev_err(
2466 			&priv->spi->dev,
2467 			"%d bytes could not be copied from userspace\n",
2468 			ret
2469 		);
2470 		return -EIO;
2471 	}
2472 	if (len != command[1] + 2) {
2473 		dev_err(
2474 			&priv->spi->dev,
2475 			"write len does not match packet length field\n"
2476 		);
2477 		return -EBADE;
2478 	}
2479 
2480 	ret = ca8210_test_check_upstream(command, priv->spi);
2481 	if (ret == 0) {
2482 		ret = ca8210_spi_exchange(
2483 			command,
2484 			command[1] + 2,
2485 			NULL,
2486 			priv->spi
2487 		);
2488 		if (ret < 0) {
2489 			/* effectively 0 bytes were written successfully */
2490 			dev_err(
2491 				&priv->spi->dev,
2492 				"spi exchange failed\n"
2493 			);
2494 			return ret;
2495 		}
2496 		if (command[0] & SPI_SYN)
2497 			priv->sync_down++;
2498 	}
2499 
2500 	return len;
2501 }
2502 
2503 /**
2504  * ca8210_test_int_user_read() - Called by a process in userspace to read a
2505  *                               message from the ca8210 drivers
2506  * @filp:  file interface
2507  * @buf:   Buffer to write message to
2508  * @len:   length of message to read (ignored)
2509  * @offp:  file offset
2510  *
2511  * If the O_NONBLOCK flag was set when opening the file then this function will
2512  * not block, i.e. it will return if the fifo is empty. Otherwise the function
2513  * will block, i.e. wait until new data arrives.
2514  *
2515  * Return: number of bytes read
2516  */
ca8210_test_int_user_read(struct file * filp,char __user * buf,size_t len,loff_t * offp)2517 static ssize_t ca8210_test_int_user_read(
2518 	struct file  *filp,
2519 	char __user  *buf,
2520 	size_t        len,
2521 	loff_t       *offp
2522 )
2523 {
2524 	int i, cmdlen;
2525 	struct ca8210_priv *priv = filp->private_data;
2526 	unsigned char *fifo_buffer;
2527 	unsigned long bytes_not_copied;
2528 
2529 	if (filp->f_flags & O_NONBLOCK) {
2530 		/* Non-blocking mode */
2531 		if (kfifo_is_empty(&priv->test.up_fifo))
2532 			return 0;
2533 	} else {
2534 		/* Blocking mode */
2535 		wait_event_interruptible(
2536 			priv->test.readq,
2537 			!kfifo_is_empty(&priv->test.up_fifo)
2538 		);
2539 	}
2540 
2541 	if (kfifo_out(&priv->test.up_fifo, &fifo_buffer, 4) != 4) {
2542 		dev_err(
2543 			&priv->spi->dev,
2544 			"test_interface: Wrong number of elements popped from upstream fifo\n"
2545 		);
2546 		return 0;
2547 	}
2548 	cmdlen = fifo_buffer[1];
2549 	bytes_not_copied = cmdlen + 2;
2550 
2551 	bytes_not_copied = copy_to_user(buf, fifo_buffer, bytes_not_copied);
2552 	if (bytes_not_copied > 0) {
2553 		dev_err(
2554 			&priv->spi->dev,
2555 			"%lu bytes could not be copied to user space!\n",
2556 			bytes_not_copied
2557 		);
2558 	}
2559 
2560 	dev_dbg(&priv->spi->dev, "test_interface: Cmd len = %d\n", cmdlen);
2561 
2562 	dev_dbg(&priv->spi->dev, "test_interface: Read\n");
2563 	for (i = 0; i < cmdlen + 2; i++)
2564 		dev_dbg(&priv->spi->dev, "%#03x\n", fifo_buffer[i]);
2565 
2566 	kfree(fifo_buffer);
2567 
2568 	return cmdlen + 2;
2569 }
2570 
2571 /**
2572  * ca8210_test_int_ioctl() - Called by a process in userspace to enact an
2573  *                           arbitrary action
2574  * @filp:        file interface
2575  * @ioctl_num:   which action to enact
2576  * @ioctl_param: arbitrary parameter for the action
2577  *
2578  * Return: status
2579  */
ca8210_test_int_ioctl(struct file * filp,unsigned int ioctl_num,unsigned long ioctl_param)2580 static long ca8210_test_int_ioctl(
2581 	struct file *filp,
2582 	unsigned int ioctl_num,
2583 	unsigned long ioctl_param
2584 )
2585 {
2586 	struct ca8210_priv *priv = filp->private_data;
2587 
2588 	switch (ioctl_num) {
2589 	case CA8210_IOCTL_HARD_RESET:
2590 		ca8210_reset_send(priv->spi, ioctl_param);
2591 		break;
2592 	default:
2593 		break;
2594 	}
2595 	return 0;
2596 }
2597 
2598 /**
2599  * ca8210_test_int_poll() - Called by a process in userspace to determine which
2600  *                          actions are currently possible for the file
2601  * @filp:   file interface
2602  * @ptable: poll table
2603  *
2604  * Return: set of poll return flags
2605  */
ca8210_test_int_poll(struct file * filp,struct poll_table_struct * ptable)2606 static __poll_t ca8210_test_int_poll(
2607 	struct file *filp,
2608 	struct poll_table_struct *ptable
2609 )
2610 {
2611 	__poll_t return_flags = 0;
2612 	struct ca8210_priv *priv = filp->private_data;
2613 
2614 	poll_wait(filp, &priv->test.readq, ptable);
2615 	if (!kfifo_is_empty(&priv->test.up_fifo))
2616 		return_flags |= (EPOLLIN | EPOLLRDNORM);
2617 	if (wait_event_interruptible(
2618 		priv->test.readq,
2619 		!kfifo_is_empty(&priv->test.up_fifo))) {
2620 		return EPOLLERR;
2621 	}
2622 	return return_flags;
2623 }
2624 
2625 static const struct file_operations test_int_fops = {
2626 	.read =           ca8210_test_int_user_read,
2627 	.write =          ca8210_test_int_user_write,
2628 	.open =           ca8210_test_int_open,
2629 	.release =        NULL,
2630 	.unlocked_ioctl = ca8210_test_int_ioctl,
2631 	.poll =           ca8210_test_int_poll
2632 };
2633 
2634 /* Init/Deinit */
2635 
2636 /**
2637  * ca8210_get_platform_data() - Populate a ca8210_platform_data object
2638  * @spi_device:  Pointer to ca8210 spi device object to get data for
2639  * @pdata:       Pointer to ca8210_platform_data object to populate
2640  *
2641  * Return: 0 or linux error code
2642  */
ca8210_get_platform_data(struct spi_device * spi_device,struct ca8210_platform_data * pdata)2643 static int ca8210_get_platform_data(
2644 	struct spi_device *spi_device,
2645 	struct ca8210_platform_data *pdata
2646 )
2647 {
2648 	int ret = 0;
2649 
2650 	if (!spi_device->dev.of_node)
2651 		return -EINVAL;
2652 
2653 	pdata->extclockenable = of_property_read_bool(
2654 		spi_device->dev.of_node,
2655 		"extclock-enable"
2656 	);
2657 	if (pdata->extclockenable) {
2658 		ret = of_property_read_u32(
2659 			spi_device->dev.of_node,
2660 			"extclock-freq",
2661 			&pdata->extclockfreq
2662 		);
2663 		if (ret < 0)
2664 			return ret;
2665 
2666 		ret = of_property_read_u32(
2667 			spi_device->dev.of_node,
2668 			"extclock-gpio",
2669 			&pdata->extclockgpio
2670 		);
2671 	}
2672 
2673 	return ret;
2674 }
2675 
2676 /**
2677  * ca8210_config_extern_clk() - Configure the external clock provided by the
2678  *                              ca8210
2679  * @pdata:  Pointer to ca8210_platform_data containing clock parameters
2680  * @spi:    Pointer to target ca8210 spi device
2681  * @on:	    True to turn the clock on, false to turn off
2682  *
2683  * The external clock is configured with a frequency and output pin taken from
2684  * the platform data.
2685  *
2686  * Return: 0 or linux error code
2687  */
ca8210_config_extern_clk(struct ca8210_platform_data * pdata,struct spi_device * spi,bool on)2688 static int ca8210_config_extern_clk(
2689 	struct ca8210_platform_data *pdata,
2690 	struct spi_device *spi,
2691 	bool on
2692 )
2693 {
2694 	u8 clkparam[2];
2695 
2696 	if (on) {
2697 		dev_info(&spi->dev, "Switching external clock on\n");
2698 		switch (pdata->extclockfreq) {
2699 		case SIXTEEN_MHZ:
2700 			clkparam[0] = 1;
2701 			break;
2702 		case EIGHT_MHZ:
2703 			clkparam[0] = 2;
2704 			break;
2705 		case FOUR_MHZ:
2706 			clkparam[0] = 3;
2707 			break;
2708 		case TWO_MHZ:
2709 			clkparam[0] = 4;
2710 			break;
2711 		case ONE_MHZ:
2712 			clkparam[0] = 5;
2713 			break;
2714 		default:
2715 			dev_crit(&spi->dev, "Invalid extclock-freq\n");
2716 			return -EINVAL;
2717 		}
2718 		clkparam[1] = pdata->extclockgpio;
2719 	} else {
2720 		dev_info(&spi->dev, "Switching external clock off\n");
2721 		clkparam[0] = 0; /* off */
2722 		clkparam[1] = 0;
2723 	}
2724 	return link_to_linux_err(
2725 		hwme_set_request_sync(HWME_SYSCLKOUT, 2, clkparam, spi)
2726 	);
2727 }
2728 
2729 /**
2730  * ca8210_register_ext_clock() - Register ca8210's external clock with kernel
2731  * @spi:  Pointer to target ca8210 spi device
2732  *
2733  * Return: 0 or linux error code
2734  */
ca8210_register_ext_clock(struct spi_device * spi)2735 static int ca8210_register_ext_clock(struct spi_device *spi)
2736 {
2737 	struct device *dev = &spi->dev;
2738 	struct ca8210_platform_data *pdata = dev_get_platdata(dev);
2739 	struct device_node *np = spi->dev.of_node;
2740 	struct ca8210_priv *priv = spi_get_drvdata(spi);
2741 
2742 	if (!np)
2743 		return -EFAULT;
2744 
2745 	priv->clk = clk_register_fixed_rate(
2746 		&spi->dev,
2747 		np->name,
2748 		NULL,
2749 		0,
2750 		pdata->extclockfreq
2751 	);
2752 
2753 	if (IS_ERR(priv->clk)) {
2754 		dev_crit(&spi->dev, "Failed to register external clk\n");
2755 		return PTR_ERR(priv->clk);
2756 	}
2757 
2758 	return of_clk_add_provider(np, of_clk_src_simple_get, priv->clk);
2759 }
2760 
2761 /**
2762  * ca8210_unregister_ext_clock() - Unregister ca8210's external clock with
2763  *                                 kernel
2764  * @spi:  Pointer to target ca8210 spi device
2765  */
ca8210_unregister_ext_clock(struct spi_device * spi)2766 static void ca8210_unregister_ext_clock(struct spi_device *spi)
2767 {
2768 	struct ca8210_priv *priv = spi_get_drvdata(spi);
2769 
2770 	if (IS_ERR_OR_NULL(priv->clk))
2771 		return;
2772 
2773 	of_clk_del_provider(spi->dev.of_node);
2774 	clk_unregister(priv->clk);
2775 	dev_info(&spi->dev, "External clock unregistered\n");
2776 }
2777 
2778 /**
2779  * ca8210_reset_init() - Initialise the reset input to the ca8210
2780  * @spi:  Pointer to target ca8210 spi device
2781  *
2782  * Return: 0 or linux error code
2783  */
ca8210_reset_init(struct spi_device * spi)2784 static int ca8210_reset_init(struct spi_device *spi)
2785 {
2786 	struct device *dev = &spi->dev;
2787 	struct ca8210_platform_data *pdata = dev_get_platdata(dev);
2788 
2789 	pdata->reset_gpio = devm_gpiod_get(dev, "reset", GPIOD_OUT_LOW);
2790 	if (IS_ERR(pdata->reset_gpio)) {
2791 		dev_crit(dev, "Reset GPIO did not set to output mode\n");
2792 		return PTR_ERR(pdata->reset_gpio);
2793 	}
2794 
2795 	return 0;
2796 }
2797 
2798 /**
2799  * ca8210_interrupt_init() - Initialise the irq output from the ca8210
2800  * @spi:  Pointer to target ca8210 spi device
2801  *
2802  * Return: 0 or linux error code
2803  */
ca8210_interrupt_init(struct spi_device * spi)2804 static int ca8210_interrupt_init(struct spi_device *spi)
2805 {
2806 	struct device *dev = &spi->dev;
2807 	struct ca8210_platform_data *pdata = dev_get_platdata(dev);
2808 	int ret;
2809 
2810 	pdata->irq_gpio = devm_gpiod_get(dev, "irq", GPIOD_IN);
2811 	if (IS_ERR(pdata->irq_gpio)) {
2812 		dev_crit(dev, "Could not retrieve IRQ GPIO\n");
2813 		return PTR_ERR(pdata->irq_gpio);
2814 	}
2815 
2816 	pdata->irq_id = gpiod_to_irq(pdata->irq_gpio);
2817 	if (pdata->irq_id < 0) {
2818 		dev_crit(dev, "Could not get irq for IRQ GPIO\n");
2819 		return pdata->irq_id;
2820 	}
2821 
2822 	ret = request_irq(
2823 		pdata->irq_id,
2824 		ca8210_interrupt_handler,
2825 		IRQF_TRIGGER_FALLING,
2826 		"ca8210-irq",
2827 		spi_get_drvdata(spi)
2828 	);
2829 	if (ret)
2830 		dev_crit(&spi->dev, "request_irq %d failed\n", pdata->irq_id);
2831 
2832 	return ret;
2833 }
2834 
2835 /**
2836  * ca8210_dev_com_init() - Initialise the spi communication component
2837  * @priv:  Pointer to private data structure
2838  *
2839  * Return: 0 or linux error code
2840  */
ca8210_dev_com_init(struct ca8210_priv * priv)2841 static int ca8210_dev_com_init(struct ca8210_priv *priv)
2842 {
2843 	priv->mlme_workqueue = alloc_ordered_workqueue("MLME work queue", 0);
2844 	if (!priv->mlme_workqueue) {
2845 		dev_crit(&priv->spi->dev, "alloc of mlme_workqueue failed!\n");
2846 		return -ENOMEM;
2847 	}
2848 
2849 	priv->irq_workqueue = alloc_ordered_workqueue("ca8210 irq worker", 0);
2850 	if (!priv->irq_workqueue) {
2851 		dev_crit(&priv->spi->dev, "alloc of irq_workqueue failed!\n");
2852 		destroy_workqueue(priv->mlme_workqueue);
2853 		return -ENOMEM;
2854 	}
2855 
2856 	return 0;
2857 }
2858 
2859 /**
2860  * ca8210_dev_com_clear() - Deinitialise the spi communication component
2861  * @priv:  Pointer to private data structure
2862  */
ca8210_dev_com_clear(struct ca8210_priv * priv)2863 static void ca8210_dev_com_clear(struct ca8210_priv *priv)
2864 {
2865 	destroy_workqueue(priv->mlme_workqueue);
2866 	destroy_workqueue(priv->irq_workqueue);
2867 }
2868 
2869 #define CA8210_MAX_TX_POWERS (9)
2870 static const s32 ca8210_tx_powers[CA8210_MAX_TX_POWERS] = {
2871 	800, 700, 600, 500, 400, 300, 200, 100, 0
2872 };
2873 
2874 #define CA8210_MAX_ED_LEVELS (21)
2875 static const s32 ca8210_ed_levels[CA8210_MAX_ED_LEVELS] = {
2876 	-10300, -10250, -10200, -10150, -10100, -10050, -10000, -9950, -9900,
2877 	-9850, -9800, -9750, -9700, -9650, -9600, -9550, -9500, -9450, -9400,
2878 	-9350, -9300
2879 };
2880 
2881 /**
2882  * ca8210_hw_setup() - Populate the ieee802154_hw phy attributes with the
2883  *                     ca8210's defaults
2884  * @ca8210_hw:  Pointer to ieee802154_hw to populate
2885  */
ca8210_hw_setup(struct ieee802154_hw * ca8210_hw)2886 static void ca8210_hw_setup(struct ieee802154_hw *ca8210_hw)
2887 {
2888 	/* Support channels 11-26 */
2889 	ca8210_hw->phy->supported.channels[0] = CA8210_VALID_CHANNELS;
2890 	ca8210_hw->phy->supported.tx_powers_size = CA8210_MAX_TX_POWERS;
2891 	ca8210_hw->phy->supported.tx_powers = ca8210_tx_powers;
2892 	ca8210_hw->phy->supported.cca_ed_levels_size = CA8210_MAX_ED_LEVELS;
2893 	ca8210_hw->phy->supported.cca_ed_levels = ca8210_ed_levels;
2894 	ca8210_hw->phy->current_channel = 18;
2895 	ca8210_hw->phy->current_page = 0;
2896 	ca8210_hw->phy->transmit_power = 800;
2897 	ca8210_hw->phy->cca.mode = NL802154_CCA_ENERGY_CARRIER;
2898 	ca8210_hw->phy->cca.opt = NL802154_CCA_OPT_ENERGY_CARRIER_AND;
2899 	ca8210_hw->phy->cca_ed_level = -9800;
2900 	ca8210_hw->phy->symbol_duration = 16;
2901 	ca8210_hw->phy->lifs_period = 40 * ca8210_hw->phy->symbol_duration;
2902 	ca8210_hw->phy->sifs_period = 12 * ca8210_hw->phy->symbol_duration;
2903 	ca8210_hw->flags =
2904 		IEEE802154_HW_AFILT |
2905 		IEEE802154_HW_OMIT_CKSUM |
2906 		IEEE802154_HW_FRAME_RETRIES |
2907 		IEEE802154_HW_PROMISCUOUS |
2908 		IEEE802154_HW_CSMA_PARAMS;
2909 	ca8210_hw->phy->flags =
2910 		WPAN_PHY_FLAG_TXPOWER |
2911 		WPAN_PHY_FLAG_CCA_ED_LEVEL |
2912 		WPAN_PHY_FLAG_CCA_MODE |
2913 		WPAN_PHY_FLAG_DATAGRAMS_ONLY;
2914 }
2915 
2916 /**
2917  * ca8210_test_interface_init() - Initialise the test file interface
2918  * @priv:  Pointer to private data structure
2919  *
2920  * Provided as an alternative to the standard linux network interface, the test
2921  * interface exposes a file in the filesystem (ca8210_test) that allows
2922  * 802.15.4 SAP Commands and Cascoda EVBME commands to be sent directly to
2923  * the stack.
2924  *
2925  * Return: 0 or linux error code
2926  */
ca8210_test_interface_init(struct ca8210_priv * priv)2927 static int ca8210_test_interface_init(struct ca8210_priv *priv)
2928 {
2929 	struct ca8210_test *test = &priv->test;
2930 	char node_name[32];
2931 
2932 	snprintf(
2933 		node_name,
2934 		sizeof(node_name),
2935 		"ca8210@%d_%d",
2936 		priv->spi->controller->bus_num,
2937 		spi_get_chipselect(priv->spi, 0)
2938 	);
2939 
2940 	test->ca8210_dfs_spi_int = debugfs_create_file(
2941 		node_name,
2942 		0600, /* S_IRUSR | S_IWUSR */
2943 		NULL,
2944 		priv,
2945 		&test_int_fops
2946 	);
2947 
2948 	debugfs_create_symlink("ca8210", NULL, node_name);
2949 	init_waitqueue_head(&test->readq);
2950 	return kfifo_alloc(
2951 		&test->up_fifo,
2952 		CA8210_TEST_INT_FIFO_SIZE,
2953 		GFP_KERNEL
2954 	);
2955 }
2956 
2957 /**
2958  * ca8210_test_interface_clear() - Deinitialise the test file interface
2959  * @priv:  Pointer to private data structure
2960  */
ca8210_test_interface_clear(struct ca8210_priv * priv)2961 static void ca8210_test_interface_clear(struct ca8210_priv *priv)
2962 {
2963 	struct ca8210_test *test = &priv->test;
2964 
2965 	debugfs_remove(test->ca8210_dfs_spi_int);
2966 	kfifo_free(&test->up_fifo);
2967 	dev_info(&priv->spi->dev, "Test interface removed\n");
2968 }
2969 
2970 /**
2971  * ca8210_remove() - Shut down a ca8210 upon being disconnected
2972  * @spi_device:  Pointer to spi device data structure
2973  *
2974  * Return: 0 or linux error code
2975  */
ca8210_remove(struct spi_device * spi_device)2976 static void ca8210_remove(struct spi_device *spi_device)
2977 {
2978 	struct ca8210_priv *priv;
2979 	struct ca8210_platform_data *pdata;
2980 
2981 	dev_info(&spi_device->dev, "Removing ca8210\n");
2982 
2983 	pdata = spi_device->dev.platform_data;
2984 	if (pdata) {
2985 		if (pdata->extclockenable) {
2986 			ca8210_unregister_ext_clock(spi_device);
2987 			ca8210_config_extern_clk(pdata, spi_device, 0);
2988 		}
2989 		free_irq(pdata->irq_id, spi_device->dev.driver_data);
2990 		kfree(pdata);
2991 		spi_device->dev.platform_data = NULL;
2992 	}
2993 	/* get spi_device private data */
2994 	priv = spi_get_drvdata(spi_device);
2995 	if (priv) {
2996 		dev_info(
2997 			&spi_device->dev,
2998 			"sync_down = %d, sync_up = %d\n",
2999 			priv->sync_down,
3000 			priv->sync_up
3001 		);
3002 		ca8210_dev_com_clear(spi_device->dev.driver_data);
3003 		if (priv->hw) {
3004 			if (priv->hw_registered)
3005 				ieee802154_unregister_hw(priv->hw);
3006 			ieee802154_free_hw(priv->hw);
3007 			priv->hw = NULL;
3008 			dev_info(
3009 				&spi_device->dev,
3010 				"Unregistered & freed ieee802154_hw.\n"
3011 			);
3012 		}
3013 		if (IS_ENABLED(CONFIG_IEEE802154_CA8210_DEBUGFS))
3014 			ca8210_test_interface_clear(priv);
3015 	}
3016 }
3017 
3018 /**
3019  * ca8210_probe() - Set up a connected ca8210 upon being detected by the system
3020  * @spi_device:  Pointer to spi device data structure
3021  *
3022  * Return: 0 or linux error code
3023  */
ca8210_probe(struct spi_device * spi_device)3024 static int ca8210_probe(struct spi_device *spi_device)
3025 {
3026 	struct ca8210_priv *priv;
3027 	struct ieee802154_hw *hw;
3028 	struct ca8210_platform_data *pdata;
3029 	int ret;
3030 
3031 	dev_info(&spi_device->dev, "Inserting ca8210\n");
3032 
3033 	/* allocate ieee802154_hw and private data */
3034 	hw = ieee802154_alloc_hw(sizeof(struct ca8210_priv), &ca8210_phy_ops);
3035 	if (!hw) {
3036 		dev_crit(&spi_device->dev, "ieee802154_alloc_hw failed\n");
3037 		ret = -ENOMEM;
3038 		goto error;
3039 	}
3040 
3041 	priv = hw->priv;
3042 	priv->hw = hw;
3043 	priv->spi = spi_device;
3044 	hw->parent = &spi_device->dev;
3045 	spin_lock_init(&priv->lock);
3046 	priv->async_tx_pending = false;
3047 	priv->hw_registered = false;
3048 	priv->sync_up = 0;
3049 	priv->sync_down = 0;
3050 	priv->promiscuous = false;
3051 	priv->retries = 0;
3052 	init_completion(&priv->ca8210_is_awake);
3053 	init_completion(&priv->spi_transfer_complete);
3054 	init_completion(&priv->sync_exchange_complete);
3055 	spi_set_drvdata(priv->spi, priv);
3056 	if (IS_ENABLED(CONFIG_IEEE802154_CA8210_DEBUGFS)) {
3057 		cascoda_api_upstream = ca8210_test_int_driver_write;
3058 		ret = ca8210_test_interface_init(priv);
3059 		if (ret) {
3060 			dev_crit(&spi_device->dev, "ca8210_test_interface_init failed\n");
3061 			goto error;
3062 		}
3063 	} else {
3064 		cascoda_api_upstream = NULL;
3065 	}
3066 	ca8210_hw_setup(hw);
3067 	ieee802154_random_extended_addr(&hw->phy->perm_extended_addr);
3068 
3069 	pdata = kmalloc_obj(*pdata);
3070 	if (!pdata) {
3071 		ret = -ENOMEM;
3072 		goto error;
3073 	}
3074 
3075 	priv->spi->dev.platform_data = pdata;
3076 	ret = ca8210_get_platform_data(priv->spi, pdata);
3077 	if (ret) {
3078 		dev_crit(&spi_device->dev, "ca8210_get_platform_data failed\n");
3079 		goto error;
3080 	}
3081 
3082 	ret = ca8210_dev_com_init(priv);
3083 	if (ret) {
3084 		dev_crit(&spi_device->dev, "ca8210_dev_com_init failed\n");
3085 		goto error;
3086 	}
3087 	ret = ca8210_reset_init(priv->spi);
3088 	if (ret) {
3089 		dev_crit(&spi_device->dev, "ca8210_reset_init failed\n");
3090 		goto error;
3091 	}
3092 
3093 	ret = ca8210_interrupt_init(priv->spi);
3094 	if (ret) {
3095 		dev_crit(&spi_device->dev, "ca8210_interrupt_init failed\n");
3096 		goto error;
3097 	}
3098 
3099 	msleep(100);
3100 
3101 	ca8210_reset_send(priv->spi, 1);
3102 
3103 	ret = tdme_chipinit(priv->spi);
3104 	if (ret) {
3105 		dev_crit(&spi_device->dev, "tdme_chipinit failed\n");
3106 		goto error;
3107 	}
3108 
3109 	if (pdata->extclockenable) {
3110 		ret = ca8210_config_extern_clk(pdata, priv->spi, 1);
3111 		if (ret) {
3112 			dev_crit(
3113 				&spi_device->dev,
3114 				"ca8210_config_extern_clk failed\n"
3115 			);
3116 			goto error;
3117 		}
3118 		ret = ca8210_register_ext_clock(priv->spi);
3119 		if (ret) {
3120 			dev_crit(
3121 				&spi_device->dev,
3122 				"ca8210_register_ext_clock failed\n"
3123 			);
3124 			goto error;
3125 		}
3126 	}
3127 
3128 	ret = ieee802154_register_hw(hw);
3129 	if (ret) {
3130 		dev_crit(&spi_device->dev, "ieee802154_register_hw failed\n");
3131 		goto error;
3132 	}
3133 	priv->hw_registered = true;
3134 
3135 	return 0;
3136 error:
3137 	msleep(100); /* wait for pending spi transfers to complete */
3138 	ca8210_remove(spi_device);
3139 	return link_to_linux_err(ret);
3140 }
3141 
3142 static const struct of_device_id ca8210_of_ids[] = {
3143 	{.compatible = "cascoda,ca8210", },
3144 	{},
3145 };
3146 MODULE_DEVICE_TABLE(of, ca8210_of_ids);
3147 
3148 static struct spi_driver ca8210_spi_driver = {
3149 	.driver = {
3150 		.name =                 DRIVER_NAME,
3151 		.of_match_table =       ca8210_of_ids,
3152 	},
3153 	.probe  =                       ca8210_probe,
3154 	.remove =                       ca8210_remove
3155 };
3156 
3157 module_spi_driver(ca8210_spi_driver);
3158 
3159 MODULE_AUTHOR("Harry Morris <h.morris@cascoda.com>");
3160 MODULE_DESCRIPTION("CA-8210 SoftMAC driver");
3161 MODULE_LICENSE("Dual BSD/GPL");
3162 MODULE_VERSION("1.0");
3163