xref: /linux/drivers/staging/fieldbus/anybuss/host.c (revision 0be3ff0c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * HMS Anybus-S Host Driver
4  *
5  * Copyright (C) 2018 Arcx Inc
6  */
7 
8 /*
9  * Architecture Overview
10  * =====================
11  * This driver (running on the CPU/SoC) and the Anybus-S card communicate
12  * by reading and writing data to/from the Anybus-S Dual-Port RAM (dpram).
13  * This is memory connected to both the SoC and Anybus-S card, which both sides
14  * can access freely and concurrently.
15  *
16  * Synchronization happens by means of two registers located in the dpram:
17  * IND_AB: written exclusively by the Anybus card; and
18  * IND_AP: written exclusively by this driver.
19  *
20  * Communication happens using one of the following mechanisms:
21  * 1. reserve, read/write, release dpram memory areas:
22  *	using an IND_AB/IND_AP protocol, the driver is able to reserve certain
23  *	memory areas. no dpram memory can be read or written except if reserved.
24  *	(with a few limited exceptions)
25  * 2. send and receive data structures via a shared mailbox:
26  *	using an IND_AB/IND_AP protocol, the driver and Anybus card are able to
27  *	exchange commands and responses using a shared mailbox.
28  * 3. receive software interrupts:
29  *	using an IND_AB/IND_AP protocol, the Anybus card is able to notify the
30  *	driver of certain events such as: bus online/offline, data available.
31  *	note that software interrupt event bits are located in a memory area
32  *	which must be reserved before it can be accessed.
33  *
34  * The manual[1] is silent on whether these mechanisms can happen concurrently,
35  * or how they should be synchronized. However, section 13 (Driver Example)
36  * provides the following suggestion for developing a driver:
37  * a) an interrupt handler which updates global variables;
38  * b) a continuously-running task handling area requests (1 above)
39  * c) a continuously-running task handling mailbox requests (2 above)
40  * The example conspicuously leaves out software interrupts (3 above), which
41  * is the thorniest issue to get right (see below).
42  *
43  * The naive, straightforward way to implement this would be:
44  * - create an isr which updates shared variables;
45  * - create a work_struct which handles software interrupts on a queue;
46  * - create a function which does reserve/update/unlock in a loop;
47  * - create a function which does mailbox send/receive in a loop;
48  * - call the above functions from the driver's read/write/ioctl;
49  * - synchronize using mutexes/spinlocks:
50  *	+ only one area request at a time
51  *	+ only one mailbox request at a time
52  *	+ protect AB_IND, AB_IND against data hazards (e.g. read-after-write)
53  *
54  * Unfortunately, the presence of the software interrupt causes subtle yet
55  * considerable synchronization issues; especially problematic is the
56  * requirement to reserve/release the area which contains the status bits.
57  *
58  * The driver architecture presented here sidesteps these synchronization issues
59  * by accessing the dpram from a single kernel thread only. User-space throws
60  * "tasks" (i.e. 1, 2 above) into a task queue, waits for their completion,
61  * and the kernel thread runs them to completion.
62  *
63  * Each task has a task_function, which is called/run by the queue thread.
64  * That function communicates with the Anybus card, and returns either
65  * 0 (OK), a negative error code (error), or -EINPROGRESS (waiting).
66  * On OK or error, the queue thread completes and dequeues the task,
67  * which also releases the user space thread which may still be waiting for it.
68  * On -EINPROGRESS (waiting), the queue thread will leave the task on the queue,
69  * and revisit (call again) whenever an interrupt event comes in.
70  *
71  * Each task has a state machine, which is run by calling its task_function.
72  * It ensures that the task will go through its various stages over time,
73  * returning -EINPROGRESS if it wants to wait for an event to happen.
74  *
75  * Note that according to the manual's driver example, the following operations
76  * may run independent of each other:
77  * - area reserve/read/write/release	(point 1 above)
78  * - mailbox operations			(point 2 above)
79  * - switching power on/off
80  *
81  * To allow them to run independently, each operation class gets its own queue.
82  *
83  * Userspace processes A, B, C, D post tasks to the appropriate queue,
84  * and wait for task completion:
85  *
86  *	process A	B	C	D
87  *		|	|	|	|
88  *		v	v	v	v
89  *	|<-----	========================================
90  *	|		|	   |		|
91  *	|		v	   v		v-------<-------+
92  *	|	+--------------------------------------+	|
93  *	|	| power q     | mbox q    | area q     |	|
94  *	|	|------------|------------|------------|	|
95  *	|	| task       | task       | task       |	|
96  *	|	| task       | task       | task       |	|
97  *	|	| task wait  | task wait  | task wait  |	|
98  *	|	+--------------------------------------+	|
99  *	|		^	   ^		^		|
100  *	|		|	   |		|		^
101  *	|	+--------------------------------------+	|
102  *	|	|	     queue thread	       |	|
103  *	|	|--------------------------------------|	|
104  *	|	| single-threaded:		       |	|
105  *	|	| loop:				       |	|
106  *	v	|   for each queue:		       |	|
107  *	|	|     run task state machine	       |	|
108  *	|	|     if task waiting:		       |	|
109  *	|	|       leave on queue		       |	|
110  *	|	|     if task done:		       |	|
111  *	|	|       complete task, remove from q   |	|
112  *	|	|   if software irq event bits set:    |	|
113  *	|	|     notify userspace		       |	|
114  *	|	|     post clear event bits task------>|>-------+
115  *	|	|   wait for IND_AB changed event OR   |
116  *	|	|            task added event	  OR   |
117  *	|	|	     timeout		       |
118  *	|	| end loop			       |
119  *	|	+--------------------------------------+
120  *	|	+		wake up		       +
121  *	|	+--------------------------------------+
122  *	|		^			^
123  *	|		|			|
124  *	+-------->-------			|
125  *						|
126  *		+--------------------------------------+
127  *		|	interrupt service routine      |
128  *		|--------------------------------------|
129  *		| wake up queue thread on IND_AB change|
130  *		+--------------------------------------+
131  *
132  * Note that the Anybus interrupt is dual-purpose:
133  * - after a reset, triggered when the card becomes ready;
134  * - during normal operation, triggered when AB_IND changes.
135  * This is why the interrupt service routine doesn't just wake up the
136  * queue thread, but also completes the card_boot completion.
137  *
138  * [1] https://www.anybus.com/docs/librariesprovider7/default-document-library/
139  *	manuals-design-guides/hms-hmsi-27-275.pdf
140  */
141 
142 #include <linux/kernel.h>
143 #include <linux/module.h>
144 #include <linux/init.h>
145 #include <linux/slab.h>
146 #include <linux/interrupt.h>
147 #include <linux/atomic.h>
148 #include <linux/kthread.h>
149 #include <linux/kfifo.h>
150 #include <linux/spinlock.h>
151 #include <linux/uaccess.h>
152 #include <linux/regmap.h>
153 #include <linux/of.h>
154 #include <linux/random.h>
155 #include <linux/kref.h>
156 #include <linux/of_address.h>
157 
158 /* move to <linux/anybuss-*.h> when taking this out of staging */
159 #include "anybuss-client.h"
160 #include "anybuss-controller.h"
161 
162 #define DPRAM_SIZE		0x800
163 #define MAX_MBOX_MSG_SZ		0x0FF
164 #define TIMEOUT			(HZ * 2)
165 #define MAX_DATA_AREA_SZ	0x200
166 #define MAX_FBCTRL_AREA_SZ	0x1BE
167 
168 #define REG_BOOTLOADER_V	0x7C0
169 #define REG_API_V		0x7C2
170 #define REG_FIELDBUS_V		0x7C4
171 #define REG_SERIAL_NO		0x7C6
172 #define REG_FIELDBUS_TYPE	0x7CC
173 #define REG_MODULE_SW_V		0x7CE
174 #define REG_IND_AB		0x7FF
175 #define REG_IND_AP		0x7FE
176 #define REG_EVENT_CAUSE		0x7ED
177 #define MBOX_IN_AREA		0x400
178 #define MBOX_OUT_AREA		0x520
179 #define DATA_IN_AREA		0x000
180 #define DATA_OUT_AREA		0x200
181 #define FBCTRL_AREA		0x640
182 
183 #define EVENT_CAUSE_DC          0x01
184 #define EVENT_CAUSE_FBOF        0x02
185 #define EVENT_CAUSE_FBON        0x04
186 
187 #define IND_AB_UPDATED		0x08
188 #define IND_AX_MIN		0x80
189 #define IND_AX_MOUT		0x40
190 #define IND_AX_IN		0x04
191 #define IND_AX_OUT		0x02
192 #define IND_AX_FBCTRL		0x01
193 #define IND_AP_LOCK		0x08
194 #define IND_AP_ACTION		0x10
195 #define IND_AX_EVNT		0x20
196 #define IND_AP_ABITS		(IND_AX_IN | IND_AX_OUT | \
197 					IND_AX_FBCTRL | \
198 					IND_AP_ACTION | IND_AP_LOCK)
199 
200 #define INFO_TYPE_FB		0x0002
201 #define INFO_TYPE_APP		0x0001
202 #define INFO_COMMAND		0x4000
203 
204 #define OP_MODE_FBFC		0x0002
205 #define OP_MODE_FBS		0x0004
206 #define OP_MODE_CD		0x0200
207 
208 #define CMD_START_INIT		0x0001
209 #define CMD_ANYBUS_INIT		0x0002
210 #define CMD_END_INIT		0x0003
211 
212 /*
213  * ---------------------------------------------------------------
214  * Anybus mailbox messages - definitions
215  * ---------------------------------------------------------------
216  * note that we're depending on the layout of these structures being
217  * exactly as advertised.
218  */
219 
220 struct anybus_mbox_hdr {
221 	__be16 id;
222 	__be16 info;
223 	__be16 cmd_num;
224 	__be16 data_size;
225 	__be16 frame_count;
226 	__be16 frame_num;
227 	__be16 offset_high;
228 	__be16 offset_low;
229 	__be16 extended[8];
230 };
231 
232 struct msg_anybus_init {
233 	__be16 input_io_len;
234 	__be16 input_dpram_len;
235 	__be16 input_total_len;
236 	__be16 output_io_len;
237 	__be16 output_dpram_len;
238 	__be16 output_total_len;
239 	__be16 op_mode;
240 	__be16 notif_config;
241 	__be16 wd_val;
242 };
243 
244 /* ------------- ref counted tasks ------------- */
245 
246 struct ab_task;
247 typedef int (*ab_task_fn_t)(struct anybuss_host *cd,
248 					struct ab_task *t);
249 typedef void (*ab_done_fn_t)(struct anybuss_host *cd);
250 
251 struct area_priv {
252 	bool is_write;
253 	u16 flags;
254 	u16 addr;
255 	size_t count;
256 	u8 buf[MAX_DATA_AREA_SZ];
257 };
258 
259 struct mbox_priv {
260 	struct anybus_mbox_hdr hdr;
261 	size_t msg_out_sz;
262 	size_t msg_in_sz;
263 	u8 msg[MAX_MBOX_MSG_SZ];
264 };
265 
266 struct ab_task {
267 	struct kmem_cache	*cache;
268 	struct kref		refcount;
269 	ab_task_fn_t		task_fn;
270 	ab_done_fn_t		done_fn;
271 	int			result;
272 	struct completion	done;
273 	unsigned long		start_jiffies;
274 	union {
275 		struct area_priv area_pd;
276 		struct mbox_priv mbox_pd;
277 	};
278 };
279 
280 static struct ab_task *ab_task_create_get(struct kmem_cache *cache,
281 					  ab_task_fn_t task_fn)
282 {
283 	struct ab_task *t;
284 
285 	t = kmem_cache_alloc(cache, GFP_KERNEL);
286 	if (!t)
287 		return NULL;
288 	t->cache = cache;
289 	kref_init(&t->refcount);
290 	t->task_fn = task_fn;
291 	t->done_fn = NULL;
292 	t->result = 0;
293 	init_completion(&t->done);
294 	return t;
295 }
296 
297 static void __ab_task_destroy(struct kref *refcount)
298 {
299 	struct ab_task *t = container_of(refcount, struct ab_task, refcount);
300 	struct kmem_cache *cache = t->cache;
301 
302 	kmem_cache_free(cache, t);
303 }
304 
305 static void ab_task_put(struct ab_task *t)
306 {
307 	kref_put(&t->refcount, __ab_task_destroy);
308 }
309 
310 static struct ab_task *__ab_task_get(struct ab_task *t)
311 {
312 	kref_get(&t->refcount);
313 	return t;
314 }
315 
316 static void __ab_task_finish(struct ab_task *t, struct anybuss_host *cd)
317 {
318 	if (t->done_fn)
319 		t->done_fn(cd);
320 	complete(&t->done);
321 }
322 
323 static void
324 ab_task_dequeue_finish_put(struct kfifo *q, struct anybuss_host *cd)
325 {
326 	int ret;
327 	struct ab_task *t;
328 
329 	ret = kfifo_out(q, &t, sizeof(t));
330 	WARN_ON(!ret);
331 	__ab_task_finish(t, cd);
332 	ab_task_put(t);
333 }
334 
335 static int
336 ab_task_enqueue(struct ab_task *t, struct kfifo *q, spinlock_t *slock,
337 		wait_queue_head_t *wq)
338 {
339 	int ret;
340 
341 	t->start_jiffies = jiffies;
342 	__ab_task_get(t);
343 	ret = kfifo_in_spinlocked(q, &t, sizeof(t), slock);
344 	if (!ret) {
345 		ab_task_put(t);
346 		return -ENOMEM;
347 	}
348 	wake_up(wq);
349 	return 0;
350 }
351 
352 static int
353 ab_task_enqueue_wait(struct ab_task *t, struct kfifo *q, spinlock_t *slock,
354 		     wait_queue_head_t *wq)
355 {
356 	int ret;
357 
358 	ret = ab_task_enqueue(t, q, slock, wq);
359 	if (ret)
360 		return ret;
361 	ret = wait_for_completion_interruptible(&t->done);
362 	if (ret)
363 		return ret;
364 	return t->result;
365 }
366 
367 /* ------------------------ anybus hardware ------------------------ */
368 
369 struct anybuss_host {
370 	struct device *dev;
371 	struct anybuss_client *client;
372 	void (*reset)(struct device *dev, bool assert);
373 	struct regmap *regmap;
374 	int irq;
375 	int host_idx;
376 	struct task_struct *qthread;
377 	wait_queue_head_t wq;
378 	struct completion card_boot;
379 	atomic_t ind_ab;
380 	spinlock_t qlock; /* protects IN side of powerq, mboxq, areaq */
381 	struct kmem_cache *qcache;
382 	struct kfifo qs[3];
383 	struct kfifo *powerq;
384 	struct kfifo *mboxq;
385 	struct kfifo *areaq;
386 	bool power_on;
387 	bool softint_pending;
388 };
389 
390 static void reset_assert(struct anybuss_host *cd)
391 {
392 	cd->reset(cd->dev, true);
393 }
394 
395 static void reset_deassert(struct anybuss_host *cd)
396 {
397 	cd->reset(cd->dev, false);
398 }
399 
400 static int test_dpram(struct regmap *regmap)
401 {
402 	int i;
403 	unsigned int val;
404 
405 	for (i = 0; i < DPRAM_SIZE; i++)
406 		regmap_write(regmap, i, (u8)i);
407 	for (i = 0; i < DPRAM_SIZE; i++) {
408 		regmap_read(regmap, i, &val);
409 		if ((u8)val != (u8)i)
410 			return -EIO;
411 	}
412 	return 0;
413 }
414 
415 static int read_ind_ab(struct regmap *regmap)
416 {
417 	unsigned long timeout = jiffies + HZ / 2;
418 	unsigned int a, b, i = 0;
419 
420 	while (time_before_eq(jiffies, timeout)) {
421 		regmap_read(regmap, REG_IND_AB, &a);
422 		regmap_read(regmap, REG_IND_AB, &b);
423 		if (likely(a == b))
424 			return (int)a;
425 		if (i < 10) {
426 			cpu_relax();
427 			i++;
428 		} else {
429 			usleep_range(500, 1000);
430 		}
431 	}
432 	WARN(1, "IND_AB register not stable");
433 	return -ETIMEDOUT;
434 }
435 
436 static int write_ind_ap(struct regmap *regmap, unsigned int ind_ap)
437 {
438 	unsigned long timeout = jiffies + HZ / 2;
439 	unsigned int v, i = 0;
440 
441 	while (time_before_eq(jiffies, timeout)) {
442 		regmap_write(regmap, REG_IND_AP, ind_ap);
443 		regmap_read(regmap, REG_IND_AP, &v);
444 		if (likely(ind_ap == v))
445 			return 0;
446 		if (i < 10) {
447 			cpu_relax();
448 			i++;
449 		} else {
450 			usleep_range(500, 1000);
451 		}
452 	}
453 	WARN(1, "IND_AP register not stable");
454 	return -ETIMEDOUT;
455 }
456 
457 static irqreturn_t irq_handler(int irq, void *data)
458 {
459 	struct anybuss_host *cd = data;
460 	int ind_ab;
461 
462 	/*
463 	 * irq handler needs exclusive access to the IND_AB register,
464 	 * because the act of reading the register acks the interrupt.
465 	 *
466 	 * store the register value in cd->ind_ab (an atomic_t), so that the
467 	 * queue thread is able to read it without causing an interrupt ack
468 	 * side-effect (and without spuriously acking an interrupt).
469 	 */
470 	ind_ab = read_ind_ab(cd->regmap);
471 	if (ind_ab < 0)
472 		return IRQ_NONE;
473 	atomic_set(&cd->ind_ab, ind_ab);
474 	complete(&cd->card_boot);
475 	wake_up(&cd->wq);
476 	return IRQ_HANDLED;
477 }
478 
479 /* ------------------------ power on/off tasks --------------------- */
480 
481 static int task_fn_power_off(struct anybuss_host *cd,
482 			     struct ab_task *t)
483 {
484 	struct anybuss_client *client = cd->client;
485 
486 	if (!cd->power_on)
487 		return 0;
488 	disable_irq(cd->irq);
489 	reset_assert(cd);
490 	atomic_set(&cd->ind_ab, IND_AB_UPDATED);
491 	if (client->on_online_changed)
492 		client->on_online_changed(client, false);
493 	cd->power_on = false;
494 	return 0;
495 }
496 
497 static int task_fn_power_on_2(struct anybuss_host *cd,
498 			      struct ab_task *t)
499 {
500 	if (completion_done(&cd->card_boot)) {
501 		cd->power_on = true;
502 		return 0;
503 	}
504 	if (time_after(jiffies, t->start_jiffies + TIMEOUT)) {
505 		disable_irq(cd->irq);
506 		reset_assert(cd);
507 		dev_err(cd->dev, "power on timed out");
508 		return -ETIMEDOUT;
509 	}
510 	return -EINPROGRESS;
511 }
512 
513 static int task_fn_power_on(struct anybuss_host *cd,
514 			    struct ab_task *t)
515 {
516 	unsigned int dummy;
517 
518 	if (cd->power_on)
519 		return 0;
520 	/*
521 	 * anybus docs: prevent false 'init done' interrupt by
522 	 * doing a dummy read of IND_AB register while in reset.
523 	 */
524 	regmap_read(cd->regmap, REG_IND_AB, &dummy);
525 	reinit_completion(&cd->card_boot);
526 	enable_irq(cd->irq);
527 	reset_deassert(cd);
528 	t->task_fn = task_fn_power_on_2;
529 	return -EINPROGRESS;
530 }
531 
532 int anybuss_set_power(struct anybuss_client *client, bool power_on)
533 {
534 	struct anybuss_host *cd = client->host;
535 	struct ab_task *t;
536 	int err;
537 
538 	t = ab_task_create_get(cd->qcache, power_on ?
539 				task_fn_power_on : task_fn_power_off);
540 	if (!t)
541 		return -ENOMEM;
542 	err = ab_task_enqueue_wait(t, cd->powerq, &cd->qlock, &cd->wq);
543 	ab_task_put(t);
544 	return err;
545 }
546 EXPORT_SYMBOL_GPL(anybuss_set_power);
547 
548 /* ---------------------------- area tasks ------------------------ */
549 
550 static int task_fn_area_3(struct anybuss_host *cd, struct ab_task *t)
551 {
552 	struct area_priv *pd = &t->area_pd;
553 
554 	if (!cd->power_on)
555 		return -EIO;
556 	if (atomic_read(&cd->ind_ab) & pd->flags) {
557 		/* area not released yet */
558 		if (time_after(jiffies, t->start_jiffies + TIMEOUT))
559 			return -ETIMEDOUT;
560 		return -EINPROGRESS;
561 	}
562 	return 0;
563 }
564 
565 static int task_fn_area_2(struct anybuss_host *cd, struct ab_task *t)
566 {
567 	struct area_priv *pd = &t->area_pd;
568 	unsigned int ind_ap;
569 	int ret;
570 
571 	if (!cd->power_on)
572 		return -EIO;
573 	regmap_read(cd->regmap, REG_IND_AP, &ind_ap);
574 	if (!(atomic_read(&cd->ind_ab) & pd->flags)) {
575 		/* we don't own the area yet */
576 		if (time_after(jiffies, t->start_jiffies + TIMEOUT)) {
577 			dev_warn(cd->dev, "timeout waiting for area");
578 			dump_stack();
579 			return -ETIMEDOUT;
580 		}
581 		return -EINPROGRESS;
582 	}
583 	/* we own the area, do what we're here to do */
584 	if (pd->is_write)
585 		regmap_bulk_write(cd->regmap, pd->addr, pd->buf,
586 				  pd->count);
587 	else
588 		regmap_bulk_read(cd->regmap, pd->addr, pd->buf,
589 				 pd->count);
590 	/* ask to release the area, must use unlocked release */
591 	ind_ap &= ~IND_AP_ABITS;
592 	ind_ap |= pd->flags;
593 	ret = write_ind_ap(cd->regmap, ind_ap);
594 	if (ret)
595 		return ret;
596 	t->task_fn = task_fn_area_3;
597 	return -EINPROGRESS;
598 }
599 
600 static int task_fn_area(struct anybuss_host *cd, struct ab_task *t)
601 {
602 	struct area_priv *pd = &t->area_pd;
603 	unsigned int ind_ap;
604 	int ret;
605 
606 	if (!cd->power_on)
607 		return -EIO;
608 	regmap_read(cd->regmap, REG_IND_AP, &ind_ap);
609 	/* ask to take the area */
610 	ind_ap &= ~IND_AP_ABITS;
611 	ind_ap |= pd->flags | IND_AP_ACTION | IND_AP_LOCK;
612 	ret = write_ind_ap(cd->regmap, ind_ap);
613 	if (ret)
614 		return ret;
615 	t->task_fn = task_fn_area_2;
616 	return -EINPROGRESS;
617 }
618 
619 static struct ab_task *
620 create_area_reader(struct kmem_cache *qcache, u16 flags, u16 addr,
621 		   size_t count)
622 {
623 	struct ab_task *t;
624 	struct area_priv *ap;
625 
626 	t = ab_task_create_get(qcache, task_fn_area);
627 	if (!t)
628 		return NULL;
629 	ap = &t->area_pd;
630 	ap->flags = flags;
631 	ap->addr = addr;
632 	ap->is_write = false;
633 	ap->count = count;
634 	return t;
635 }
636 
637 static struct ab_task *
638 create_area_writer(struct kmem_cache *qcache, u16 flags, u16 addr,
639 		   const void *buf, size_t count)
640 {
641 	struct ab_task *t;
642 	struct area_priv *ap;
643 
644 	t = ab_task_create_get(qcache, task_fn_area);
645 	if (!t)
646 		return NULL;
647 	ap = &t->area_pd;
648 	ap->flags = flags;
649 	ap->addr = addr;
650 	ap->is_write = true;
651 	ap->count = count;
652 	memcpy(ap->buf, buf, count);
653 	return t;
654 }
655 
656 static struct ab_task *
657 create_area_user_writer(struct kmem_cache *qcache, u16 flags, u16 addr,
658 			const void __user *buf, size_t count)
659 {
660 	struct ab_task *t;
661 	struct area_priv *ap;
662 
663 	t = ab_task_create_get(qcache, task_fn_area);
664 	if (!t)
665 		return ERR_PTR(-ENOMEM);
666 	ap = &t->area_pd;
667 	ap->flags = flags;
668 	ap->addr = addr;
669 	ap->is_write = true;
670 	ap->count = count;
671 	if (copy_from_user(ap->buf, buf, count)) {
672 		ab_task_put(t);
673 		return ERR_PTR(-EFAULT);
674 	}
675 	return t;
676 }
677 
678 static bool area_range_ok(u16 addr, size_t count, u16 area_start,
679 			  size_t area_sz)
680 {
681 	u16 area_end_ex = area_start + area_sz;
682 	u16 addr_end_ex;
683 
684 	if (addr < area_start)
685 		return false;
686 	if (addr >= area_end_ex)
687 		return false;
688 	addr_end_ex = addr + count;
689 	if (addr_end_ex > area_end_ex)
690 		return false;
691 	return true;
692 }
693 
694 /* -------------------------- mailbox tasks ----------------------- */
695 
696 static int task_fn_mbox_2(struct anybuss_host *cd, struct ab_task *t)
697 {
698 	struct mbox_priv *pd = &t->mbox_pd;
699 	unsigned int ind_ap;
700 
701 	if (!cd->power_on)
702 		return -EIO;
703 	regmap_read(cd->regmap, REG_IND_AP, &ind_ap);
704 	if (((atomic_read(&cd->ind_ab) ^ ind_ap) & IND_AX_MOUT) == 0) {
705 		/* output message not here */
706 		if (time_after(jiffies, t->start_jiffies + TIMEOUT))
707 			return -ETIMEDOUT;
708 		return -EINPROGRESS;
709 	}
710 	/* grab the returned header and msg */
711 	regmap_bulk_read(cd->regmap, MBOX_OUT_AREA, &pd->hdr,
712 			 sizeof(pd->hdr));
713 	regmap_bulk_read(cd->regmap, MBOX_OUT_AREA + sizeof(pd->hdr),
714 			 pd->msg, pd->msg_in_sz);
715 	/* tell anybus we've consumed the message */
716 	ind_ap ^= IND_AX_MOUT;
717 	return write_ind_ap(cd->regmap, ind_ap);
718 }
719 
720 static int task_fn_mbox(struct anybuss_host *cd, struct ab_task *t)
721 {
722 	struct mbox_priv *pd = &t->mbox_pd;
723 	unsigned int ind_ap;
724 	int ret;
725 
726 	if (!cd->power_on)
727 		return -EIO;
728 	regmap_read(cd->regmap, REG_IND_AP, &ind_ap);
729 	if ((atomic_read(&cd->ind_ab) ^ ind_ap) & IND_AX_MIN) {
730 		/* mbox input area busy */
731 		if (time_after(jiffies, t->start_jiffies + TIMEOUT))
732 			return -ETIMEDOUT;
733 		return -EINPROGRESS;
734 	}
735 	/* write the header and msg to input area */
736 	regmap_bulk_write(cd->regmap, MBOX_IN_AREA, &pd->hdr,
737 			  sizeof(pd->hdr));
738 	regmap_bulk_write(cd->regmap, MBOX_IN_AREA + sizeof(pd->hdr),
739 			  pd->msg, pd->msg_out_sz);
740 	/* tell anybus we gave it a message */
741 	ind_ap ^= IND_AX_MIN;
742 	ret = write_ind_ap(cd->regmap, ind_ap);
743 	if (ret)
744 		return ret;
745 	t->start_jiffies = jiffies;
746 	t->task_fn = task_fn_mbox_2;
747 	return -EINPROGRESS;
748 }
749 
750 static void log_invalid_other(struct device *dev,
751 			      struct anybus_mbox_hdr *hdr)
752 {
753 	size_t ext_offs = ARRAY_SIZE(hdr->extended) - 1;
754 	u16 code = be16_to_cpu(hdr->extended[ext_offs]);
755 
756 	dev_err(dev, "   Invalid other: [0x%02X]", code);
757 }
758 
759 static const char * const EMSGS[] = {
760 	"Invalid Message ID",
761 	"Invalid Message Type",
762 	"Invalid Command",
763 	"Invalid Data Size",
764 	"Message Header Malformed (offset 008h)",
765 	"Message Header Malformed (offset 00Ah)",
766 	"Message Header Malformed (offset 00Ch - 00Dh)",
767 	"Invalid Address",
768 	"Invalid Response",
769 	"Flash Config Error",
770 };
771 
772 static int mbox_cmd_err(struct device *dev, struct mbox_priv *mpriv)
773 {
774 	int i;
775 	u8 ecode;
776 	struct anybus_mbox_hdr *hdr = &mpriv->hdr;
777 	u16 info = be16_to_cpu(hdr->info);
778 	u8 *phdr = (u8 *)hdr;
779 	u8 *pmsg = mpriv->msg;
780 
781 	if (!(info & 0x8000))
782 		return 0;
783 	ecode = (info >> 8) & 0x0F;
784 	dev_err(dev, "mailbox command failed:");
785 	if (ecode == 0x0F)
786 		log_invalid_other(dev, hdr);
787 	else if (ecode < ARRAY_SIZE(EMSGS))
788 		dev_err(dev, "   Error code: %s (0x%02X)",
789 			EMSGS[ecode], ecode);
790 	else
791 		dev_err(dev, "   Error code: 0x%02X\n", ecode);
792 	dev_err(dev, "Failed command:");
793 	dev_err(dev, "Message Header:");
794 	for (i = 0; i < sizeof(mpriv->hdr); i += 2)
795 		dev_err(dev, "%02X%02X", phdr[i], phdr[i + 1]);
796 	dev_err(dev, "Message Data:");
797 	for (i = 0; i < mpriv->msg_in_sz; i += 2)
798 		dev_err(dev, "%02X%02X", pmsg[i], pmsg[i + 1]);
799 	dev_err(dev, "Stack dump:");
800 	dump_stack();
801 	return -EIO;
802 }
803 
804 static int _anybus_mbox_cmd(struct anybuss_host *cd,
805 			    u16 cmd_num, bool is_fb_cmd,
806 				const void *msg_out, size_t msg_out_sz,
807 				void *msg_in, size_t msg_in_sz,
808 				const void *ext, size_t ext_sz)
809 {
810 	struct ab_task *t;
811 	struct mbox_priv *pd;
812 	struct anybus_mbox_hdr *h;
813 	size_t msg_sz = max(msg_in_sz, msg_out_sz);
814 	u16 info;
815 	int err;
816 
817 	if (msg_sz > MAX_MBOX_MSG_SZ)
818 		return -EINVAL;
819 	if (ext && ext_sz > sizeof(h->extended))
820 		return -EINVAL;
821 	t = ab_task_create_get(cd->qcache, task_fn_mbox);
822 	if (!t)
823 		return -ENOMEM;
824 	pd = &t->mbox_pd;
825 	h = &pd->hdr;
826 	info = is_fb_cmd ? INFO_TYPE_FB : INFO_TYPE_APP;
827 	/*
828 	 * prevent uninitialized memory in the header from being sent
829 	 * across the anybus
830 	 */
831 	memset(h, 0, sizeof(*h));
832 	h->info = cpu_to_be16(info | INFO_COMMAND);
833 	h->cmd_num = cpu_to_be16(cmd_num);
834 	h->data_size = cpu_to_be16(msg_out_sz);
835 	h->frame_count = cpu_to_be16(1);
836 	h->frame_num = cpu_to_be16(1);
837 	h->offset_high = cpu_to_be16(0);
838 	h->offset_low = cpu_to_be16(0);
839 	if (ext)
840 		memcpy(h->extended, ext, ext_sz);
841 	memcpy(pd->msg, msg_out, msg_out_sz);
842 	pd->msg_out_sz = msg_out_sz;
843 	pd->msg_in_sz = msg_in_sz;
844 	err = ab_task_enqueue_wait(t, cd->powerq, &cd->qlock, &cd->wq);
845 	if (err)
846 		goto out;
847 	/*
848 	 * mailbox mechanism worked ok, but maybe the mbox response
849 	 * contains an error ?
850 	 */
851 	err = mbox_cmd_err(cd->dev, pd);
852 	if (err)
853 		goto out;
854 	memcpy(msg_in, pd->msg, msg_in_sz);
855 out:
856 	ab_task_put(t);
857 	return err;
858 }
859 
860 /* ------------------------ anybus queues ------------------------ */
861 
862 static void process_q(struct anybuss_host *cd, struct kfifo *q)
863 {
864 	struct ab_task *t;
865 	int ret;
866 
867 	ret = kfifo_out_peek(q, &t, sizeof(t));
868 	if (!ret)
869 		return;
870 	t->result = t->task_fn(cd, t);
871 	if (t->result != -EINPROGRESS)
872 		ab_task_dequeue_finish_put(q, cd);
873 }
874 
875 static bool qs_have_work(struct kfifo *qs, size_t num)
876 {
877 	size_t i;
878 	struct ab_task *t;
879 	int ret;
880 
881 	for (i = 0; i < num; i++, qs++) {
882 		ret = kfifo_out_peek(qs, &t, sizeof(t));
883 		if (ret && (t->result != -EINPROGRESS))
884 			return true;
885 	}
886 	return false;
887 }
888 
889 static void process_qs(struct anybuss_host *cd)
890 {
891 	size_t i;
892 	struct kfifo *qs = cd->qs;
893 	size_t nqs = ARRAY_SIZE(cd->qs);
894 
895 	for (i = 0; i < nqs; i++, qs++)
896 		process_q(cd, qs);
897 }
898 
899 static void softint_ack(struct anybuss_host *cd)
900 {
901 	unsigned int ind_ap;
902 
903 	cd->softint_pending = false;
904 	if (!cd->power_on)
905 		return;
906 	regmap_read(cd->regmap, REG_IND_AP, &ind_ap);
907 	ind_ap &= ~IND_AX_EVNT;
908 	ind_ap |= atomic_read(&cd->ind_ab) & IND_AX_EVNT;
909 	write_ind_ap(cd->regmap, ind_ap);
910 }
911 
912 static void process_softint(struct anybuss_host *cd)
913 {
914 	struct anybuss_client *client = cd->client;
915 	static const u8 zero;
916 	int ret;
917 	unsigned int ind_ap, ev;
918 	struct ab_task *t;
919 
920 	if (!cd->power_on)
921 		return;
922 	if (cd->softint_pending)
923 		return;
924 	regmap_read(cd->regmap, REG_IND_AP, &ind_ap);
925 	if (!((atomic_read(&cd->ind_ab) ^ ind_ap) & IND_AX_EVNT))
926 		return;
927 	/* process software interrupt */
928 	regmap_read(cd->regmap, REG_EVENT_CAUSE, &ev);
929 	if (ev & EVENT_CAUSE_FBON) {
930 		if (client->on_online_changed)
931 			client->on_online_changed(client, true);
932 		dev_dbg(cd->dev, "Fieldbus ON");
933 	}
934 	if (ev & EVENT_CAUSE_FBOF) {
935 		if (client->on_online_changed)
936 			client->on_online_changed(client, false);
937 		dev_dbg(cd->dev, "Fieldbus OFF");
938 	}
939 	if (ev & EVENT_CAUSE_DC) {
940 		if (client->on_area_updated)
941 			client->on_area_updated(client);
942 		dev_dbg(cd->dev, "Fieldbus data changed");
943 	}
944 	/*
945 	 * reset the event cause bits.
946 	 * this must be done while owning the fbctrl area, so we'll
947 	 * enqueue a task to do that.
948 	 */
949 	t = create_area_writer(cd->qcache, IND_AX_FBCTRL,
950 			       REG_EVENT_CAUSE, &zero, sizeof(zero));
951 	if (!t) {
952 		ret = -ENOMEM;
953 		goto out;
954 	}
955 	t->done_fn = softint_ack;
956 	ret = ab_task_enqueue(t, cd->powerq, &cd->qlock, &cd->wq);
957 	ab_task_put(t);
958 	cd->softint_pending = true;
959 out:
960 	WARN_ON(ret);
961 	if (ret)
962 		softint_ack(cd);
963 }
964 
965 static int qthread_fn(void *data)
966 {
967 	struct anybuss_host *cd = data;
968 	struct kfifo *qs = cd->qs;
969 	size_t nqs = ARRAY_SIZE(cd->qs);
970 	unsigned int ind_ab;
971 
972 	/*
973 	 * this kernel thread has exclusive access to the anybus's memory.
974 	 * only exception: the IND_AB register, which is accessed exclusively
975 	 * by the interrupt service routine (ISR). This thread must not touch
976 	 * the IND_AB register, but it does require access to its value.
977 	 *
978 	 * the interrupt service routine stores the register's value in
979 	 * cd->ind_ab (an atomic_t), where we may safely access it, with the
980 	 * understanding that it can be modified by the ISR at any time.
981 	 */
982 
983 	while (!kthread_should_stop()) {
984 		/*
985 		 * make a local copy of IND_AB, so we can go around the loop
986 		 * again in case it changed while processing queues and softint.
987 		 */
988 		ind_ab = atomic_read(&cd->ind_ab);
989 		process_qs(cd);
990 		process_softint(cd);
991 		wait_event_timeout(cd->wq,
992 				   (atomic_read(&cd->ind_ab) != ind_ab) ||
993 				qs_have_work(qs, nqs) ||
994 				kthread_should_stop(),
995 			HZ);
996 		/*
997 		 * time out so even 'stuck' tasks will run eventually,
998 		 * and can time out.
999 		 */
1000 	}
1001 
1002 	return 0;
1003 }
1004 
1005 /* ------------------------ anybus exports ------------------------ */
1006 
1007 int anybuss_start_init(struct anybuss_client *client,
1008 		       const struct anybuss_memcfg *cfg)
1009 {
1010 	int ret;
1011 	u16 op_mode;
1012 	struct anybuss_host *cd = client->host;
1013 	struct msg_anybus_init msg = {
1014 		.input_io_len = cpu_to_be16(cfg->input_io),
1015 		.input_dpram_len = cpu_to_be16(cfg->input_dpram),
1016 		.input_total_len = cpu_to_be16(cfg->input_total),
1017 		.output_io_len = cpu_to_be16(cfg->output_io),
1018 		.output_dpram_len = cpu_to_be16(cfg->output_dpram),
1019 		.output_total_len = cpu_to_be16(cfg->output_total),
1020 		.notif_config = cpu_to_be16(0x000F),
1021 		.wd_val = cpu_to_be16(0),
1022 	};
1023 
1024 	switch (cfg->offl_mode) {
1025 	case FIELDBUS_DEV_OFFL_MODE_CLEAR:
1026 		op_mode = 0;
1027 		break;
1028 	case FIELDBUS_DEV_OFFL_MODE_FREEZE:
1029 		op_mode = OP_MODE_FBFC;
1030 		break;
1031 	case FIELDBUS_DEV_OFFL_MODE_SET:
1032 		op_mode = OP_MODE_FBS;
1033 		break;
1034 	default:
1035 		return -EINVAL;
1036 	}
1037 	msg.op_mode = cpu_to_be16(op_mode | OP_MODE_CD);
1038 	ret = _anybus_mbox_cmd(cd, CMD_START_INIT, false, NULL, 0,
1039 			       NULL, 0, NULL, 0);
1040 	if (ret)
1041 		return ret;
1042 	return _anybus_mbox_cmd(cd, CMD_ANYBUS_INIT, false,
1043 			&msg, sizeof(msg), NULL, 0, NULL, 0);
1044 }
1045 EXPORT_SYMBOL_GPL(anybuss_start_init);
1046 
1047 int anybuss_finish_init(struct anybuss_client *client)
1048 {
1049 	struct anybuss_host *cd = client->host;
1050 
1051 	return _anybus_mbox_cmd(cd, CMD_END_INIT, false, NULL, 0,
1052 					NULL, 0, NULL, 0);
1053 }
1054 EXPORT_SYMBOL_GPL(anybuss_finish_init);
1055 
1056 int anybuss_read_fbctrl(struct anybuss_client *client, u16 addr,
1057 			void *buf, size_t count)
1058 {
1059 	struct anybuss_host *cd = client->host;
1060 	struct ab_task *t;
1061 	int ret;
1062 
1063 	if (count == 0)
1064 		return 0;
1065 	if (!area_range_ok(addr, count, FBCTRL_AREA,
1066 			   MAX_FBCTRL_AREA_SZ))
1067 		return -EFAULT;
1068 	t = create_area_reader(cd->qcache, IND_AX_FBCTRL, addr, count);
1069 	if (!t)
1070 		return -ENOMEM;
1071 	ret = ab_task_enqueue_wait(t, cd->powerq, &cd->qlock, &cd->wq);
1072 	if (ret)
1073 		goto out;
1074 	memcpy(buf, t->area_pd.buf, count);
1075 out:
1076 	ab_task_put(t);
1077 	return ret;
1078 }
1079 EXPORT_SYMBOL_GPL(anybuss_read_fbctrl);
1080 
1081 int anybuss_write_input(struct anybuss_client *client,
1082 			const char __user *buf, size_t size,
1083 				loff_t *offset)
1084 {
1085 	ssize_t len = min_t(loff_t, MAX_DATA_AREA_SZ - *offset, size);
1086 	struct anybuss_host *cd = client->host;
1087 	struct ab_task *t;
1088 	int ret;
1089 
1090 	if (len <= 0)
1091 		return 0;
1092 	t = create_area_user_writer(cd->qcache, IND_AX_IN,
1093 				    DATA_IN_AREA + *offset, buf, len);
1094 	if (IS_ERR(t))
1095 		return PTR_ERR(t);
1096 	ret = ab_task_enqueue_wait(t, cd->powerq, &cd->qlock, &cd->wq);
1097 	ab_task_put(t);
1098 	if (ret)
1099 		return ret;
1100 	/* success */
1101 	*offset += len;
1102 	return len;
1103 }
1104 EXPORT_SYMBOL_GPL(anybuss_write_input);
1105 
1106 int anybuss_read_output(struct anybuss_client *client,
1107 			char __user *buf, size_t size,
1108 				loff_t *offset)
1109 {
1110 	ssize_t len = min_t(loff_t, MAX_DATA_AREA_SZ - *offset, size);
1111 	struct anybuss_host *cd = client->host;
1112 	struct ab_task *t;
1113 	int ret;
1114 
1115 	if (len <= 0)
1116 		return 0;
1117 	t = create_area_reader(cd->qcache, IND_AX_OUT,
1118 			       DATA_OUT_AREA + *offset, len);
1119 	if (!t)
1120 		return -ENOMEM;
1121 	ret = ab_task_enqueue_wait(t, cd->powerq, &cd->qlock, &cd->wq);
1122 	if (ret)
1123 		goto out;
1124 	if (copy_to_user(buf, t->area_pd.buf, len))
1125 		ret = -EFAULT;
1126 out:
1127 	ab_task_put(t);
1128 	if (ret)
1129 		return ret;
1130 	/* success */
1131 	*offset += len;
1132 	return len;
1133 }
1134 EXPORT_SYMBOL_GPL(anybuss_read_output);
1135 
1136 int anybuss_send_msg(struct anybuss_client *client, u16 cmd_num,
1137 		     const void *buf, size_t count)
1138 {
1139 	struct anybuss_host *cd = client->host;
1140 
1141 	return _anybus_mbox_cmd(cd, cmd_num, true, buf, count, NULL, 0,
1142 					NULL, 0);
1143 }
1144 EXPORT_SYMBOL_GPL(anybuss_send_msg);
1145 
1146 int anybuss_send_ext(struct anybuss_client *client, u16 cmd_num,
1147 		     const void *buf, size_t count)
1148 {
1149 	struct anybuss_host *cd = client->host;
1150 
1151 	return _anybus_mbox_cmd(cd, cmd_num, true, NULL, 0, NULL, 0,
1152 					buf, count);
1153 }
1154 EXPORT_SYMBOL_GPL(anybuss_send_ext);
1155 
1156 int anybuss_recv_msg(struct anybuss_client *client, u16 cmd_num,
1157 		     void *buf, size_t count)
1158 {
1159 	struct anybuss_host *cd = client->host;
1160 
1161 	return _anybus_mbox_cmd(cd, cmd_num, true, NULL, 0, buf, count,
1162 					NULL, 0);
1163 }
1164 EXPORT_SYMBOL_GPL(anybuss_recv_msg);
1165 
1166 /* ------------------------ bus functions ------------------------ */
1167 
1168 static int anybus_bus_match(struct device *dev,
1169 			    struct device_driver *drv)
1170 {
1171 	struct anybuss_client_driver *adrv =
1172 		to_anybuss_client_driver(drv);
1173 	struct anybuss_client *adev =
1174 		to_anybuss_client(dev);
1175 
1176 	return adrv->anybus_id == be16_to_cpu(adev->anybus_id);
1177 }
1178 
1179 static int anybus_bus_probe(struct device *dev)
1180 {
1181 	struct anybuss_client_driver *adrv =
1182 		to_anybuss_client_driver(dev->driver);
1183 	struct anybuss_client *adev =
1184 		to_anybuss_client(dev);
1185 
1186 	return adrv->probe(adev);
1187 }
1188 
1189 static void anybus_bus_remove(struct device *dev)
1190 {
1191 	struct anybuss_client_driver *adrv =
1192 		to_anybuss_client_driver(dev->driver);
1193 
1194 	if (adrv->remove)
1195 		adrv->remove(to_anybuss_client(dev));
1196 }
1197 
1198 static struct bus_type anybus_bus = {
1199 	.name		= "anybuss",
1200 	.match		= anybus_bus_match,
1201 	.probe		= anybus_bus_probe,
1202 	.remove		= anybus_bus_remove,
1203 };
1204 
1205 int anybuss_client_driver_register(struct anybuss_client_driver *drv)
1206 {
1207 	if (!drv->probe)
1208 		return -ENODEV;
1209 
1210 	drv->driver.bus = &anybus_bus;
1211 	return driver_register(&drv->driver);
1212 }
1213 EXPORT_SYMBOL_GPL(anybuss_client_driver_register);
1214 
1215 void anybuss_client_driver_unregister(struct anybuss_client_driver *drv)
1216 {
1217 	return driver_unregister(&drv->driver);
1218 }
1219 EXPORT_SYMBOL_GPL(anybuss_client_driver_unregister);
1220 
1221 static void client_device_release(struct device *dev)
1222 {
1223 	kfree(to_anybuss_client(dev));
1224 }
1225 
1226 static int taskq_alloc(struct device *dev, struct kfifo *q)
1227 {
1228 	void *buf;
1229 	size_t size = 64 * sizeof(struct ab_task *);
1230 
1231 	buf = devm_kzalloc(dev, size, GFP_KERNEL);
1232 	if (!buf)
1233 		return -EIO;
1234 	return kfifo_init(q, buf, size);
1235 }
1236 
1237 static int anybus_of_get_host_idx(struct device_node *np)
1238 {
1239 	const __be32 *host_idx;
1240 
1241 	host_idx = of_get_address(np, 0, NULL, NULL);
1242 	if (!host_idx)
1243 		return -ENOENT;
1244 	return __be32_to_cpu(*host_idx);
1245 }
1246 
1247 static struct device_node *
1248 anybus_of_find_child_device(struct device *dev, int host_idx)
1249 {
1250 	struct device_node *node;
1251 
1252 	if (!dev || !dev->of_node)
1253 		return NULL;
1254 	for_each_child_of_node(dev->of_node, node) {
1255 		if (anybus_of_get_host_idx(node) == host_idx)
1256 			return node;
1257 	}
1258 	return NULL;
1259 }
1260 
1261 struct anybuss_host * __must_check
1262 anybuss_host_common_probe(struct device *dev,
1263 			  const struct anybuss_ops *ops)
1264 {
1265 	int ret, i;
1266 	u8 val[4];
1267 	__be16 fieldbus_type;
1268 	struct anybuss_host *cd;
1269 
1270 	cd = devm_kzalloc(dev, sizeof(*cd), GFP_KERNEL);
1271 	if (!cd)
1272 		return ERR_PTR(-ENOMEM);
1273 	cd->dev = dev;
1274 	cd->host_idx = ops->host_idx;
1275 	init_completion(&cd->card_boot);
1276 	init_waitqueue_head(&cd->wq);
1277 	for (i = 0; i < ARRAY_SIZE(cd->qs); i++) {
1278 		ret = taskq_alloc(dev, &cd->qs[i]);
1279 		if (ret)
1280 			return ERR_PTR(ret);
1281 	}
1282 	if (WARN_ON(ARRAY_SIZE(cd->qs) < 3))
1283 		return ERR_PTR(-EINVAL);
1284 	cd->powerq = &cd->qs[0];
1285 	cd->mboxq = &cd->qs[1];
1286 	cd->areaq = &cd->qs[2];
1287 	cd->reset = ops->reset;
1288 	if (!cd->reset)
1289 		return ERR_PTR(-EINVAL);
1290 	cd->regmap = ops->regmap;
1291 	if (!cd->regmap)
1292 		return ERR_PTR(-EINVAL);
1293 	spin_lock_init(&cd->qlock);
1294 	cd->qcache = kmem_cache_create(dev_name(dev),
1295 				       sizeof(struct ab_task), 0, 0, NULL);
1296 	if (!cd->qcache)
1297 		return ERR_PTR(-ENOMEM);
1298 	cd->irq = ops->irq;
1299 	if (cd->irq <= 0) {
1300 		ret = -EINVAL;
1301 		goto err_qcache;
1302 	}
1303 	/*
1304 	 * use a dpram test to check if a card is present, this is only
1305 	 * possible while in reset.
1306 	 */
1307 	reset_assert(cd);
1308 	if (test_dpram(cd->regmap)) {
1309 		dev_err(dev, "no Anybus-S card in slot");
1310 		ret = -ENODEV;
1311 		goto err_qcache;
1312 	}
1313 	ret = devm_request_threaded_irq(dev, cd->irq, NULL, irq_handler,
1314 					IRQF_ONESHOT, dev_name(dev), cd);
1315 	if (ret) {
1316 		dev_err(dev, "could not request irq");
1317 		goto err_qcache;
1318 	}
1319 	/*
1320 	 * startup sequence:
1321 	 *   a) perform dummy IND_AB read to prevent false 'init done' irq
1322 	 *     (already done by test_dpram() above)
1323 	 *   b) release reset
1324 	 *   c) wait for first interrupt
1325 	 *   d) interrupt came in: ready to go !
1326 	 */
1327 	reset_deassert(cd);
1328 	if (!wait_for_completion_timeout(&cd->card_boot, TIMEOUT)) {
1329 		ret = -ETIMEDOUT;
1330 		goto err_reset;
1331 	}
1332 	/*
1333 	 * according to the anybus docs, we're allowed to read these
1334 	 * without handshaking / reserving the area
1335 	 */
1336 	dev_info(dev, "Anybus-S card detected");
1337 	regmap_bulk_read(cd->regmap, REG_BOOTLOADER_V, val, 2);
1338 	dev_info(dev, "Bootloader version: %02X%02X",
1339 		 val[0], val[1]);
1340 	regmap_bulk_read(cd->regmap, REG_API_V, val, 2);
1341 	dev_info(dev, "API version: %02X%02X", val[0], val[1]);
1342 	regmap_bulk_read(cd->regmap, REG_FIELDBUS_V, val, 2);
1343 	dev_info(dev, "Fieldbus version: %02X%02X", val[0], val[1]);
1344 	regmap_bulk_read(cd->regmap, REG_SERIAL_NO, val, 4);
1345 	dev_info(dev, "Serial number: %02X%02X%02X%02X",
1346 		 val[0], val[1], val[2], val[3]);
1347 	add_device_randomness(&val, 4);
1348 	regmap_bulk_read(cd->regmap, REG_FIELDBUS_TYPE, &fieldbus_type,
1349 			 sizeof(fieldbus_type));
1350 	dev_info(dev, "Fieldbus type: %04X", be16_to_cpu(fieldbus_type));
1351 	regmap_bulk_read(cd->regmap, REG_MODULE_SW_V, val, 2);
1352 	dev_info(dev, "Module SW version: %02X%02X",
1353 		 val[0], val[1]);
1354 	/* put card back reset until a client driver releases it */
1355 	disable_irq(cd->irq);
1356 	reset_assert(cd);
1357 	atomic_set(&cd->ind_ab, IND_AB_UPDATED);
1358 	/* fire up the queue thread */
1359 	cd->qthread = kthread_run(qthread_fn, cd, dev_name(dev));
1360 	if (IS_ERR(cd->qthread)) {
1361 		dev_err(dev, "could not create kthread");
1362 		ret = PTR_ERR(cd->qthread);
1363 		goto err_reset;
1364 	}
1365 	/*
1366 	 * now advertise that we've detected a client device (card).
1367 	 * the bus infrastructure will match it to a client driver.
1368 	 */
1369 	cd->client = kzalloc(sizeof(*cd->client), GFP_KERNEL);
1370 	if (!cd->client) {
1371 		ret = -ENOMEM;
1372 		goto err_kthread;
1373 	}
1374 	cd->client->anybus_id = fieldbus_type;
1375 	cd->client->host = cd;
1376 	cd->client->dev.bus = &anybus_bus;
1377 	cd->client->dev.parent = dev;
1378 	cd->client->dev.release = client_device_release;
1379 	cd->client->dev.of_node =
1380 		anybus_of_find_child_device(dev, cd->host_idx);
1381 	dev_set_name(&cd->client->dev, "anybuss.card%d", cd->host_idx);
1382 	ret = device_register(&cd->client->dev);
1383 	if (ret)
1384 		goto err_device;
1385 	return cd;
1386 err_device:
1387 	device_unregister(&cd->client->dev);
1388 err_kthread:
1389 	kthread_stop(cd->qthread);
1390 err_reset:
1391 	reset_assert(cd);
1392 err_qcache:
1393 	kmem_cache_destroy(cd->qcache);
1394 	return ERR_PTR(ret);
1395 }
1396 EXPORT_SYMBOL_GPL(anybuss_host_common_probe);
1397 
1398 void anybuss_host_common_remove(struct anybuss_host *host)
1399 {
1400 	struct anybuss_host *cd = host;
1401 
1402 	device_unregister(&cd->client->dev);
1403 	kthread_stop(cd->qthread);
1404 	reset_assert(cd);
1405 	kmem_cache_destroy(cd->qcache);
1406 }
1407 EXPORT_SYMBOL_GPL(anybuss_host_common_remove);
1408 
1409 static void host_release(void *res)
1410 {
1411 	anybuss_host_common_remove(res);
1412 }
1413 
1414 struct anybuss_host * __must_check
1415 devm_anybuss_host_common_probe(struct device *dev,
1416 			       const struct anybuss_ops *ops)
1417 {
1418 	struct anybuss_host *host;
1419 	int ret;
1420 
1421 	host = anybuss_host_common_probe(dev, ops);
1422 	if (IS_ERR(host))
1423 		return host;
1424 
1425 	ret = devm_add_action_or_reset(dev, host_release, host);
1426 	if (ret)
1427 		return ERR_PTR(ret);
1428 
1429 	return host;
1430 }
1431 EXPORT_SYMBOL_GPL(devm_anybuss_host_common_probe);
1432 
1433 static int __init anybus_init(void)
1434 {
1435 	int ret;
1436 
1437 	ret = bus_register(&anybus_bus);
1438 	if (ret)
1439 		pr_err("could not register Anybus-S bus: %d\n", ret);
1440 	return ret;
1441 }
1442 module_init(anybus_init);
1443 
1444 static void __exit anybus_exit(void)
1445 {
1446 	bus_unregister(&anybus_bus);
1447 }
1448 module_exit(anybus_exit);
1449 
1450 MODULE_DESCRIPTION("HMS Anybus-S Host Driver");
1451 MODULE_AUTHOR("Sven Van Asbroeck <TheSven73@gmail.com>");
1452 MODULE_LICENSE("GPL v2");
1453