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