Home | History | Annotate | Line # | Download | only in pci
xmm7360.c revision 1.11
      1 /*	$NetBSD: xmm7360.c,v 1.11 2021/10/11 01:07:36 thorpej Exp $	*/
      2 
      3 /*
      4  * Device driver for Intel XMM7360 LTE modems, eg. Fibocom L850-GL.
      5  * Written by James Wah
      6  * james (at) laird-wah.net
      7  *
      8  * Development of this driver was supported by genua GmbH
      9  *
     10  * Copyright (c) 2020 genua GmbH <info (at) genua.de>
     11  * Copyright (c) 2020 James Wah <james (at) laird-wah.net>
     12  *
     13  * The OpenBSD and NetBSD support was written by Jaromir Dolecek for
     14  * Moritz Systems Technology Company Sp. z o.o.
     15  *
     16  * Permission to use, copy, modify, and/or distribute this software for any
     17  * purpose with or without fee is hereby granted, provided that the above
     18  * copyright notice and this permission notice appear in all copies.
     19  *
     20  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     21  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES ON
     22  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     23  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGE
     24  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     25  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     26  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     27  */
     28 
     29 #ifdef __linux__
     30 
     31 #include <linux/init.h>
     32 #include <linux/interrupt.h>
     33 #include <linux/kernel.h>
     34 #include <linux/module.h>
     35 #include <linux/pci.h>
     36 #include <linux/delay.h>
     37 #include <linux/uaccess.h>
     38 #include <linux/cdev.h>
     39 #include <linux/wait.h>
     40 #include <linux/tty.h>
     41 #include <linux/tty_flip.h>
     42 #include <linux/poll.h>
     43 #include <linux/skbuff.h>
     44 #include <linux/netdevice.h>
     45 #include <linux/if.h>
     46 #include <linux/if_arp.h>
     47 #include <net/rtnetlink.h>
     48 #include <linux/hrtimer.h>
     49 #include <linux/workqueue.h>
     50 
     51 MODULE_LICENSE("Dual BSD/GPL");
     52 
     53 static const struct pci_device_id xmm7360_ids[] = {
     54 	{ PCI_DEVICE(0x8086, 0x7360), },
     55 	{ 0, }
     56 };
     57 MODULE_DEVICE_TABLE(pci, xmm7360_ids);
     58 
     59 /* Actually this ioctl not used for xmm0/rpc device by python code */
     60 #define XMM7360_IOCTL_GET_PAGE_SIZE _IOC(_IOC_READ, 'x', 0xc0, sizeof(u32))
     61 
     62 #define xmm7360_os_msleep(msec)		msleep(msec)
     63 
     64 #define __unused			/* nothing */
     65 
     66 #endif
     67 
     68 #if defined(__OpenBSD__) || defined(__NetBSD__)
     69 
     70 #ifdef __OpenBSD__
     71 #include "bpfilter.h"
     72 #endif
     73 #ifdef __NetBSD__
     74 #include "opt_inet.h"
     75 #include "opt_gateway.h"
     76 
     77 #include <sys/cdefs.h>
     78 __KERNEL_RCSID(0, "$NetBSD: xmm7360.c,v 1.11 2021/10/11 01:07:36 thorpej Exp $");
     79 #endif
     80 
     81 #include <sys/param.h>
     82 #include <sys/systm.h>
     83 #include <sys/sockio.h>
     84 #include <sys/mbuf.h>
     85 #include <sys/kernel.h>
     86 #include <sys/device.h>
     87 #include <sys/socket.h>
     88 #include <sys/mutex.h>
     89 #include <sys/tty.h>
     90 #include <sys/conf.h>
     91 #include <sys/kthread.h>
     92 #include <sys/poll.h>
     93 #include <sys/fcntl.h>		/* for FREAD/FWRITE */
     94 #include <sys/vnode.h>
     95 #include <uvm/uvm_param.h>
     96 
     97 #include <dev/pci/pcireg.h>
     98 #include <dev/pci/pcivar.h>
     99 #include <dev/pci/pcidevs.h>
    100 
    101 #include <net/if.h>
    102 #include <net/if_types.h>
    103 
    104 #include <netinet/in.h>
    105 #include <netinet/ip.h>
    106 #include <netinet/ip6.h>
    107 
    108 #ifdef __OpenBSD__
    109 #include <netinet/if_ether.h>
    110 #include <sys/timeout.h>
    111 #include <machine/bus.h>
    112 #endif
    113 
    114 #if NBPFILTER > 0 || defined(__NetBSD__)
    115 #include <net/bpf.h>
    116 #endif
    117 
    118 #ifdef __NetBSD__
    119 #include "ioconf.h"
    120 #include <sys/cpu.h>
    121 #endif
    122 
    123 #ifdef INET
    124 #include <netinet/in_var.h>
    125 #endif
    126 #ifdef INET6
    127 #include <netinet6/in6_var.h>
    128 #endif
    129 
    130 typedef uint8_t u8;
    131 typedef uint16_t u16;
    132 typedef uint32_t u32;
    133 typedef bus_addr_t dma_addr_t;
    134 typedef void * wait_queue_head_t;	/* just address for tsleep() */
    135 
    136 #define WWAN_BAR0	PCI_MAPREG_START
    137 #define WWAN_BAR1	(PCI_MAPREG_START + 4)
    138 #define WWAN_BAR2	(PCI_MAPREG_START + 8)
    139 
    140 #define BUG_ON(never_true)	KASSERT(!(never_true))
    141 #define WARN_ON(x)		/* nothing */
    142 
    143 #ifdef __OpenBSD__
    144 typedef struct mutex spinlock_t;
    145 #define dev_err(devp, fmt, ...)		\
    146 	printf("%s: " fmt, (devp)->dv_xname, ##__VA_ARGS__)
    147 #define dev_info(devp, fmt, ...)	\
    148 	printf("%s: " fmt, (devp)->dv_xname, ##__VA_ARGS__)
    149 #define	kzalloc(size, flags)	malloc(size, M_DEVBUF, M_WAITOK | M_ZERO)
    150 #define kfree(addr)		free(addr, M_DEVBUF, 0)
    151 #define mutex_init(lock)	mtx_init(lock, IPL_TTY)
    152 #define mutex_lock(lock)	mtx_enter(lock)
    153 #define mutex_unlock(lock)	mtx_leave(lock)
    154 /* In OpenBSD every mutex is spin mutex, and it must not be held on sleep */
    155 #define spin_lock_irqsave(lock, flags)		mtx_enter(lock)
    156 #define spin_unlock_irqrestore(lock, flags)	mtx_leave(lock)
    157 
    158 /* Compat defines for NetBSD API */
    159 #define curlwp			curproc
    160 #define LINESW(tp)				(linesw[(tp)->t_line])
    161 #define selnotify(sel, band, note)		selwakeup(sel)
    162 #define cfdata_t				void *
    163 #define device_lookup_private(cdp, unit)	\
    164 	(unit < (*cdp).cd_ndevs) ? (*cdp).cd_devs[unit] : NULL
    165 #define IFQ_SET_READY(ifq)			/* nothing */
    166 #define device_private(devt)			(void *)devt;
    167 #define if_deferred_start_init(ifp, arg)	/* nothing */
    168 #define IF_OUTPUT_CONST				/* nothing */
    169 #define knote_set_eof(kn, f)			(kn)->kn_flags |= EV_EOF | (f)
    170 #define tty_lock()				int s = spltty()
    171 #define tty_unlock()				splx(s)
    172 #define tty_locked()				/* nothing */
    173 #define pmf_device_deregister(dev)		/* nothing */
    174 #if NBPFILTER > 0
    175 #define BPF_MTAP_OUT(ifp, m)						\
    176                 if (ifp->if_bpf) {					\
    177                         bpf_mtap_af(ifp->if_bpf, m->m_pkthdr.ph_family,	\
    178 			    m, BPF_DIRECTION_OUT);			\
    179 		}
    180 #else
    181 #define BPF_MTAP_OUT(ifp, m)			/* nothing */
    182 #endif
    183 
    184 /* Copied from NetBSD <lib/libkern/libkern.h> */
    185 #define __validate_container_of(PTR, TYPE, FIELD)			\
    186     (0 * sizeof((PTR) - &((TYPE *)(((char *)(PTR)) -			\
    187     offsetof(TYPE, FIELD)))->FIELD))
    188 #define	container_of(PTR, TYPE, FIELD)					\
    189     ((TYPE *)(((char *)(PTR)) - offsetof(TYPE, FIELD))			\
    190 	+ __validate_container_of(PTR, TYPE, FIELD))
    191 
    192 /* Copied from NetBSD <sys/cdefs.h> */
    193 #define __UNVOLATILE(a)		((void *)(unsigned long)(volatile void *)(a))
    194 
    195 #if OpenBSD <= 201911
    196 /* Backward compat with OpenBSD 6.6 */
    197 #define klist_insert(klist, kn)		\
    198 		SLIST_INSERT_HEAD(klist, kn, kn_selnext)
    199 #define klist_remove(klist, kn)		\
    200 		SLIST_REMOVE(klist, kn, knote, kn_selnext)
    201 #define XMM_KQ_ISFD_INITIALIZER		.f_isfd = 1
    202 #else
    203 #define XMM_KQ_ISFD_INITIALIZER		.f_flags = FILTEROP_ISFD
    204 #endif /* OpenBSD <= 201911 */
    205 
    206 #endif
    207 
    208 #ifdef __NetBSD__
    209 typedef struct kmutex spinlock_t;
    210 #define dev_err			aprint_error_dev
    211 #define dev_info		aprint_normal_dev
    212 #define mutex			kmutex
    213 #define kzalloc(size, flags)	malloc(size, M_DEVBUF, M_WAITOK | M_ZERO)
    214 #define kfree(addr)		free(addr, M_DEVBUF)
    215 #define mutex_init(lock)	mutex_init(lock, MUTEX_DEFAULT, IPL_TTY)
    216 #define mutex_lock(lock)	mutex_enter(lock)
    217 #define mutex_unlock(lock)	mutex_exit(lock)
    218 #define spin_lock_irqsave(lock, flags)	mutex_enter(lock)
    219 #define spin_unlock_irqrestore(lock, flags)	mutex_exit(lock)
    220 
    221 /* Compat defines with OpenBSD API */
    222 #define caddr_t			void *
    223 #define proc			lwp
    224 #define LINESW(tp)		(*tp->t_linesw)
    225 #define ttymalloc(speed)	tty_alloc()
    226 #define ttyfree(tp)		tty_free(tp)
    227 #define l_open(dev, tp, p)	l_open(dev, tp)
    228 #define l_close(tp, flag, p)	l_close(tp, flag)
    229 #define ttkqfilter(dev, kn)	ttykqfilter(dev, kn)
    230 #define msleep(ident, lock, prio, wmesg, timo) \
    231 		mtsleep(ident, prio, wmesg, timo, lock)
    232 #define pci_mapreg_map(pa, reg, type, busfl, tp, hp, bp, szp, maxsize) \
    233 	pci_mapreg_map(pa, reg, type, busfl, tp, hp, bp, szp)
    234 #define pci_intr_establish(pc, ih, lvl, func, arg, name) \
    235 	pci_intr_establish_xname(pc, ih, lvl, func, arg, name)
    236 #define suser(l)					\
    237 	kauth_authorize_device_tty(l->l_cred, KAUTH_DEVICE_TTY_OPEN, tp)
    238 #define kthread_create(func, arg, lwpp, name)		\
    239 	kthread_create(0, 0, NULL, func, arg, lwpp, "%s", name)
    240 #define MUTEX_ASSERT_LOCKED(lock)	KASSERT(mutex_owned(lock))
    241 #define MCLGETI(m, how, m0, sz)		MCLGET(m, how)
    242 #define m_copyback(m, off, sz, buf, how)		\
    243 					m_copyback(m, off, sz, buf)
    244 #define ifq_deq_begin(ifq)		({		\
    245 		struct mbuf *m0;			\
    246 		IFQ_DEQUEUE(ifq, m0);			\
    247 		m0;					\
    248 })
    249 #define ifq_deq_rollback(ifq, m)	m_freem(m)
    250 #define ifq_deq_commit(ifq, m)		/* nothing to do */
    251 #define ifq_is_oactive(ifq)		true	/* always restart queue */
    252 #define ifq_clr_oactive(ifq)		/* nothing to do */
    253 #define ifq_empty(ifq)			IFQ_IS_EMPTY(ifq)
    254 #define ifq_purge(ifq)			IF_PURGE(ifq)
    255 #define if_enqueue(ifp, m)		ifq_enqueue(ifp, m)
    256 #define if_ih_insert(ifp, func, arg)	(ifp)->_if_input = (func)
    257 #define if_ih_remove(ifp, func, arg)	/* nothing to do */
    258 #define if_hardmtu			if_mtu
    259 #define IF_OUTPUT_CONST			const
    260 #define si_note				sel_klist
    261 #define klist_insert(klist, kn)		\
    262 		SLIST_INSERT_HEAD(klist, kn, kn_selnext)
    263 #define klist_remove(klist, kn)		\
    264 		SLIST_REMOVE(klist, kn, knote, kn_selnext)
    265 #define XMM_KQ_ISFD_INITIALIZER		.f_flags = FILTEROP_ISFD
    266 #define tty_lock()			mutex_spin_enter(&tty_lock)
    267 #define tty_unlock()			mutex_spin_exit(&tty_lock)
    268 #define tty_locked()			KASSERT(mutex_owned(&tty_lock))
    269 #define bpfattach(bpf, ifp, dlt, sz)	bpf_attach(ifp, dlt, sz)
    270 #define NBPFILTER			1
    271 #define BPF_MTAP_OUT(ifp, m)		bpf_mtap(ifp, m, BPF_D_OUT)
    272 #endif /* __NetBSD__ */
    273 
    274 #define __user				/* nothing */
    275 #define copy_from_user(kbuf, userbuf, sz)		\
    276 ({							\
    277 	int __ret = 0;					\
    278 	int error = copyin(userbuf, kbuf, sz);		\
    279 	if (error != 0)					\
    280 		return -error;				\
    281 	__ret;						\
    282 })
    283 #define copy_to_user(kbuf, userbuf, sz)			\
    284 ({							\
    285 	int __ret = 0;					\
    286 	int error = copyout(userbuf, kbuf, sz);		\
    287 	if (error != 0)					\
    288 		return -error;				\
    289 	__ret;						\
    290 })
    291 #define xmm7360_os_msleep(msec)					\
    292 	do {							\
    293 		KASSERT(!cold);					\
    294 		tsleep(xmm, 0, "wwancsl", msec * hz / 1000);	\
    295 	} while (0)
    296 
    297 static void *dma_alloc_coherent(struct device *, size_t, dma_addr_t *, int);
    298 static void dma_free_coherent(struct device *, size_t, volatile void *, dma_addr_t);
    299 
    300 #ifndef PCI_PRODUCT_INTEL_XMM7360
    301 #define PCI_PRODUCT_INTEL_XMM7360	0x7360
    302 #endif
    303 
    304 #define init_waitqueue_head(wqp)	*(wqp) = (wqp)
    305 #define wait_event_interruptible(wq, cond)				\
    306 ({									\
    307 	int __ret = 1;							\
    308 	while (!(cond)) {						\
    309 		KASSERT(!cold);						\
    310 		int error = tsleep(wq, PCATCH, "xmmwq", 0);		\
    311 		if (error) {						\
    312 			__ret = (cond) ? 1				\
    313 			    : ((error != ERESTART) ? -error : error);	\
    314 			break;						\
    315 		}							\
    316 	}								\
    317 	__ret;								\
    318 })
    319 
    320 #define msecs_to_jiffies(msec)						\
    321 ({									\
    322 	KASSERT(hz < 1000);						\
    323 	KASSERT(msec > (1000 / hz));					\
    324 	msec * hz / 1000;						\
    325 })
    326 
    327 #define wait_event_interruptible_timeout(wq, cond, jiffies)		\
    328 ({									\
    329 	int __ret = 1;							\
    330 	while (!(cond)) {						\
    331 		if (cold) {						\
    332 			for (int loop = 0; loop < 10; loop++) {		\
    333 				delay(jiffies * 1000 * 1000 / hz / 10);	\
    334 				if (cond)				\
    335 					break;				\
    336 			}						\
    337 			__ret = (cond) ? 1 : 0;				\
    338 			break;						\
    339 		}							\
    340 		int error = tsleep(wq, PCATCH, "xmmwq", jiffies);	\
    341 		if (error) {						\
    342 			__ret = (cond) ? 1				\
    343 			    : ((error != ERESTART) ? -error : error);	\
    344 			break;						\
    345 		}							\
    346 	}								\
    347 	__ret;								\
    348 })
    349 
    350 #define GFP_KERNEL			0
    351 
    352 #endif /* __OpenBSD__ || __NetBSD__ */
    353 
    354 /*
    355  * The XMM7360 communicates via DMA ring buffers. It has one
    356  * command ring, plus sixteen transfer descriptor (TD)
    357  * rings. The command ring is mainly used to configure and
    358  * deconfigure the TD rings.
    359  *
    360  * The 16 TD rings form 8 queue pairs (QP). For example, QP
    361  * 0 uses ring 0 for host->device, and ring 1 for
    362  * device->host.
    363  *
    364  * The known queue pair functions are as follows:
    365  *
    366  * 0:	Mux (Raw IP packets, amongst others)
    367  * 1:	RPC (funky command protocol based in part on ASN.1 BER)
    368  * 2:	AT trace? port; does not accept commands after init
    369  * 4:	AT command port
    370  * 7:	AT command port
    371  *
    372  */
    373 
    374 /* Command ring, which is used to configure the queue pairs */
    375 struct cmd_ring_entry {
    376 	dma_addr_t ptr;
    377 	u16 len;
    378 	u8 parm;
    379 	u8 cmd;
    380 	u32 extra;
    381 	u32 unk, flags;
    382 };
    383 
    384 #define CMD_RING_OPEN	1
    385 #define CMD_RING_CLOSE	2
    386 #define CMD_RING_FLUSH	3
    387 #define CMD_WAKEUP	4
    388 
    389 #define CMD_FLAG_DONE	1
    390 #define CMD_FLAG_READY	2
    391 
    392 /* Transfer descriptors used on the Tx and Rx rings of each queue pair */
    393 struct td_ring_entry {
    394 	dma_addr_t addr;
    395 	u16 length;
    396 	u16 flags;
    397 	u32 unk;
    398 };
    399 
    400 #define TD_FLAG_COMPLETE 0x200
    401 
    402 /* Root configuration object. This contains pointers to all of the control
    403  * structures that the modem will interact with.
    404  */
    405 struct control {
    406 	dma_addr_t status;
    407 	dma_addr_t s_wptr, s_rptr;
    408 	dma_addr_t c_wptr, c_rptr;
    409 	dma_addr_t c_ring;
    410 	u16 c_ring_size;
    411 	u16 unk;
    412 };
    413 
    414 struct status {
    415 	u32 code;
    416 	u32 mode;
    417 	u32 asleep;
    418 	u32 pad;
    419 };
    420 
    421 #define CMD_RING_SIZE 0x80
    422 
    423 /* All of the control structures can be packed into one page of RAM. */
    424 struct control_page {
    425 	struct control ctl;
    426 	// Status words - written by modem.
    427 	volatile struct status status;
    428 	// Slave ring write/read pointers.
    429 	volatile u32 s_wptr[16], s_rptr[16];
    430 	// Command ring write/read pointers.
    431 	volatile u32 c_wptr, c_rptr;
    432 	// Command ring entries.
    433 	volatile struct cmd_ring_entry c_ring[CMD_RING_SIZE];
    434 };
    435 
    436 #define BAR0_MODE	0x0c
    437 #define BAR0_DOORBELL	0x04
    438 #define BAR0_WAKEUP	0x14
    439 
    440 #define DOORBELL_TD	0
    441 #define DOORBELL_CMD	1
    442 
    443 #define BAR2_STATUS	0x00
    444 #define BAR2_MODE	0x18
    445 #define BAR2_CONTROL	0x19
    446 #define BAR2_CONTROLH	0x1a
    447 
    448 #define BAR2_BLANK0	0x1b
    449 #define BAR2_BLANK1	0x1c
    450 #define BAR2_BLANK2	0x1d
    451 #define BAR2_BLANK3	0x1e
    452 
    453 #define XMM_MODEM_BOOTING	0xfeedb007
    454 #define XMM_MODEM_READY		0x600df00d
    455 
    456 #define XMM_TAG_ACBH		0x41434248	// 'ACBH'
    457 #define XMM_TAG_CMDH		0x434d4448	// 'CMDH'
    458 #define XMM_TAG_ADBH		0x41444248	// 'ADBH'
    459 #define XMM_TAG_ADTH		0x41445448	// 'ADTH'
    460 
    461 /* There are 16 TD rings: a Tx and Rx ring for each queue pair */
    462 struct td_ring {
    463 	u8 depth;
    464 	u8 last_handled;
    465 	u16 page_size;
    466 
    467 	struct td_ring_entry *tds;
    468 	dma_addr_t tds_phys;
    469 
    470 	// One page of page_size per td
    471 	void **pages;
    472 	dma_addr_t *pages_phys;
    473 };
    474 
    475 #define TD_MAX_PAGE_SIZE 16384
    476 
    477 struct queue_pair {
    478 	struct xmm_dev *xmm;
    479 	u8 depth;
    480 	u16 page_size;
    481 	int tty_index;
    482 	int tty_needs_wake;
    483 	struct device dev;
    484 	int num;
    485 	int open;
    486 	struct mutex lock;
    487 	unsigned char user_buf[TD_MAX_PAGE_SIZE];
    488 	wait_queue_head_t wq;
    489 
    490 #ifdef __linux__
    491 	struct cdev cdev;
    492 	struct tty_port port;
    493 #endif
    494 #if defined(__OpenBSD__) || defined(__NetBSD__)
    495 	struct selinfo selr, selw;
    496 #endif
    497 };
    498 
    499 #define XMM_QP_COUNT	8
    500 
    501 struct xmm_dev {
    502 	struct device *dev;
    503 
    504 	volatile uint32_t *bar0, *bar2;
    505 
    506 	volatile struct control_page *cp;
    507 	dma_addr_t cp_phys;
    508 
    509 	struct td_ring td_ring[2 * XMM_QP_COUNT];
    510 
    511 	struct queue_pair qp[XMM_QP_COUNT];
    512 
    513 	struct xmm_net *net;
    514 	struct net_device *netdev;
    515 
    516 	int error;
    517 	int card_num;
    518 	int num_ttys;
    519 	wait_queue_head_t wq;
    520 
    521 #ifdef __linux__
    522 	struct pci_dev *pci_dev;
    523 
    524 	int irq;
    525 
    526 	struct work_struct init_work;	// XXX work not actually scheduled
    527 #endif
    528 };
    529 
    530 struct mux_bounds {
    531 	uint32_t offset;
    532 	uint32_t length;
    533 };
    534 
    535 struct mux_first_header {
    536 	uint32_t tag;
    537 	uint16_t unknown;
    538 	uint16_t sequence;
    539 	uint16_t length;
    540 	uint16_t extra;
    541 	uint16_t next;
    542 	uint16_t pad;
    543 };
    544 
    545 struct mux_next_header {
    546 	uint32_t tag;
    547 	uint16_t length;
    548 	uint16_t extra;
    549 	uint16_t next;
    550 	uint16_t pad;
    551 };
    552 
    553 #define MUX_MAX_PACKETS	64
    554 
    555 struct mux_frame {
    556 	int n_packets, n_bytes, max_size, sequence;
    557 	uint16_t *last_tag_length, *last_tag_next;
    558 	struct mux_bounds bounds[MUX_MAX_PACKETS];
    559 	uint8_t data[TD_MAX_PAGE_SIZE];
    560 };
    561 
    562 struct xmm_net {
    563 	struct xmm_dev *xmm;
    564 	struct queue_pair *qp;
    565 	int channel;
    566 
    567 #ifdef __linux__
    568 	struct sk_buff_head queue;
    569 	struct hrtimer deadline;
    570 #endif
    571 	int queued_packets, queued_bytes;
    572 
    573 	int sequence;
    574 	spinlock_t lock;
    575 	struct mux_frame frame;
    576 };
    577 
    578 static void xmm7360_os_handle_net_frame(struct xmm_dev *, const u8 *, size_t);
    579 static void xmm7360_os_handle_net_dequeue(struct xmm_net *, struct mux_frame *);
    580 static void xmm7360_os_handle_net_txwake(struct xmm_net *);
    581 static void xmm7360_os_handle_tty_idata(struct queue_pair *, const u8 *, size_t);
    582 
    583 static void xmm7360_poll(struct xmm_dev *xmm)
    584 {
    585 	if (xmm->cp->status.code == 0xbadc0ded) {
    586 		dev_err(xmm->dev, "crashed but dma up\n");
    587 		xmm->error = -ENODEV;
    588 	}
    589 	if (xmm->bar2[BAR2_STATUS] != XMM_MODEM_READY) {
    590 		dev_err(xmm->dev, "bad status %x\n",xmm->bar2[BAR2_STATUS]);
    591 		xmm->error = -ENODEV;
    592 	}
    593 }
    594 
    595 static void xmm7360_ding(struct xmm_dev *xmm, int bell)
    596 {
    597 	if (xmm->cp->status.asleep)
    598 		xmm->bar0[BAR0_WAKEUP] = 1;
    599 	xmm->bar0[BAR0_DOORBELL] = bell;
    600 	xmm7360_poll(xmm);
    601 }
    602 
    603 static int xmm7360_cmd_ring_wait(struct xmm_dev *xmm)
    604 {
    605 	// Wait for all commands to complete
    606 	// XXX locking?
    607 	int ret = wait_event_interruptible_timeout(xmm->wq, (xmm->cp->c_rptr == xmm->cp->c_wptr) || xmm->error, msecs_to_jiffies(1000));
    608 	if (ret == 0)
    609 		return -ETIMEDOUT;
    610 	if (ret < 0)
    611 		return ret;
    612 	return xmm->error;
    613 }
    614 
    615 static int xmm7360_cmd_ring_execute(struct xmm_dev *xmm, u8 cmd, u8 parm, u16 len, dma_addr_t ptr, u32 extra)
    616 {
    617 	u8 wptr = xmm->cp->c_wptr;
    618 	u8 new_wptr = (wptr + 1) % CMD_RING_SIZE;
    619 	if (xmm->error)
    620 		return xmm->error;
    621 	if (new_wptr == xmm->cp->c_rptr)	// ring full
    622 		return -EAGAIN;
    623 
    624 	xmm->cp->c_ring[wptr].ptr = ptr;
    625 	xmm->cp->c_ring[wptr].cmd = cmd;
    626 	xmm->cp->c_ring[wptr].parm = parm;
    627 	xmm->cp->c_ring[wptr].len = len;
    628 	xmm->cp->c_ring[wptr].extra = extra;
    629 	xmm->cp->c_ring[wptr].unk = 0;
    630 	xmm->cp->c_ring[wptr].flags = CMD_FLAG_READY;
    631 
    632 	xmm->cp->c_wptr = new_wptr;
    633 
    634 	xmm7360_ding(xmm, DOORBELL_CMD);
    635 	return xmm7360_cmd_ring_wait(xmm);
    636 }
    637 
    638 static int xmm7360_cmd_ring_init(struct xmm_dev *xmm) {
    639 	int timeout;
    640 	int ret;
    641 
    642 	xmm->cp = dma_alloc_coherent(xmm->dev, sizeof(struct control_page), &xmm->cp_phys, GFP_KERNEL);
    643 	BUG_ON(xmm->cp == NULL);
    644 
    645 	xmm->cp->ctl.status = xmm->cp_phys + offsetof(struct control_page, status);
    646 	xmm->cp->ctl.s_wptr = xmm->cp_phys + offsetof(struct control_page, s_wptr);
    647 	xmm->cp->ctl.s_rptr = xmm->cp_phys + offsetof(struct control_page, s_rptr);
    648 	xmm->cp->ctl.c_wptr = xmm->cp_phys + offsetof(struct control_page, c_wptr);
    649 	xmm->cp->ctl.c_rptr = xmm->cp_phys + offsetof(struct control_page, c_rptr);
    650 	xmm->cp->ctl.c_ring = xmm->cp_phys + offsetof(struct control_page, c_ring);
    651 	xmm->cp->ctl.c_ring_size = CMD_RING_SIZE;
    652 
    653 	xmm->bar2[BAR2_CONTROL] = xmm->cp_phys;
    654 	xmm->bar2[BAR2_CONTROLH] = xmm->cp_phys >> 32;
    655 
    656 	xmm->bar0[BAR0_MODE] = 1;
    657 
    658 	timeout = 100;
    659 	while (xmm->bar2[BAR2_MODE] == 0 && --timeout)
    660 		xmm7360_os_msleep(10);
    661 
    662 	if (!timeout)
    663 		return -ETIMEDOUT;
    664 
    665 	xmm->bar2[BAR2_BLANK0] = 0;
    666 	xmm->bar2[BAR2_BLANK1] = 0;
    667 	xmm->bar2[BAR2_BLANK2] = 0;
    668 	xmm->bar2[BAR2_BLANK3] = 0;
    669 
    670 	xmm->bar0[BAR0_MODE] = 2;	// enable intrs?
    671 
    672 	timeout = 100;
    673 	while (xmm->bar2[BAR2_MODE] != 2 && --timeout)
    674 		xmm7360_os_msleep(10);
    675 
    676 	if (!timeout)
    677 		return -ETIMEDOUT;
    678 
    679 	// enable going to sleep when idle
    680 	ret = xmm7360_cmd_ring_execute(xmm, CMD_WAKEUP, 0, 1, 0, 0);
    681 	if (ret)
    682 		return ret;
    683 
    684 	return 0;
    685 }
    686 
    687 static void xmm7360_cmd_ring_free(struct xmm_dev *xmm) {
    688 	if (xmm->bar0)
    689 		xmm->bar0[BAR0_MODE] = 0;
    690 	if (xmm->cp)
    691 		dma_free_coherent(xmm->dev, sizeof(struct control_page), (volatile void *)xmm->cp, xmm->cp_phys);
    692 	xmm->cp = NULL;
    693 	return;
    694 }
    695 
    696 static void xmm7360_td_ring_activate(struct xmm_dev *xmm, u8 ring_id)
    697 {
    698 	struct td_ring *ring = &xmm->td_ring[ring_id];
    699 	int ret __diagused;
    700 
    701 	xmm->cp->s_rptr[ring_id] = xmm->cp->s_wptr[ring_id] = 0;
    702 	ring->last_handled = 0;
    703 	ret = xmm7360_cmd_ring_execute(xmm, CMD_RING_OPEN, ring_id, ring->depth, ring->tds_phys, 0x60);
    704 	BUG_ON(ret);
    705 }
    706 
    707 static void xmm7360_td_ring_create(struct xmm_dev *xmm, u8 ring_id, u8 depth, u16 page_size)
    708 {
    709 	struct td_ring *ring = &xmm->td_ring[ring_id];
    710 	int i;
    711 
    712 	BUG_ON(ring->depth);
    713 	BUG_ON(depth & (depth-1));
    714 	BUG_ON(page_size > TD_MAX_PAGE_SIZE);
    715 
    716 	memset(ring, 0, sizeof(struct td_ring));
    717 	ring->depth = depth;
    718 	ring->page_size = page_size;
    719 	ring->tds = dma_alloc_coherent(xmm->dev, sizeof(struct td_ring_entry)*depth, &ring->tds_phys, GFP_KERNEL);
    720 
    721 	ring->pages = kzalloc(sizeof(void*)*depth, GFP_KERNEL);
    722 	ring->pages_phys = kzalloc(sizeof(dma_addr_t)*depth, GFP_KERNEL);
    723 
    724 	for (i=0; i<depth; i++) {
    725 		ring->pages[i] = dma_alloc_coherent(xmm->dev, ring->page_size, &ring->pages_phys[i], GFP_KERNEL);
    726 		ring->tds[i].addr = ring->pages_phys[i];
    727 	}
    728 
    729 	xmm7360_td_ring_activate(xmm, ring_id);
    730 }
    731 
    732 static void xmm7360_td_ring_deactivate(struct xmm_dev *xmm, u8 ring_id)
    733 {
    734 	xmm7360_cmd_ring_execute(xmm, CMD_RING_CLOSE, ring_id, 0, 0, 0);
    735 }
    736 
    737 static void xmm7360_td_ring_destroy(struct xmm_dev *xmm, u8 ring_id)
    738 {
    739 	struct td_ring *ring = &xmm->td_ring[ring_id];
    740 	int i, depth=ring->depth;
    741 
    742 	if (!depth) {
    743 		WARN_ON(1);
    744 		dev_err(xmm->dev, "Tried destroying empty ring!\n");
    745 		return;
    746 	}
    747 
    748 	xmm7360_td_ring_deactivate(xmm, ring_id);
    749 
    750 	for (i=0; i<depth; i++) {
    751 		dma_free_coherent(xmm->dev, ring->page_size, ring->pages[i], ring->pages_phys[i]);
    752 	}
    753 
    754 	kfree(ring->pages_phys);
    755 	kfree(ring->pages);
    756 
    757 	dma_free_coherent(xmm->dev, sizeof(struct td_ring_entry)*depth, ring->tds, ring->tds_phys);
    758 
    759 	ring->depth = 0;
    760 }
    761 
    762 static void xmm7360_td_ring_write(struct xmm_dev *xmm, u8 ring_id, const void *buf, int len)
    763 {
    764 	struct td_ring *ring = &xmm->td_ring[ring_id];
    765 	u8 wptr = xmm->cp->s_wptr[ring_id];
    766 
    767 	BUG_ON(!ring->depth);
    768 	BUG_ON(len > ring->page_size);
    769 	BUG_ON(ring_id & 1);
    770 
    771 	memcpy(ring->pages[wptr], buf, len);
    772 	ring->tds[wptr].length = len;
    773 	ring->tds[wptr].flags = 0;
    774 	ring->tds[wptr].unk = 0;
    775 
    776 	wptr = (wptr + 1) & (ring->depth - 1);
    777 	BUG_ON(wptr == xmm->cp->s_rptr[ring_id]);
    778 
    779 	xmm->cp->s_wptr[ring_id] = wptr;
    780 }
    781 
    782 static int xmm7360_td_ring_full(struct xmm_dev *xmm, u8 ring_id)
    783 {
    784 	struct td_ring *ring = &xmm->td_ring[ring_id];
    785 	u8 wptr = xmm->cp->s_wptr[ring_id];
    786 	wptr = (wptr + 1) & (ring->depth - 1);
    787 	return wptr == xmm->cp->s_rptr[ring_id];
    788 }
    789 
    790 static void xmm7360_td_ring_read(struct xmm_dev *xmm, u8 ring_id)
    791 {
    792 	struct td_ring *ring = &xmm->td_ring[ring_id];
    793 	u8 wptr = xmm->cp->s_wptr[ring_id];
    794 
    795 	if (!ring->depth) {
    796 		dev_err(xmm->dev, "read on disabled ring\n");
    797 		WARN_ON(1);
    798 		return;
    799 	}
    800 	if (!(ring_id & 1)) {
    801 		dev_err(xmm->dev, "read on write ring\n");
    802 		WARN_ON(1);
    803 		return;
    804 	}
    805 
    806 	ring->tds[wptr].length = ring->page_size;
    807 	ring->tds[wptr].flags = 0;
    808 	ring->tds[wptr].unk = 0;
    809 
    810 	wptr = (wptr + 1) & (ring->depth - 1);
    811 	BUG_ON(wptr == xmm->cp->s_rptr[ring_id]);
    812 
    813 	xmm->cp->s_wptr[ring_id] = wptr;
    814 }
    815 
    816 static struct queue_pair * xmm7360_init_qp(struct xmm_dev *xmm, int num, u8 depth, u16 page_size)
    817 {
    818 	struct queue_pair *qp = &xmm->qp[num];
    819 
    820 	qp->xmm = xmm;
    821 	qp->num = num;
    822 	qp->open = 0;
    823 	qp->depth = depth;
    824 	qp->page_size = page_size;
    825 
    826 	mutex_init(&qp->lock);
    827 	init_waitqueue_head(&qp->wq);
    828 	return qp;
    829 }
    830 
    831 static void xmm7360_qp_arm(struct xmm_dev *xmm, struct queue_pair *qp)
    832 {
    833 	while (!xmm7360_td_ring_full(xmm, qp->num*2+1))
    834 		xmm7360_td_ring_read(xmm, qp->num*2+1);
    835 	xmm7360_ding(xmm, DOORBELL_TD);
    836 }
    837 
    838 static int xmm7360_qp_start(struct queue_pair *qp)
    839 {
    840 	struct xmm_dev *xmm = qp->xmm;
    841 	int ret;
    842 
    843 	mutex_lock(&qp->lock);
    844 	if (qp->open) {
    845 		ret = -EBUSY;
    846 	} else {
    847 		ret = 0;
    848 		qp->open = 1;
    849 	}
    850 	mutex_unlock(&qp->lock);
    851 
    852 	if (ret == 0) {
    853 		xmm7360_td_ring_create(xmm, qp->num*2, qp->depth, qp->page_size);
    854 		xmm7360_td_ring_create(xmm, qp->num*2+1, qp->depth, qp->page_size);
    855 		xmm7360_qp_arm(xmm, qp);
    856 	}
    857 
    858 	return ret;
    859 }
    860 
    861 static void xmm7360_qp_resume(struct queue_pair *qp)
    862 {
    863 	struct xmm_dev *xmm = qp->xmm;
    864 
    865 	BUG_ON(!qp->open);
    866 	xmm7360_td_ring_activate(xmm, qp->num*2);
    867 	xmm7360_td_ring_activate(xmm, qp->num*2+1);
    868 	xmm7360_qp_arm(xmm, qp);
    869 }
    870 
    871 static int xmm7360_qp_stop(struct queue_pair *qp)
    872 {
    873 	struct xmm_dev *xmm = qp->xmm;
    874 	int ret = 0;
    875 
    876 	mutex_lock(&qp->lock);
    877 	if (!qp->open) {
    878 		ret = -ENODEV;
    879 	} else {
    880 		ret = 0;
    881 		/* still holding qp->open to prevent concurrent access */
    882 	}
    883 	mutex_unlock(&qp->lock);
    884 
    885 	if (ret == 0) {
    886 		xmm7360_td_ring_destroy(xmm, qp->num*2);
    887 		xmm7360_td_ring_destroy(xmm, qp->num*2+1);
    888 
    889 		mutex_lock(&qp->lock);
    890 		qp->open = 0;
    891 		mutex_unlock(&qp->lock);
    892 	}
    893 
    894 	return ret;
    895 }
    896 
    897 static void xmm7360_qp_suspend(struct queue_pair *qp)
    898 {
    899 	struct xmm_dev *xmm = qp->xmm;
    900 
    901 	BUG_ON(!qp->open);
    902 	xmm7360_td_ring_deactivate(xmm, qp->num*2);
    903 }
    904 
    905 static int xmm7360_qp_can_write(struct queue_pair *qp)
    906 {
    907 	struct xmm_dev *xmm = qp->xmm;
    908 	return !xmm7360_td_ring_full(xmm, qp->num*2);
    909 }
    910 
    911 static ssize_t xmm7360_qp_write(struct queue_pair *qp, const char *buf, size_t size)
    912 {
    913 	struct xmm_dev *xmm = qp->xmm;
    914 	int page_size = qp->xmm->td_ring[qp->num*2].page_size;
    915 	if (xmm->error)
    916 		return xmm->error;
    917 	if (!xmm7360_qp_can_write(qp))
    918 		return 0;
    919 	if (size > page_size)
    920 		size = page_size;
    921 	xmm7360_td_ring_write(xmm, qp->num*2, buf, size);
    922 	xmm7360_ding(xmm, DOORBELL_TD);
    923 	return size;
    924 }
    925 
    926 static ssize_t xmm7360_qp_write_user(struct queue_pair *qp, const char __user *buf, size_t size)
    927 {
    928 	int page_size = qp->xmm->td_ring[qp->num*2].page_size;
    929 	int ret;
    930 
    931 	if (size > page_size)
    932 		size = page_size;
    933 
    934 	ret = copy_from_user(qp->user_buf, buf, size);
    935 	size = size - ret;
    936 	if (!size)
    937 		return 0;
    938 	return xmm7360_qp_write(qp, qp->user_buf, size);
    939 }
    940 
    941 static int xmm7360_qp_has_data(struct queue_pair *qp)
    942 {
    943 	struct xmm_dev *xmm = qp->xmm;
    944 	struct td_ring *ring = &xmm->td_ring[qp->num*2+1];
    945 
    946 	return (xmm->cp->s_rptr[qp->num*2+1] != ring->last_handled);
    947 }
    948 
    949 static ssize_t xmm7360_qp_read_user(struct queue_pair *qp, char __user *buf, size_t size)
    950 {
    951 	struct xmm_dev *xmm = qp->xmm;
    952 	struct td_ring *ring = &xmm->td_ring[qp->num*2+1];
    953 	int idx, nread, ret;
    954 	// XXX locking?
    955 	ret = wait_event_interruptible(qp->wq, xmm7360_qp_has_data(qp) || xmm->error);
    956 	if (ret < 0)
    957 		return ret;
    958 	if (xmm->error)
    959 		return xmm->error;
    960 
    961 	idx = ring->last_handled;
    962 	nread = ring->tds[idx].length;
    963 	if (nread > size)
    964 		nread = size;
    965 	ret = copy_to_user(buf, ring->pages[idx], nread);
    966 	nread -= ret;
    967 	if (nread == 0)
    968 		return 0;
    969 
    970 	// XXX all data not fitting into buf+size is discarded
    971 	xmm7360_td_ring_read(xmm, qp->num*2+1);
    972 	xmm7360_ding(xmm, DOORBELL_TD);
    973 	ring->last_handled = (idx + 1) & (ring->depth - 1);
    974 
    975 	return nread;
    976 }
    977 
    978 static void xmm7360_tty_poll_qp(struct queue_pair *qp)
    979 {
    980 	struct xmm_dev *xmm = qp->xmm;
    981 	struct td_ring *ring = &xmm->td_ring[qp->num*2+1];
    982 	int idx, nread;
    983 	while (xmm7360_qp_has_data(qp)) {
    984 		idx = ring->last_handled;
    985 		nread = ring->tds[idx].length;
    986 		xmm7360_os_handle_tty_idata(qp, ring->pages[idx], nread);
    987 
    988 		xmm7360_td_ring_read(xmm, qp->num*2+1);
    989 		xmm7360_ding(xmm, DOORBELL_TD);
    990 		ring->last_handled = (idx + 1) & (ring->depth - 1);
    991 	}
    992 }
    993 
    994 #ifdef __linux__
    995 
    996 static void xmm7360_os_handle_tty_idata(struct queue_pair *qp, const u8 *data, size_t nread)
    997 {
    998 	tty_insert_flip_string(&qp->port, data, nread);
    999 	tty_flip_buffer_push(&qp->port);
   1000 }
   1001 
   1002 int xmm7360_cdev_open (struct inode *inode, struct file *file)
   1003 {
   1004 	struct queue_pair *qp = container_of(inode->i_cdev, struct queue_pair, cdev);
   1005 	file->private_data = qp;
   1006 	return xmm7360_qp_start(qp);
   1007 }
   1008 
   1009 int xmm7360_cdev_release (struct inode *inode, struct file *file)
   1010 {
   1011 	struct queue_pair *qp = file->private_data;
   1012 	return xmm7360_qp_stop(qp);
   1013 }
   1014 
   1015 ssize_t xmm7360_cdev_write (struct file *file, const char __user *buf, size_t size, loff_t *offset)
   1016 {
   1017 	struct queue_pair *qp = file->private_data;
   1018 	int ret;
   1019 
   1020 	ret = xmm7360_qp_write_user(qp, buf, size);
   1021 	if (ret < 0)
   1022 		return ret;
   1023 
   1024 	*offset += ret;
   1025 	return ret;
   1026 }
   1027 
   1028 ssize_t xmm7360_cdev_read (struct file *file, char __user *buf, size_t size, loff_t *offset)
   1029 {
   1030 	struct queue_pair *qp = file->private_data;
   1031 	int ret;
   1032 
   1033 	ret = xmm7360_qp_read_user(qp, buf, size);
   1034 	if (ret < 0)
   1035 		return ret;
   1036 
   1037 	*offset += ret;
   1038 	return ret;
   1039 }
   1040 
   1041 static unsigned int xmm7360_cdev_poll(struct file *file, poll_table *wait)
   1042 {
   1043 	struct queue_pair *qp = file->private_data;
   1044 	unsigned int mask = 0;
   1045 
   1046 	poll_wait(file, &qp->wq, wait);
   1047 
   1048 	if (qp->xmm->error)
   1049 		return POLLHUP;
   1050 
   1051 	if (xmm7360_qp_has_data(qp))
   1052 		mask |= POLLIN | POLLRDNORM;
   1053 
   1054 	if (xmm7360_qp_can_write(qp))
   1055 		mask |= POLLOUT | POLLWRNORM;
   1056 
   1057 	return mask;
   1058 }
   1059 
   1060 static long xmm7360_cdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
   1061 {
   1062 	struct queue_pair *qp = file->private_data;
   1063 
   1064 	u32 val;
   1065 
   1066 	switch (cmd) {
   1067 		case XMM7360_IOCTL_GET_PAGE_SIZE:
   1068 			val = qp->xmm->td_ring[qp->num*2].page_size;
   1069 			if (copy_to_user((u32*)arg, &val, sizeof(u32)))
   1070 				return -EFAULT;
   1071 			return 0;
   1072 	}
   1073 
   1074 	return -ENOTTY;
   1075 }
   1076 
   1077 static struct file_operations xmm7360_fops = {
   1078 	.read		= xmm7360_cdev_read,
   1079 	.write		= xmm7360_cdev_write,
   1080 	.poll		= xmm7360_cdev_poll,
   1081 	.unlocked_ioctl	= xmm7360_cdev_ioctl,
   1082 	.open		= xmm7360_cdev_open,
   1083 	.release	= xmm7360_cdev_release
   1084 };
   1085 
   1086 #endif /* __linux__ */
   1087 
   1088 static void xmm7360_mux_frame_init(struct xmm_net *xn, struct mux_frame *frame, int sequence)
   1089 {
   1090 	frame->sequence = xn->sequence;
   1091 	frame->max_size = xn->xmm->td_ring[0].page_size;
   1092 	frame->n_packets = 0;
   1093 	frame->n_bytes = 0;
   1094 	frame->last_tag_next = NULL;
   1095 	frame->last_tag_length = NULL;
   1096 }
   1097 
   1098 static void xmm7360_mux_frame_add_tag(struct mux_frame *frame, uint32_t tag, uint16_t extra, void *data, int data_len)
   1099 {
   1100 	int total_length;
   1101 	if (frame->n_bytes == 0)
   1102 		total_length = sizeof(struct mux_first_header) + data_len;
   1103 	else
   1104 		total_length = sizeof(struct mux_next_header) + data_len;
   1105 
   1106 	while (frame->n_bytes & 3)
   1107 		frame->n_bytes++;
   1108 
   1109 	BUG_ON(frame->n_bytes + total_length > frame->max_size);
   1110 
   1111 	if (frame->last_tag_next)
   1112 		*frame->last_tag_next = frame->n_bytes;
   1113 
   1114 	if (frame->n_bytes == 0) {
   1115 		struct mux_first_header *hdr = (struct mux_first_header *)frame->data;
   1116 		memset(hdr, 0, sizeof(struct mux_first_header));
   1117 		hdr->tag = htonl(tag);
   1118 		hdr->sequence = frame->sequence;
   1119 		hdr->length = total_length;
   1120 		hdr->extra = extra;
   1121 		frame->last_tag_length = &hdr->length;
   1122 		frame->last_tag_next = &hdr->next;
   1123 		frame->n_bytes += sizeof(struct mux_first_header);
   1124 	} else {
   1125 		struct mux_next_header *hdr = (struct mux_next_header *)(&frame->data[frame->n_bytes]);
   1126 		memset(hdr, 0, sizeof(struct mux_next_header));
   1127 		hdr->tag = htonl(tag);
   1128 		hdr->length = total_length;
   1129 		hdr->extra = extra;
   1130 		frame->last_tag_length = &hdr->length;
   1131 		frame->last_tag_next = &hdr->next;
   1132 		frame->n_bytes += sizeof(struct mux_next_header);
   1133 	}
   1134 
   1135 	if (data_len) {
   1136 		memcpy(&frame->data[frame->n_bytes], data, data_len);
   1137 		frame->n_bytes += data_len;
   1138 	}
   1139 }
   1140 
   1141 static void xmm7360_mux_frame_append_data(struct mux_frame *frame, const void *data, int data_len)
   1142 {
   1143 	BUG_ON(frame->n_bytes + data_len > frame->max_size);
   1144 	BUG_ON(!frame->last_tag_length);
   1145 
   1146 	memcpy(&frame->data[frame->n_bytes], data, data_len);
   1147 	*frame->last_tag_length += data_len;
   1148 	frame->n_bytes += data_len;
   1149 }
   1150 
   1151 static int xmm7360_mux_frame_append_packet(struct mux_frame *frame, const void *data, int data_len)
   1152 {
   1153 	int expected_adth_size = sizeof(struct mux_next_header) + 4 + (frame->n_packets+1)*sizeof(struct mux_bounds);
   1154 	uint8_t pad[16];
   1155 
   1156 	if (frame->n_packets >= MUX_MAX_PACKETS)
   1157 		return -1;
   1158 
   1159 	if (frame->n_bytes + data_len + 16 + expected_adth_size > frame->max_size)
   1160 		return -1;
   1161 
   1162 	BUG_ON(!frame->last_tag_length);
   1163 
   1164 	frame->bounds[frame->n_packets].offset = frame->n_bytes;
   1165 	frame->bounds[frame->n_packets].length = data_len + 16;
   1166 	frame->n_packets++;
   1167 
   1168 	memset(pad, 0, sizeof(pad));
   1169 	xmm7360_mux_frame_append_data(frame, pad, 16);
   1170 	xmm7360_mux_frame_append_data(frame, data, data_len);
   1171 	return 0;
   1172 }
   1173 
   1174 static int xmm7360_mux_frame_push(struct xmm_dev *xmm, struct mux_frame *frame)
   1175 {
   1176 	struct mux_first_header *hdr = (void*)&frame->data[0];
   1177 	int ret;
   1178 	hdr->length = frame->n_bytes;
   1179 
   1180 	ret = xmm7360_qp_write(xmm->net->qp, frame->data, frame->n_bytes);
   1181 	if (ret < 0)
   1182 		return ret;
   1183 	return 0;
   1184 }
   1185 
   1186 static int xmm7360_mux_control(struct xmm_net *xn, u32 arg1, u32 arg2, u32 arg3, u32 arg4)
   1187 {
   1188 	struct mux_frame *frame = &xn->frame;
   1189 	int ret;
   1190 	uint32_t cmdh_args[] = {arg1, arg2, arg3, arg4};
   1191 	unsigned long flags __unused;
   1192 
   1193 	spin_lock_irqsave(&xn->lock, flags);
   1194 
   1195 	xmm7360_mux_frame_init(xn, frame, 0);
   1196 	xmm7360_mux_frame_add_tag(frame, XMM_TAG_ACBH, 0, NULL, 0);
   1197 	xmm7360_mux_frame_add_tag(frame, XMM_TAG_CMDH, xn->channel, cmdh_args, sizeof(cmdh_args));
   1198 	ret = xmm7360_mux_frame_push(xn->xmm, frame);
   1199 
   1200 	spin_unlock_irqrestore(&xn->lock, flags);
   1201 
   1202 	return ret;
   1203 }
   1204 
   1205 static void xmm7360_net_flush(struct xmm_net *xn)
   1206 {
   1207 	struct mux_frame *frame = &xn->frame;
   1208 	int ret;
   1209 	u32 unknown = 0;
   1210 
   1211 #ifdef __linux__
   1212 	/* Never called with empty queue */
   1213 	BUG_ON(skb_queue_empty(&xn->queue));
   1214 #endif
   1215 	BUG_ON(!xmm7360_qp_can_write(xn->qp));
   1216 
   1217 	xmm7360_mux_frame_init(xn, frame, xn->sequence++);
   1218 	xmm7360_mux_frame_add_tag(frame, XMM_TAG_ADBH, 0, NULL, 0);
   1219 
   1220 	xmm7360_os_handle_net_dequeue(xn, frame);
   1221 	xn->queued_packets = xn->queued_bytes = 0;
   1222 
   1223 	xmm7360_mux_frame_add_tag(frame, XMM_TAG_ADTH, xn->channel, &unknown, sizeof(uint32_t));
   1224 	xmm7360_mux_frame_append_data(frame, &frame->bounds[0], sizeof(struct mux_bounds)*frame->n_packets);
   1225 
   1226 	ret = xmm7360_mux_frame_push(xn->xmm, frame);
   1227 	if (ret)
   1228 		goto drop;
   1229 
   1230 	return;
   1231 
   1232 drop:
   1233 	dev_err(xn->xmm->dev, "Failed to ship coalesced frame");
   1234 }
   1235 
   1236 static int xmm7360_base_init(struct xmm_dev *xmm)
   1237 {
   1238 	int ret, i;
   1239 	u32 status;
   1240 
   1241 	xmm->error = 0;
   1242 	xmm->num_ttys = 0;
   1243 
   1244 	status = xmm->bar2[BAR2_STATUS];
   1245 	if (status == XMM_MODEM_BOOTING) {
   1246 		dev_info(xmm->dev, "modem still booting, waiting...\n");
   1247 		for (i=0; i<100; i++) {
   1248 			status = xmm->bar2[BAR2_STATUS];
   1249 			if (status != XMM_MODEM_BOOTING)
   1250 				break;
   1251 			xmm7360_os_msleep(200);
   1252 		}
   1253 	}
   1254 
   1255 	if (status != XMM_MODEM_READY) {
   1256 		dev_err(xmm->dev, "unknown modem status: 0x%08x\n", status);
   1257 		return -EINVAL;
   1258 	}
   1259 
   1260 	dev_info(xmm->dev, "modem is ready\n");
   1261 
   1262 	ret = xmm7360_cmd_ring_init(xmm);
   1263 	if (ret) {
   1264 		dev_err(xmm->dev, "Could not bring up command ring %d\n",
   1265 		    ret);
   1266 		return ret;
   1267 	}
   1268 
   1269 	return 0;
   1270 }
   1271 
   1272 static void xmm7360_net_mux_handle_frame(struct xmm_net *xn, u8 *data, int len)
   1273 {
   1274 	struct mux_first_header *first;
   1275 	struct mux_next_header *adth;
   1276 	int n_packets, i;
   1277 	struct mux_bounds *bounds;
   1278 
   1279 	first = (void*)data;
   1280 	if (ntohl(first->tag) == XMM_TAG_ACBH)
   1281 		return;
   1282 
   1283 	if (ntohl(first->tag) != XMM_TAG_ADBH) {
   1284 		dev_info(xn->xmm->dev, "Unexpected tag %x\n", first->tag);
   1285 		return;
   1286 	}
   1287 
   1288 	adth = (void*)(&data[first->next]);
   1289 	if (ntohl(adth->tag) != XMM_TAG_ADTH) {
   1290 		dev_err(xn->xmm->dev, "Unexpected tag %x, expected ADTH\n", adth->tag);
   1291 		return;
   1292 	}
   1293 
   1294 	n_packets = (adth->length - sizeof(struct mux_next_header) - 4) / sizeof(struct mux_bounds);
   1295 
   1296 	bounds = (void*)&data[first->next + sizeof(struct mux_next_header) + 4];
   1297 
   1298 	for (i=0; i<n_packets; i++) {
   1299 		if (!bounds[i].length)
   1300 			continue;
   1301 
   1302 		xmm7360_os_handle_net_frame(xn->xmm,
   1303 		    &data[bounds[i].offset], bounds[i].length);
   1304 	}
   1305 }
   1306 
   1307 static void xmm7360_net_poll(struct xmm_dev *xmm)
   1308 {
   1309 	struct queue_pair *qp;
   1310 	struct td_ring *ring;
   1311 	int idx, nread;
   1312 	struct xmm_net *xn = xmm->net;
   1313 	unsigned long flags __unused;
   1314 
   1315 	BUG_ON(!xn);
   1316 
   1317 	qp = xn->qp;
   1318 	ring = &xmm->td_ring[qp->num*2+1];
   1319 
   1320 	spin_lock_irqsave(&xn->lock, flags);
   1321 
   1322 	if (xmm7360_qp_can_write(qp))
   1323 		xmm7360_os_handle_net_txwake(xn);
   1324 
   1325 	while (xmm7360_qp_has_data(qp)) {
   1326 		idx = ring->last_handled;
   1327 		nread = ring->tds[idx].length;
   1328 		xmm7360_net_mux_handle_frame(xn, ring->pages[idx], nread);
   1329 
   1330 		xmm7360_td_ring_read(xmm, qp->num*2+1);
   1331 		xmm7360_ding(xmm, DOORBELL_TD);
   1332 		ring->last_handled = (idx + 1) & (ring->depth - 1);
   1333 	}
   1334 
   1335 	spin_unlock_irqrestore(&xn->lock, flags);
   1336 }
   1337 
   1338 #ifdef __linux__
   1339 
   1340 static void xmm7360_net_uninit(struct net_device *dev)
   1341 {
   1342 }
   1343 
   1344 static int xmm7360_net_open(struct net_device *dev)
   1345 {
   1346 	struct xmm_net *xn = netdev_priv(dev);
   1347 	xn->queued_packets = xn->queued_bytes = 0;
   1348 	skb_queue_purge(&xn->queue);
   1349 	netif_start_queue(dev);
   1350 	return xmm7360_mux_control(xn, 1, 0, 0, 0);
   1351 }
   1352 
   1353 static int xmm7360_net_close(struct net_device *dev)
   1354 {
   1355 	netif_stop_queue(dev);
   1356 	return 0;
   1357 }
   1358 
   1359 static int xmm7360_net_must_flush(struct xmm_net *xn, int new_packet_bytes)
   1360 {
   1361 	int frame_size;
   1362 	if (xn->queued_packets >= MUX_MAX_PACKETS)
   1363 		return 1;
   1364 
   1365 	frame_size = sizeof(struct mux_first_header) + xn->queued_bytes + sizeof(struct mux_next_header) + 4 + sizeof(struct mux_bounds)*xn->queued_packets;
   1366 
   1367 	frame_size += 16 + new_packet_bytes + sizeof(struct mux_bounds);
   1368 
   1369 	return frame_size > xn->frame.max_size;
   1370 }
   1371 
   1372 static enum hrtimer_restart xmm7360_net_deadline_cb(struct hrtimer *t)
   1373 {
   1374 	struct xmm_net *xn = container_of(t, struct xmm_net, deadline);
   1375 	unsigned long flags;
   1376 	spin_lock_irqsave(&xn->lock, flags);
   1377 	if (!skb_queue_empty(&xn->queue) && xmm7360_qp_can_write(xn->qp))
   1378 		xmm7360_net_flush(xn);
   1379 	spin_unlock_irqrestore(&xn->lock, flags);
   1380 	return HRTIMER_NORESTART;
   1381 }
   1382 
   1383 static netdev_tx_t xmm7360_net_xmit(struct sk_buff *skb, struct net_device *dev)
   1384 {
   1385 	struct xmm_net *xn = netdev_priv(dev);
   1386 	ktime_t kt;
   1387 	unsigned long flags;
   1388 
   1389 	if (netif_queue_stopped(dev))
   1390 		return NETDEV_TX_BUSY;
   1391 
   1392 	skb_orphan(skb);
   1393 
   1394 	spin_lock_irqsave(&xn->lock, flags);
   1395 	if (xmm7360_net_must_flush(xn, skb->len)) {
   1396 		if (xmm7360_qp_can_write(xn->qp)) {
   1397 			xmm7360_net_flush(xn);
   1398 		} else {
   1399 			netif_stop_queue(dev);
   1400 			spin_unlock_irqrestore(&xn->lock, flags);
   1401 			return NETDEV_TX_BUSY;
   1402 		}
   1403 	}
   1404 
   1405 	xn->queued_packets++;
   1406 	xn->queued_bytes += 16 + skb->len;
   1407 	skb_queue_tail(&xn->queue, skb);
   1408 
   1409 	spin_unlock_irqrestore(&xn->lock, flags);
   1410 
   1411 	if (!hrtimer_active(&xn->deadline)) {
   1412 		kt = ktime_set(0, 100000);
   1413 		hrtimer_start(&xn->deadline, kt, HRTIMER_MODE_REL);
   1414 	}
   1415 
   1416 	return NETDEV_TX_OK;
   1417 }
   1418 
   1419 static void xmm7360_os_handle_net_frame(struct xmm_dev *xmm, const u8 *buf, size_t sz)
   1420 {
   1421 	struct sk_buff *skb;
   1422 	void *p;
   1423 	u8 ip_version;
   1424 
   1425 	skb = dev_alloc_skb(sz + NET_IP_ALIGN);
   1426 	if (!skb)
   1427 		return;
   1428 	skb_reserve(skb, NET_IP_ALIGN);
   1429 	p = skb_put(skb, sz);
   1430 	memcpy(p, buf, sz);
   1431 
   1432 	skb->dev = xmm->netdev;
   1433 
   1434 	ip_version = skb->data[0] >> 4;
   1435 	if (ip_version == 4) {
   1436 		skb->protocol = htons(ETH_P_IP);
   1437 	} else if (ip_version == 6) {
   1438 		skb->protocol = htons(ETH_P_IPV6);
   1439 	} else {
   1440 		kfree_skb(skb);
   1441 		return;
   1442 	}
   1443 
   1444 	netif_rx(skb);
   1445 }
   1446 
   1447 static void xmm7360_os_handle_net_dequeue(struct xmm_net *xn, struct mux_frame *frame)
   1448 {
   1449 	struct sk_buff *skb;
   1450 	int ret;
   1451 
   1452 	while ((skb = skb_dequeue(&xn->queue))) {
   1453 		ret = xmm7360_mux_frame_append_packet(frame,
   1454 		    skb->data, skb->len);
   1455 		kfree_skb(skb);
   1456 		if (ret) {
   1457 			/* No more space in the frame */
   1458 			break;
   1459 		}
   1460 	}
   1461 }
   1462 
   1463 static void xmm7360_os_handle_net_txwake(struct xmm_net *xn)
   1464 {
   1465 	BUG_ON(!xmm7360_qp_can_write(xn->qp));
   1466 
   1467 	if (netif_queue_stopped(xn->xmm->netdev))
   1468 		netif_wake_queue(xn->xmm->netdev);
   1469 }
   1470 
   1471 static const struct net_device_ops xmm7360_netdev_ops = {
   1472 	.ndo_uninit		= xmm7360_net_uninit,
   1473 	.ndo_open		= xmm7360_net_open,
   1474 	.ndo_stop		= xmm7360_net_close,
   1475 	.ndo_start_xmit		= xmm7360_net_xmit,
   1476 };
   1477 
   1478 static void xmm7360_net_setup(struct net_device *dev)
   1479 {
   1480 	struct xmm_net *xn = netdev_priv(dev);
   1481 	spin_lock_init(&xn->lock);
   1482 	hrtimer_init(&xn->deadline, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
   1483 	xn->deadline.function = xmm7360_net_deadline_cb;
   1484 	skb_queue_head_init(&xn->queue);
   1485 
   1486 	dev->netdev_ops = &xmm7360_netdev_ops;
   1487 
   1488 	dev->hard_header_len = 0;
   1489 	dev->addr_len = 0;
   1490 	dev->mtu = 1500;
   1491 	dev->min_mtu = 1500;
   1492 	dev->max_mtu = 1500;
   1493 
   1494 	dev->tx_queue_len = 1000;
   1495 
   1496 	dev->type = ARPHRD_NONE;
   1497 	dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
   1498 }
   1499 
   1500 static int xmm7360_create_net(struct xmm_dev *xmm, int num)
   1501 {
   1502 	struct net_device *netdev;
   1503 	struct xmm_net *xn;
   1504 	int ret;
   1505 
   1506 	netdev = alloc_netdev(sizeof(struct xmm_net), "wwan%d", NET_NAME_UNKNOWN, xmm7360_net_setup);
   1507 
   1508 	if (!netdev)
   1509 		return -ENOMEM;
   1510 
   1511 	SET_NETDEV_DEV(netdev, xmm->dev);
   1512 
   1513 	xmm->netdev = netdev;
   1514 
   1515 	xn = netdev_priv(netdev);
   1516 	xn->xmm = xmm;
   1517 	xmm->net = xn;
   1518 
   1519 	rtnl_lock();
   1520 	ret = register_netdevice(netdev);
   1521 	rtnl_unlock();
   1522 
   1523 	xn->qp = xmm7360_init_qp(xmm, num, 128, TD_MAX_PAGE_SIZE);
   1524 
   1525 	if (!ret)
   1526 		ret = xmm7360_qp_start(xn->qp);
   1527 
   1528 	if (ret < 0) {
   1529 		free_netdev(netdev);
   1530 		xmm->netdev = NULL;
   1531 		xmm7360_qp_stop(xn->qp);
   1532 	}
   1533 
   1534 	return ret;
   1535 }
   1536 
   1537 static void xmm7360_destroy_net(struct xmm_dev *xmm)
   1538 {
   1539 	if (xmm->netdev) {
   1540 		xmm7360_qp_stop(xmm->net->qp);
   1541 		rtnl_lock();
   1542 		unregister_netdevice(xmm->netdev);
   1543 		rtnl_unlock();
   1544 		free_netdev(xmm->netdev);
   1545 		xmm->net = NULL;
   1546 		xmm->netdev = NULL;
   1547 	}
   1548 }
   1549 
   1550 static irqreturn_t xmm7360_irq0(int irq, void *dev_id) {
   1551 	struct xmm_dev *xmm = dev_id;
   1552 	struct queue_pair *qp;
   1553 	int id;
   1554 
   1555 	xmm7360_poll(xmm);
   1556 	wake_up(&xmm->wq);
   1557 	if (xmm->td_ring) {
   1558 		if (xmm->net)
   1559 			xmm7360_net_poll(xmm);
   1560 
   1561 		for (id=1; id<XMM_QP_COUNT; id++) {
   1562 			qp = &xmm->qp[id];
   1563 
   1564 			/* wake _cdev_read() */
   1565 			if (qp->open)
   1566 				wake_up(&qp->wq);
   1567 
   1568 			/* tty tasks */
   1569 			if (qp->open && qp->port.ops) {
   1570 				xmm7360_tty_poll_qp(qp);
   1571 				if (qp->tty_needs_wake && xmm7360_qp_can_write(qp) && qp->port.tty) {
   1572 					struct tty_ldisc *ldisc = tty_ldisc_ref(qp->port.tty);
   1573 					if (ldisc) {
   1574 						if (ldisc->ops->write_wakeup)
   1575 							ldisc->ops->write_wakeup(qp->port.tty);
   1576 						tty_ldisc_deref(ldisc);
   1577 					}
   1578 					qp->tty_needs_wake = 0;
   1579 				}
   1580 			}
   1581 		}
   1582 	}
   1583 
   1584 	return IRQ_HANDLED;
   1585 }
   1586 
   1587 static dev_t xmm_base;
   1588 
   1589 static struct tty_driver *xmm7360_tty_driver;
   1590 
   1591 static void xmm7360_dev_deinit(struct xmm_dev *xmm)
   1592 {
   1593 	int i;
   1594 	xmm->error = -ENODEV;
   1595 
   1596 	cancel_work_sync(&xmm->init_work);
   1597 
   1598 	xmm7360_destroy_net(xmm);
   1599 
   1600 	for (i=0; i<XMM_QP_COUNT; i++) {
   1601 		if (xmm->qp[i].xmm) {
   1602 			if (xmm->qp[i].cdev.owner) {
   1603 				cdev_del(&xmm->qp[i].cdev);
   1604 				device_unregister(&xmm->qp[i].dev);
   1605 			}
   1606 			if (xmm->qp[i].port.ops) {
   1607 				tty_unregister_device(xmm7360_tty_driver, xmm->qp[i].tty_index);
   1608 				tty_port_destroy(&xmm->qp[i].port);
   1609 			}
   1610 		}
   1611 		memset(&xmm->qp[i], 0, sizeof(struct queue_pair));
   1612 	}
   1613 	xmm7360_cmd_ring_free(xmm);
   1614 
   1615 }
   1616 
   1617 static void xmm7360_remove(struct pci_dev *dev)
   1618 {
   1619 	struct xmm_dev *xmm = pci_get_drvdata(dev);
   1620 
   1621 	xmm7360_dev_deinit(xmm);
   1622 
   1623 	if (xmm->irq)
   1624 		free_irq(xmm->irq, xmm);
   1625 	pci_free_irq_vectors(dev);
   1626 	pci_release_region(dev, 0);
   1627 	pci_release_region(dev, 2);
   1628 	pci_disable_device(dev);
   1629 	kfree(xmm);
   1630 }
   1631 
   1632 static void xmm7360_cdev_dev_release(struct device *dev)
   1633 {
   1634 }
   1635 
   1636 static int xmm7360_tty_open(struct tty_struct *tty, struct file *filp)
   1637 {
   1638 	struct queue_pair *qp = tty->driver_data;
   1639 	return tty_port_open(&qp->port, tty, filp);
   1640 }
   1641 
   1642 static void xmm7360_tty_close(struct tty_struct *tty, struct file *filp)
   1643 {
   1644 	struct queue_pair *qp = tty->driver_data;
   1645 	if (qp)
   1646 		tty_port_close(&qp->port, tty, filp);
   1647 }
   1648 
   1649 static int xmm7360_tty_write(struct tty_struct *tty, const unsigned char *buffer,
   1650 		      int count)
   1651 {
   1652 	struct queue_pair *qp = tty->driver_data;
   1653 	int written;
   1654 	written = xmm7360_qp_write(qp, buffer, count);
   1655 	if (written < count)
   1656 		qp->tty_needs_wake = 1;
   1657 	return written;
   1658 }
   1659 
   1660 static int xmm7360_tty_write_room(struct tty_struct *tty)
   1661 {
   1662 	struct queue_pair *qp = tty->driver_data;
   1663 	if (!xmm7360_qp_can_write(qp))
   1664 		return 0;
   1665 	else
   1666 		return qp->xmm->td_ring[qp->num*2].page_size;
   1667 }
   1668 
   1669 static int xmm7360_tty_install(struct tty_driver *driver, struct tty_struct *tty)
   1670 {
   1671 	struct queue_pair *qp;
   1672 	int ret;
   1673 
   1674 	ret = tty_standard_install(driver, tty);
   1675 	if (ret)
   1676 		return ret;
   1677 
   1678 	tty->port = driver->ports[tty->index];
   1679 	qp = container_of(tty->port, struct queue_pair, port);
   1680 	tty->driver_data = qp;
   1681 	return 0;
   1682 }
   1683 
   1684 
   1685 static int xmm7360_tty_port_activate(struct tty_port *tport, struct tty_struct *tty)
   1686 {
   1687 	struct queue_pair *qp = tty->driver_data;
   1688 	return xmm7360_qp_start(qp);
   1689 }
   1690 
   1691 static void xmm7360_tty_port_shutdown(struct tty_port *tport)
   1692 {
   1693 	struct queue_pair *qp = tport->tty->driver_data;
   1694 	xmm7360_qp_stop(qp);
   1695 }
   1696 
   1697 
   1698 static const struct tty_port_operations xmm7360_tty_port_ops = {
   1699 	.activate = xmm7360_tty_port_activate,
   1700 	.shutdown = xmm7360_tty_port_shutdown,
   1701 };
   1702 
   1703 static const struct tty_operations xmm7360_tty_ops = {
   1704 	.open = xmm7360_tty_open,
   1705 	.close = xmm7360_tty_close,
   1706 	.write = xmm7360_tty_write,
   1707 	.write_room = xmm7360_tty_write_room,
   1708 	.install = xmm7360_tty_install,
   1709 };
   1710 
   1711 static int xmm7360_create_tty(struct xmm_dev *xmm, int num)
   1712 {
   1713 	struct device *tty_dev;
   1714 	struct queue_pair *qp = xmm7360_init_qp(xmm, num, 8, 4096);
   1715 	int ret;
   1716 	tty_port_init(&qp->port);
   1717 	qp->port.low_latency = 1;
   1718 	qp->port.ops = &xmm7360_tty_port_ops;
   1719 	qp->tty_index = xmm->num_ttys++;
   1720 	tty_dev = tty_port_register_device(&qp->port, xmm7360_tty_driver, qp->tty_index, xmm->dev);
   1721 
   1722 	if (IS_ERR(tty_dev)) {
   1723 		qp->port.ops = NULL;	// prevent calling unregister
   1724 		ret = PTR_ERR(tty_dev);
   1725 		dev_err(xmm->dev, "Could not allocate tty?\n");
   1726 		tty_port_destroy(&qp->port);
   1727 		return ret;
   1728 	}
   1729 
   1730 	return 0;
   1731 }
   1732 
   1733 static int xmm7360_create_cdev(struct xmm_dev *xmm, int num, const char *name, int cardnum)
   1734 {
   1735 	struct queue_pair *qp = xmm7360_init_qp(xmm, num, 16, TD_MAX_PAGE_SIZE);
   1736 	int ret;
   1737 
   1738 	cdev_init(&qp->cdev, &xmm7360_fops);
   1739 	qp->cdev.owner = THIS_MODULE;
   1740 	device_initialize(&qp->dev);
   1741 	qp->dev.devt = MKDEV(MAJOR(xmm_base), num); // XXX multiple cards
   1742 	qp->dev.parent = &xmm->pci_dev->dev;
   1743 	qp->dev.release = xmm7360_cdev_dev_release;
   1744 	dev_set_name(&qp->dev, name, cardnum);
   1745 	dev_set_drvdata(&qp->dev, qp);
   1746 	ret = cdev_device_add(&qp->cdev, &qp->dev);
   1747 	if (ret) {
   1748 		dev_err(xmm->dev, "cdev_device_add: %d\n", ret);
   1749 		return ret;
   1750 	}
   1751 	return 0;
   1752 }
   1753 
   1754 static int xmm7360_dev_init(struct xmm_dev *xmm)
   1755 {
   1756 	int ret;
   1757 
   1758 	ret = xmm7360_base_init(xmm);
   1759 	if (ret)
   1760 		return ret;
   1761 
   1762 	ret = xmm7360_create_cdev(xmm, 1, "xmm%d/rpc", xmm->card_num);
   1763 	if (ret)
   1764 		return ret;
   1765 	ret = xmm7360_create_cdev(xmm, 3, "xmm%d/trace", xmm->card_num);
   1766 	if (ret)
   1767 		return ret;
   1768 	ret = xmm7360_create_tty(xmm, 2);
   1769 	if (ret)
   1770 		return ret;
   1771 	ret = xmm7360_create_tty(xmm, 4);
   1772 	if (ret)
   1773 		return ret;
   1774 	ret = xmm7360_create_tty(xmm, 7);
   1775 	if (ret)
   1776 		return ret;
   1777 	ret = xmm7360_create_net(xmm, 0);
   1778 	if (ret)
   1779 		return ret;
   1780 
   1781 	return 0;
   1782 }
   1783 
   1784 void xmm7360_dev_init_work(struct work_struct *work)
   1785 {
   1786 	struct xmm_dev *xmm = container_of(work, struct xmm_dev, init_work);
   1787 	xmm7360_dev_init(xmm);
   1788 }
   1789 
   1790 static int xmm7360_probe(struct pci_dev *dev, const struct pci_device_id *id)
   1791 {
   1792 	struct xmm_dev *xmm = kzalloc(sizeof(struct xmm_dev), GFP_KERNEL);
   1793 	int ret;
   1794 
   1795 	xmm->pci_dev = dev;
   1796 	xmm->dev = &dev->dev;
   1797 
   1798 	if (!xmm) {
   1799 		dev_err(&(dev->dev), "kzalloc\n");
   1800 		return -ENOMEM;
   1801 	}
   1802 
   1803 	ret = pci_enable_device(dev);
   1804 	if (ret) {
   1805 		dev_err(&(dev->dev), "pci_enable_device\n");
   1806 		goto fail;
   1807 	}
   1808 	pci_set_master(dev);
   1809 
   1810 	ret = pci_set_dma_mask(dev, 0xffffffffffffffff);
   1811 	if (ret) {
   1812 		dev_err(xmm->dev, "Cannot set DMA mask\n");
   1813 		goto fail;
   1814 	}
   1815 	dma_set_coherent_mask(xmm->dev, 0xffffffffffffffff);
   1816 
   1817 
   1818 	ret = pci_request_region(dev, 0, "xmm0");
   1819 	if (ret) {
   1820 		dev_err(&(dev->dev), "pci_request_region(0)\n");
   1821 		goto fail;
   1822 	}
   1823 	xmm->bar0 = pci_iomap(dev, 0, pci_resource_len(dev, 0));
   1824 
   1825 	ret = pci_request_region(dev, 2, "xmm2");
   1826 	if (ret) {
   1827 		dev_err(&(dev->dev), "pci_request_region(2)\n");
   1828 		goto fail;
   1829 	}
   1830 	xmm->bar2 = pci_iomap(dev, 2, pci_resource_len(dev, 2));
   1831 
   1832 	ret = pci_alloc_irq_vectors(dev, 1, 1, PCI_IRQ_MSI | PCI_IRQ_MSIX);
   1833 	if (ret < 0) {
   1834 		dev_err(&(dev->dev), "pci_alloc_irq_vectors\n");
   1835 		goto fail;
   1836 	}
   1837 
   1838 	init_waitqueue_head(&xmm->wq);
   1839 	INIT_WORK(&xmm->init_work, xmm7360_dev_init_work);
   1840 
   1841 	pci_set_drvdata(dev, xmm);
   1842 
   1843 	ret = xmm7360_dev_init(xmm);
   1844 	if (ret)
   1845 		goto fail;
   1846 
   1847 	xmm->irq = pci_irq_vector(dev, 0);
   1848 	ret = request_irq(xmm->irq, xmm7360_irq0, 0, "xmm7360", xmm);
   1849 	if (ret) {
   1850 		dev_err(&(dev->dev), "request_irq\n");
   1851 		goto fail;
   1852 	}
   1853 
   1854 	return ret;
   1855 
   1856 fail:
   1857 	xmm7360_dev_deinit(xmm);
   1858 	xmm7360_remove(dev);
   1859 	return ret;
   1860 }
   1861 
   1862 static struct pci_driver xmm7360_driver = {
   1863 	.name		= "xmm7360",
   1864 	.id_table	= xmm7360_ids,
   1865 	.probe		= xmm7360_probe,
   1866 	.remove		= xmm7360_remove,
   1867 };
   1868 
   1869 static int xmm7360_init(void)
   1870 {
   1871 	int ret;
   1872 	ret = alloc_chrdev_region(&xmm_base, 0, 8, "xmm");
   1873 	if (ret)
   1874 		return ret;
   1875 
   1876 	xmm7360_tty_driver = alloc_tty_driver(8);
   1877 	if (!xmm7360_tty_driver)
   1878 		return -ENOMEM;
   1879 
   1880 	xmm7360_tty_driver->driver_name = "xmm7360";
   1881 	xmm7360_tty_driver->name = "ttyXMM";
   1882 	xmm7360_tty_driver->major = 0;
   1883 	xmm7360_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
   1884 	xmm7360_tty_driver->subtype = SERIAL_TYPE_NORMAL;
   1885 	xmm7360_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
   1886 	xmm7360_tty_driver->init_termios = tty_std_termios;
   1887 	xmm7360_tty_driver->init_termios.c_cflag = B115200 | CS8 | CREAD | \
   1888 						HUPCL | CLOCAL;
   1889 	xmm7360_tty_driver->init_termios.c_lflag &= ~ECHO;
   1890 	xmm7360_tty_driver->init_termios.c_ispeed = 115200;
   1891 	xmm7360_tty_driver->init_termios.c_ospeed = 115200;
   1892 	tty_set_operations(xmm7360_tty_driver, &xmm7360_tty_ops);
   1893 
   1894 	ret = tty_register_driver(xmm7360_tty_driver);
   1895 	if (ret) {
   1896 		pr_err("xmm7360: failed to register xmm7360_tty driver\n");
   1897 		return ret;
   1898 	}
   1899 
   1900 
   1901 	ret = pci_register_driver(&xmm7360_driver);
   1902 	if (ret)
   1903 		return ret;
   1904 
   1905 	return 0;
   1906 }
   1907 
   1908 static void xmm7360_exit(void)
   1909 {
   1910 	pci_unregister_driver(&xmm7360_driver);
   1911 	unregister_chrdev_region(xmm_base, 8);
   1912 	tty_unregister_driver(xmm7360_tty_driver);
   1913 	put_tty_driver(xmm7360_tty_driver);
   1914 }
   1915 
   1916 module_init(xmm7360_init);
   1917 module_exit(xmm7360_exit);
   1918 
   1919 #endif /* __linux__ */
   1920 
   1921 #if defined(__OpenBSD__) || defined(__NetBSD__)
   1922 
   1923 /*
   1924  * RPC and trace devices behave as regular character device,
   1925  * other devices behave as terminal.
   1926  */
   1927 #define DEVCUA(x)	(minor(x) & 0x80)
   1928 #define DEVUNIT(x)	((minor(x) & 0x70) >> 4)
   1929 #define DEVFUNC_MASK	0x0f
   1930 #define DEVFUNC(x)	(minor(x) & DEVFUNC_MASK)
   1931 #define DEV_IS_TTY(x)	(DEVFUNC(x) == 2 || DEVFUNC(x) > 3)
   1932 
   1933 struct wwanc_softc {
   1934 #ifdef __OpenBSD__
   1935 	struct device		sc_devx;	/* gen. device info storage */
   1936 #endif
   1937 	struct device		*sc_dev;	/* generic device information */
   1938         pci_chipset_tag_t       sc_pc;
   1939         pcitag_t                sc_tag;
   1940 	bus_dma_tag_t		sc_dmat;
   1941 	pci_intr_handle_t	sc_pih;
   1942         void                    *sc_ih;         /* interrupt vectoring */
   1943 
   1944 	bus_space_tag_t		sc_bar0_tag;
   1945 	bus_space_handle_t	sc_bar0_handle;
   1946 	bus_size_t		sc_bar0_sz;
   1947 	bus_space_tag_t		sc_bar2_tag;
   1948 	bus_space_handle_t	sc_bar2_handle;
   1949 	bus_size_t		sc_bar2_sz;
   1950 
   1951 	struct xmm_dev		sc_xmm;
   1952 	struct tty		*sc_tty[XMM_QP_COUNT];
   1953 	struct device		*sc_net;
   1954 	struct selinfo		sc_selr, sc_selw;
   1955 	bool			sc_resume;
   1956 };
   1957 
   1958 struct wwanc_attach_args {
   1959 	enum wwanc_type {
   1960 		WWMC_TYPE_RPC,
   1961 		WWMC_TYPE_TRACE,
   1962 		WWMC_TYPE_TTY,
   1963 		WWMC_TYPE_NET
   1964 	} aa_type;
   1965 };
   1966 
   1967 static int     wwanc_match(struct device *, cfdata_t, void *);
   1968 static void    wwanc_attach(struct device *, struct device *, void *);
   1969 static int     wwanc_detach(struct device *, int);
   1970 
   1971 #ifdef __OpenBSD__
   1972 static int     wwanc_activate(struct device *, int);
   1973 
   1974 struct cfattach wwanc_ca = {
   1975         sizeof(struct wwanc_softc), wwanc_match, wwanc_attach,
   1976         wwanc_detach, wwanc_activate
   1977 };
   1978 
   1979 struct cfdriver wwanc_cd = {
   1980         NULL, "wwanc", DV_DULL
   1981 };
   1982 #endif
   1983 
   1984 #ifdef __NetBSD__
   1985 CFATTACH_DECL3_NEW(wwanc, sizeof(struct wwanc_softc),
   1986    wwanc_match, wwanc_attach, wwanc_detach, NULL,
   1987    NULL, NULL, DVF_DETACH_SHUTDOWN);
   1988 
   1989 static bool wwanc_pmf_suspend(device_t, const pmf_qual_t *);
   1990 static bool wwanc_pmf_resume(device_t, const pmf_qual_t *);
   1991 #endif /* __NetBSD__ */
   1992 
   1993 static int
   1994 wwanc_match(struct device *parent, cfdata_t match, void *aux)
   1995 {
   1996 	struct pci_attach_args *pa = aux;
   1997 
   1998 	return (PCI_VENDOR(pa->pa_id) == PCI_VENDOR_INTEL &&
   1999 		PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_XMM7360);
   2000 }
   2001 
   2002 static int xmm7360_dev_init(struct xmm_dev *xmm)
   2003 {
   2004 	int ret;
   2005 	int depth, page_size;
   2006 
   2007 	ret = xmm7360_base_init(xmm);
   2008 	if (ret)
   2009 		return ret;
   2010 
   2011 	/* Initialize queue pairs for later use */
   2012 	for (int num = 0; num < XMM_QP_COUNT; num++) {
   2013 		switch (num) {
   2014 		case 0:	/* net */
   2015 			depth = 128;
   2016 			page_size = TD_MAX_PAGE_SIZE;
   2017 			break;
   2018 		case 1:	/* rpc */
   2019 		case 3: /* trace */
   2020 			depth = 16;
   2021 			page_size = TD_MAX_PAGE_SIZE;
   2022 			break;
   2023 		default: /* tty */
   2024 			depth = 8;
   2025 			page_size = 4096;
   2026 			break;
   2027 		}
   2028 
   2029 		xmm7360_init_qp(xmm, num, depth, page_size);
   2030 	}
   2031 
   2032 	return 0;
   2033 }
   2034 
   2035 static void xmm7360_dev_deinit(struct xmm_dev *xmm)
   2036 {
   2037 	struct wwanc_softc *sc = device_private(xmm->dev);
   2038 	bool devgone = false;
   2039 	struct tty *tp;
   2040 
   2041 	xmm->error = -ENODEV;
   2042 
   2043 	/* network device should be gone by now */
   2044 	KASSERT(sc->sc_net == NULL);
   2045 	KASSERT(xmm->net == NULL);
   2046 
   2047 	/* free ttys */
   2048 	for (int i=0; i<XMM_QP_COUNT; i++) {
   2049 		tp = sc->sc_tty[i];
   2050 		if (tp) {
   2051 			KASSERT(DEV_IS_TTY(i));
   2052 			if (!devgone) {
   2053 				vdevgone(major(tp->t_dev), 0, DEVFUNC_MASK,
   2054 				    VCHR);
   2055 				devgone = true;
   2056 			}
   2057 			ttyfree(tp);
   2058 			sc->sc_tty[i] = NULL;
   2059 		}
   2060 	}
   2061 
   2062 	xmm7360_cmd_ring_free(xmm);
   2063 }
   2064 
   2065 static void
   2066 wwanc_io_wakeup(struct queue_pair *qp, int flag)
   2067 {
   2068         if (flag & FREAD) {
   2069                 selnotify(&qp->selr, POLLIN|POLLRDNORM, NOTE_SUBMIT);
   2070                 wakeup(qp->wq);
   2071         }
   2072         if (flag & FWRITE) {
   2073                 selnotify(&qp->selw, POLLOUT|POLLWRNORM, NOTE_SUBMIT);
   2074                 wakeup(qp->wq);
   2075         }
   2076 }
   2077 
   2078 static int
   2079 wwanc_intr(void *xsc)
   2080 {
   2081 	struct wwanc_softc *sc = xsc;
   2082 	struct xmm_dev *xmm = &sc->sc_xmm;
   2083 	struct queue_pair *qp;
   2084 
   2085 	xmm7360_poll(xmm);
   2086 	wakeup(&xmm->wq);
   2087 
   2088 	if (xmm->net && xmm->net->qp->open && xmm7360_qp_has_data(xmm->net->qp))
   2089 		xmm7360_net_poll(xmm);
   2090 
   2091 	for (int func = 1; func < XMM_QP_COUNT; func++) {
   2092 		qp = &xmm->qp[func];
   2093 		if (!qp->open)
   2094 			continue;
   2095 
   2096 		/* Check for input, wwancstart()/wwancwrite() does output */
   2097 		if (xmm7360_qp_has_data(qp)) {
   2098 			if (DEV_IS_TTY(func)) {
   2099 				int s = spltty();
   2100 				xmm7360_tty_poll_qp(qp);
   2101 				splx(s);
   2102 			}
   2103 			wwanc_io_wakeup(qp, FREAD);
   2104 		}
   2105 
   2106 		/* Wakeup/notify eventual writers */
   2107 		if (xmm7360_qp_can_write(qp))
   2108 			wwanc_io_wakeup(qp, FWRITE);
   2109 	}
   2110 
   2111 	return 1;
   2112 }
   2113 
   2114 static int
   2115 wwancprint(void *aux, const char *pnp)
   2116 {
   2117 	struct wwanc_attach_args *wa = aux;
   2118 
   2119 	if (pnp)
   2120                 printf("wwanc type %s at %s",
   2121 		    (wa->aa_type == WWMC_TYPE_NET) ? "net" : "unk", pnp);
   2122 	else
   2123 		printf(" type %s",
   2124 		    (wa->aa_type == WWMC_TYPE_NET) ? "net" : "unk");
   2125 
   2126 	return (UNCONF);
   2127 }
   2128 
   2129 static void
   2130 wwanc_attach_finish(struct device *self)
   2131 {
   2132 	struct wwanc_softc *sc = device_private(self);
   2133 
   2134 	if (xmm7360_dev_init(&sc->sc_xmm)) {
   2135 		/* error already printed */
   2136 		return;
   2137 	}
   2138 
   2139 	/* Attach the network device */
   2140 	struct wwanc_attach_args wa;
   2141 	memset(&wa, 0, sizeof(wa));
   2142 	wa.aa_type = WWMC_TYPE_NET;
   2143 	sc->sc_net = config_found(self, &wa, wwancprint, CFARGS_NONE);
   2144 }
   2145 
   2146 static void
   2147 wwanc_attach(struct device *parent, struct device *self, void *aux)
   2148 {
   2149 	struct wwanc_softc *sc = device_private(self);
   2150 	struct pci_attach_args *pa = aux;
   2151 	bus_space_tag_t memt;
   2152 	bus_space_handle_t memh;
   2153 	bus_size_t sz;
   2154 	int error;
   2155 	const char *intrstr;
   2156 #ifdef __OpenBSD__
   2157 	pci_intr_handle_t ih;
   2158 #endif
   2159 #ifdef __NetBSD__
   2160 	pci_intr_handle_t *ih;
   2161 	char intrbuf[PCI_INTRSTR_LEN];
   2162 #endif
   2163 
   2164 	sc->sc_dev = self;
   2165 	sc->sc_pc = pa->pa_pc;
   2166 	sc->sc_tag = pa->pa_tag;
   2167 	sc->sc_dmat = pa->pa_dmat;
   2168 
   2169 	/* map the register window, memory mapped 64-bit non-prefetchable */
   2170 	error = pci_mapreg_map(pa, WWAN_BAR0,
   2171 	    PCI_MAPREG_TYPE_MEM | PCI_MAPREG_MEM_TYPE_64BIT,
   2172 	    BUS_SPACE_MAP_LINEAR, &memt, &memh, NULL, &sz, 0);
   2173 	if (error != 0) {
   2174 		printf(": can't map mem space for BAR0 %d\n", error);
   2175 		return;
   2176 	}
   2177 	sc->sc_bar0_tag = memt;
   2178 	sc->sc_bar0_handle = memh;
   2179 	sc->sc_bar0_sz = sz;
   2180 
   2181 	error = pci_mapreg_map(pa, WWAN_BAR2,
   2182 	    PCI_MAPREG_TYPE_MEM | PCI_MAPREG_MEM_TYPE_64BIT,
   2183 	    BUS_SPACE_MAP_LINEAR, &memt, &memh, NULL, &sz, 0);
   2184 	if (error != 0) {
   2185 		bus_space_unmap(sc->sc_bar0_tag, sc->sc_bar0_handle,
   2186 		    sc->sc_bar0_sz);
   2187 		printf(": can't map mem space for BAR2\n");
   2188 		return;
   2189 	}
   2190 	sc->sc_bar2_tag = memt;
   2191 	sc->sc_bar2_handle = memh;
   2192 	sc->sc_bar2_sz = sz;
   2193 
   2194 	/* Set xmm members needed for xmm7360_dev_init() */
   2195 	sc->sc_xmm.dev = self;
   2196 	sc->sc_xmm.bar0 = bus_space_vaddr(sc->sc_bar0_tag, sc->sc_bar0_handle);
   2197 	sc->sc_xmm.bar2 = bus_space_vaddr(sc->sc_bar0_tag, sc->sc_bar2_handle);
   2198 	init_waitqueue_head(&sc->sc_xmm.wq);
   2199 
   2200 #ifdef __OpenBSD__
   2201 	if (pci_intr_map_msi(pa, &ih) && pci_intr_map(pa, &ih)) {
   2202 		printf(": can't map interrupt\n");
   2203 		goto fail;
   2204 	}
   2205 	sc->sc_pih = ih;
   2206 	intrstr = pci_intr_string(sc->sc_pc, ih);
   2207 	printf(": %s\n", intrstr);
   2208 #endif
   2209 #ifdef __NetBSD__
   2210 	if (pci_intr_alloc(pa, &ih, NULL, 0)) {
   2211 		printf(": can't map interrupt\n");
   2212 		goto fail;
   2213 	}
   2214 	sc->sc_pih = ih[0];
   2215 	intrstr = pci_intr_string(pa->pa_pc, ih[0], intrbuf, sizeof(intrbuf));
   2216 	aprint_normal(": LTE modem\n");
   2217 	aprint_normal_dev(sc->sc_dev, "interrupting at %s\n", intrstr);
   2218 #endif
   2219 
   2220 	/* Device initialized, can establish the interrupt now */
   2221 	sc->sc_ih = pci_intr_establish(sc->sc_pc, sc->sc_pih, IPL_NET,
   2222 	    wwanc_intr, sc, sc->sc_dev->dv_xname);
   2223 	if (sc->sc_ih == NULL) {
   2224 		printf("%s: can't establish interrupt\n", self->dv_xname);
   2225 		return;
   2226 	}
   2227 
   2228 #ifdef __NetBSD__
   2229 	if (!pmf_device_register(self, wwanc_pmf_suspend, wwanc_pmf_resume))
   2230 		aprint_error_dev(self, "couldn't establish power handler\n");
   2231 #endif
   2232 
   2233 	/*
   2234 	 * Device initialization requires working interrupts, so need
   2235 	 * to postpone this until they are enabled.
   2236 	 */
   2237 	config_mountroot(self, wwanc_attach_finish);
   2238 	return;
   2239 
   2240 fail:
   2241 	bus_space_unmap(sc->sc_bar0_tag, sc->sc_bar0_handle, sc->sc_bar0_sz);
   2242 	sc->sc_bar0_tag = 0;
   2243 	bus_space_unmap(sc->sc_bar2_tag, sc->sc_bar2_handle, sc->sc_bar2_sz);
   2244 	sc->sc_bar2_tag = 0;
   2245 	return;
   2246 }
   2247 
   2248 static int
   2249 wwanc_detach(struct device *self, int flags)
   2250 {
   2251 	int error;
   2252 	struct wwanc_softc *sc = device_private(self);
   2253 
   2254 	if (sc->sc_ih) {
   2255 		pci_intr_disestablish(sc->sc_pc, sc->sc_ih);
   2256 		sc->sc_ih = NULL;
   2257 	}
   2258 
   2259 	if (sc->sc_net) {
   2260 		error = config_detach_children(self, flags);
   2261 		if (error)
   2262 			return error;
   2263 		sc->sc_net = NULL;
   2264 	}
   2265 
   2266 	pmf_device_deregister(self);
   2267 
   2268 	xmm7360_dev_deinit(&sc->sc_xmm);
   2269 
   2270 	if (sc->sc_bar0_tag) {
   2271 		bus_space_unmap(sc->sc_bar0_tag, sc->sc_bar0_handle,
   2272 		    sc->sc_bar0_sz);
   2273 		sc->sc_bar0_tag = 0;
   2274 	}
   2275 	sc->sc_xmm.bar0 = NULL;
   2276 
   2277 	if (sc->sc_bar2_tag) {
   2278 		bus_space_unmap(sc->sc_bar2_tag, sc->sc_bar2_handle,
   2279 		    sc->sc_bar2_sz);
   2280 		sc->sc_bar2_tag = 0;
   2281 	}
   2282 	sc->sc_xmm.bar2 = NULL;
   2283 
   2284 	return 0;
   2285 }
   2286 
   2287 static void
   2288 wwanc_suspend(struct device *self)
   2289 {
   2290 	struct wwanc_softc *sc = device_private(self);
   2291 	struct xmm_dev *xmm = &sc->sc_xmm;
   2292 	struct queue_pair *qp;
   2293 
   2294 	KASSERT(!sc->sc_resume);
   2295 	KASSERT(xmm->cp != NULL);
   2296 
   2297 	for (int i = 0; i < XMM_QP_COUNT; i++) {
   2298 		qp = &xmm->qp[i];
   2299 		if (qp->open)
   2300 			xmm7360_qp_suspend(qp);
   2301 	}
   2302 
   2303 	xmm7360_cmd_ring_free(xmm);
   2304 	KASSERT(xmm->cp == NULL);
   2305 }
   2306 
   2307 static void
   2308 wwanc_resume(struct device *self)
   2309 {
   2310 	struct wwanc_softc *sc = device_private(self);
   2311 	struct xmm_dev *xmm = &sc->sc_xmm;
   2312 	struct queue_pair *qp;
   2313 
   2314 	KASSERT(xmm->cp == NULL);
   2315 
   2316 	xmm7360_base_init(xmm);
   2317 
   2318 	for (int i = 0; i < XMM_QP_COUNT; i++) {
   2319 		qp = &xmm->qp[i];
   2320 		if (qp->open)
   2321 			xmm7360_qp_resume(qp);
   2322 	}
   2323 }
   2324 
   2325 #ifdef __OpenBSD__
   2326 
   2327 static void
   2328 wwanc_defer_resume(void *xarg)
   2329 {
   2330 	struct device *self = xarg;
   2331 	struct wwanc_softc *sc = device_private(self);
   2332 
   2333 	tsleep(&sc->sc_resume, 0, "wwancdr", 2 * hz);
   2334 
   2335 	wwanc_resume(self);
   2336 
   2337 	(void)config_activate_children(self, DVACT_RESUME);
   2338 
   2339 	sc->sc_resume = false;
   2340 	kthread_exit(0);
   2341 }
   2342 
   2343 static int
   2344 wwanc_activate(struct device *self, int act)
   2345 {
   2346 	struct wwanc_softc *sc = device_private(self);
   2347 
   2348 	switch (act) {
   2349 	case DVACT_QUIESCE:
   2350 		(void)config_activate_children(self, act);
   2351 		break;
   2352 	case DVACT_SUSPEND:
   2353 		if (sc->sc_resume) {
   2354 			/* Refuse to suspend if resume still ongoing */
   2355 			printf("%s: not suspending, resume still ongoing\n",
   2356 			    self->dv_xname);
   2357 			return EBUSY;
   2358 		}
   2359 
   2360 		(void)config_activate_children(self, act);
   2361 		wwanc_suspend(self);
   2362 		break;
   2363 	case DVACT_RESUME:
   2364 		/*
   2365 		 * Modem reinitialization can take several seconds, defer
   2366 		 * it via kernel thread to avoid blocking the resume.
   2367 		 */
   2368 		sc->sc_resume = true;
   2369 		kthread_create(wwanc_defer_resume, self, NULL, "wwancres");
   2370 		break;
   2371 	default:
   2372 		break;
   2373 	}
   2374 
   2375 	return 0;
   2376 }
   2377 
   2378 cdev_decl(wwanc);
   2379 #endif /* __OpenBSD__ */
   2380 
   2381 #ifdef __NetBSD__
   2382 static bool
   2383 wwanc_pmf_suspend(device_t self, const pmf_qual_t *qual)
   2384 {
   2385 	wwanc_suspend(self);
   2386 	return true;
   2387 }
   2388 
   2389 static bool
   2390 wwanc_pmf_resume(device_t self, const pmf_qual_t *qual)
   2391 {
   2392 	wwanc_resume(self);
   2393 	return true;
   2394 }
   2395 
   2396 static dev_type_open(wwancopen);
   2397 static dev_type_close(wwancclose);
   2398 static dev_type_read(wwancread);
   2399 static dev_type_write(wwancwrite);
   2400 static dev_type_ioctl(wwancioctl);
   2401 static dev_type_poll(wwancpoll);
   2402 static dev_type_kqfilter(wwanckqfilter);
   2403 static dev_type_tty(wwanctty);
   2404 
   2405 const struct cdevsw wwanc_cdevsw = {
   2406 	.d_open = wwancopen,
   2407 	.d_close = wwancclose,
   2408 	.d_read = wwancread,
   2409 	.d_write = wwancwrite,
   2410 	.d_ioctl = wwancioctl,
   2411 	.d_stop = nullstop,
   2412 	.d_tty = wwanctty,
   2413 	.d_poll = wwancpoll,
   2414 	.d_mmap = nommap,
   2415 	.d_kqfilter = wwanckqfilter,
   2416 	.d_discard = nodiscard,
   2417 	.d_flag = D_TTY
   2418 };
   2419 #endif
   2420 
   2421 static int wwancparam(struct tty *, struct termios *);
   2422 static void wwancstart(struct tty *);
   2423 
   2424 static void xmm7360_os_handle_tty_idata(struct queue_pair *qp, const u8 *data, size_t nread)
   2425 {
   2426 	struct xmm_dev *xmm = qp->xmm;
   2427 	struct wwanc_softc *sc = device_private(xmm->dev);
   2428 	int func = qp->num;
   2429 	struct tty *tp = sc->sc_tty[func];
   2430 
   2431 	KASSERT(DEV_IS_TTY(func));
   2432 	KASSERT(tp);
   2433 
   2434 	for (int i = 0; i < nread; i++)
   2435 		LINESW(tp).l_rint(data[i], tp);
   2436 }
   2437 
   2438 int
   2439 wwancopen(dev_t dev, int flags, int mode, struct proc *p)
   2440 {
   2441 	int unit = DEVUNIT(dev);
   2442 	struct wwanc_softc *sc = device_lookup_private(&wwanc_cd, unit);
   2443 	struct tty *tp;
   2444 	int func, error;
   2445 
   2446 	if (sc == NULL)
   2447 		return ENXIO;
   2448 
   2449 	/* Only allow opening the rpc/trace/AT queue pairs */
   2450 	func = DEVFUNC(dev);
   2451 	if (func < 1 || func > 7)
   2452 		return ENXIO;
   2453 
   2454 	if (DEV_IS_TTY(dev)) {
   2455 		if (!sc->sc_tty[func]) {
   2456 			tp = sc->sc_tty[func] = ttymalloc(1000000);
   2457 
   2458 			tp->t_oproc = wwancstart;
   2459 		        tp->t_param = wwancparam;
   2460 			tp->t_dev = dev;
   2461 			tp->t_sc = (void *)sc;
   2462 		} else
   2463 			tp = sc->sc_tty[func];
   2464 
   2465 		if (!ISSET(tp->t_state, TS_ISOPEN)) {
   2466 			ttychars(tp);
   2467 			tp->t_iflag = TTYDEF_IFLAG;
   2468 			tp->t_oflag = TTYDEF_OFLAG;
   2469 			tp->t_lflag = TTYDEF_LFLAG;
   2470 			tp->t_cflag = TTYDEF_CFLAG;
   2471 			tp->t_ispeed = tp->t_ospeed = B115200;
   2472 			SET(tp->t_cflag, CS8 | CREAD | HUPCL | CLOCAL);
   2473 
   2474 			SET(tp->t_state, TS_CARR_ON);
   2475 		} else if (suser(p) != 0) {
   2476 			return EBUSY;
   2477 		}
   2478 
   2479 		error = LINESW(tp).l_open(dev, tp, p);
   2480 		if (error)
   2481 			return error;
   2482 	}
   2483 
   2484 	/* Initialize ring if qp not open yet */
   2485 	xmm7360_qp_start(&sc->sc_xmm.qp[func]);
   2486 
   2487 	return 0;
   2488 }
   2489 
   2490 int
   2491 wwancread(dev_t dev, struct uio *uio, int flag)
   2492 {
   2493 	struct wwanc_softc *sc = device_lookup_private(&wwanc_cd, DEVUNIT(dev));
   2494 	int func = DEVFUNC(dev);
   2495 
   2496 	KASSERT(sc != NULL);
   2497 
   2498 	if (DEV_IS_TTY(dev)) {
   2499 		struct tty *tp = sc->sc_tty[func];
   2500 
   2501 		return (LINESW(tp).l_read(tp, uio, flag));
   2502 	} else {
   2503 		struct queue_pair *qp = &sc->sc_xmm.qp[func];
   2504 		ssize_t ret;
   2505 		char *buf;
   2506 		size_t size, read = 0;
   2507 
   2508 #ifdef __OpenBSD__
   2509 		KASSERT(uio->uio_segflg == UIO_USERSPACE);
   2510 #endif
   2511 
   2512 		for (int i = 0; i < uio->uio_iovcnt; i++) {
   2513 			buf = uio->uio_iov[i].iov_base;
   2514 			size = uio->uio_iov[i].iov_len;
   2515 
   2516 			while (size > 0) {
   2517 				ret = xmm7360_qp_read_user(qp, buf, size);
   2518 				if (ret < 0) {
   2519 					/*
   2520 					 * This shadows -EPERM, but that is
   2521 					 * not returned by the call stack,
   2522 					 * so this condition is safe.
   2523 					 */
   2524 					return (ret == ERESTART) ? ret : -ret;
   2525 				}
   2526 
   2527 				KASSERT(ret > 0 && ret <= size);
   2528 				size -= ret;
   2529 				buf += ret;
   2530 				read += ret;
   2531 
   2532 				/* Reader will re-try if they want more */
   2533 				goto out;
   2534 			}
   2535 		}
   2536 
   2537 out:
   2538 		uio->uio_resid -= read;
   2539 		uio->uio_offset += read;
   2540 
   2541 		return 0;
   2542 	}
   2543 }
   2544 
   2545 int
   2546 wwancwrite(dev_t dev, struct uio *uio, int flag)
   2547 {
   2548 	struct wwanc_softc *sc = device_lookup_private(&wwanc_cd, DEVUNIT(dev));
   2549 	int func = DEVFUNC(dev);
   2550 
   2551 	if (DEV_IS_TTY(dev)) {
   2552 		struct tty *tp = sc->sc_tty[func];
   2553 
   2554 		return (LINESW(tp).l_write(tp, uio, flag));
   2555 	} else {
   2556 		struct queue_pair *qp = &sc->sc_xmm.qp[func];
   2557 		ssize_t ret;
   2558 		const char *buf;
   2559 		size_t size, wrote = 0;
   2560 
   2561 #ifdef __OpenBSD__
   2562 		KASSERT(uio->uio_segflg == UIO_USERSPACE);
   2563 #endif
   2564 
   2565 		for (int i = 0; i < uio->uio_iovcnt; i++) {
   2566 			buf = uio->uio_iov[i].iov_base;
   2567 			size = uio->uio_iov[i].iov_len;
   2568 
   2569 			while (size > 0) {
   2570 				ret = xmm7360_qp_write_user(qp, buf, size);
   2571 				if (ret < 0) {
   2572 					/*
   2573 					 * This shadows -EPERM, but that is
   2574 					 * not returned by the call stack,
   2575 					 * so this condition is safe.
   2576 					 */
   2577 					return (ret == ERESTART) ? ret : -ret;
   2578 				}
   2579 
   2580 				KASSERT(ret > 0 && ret <= size);
   2581 				size -= ret;
   2582 				buf += ret;
   2583 				wrote += ret;
   2584 			}
   2585 		}
   2586 
   2587 		uio->uio_resid -= wrote;
   2588 		uio->uio_offset += wrote;
   2589 
   2590 		return 0;
   2591 	}
   2592 }
   2593 
   2594 int
   2595 wwancioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
   2596 {
   2597 	struct wwanc_softc *sc = device_lookup_private(&wwanc_cd, DEVUNIT(dev));
   2598 	int error;
   2599 
   2600 	if (DEV_IS_TTY(dev)) {
   2601 		struct tty *tp = sc->sc_tty[DEVFUNC(dev)];
   2602 		KASSERT(tp);
   2603 
   2604 		error = LINESW(tp).l_ioctl(tp, cmd, data, flag, p);
   2605 		if (error >= 0)
   2606 			return error;
   2607 		error = ttioctl(tp, cmd, data, flag, p);
   2608 		if (error >= 0)
   2609 			return error;
   2610 	}
   2611 
   2612 	return ENOTTY;
   2613 }
   2614 
   2615 int
   2616 wwancclose(dev_t dev, int flag, int mode, struct proc *p)
   2617 {
   2618 	struct wwanc_softc *sc = device_lookup_private(&wwanc_cd, DEVUNIT(dev));
   2619 	int func = DEVFUNC(dev);
   2620 
   2621 	if (DEV_IS_TTY(dev)) {
   2622 		struct tty *tp = sc->sc_tty[func];
   2623 		KASSERT(tp);
   2624 
   2625 		CLR(tp->t_state, TS_BUSY | TS_FLUSH);
   2626 		LINESW(tp).l_close(tp, flag, p);
   2627 		ttyclose(tp);
   2628 	}
   2629 
   2630 	xmm7360_qp_stop(&sc->sc_xmm.qp[func]);
   2631 
   2632 	return 0;
   2633 }
   2634 
   2635 struct tty *
   2636 wwanctty(dev_t dev)
   2637 {
   2638 	struct wwanc_softc *sc = device_lookup_private(&wwanc_cd, DEVUNIT(dev));
   2639 	struct tty *tp = sc->sc_tty[DEVFUNC(dev)];
   2640 
   2641 	KASSERT(DEV_IS_TTY(dev));
   2642 	KASSERT(tp);
   2643 
   2644 	return tp;
   2645 }
   2646 
   2647 static int
   2648 wwancparam(struct tty *tp, struct termios *t)
   2649 {
   2650 	struct wwanc_softc *sc __diagused = (struct wwanc_softc *)tp->t_sc;
   2651 	dev_t dev = tp->t_dev;
   2652 	int func __diagused = DEVFUNC(dev);
   2653 
   2654 	KASSERT(DEV_IS_TTY(dev));
   2655 	KASSERT(tp == sc->sc_tty[func]);
   2656 	/* Can't assert tty_locked(), it's not taken when called via ttioctl()*/
   2657 
   2658 	/* Nothing to set on hardware side, just copy values */
   2659 	tp->t_ispeed = t->c_ispeed;
   2660 	tp->t_ospeed = t->c_ospeed;
   2661 	tp->t_cflag = t->c_cflag;
   2662 
   2663 	return 0;
   2664 }
   2665 
   2666 static void
   2667 wwancstart(struct tty *tp)
   2668 {
   2669 	struct wwanc_softc *sc = (struct wwanc_softc *)tp->t_sc;
   2670 	dev_t dev = tp->t_dev;
   2671 	int func = DEVFUNC(dev);
   2672 	struct queue_pair *qp = &sc->sc_xmm.qp[func];
   2673 	int n, written;
   2674 
   2675 	KASSERT(DEV_IS_TTY(dev));
   2676 	KASSERT(tp == sc->sc_tty[func]);
   2677 	tty_locked();
   2678 
   2679 	if (ISSET(tp->t_state, TS_BUSY) || !xmm7360_qp_can_write(qp))
   2680 		return;
   2681 	if (tp->t_outq.c_cc == 0)
   2682 		return;
   2683 
   2684 	/*
   2685 	 * If we can write, we can write full qb page_size amount of data.
   2686 	 * Once q_to_b() is called, the data must be trasmitted - q_to_b()
   2687 	 * removes them from the tty output queue. Partial write is not
   2688 	 * possible.
   2689 	 */
   2690 	KASSERT(sizeof(qp->user_buf) >= qp->page_size);
   2691 	SET(tp->t_state, TS_BUSY);
   2692 	n = q_to_b(&tp->t_outq, qp->user_buf, qp->page_size);
   2693 	KASSERT(n > 0);
   2694 	KASSERT(n <= qp->page_size);
   2695 	written = xmm7360_qp_write(qp, qp->user_buf, n);
   2696 	CLR(tp->t_state, TS_BUSY);
   2697 
   2698 	if (written != n) {
   2699 		dev_err(sc->sc_dev, "xmm7360_qp_write(%d) failed %d != %d\n",
   2700 		    func, written, n);
   2701 		/* nothing to recover, just return */
   2702 	}
   2703 }
   2704 
   2705 int
   2706 wwancpoll(dev_t dev, int events, struct proc *p)
   2707 {
   2708 	struct wwanc_softc *sc = device_lookup_private(&wwanc_cd, DEVUNIT(dev));
   2709 	int func = DEVFUNC(dev);
   2710 	struct queue_pair *qp = &sc->sc_xmm.qp[func];
   2711 	int mask = 0;
   2712 
   2713 	if (DEV_IS_TTY(dev)) {
   2714 #ifdef __OpenBSD__
   2715 		return ttpoll(dev, events, p);
   2716 #endif
   2717 #ifdef __NetBSD__
   2718 		struct tty *tp = sc->sc_tty[func];
   2719 
   2720 		return LINESW(tp).l_poll(tp, events, p);
   2721 #endif
   2722 	}
   2723 
   2724 	KASSERT(!DEV_IS_TTY(dev));
   2725 
   2726 	if (qp->xmm->error) {
   2727 		mask |= POLLHUP;
   2728 		goto out;
   2729 	}
   2730 
   2731 	if (xmm7360_qp_has_data(qp))
   2732 		mask |= POLLIN | POLLRDNORM;
   2733 
   2734 	if (xmm7360_qp_can_write(qp))
   2735 		mask |= POLLOUT | POLLWRNORM;
   2736 
   2737 out:
   2738 	if ((mask & events) == 0) {
   2739 		if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND))
   2740 			selrecord(p, &sc->sc_selr);
   2741                 if (events & (POLLOUT | POLLWRNORM))
   2742                         selrecord(p, &sc->sc_selw);
   2743 	}
   2744 
   2745 	return mask & events;
   2746 }
   2747 
   2748 static void
   2749 filt_wwancrdetach(struct knote *kn)
   2750 {
   2751 	struct queue_pair *qp = (struct queue_pair *)kn->kn_hook;
   2752 
   2753 	tty_lock();
   2754 	klist_remove(&qp->selr.si_note, kn);
   2755 	tty_unlock();
   2756 }
   2757 
   2758 static int
   2759 filt_wwancread(struct knote *kn, long hint)
   2760 {
   2761 	struct queue_pair *qp = (struct queue_pair *)kn->kn_hook;
   2762 
   2763 	kn->kn_data = 0;
   2764 
   2765 	if (!qp->open) {
   2766 		knote_set_eof(kn, 0);
   2767 		return (1);
   2768 	} else {
   2769 		kn->kn_data = xmm7360_qp_has_data(qp) ? 1 : 0;
   2770 	}
   2771 
   2772 	return (kn->kn_data > 0);
   2773 }
   2774 
   2775 static void
   2776 filt_wwancwdetach(struct knote *kn)
   2777 {
   2778 	struct queue_pair *qp = (struct queue_pair *)kn->kn_hook;
   2779 
   2780 	tty_lock();
   2781 	klist_remove(&qp->selw.si_note, kn);
   2782 	tty_unlock();
   2783 }
   2784 
   2785 static int
   2786 filt_wwancwrite(struct knote *kn, long hint)
   2787 {
   2788 	struct queue_pair *qp = (struct queue_pair *)kn->kn_hook;
   2789 
   2790 	kn->kn_data = 0;
   2791 
   2792 	if (qp->open) {
   2793 		if (xmm7360_qp_can_write(qp))
   2794 			kn->kn_data = qp->page_size;
   2795 	}
   2796 
   2797 	return (kn->kn_data > 0);
   2798 }
   2799 
   2800 static const struct filterops wwancread_filtops = {
   2801 	XMM_KQ_ISFD_INITIALIZER,
   2802 	.f_attach	= NULL,
   2803 	.f_detach	= filt_wwancrdetach,
   2804 	.f_event	= filt_wwancread,
   2805 };
   2806 
   2807 static const struct filterops wwancwrite_filtops = {
   2808 	XMM_KQ_ISFD_INITIALIZER,
   2809 	.f_attach	= NULL,
   2810 	.f_detach	= filt_wwancwdetach,
   2811 	.f_event	= filt_wwancwrite,
   2812 };
   2813 
   2814 int
   2815 wwanckqfilter(dev_t dev, struct knote *kn)
   2816 {
   2817 	struct wwanc_softc *sc = device_lookup_private(&wwanc_cd, DEVUNIT(dev));
   2818 	int func = DEVFUNC(dev);
   2819 	struct queue_pair *qp = &sc->sc_xmm.qp[func];
   2820 	struct klist *klist;
   2821 
   2822 	if (DEV_IS_TTY(func))
   2823 		return ttkqfilter(dev, kn);
   2824 
   2825 	KASSERT(!DEV_IS_TTY(func));
   2826 
   2827 	switch (kn->kn_filter) {
   2828 	case EVFILT_READ:
   2829 		klist = &qp->selr.si_note;
   2830 		kn->kn_fop = &wwancread_filtops;
   2831 		break;
   2832 	case EVFILT_WRITE:
   2833 		klist = &qp->selw.si_note;
   2834 		kn->kn_fop = &wwancwrite_filtops;
   2835 		break;
   2836 	default:
   2837 		return (EINVAL);
   2838 	}
   2839 
   2840 	kn->kn_hook = (void *)qp;
   2841 
   2842 	tty_lock();
   2843 	klist_insert(klist, kn);
   2844 	tty_unlock();
   2845 
   2846 	return (0);
   2847 }
   2848 
   2849 static void *
   2850 dma_alloc_coherent(struct device *self, size_t sz, dma_addr_t *physp, int flags)
   2851 {
   2852 	struct wwanc_softc *sc = device_private(self);
   2853 	bus_dma_segment_t seg;
   2854 	int nsegs;
   2855 	int error;
   2856 	caddr_t kva;
   2857 
   2858 	error = bus_dmamem_alloc(sc->sc_dmat, sz, 0, 0, &seg, 1, &nsegs,
   2859 	    BUS_DMA_WAITOK);
   2860 	if (error) {
   2861 		panic("%s: bus_dmamem_alloc(%lu) failed %d\n",
   2862 		    self->dv_xname, (unsigned long)sz, error);
   2863 		/* NOTREACHED */
   2864 	}
   2865 
   2866 	KASSERT(nsegs == 1);
   2867 	KASSERT(seg.ds_len == round_page(sz));
   2868 
   2869 	error = bus_dmamem_map(sc->sc_dmat, &seg, nsegs, sz, &kva,
   2870 	    BUS_DMA_WAITOK | BUS_DMA_COHERENT);
   2871 	if (error) {
   2872 		panic("%s: bus_dmamem_alloc(%lu) failed %d\n",
   2873 		    self->dv_xname, (unsigned long)sz, error);
   2874 		/* NOTREACHED */
   2875 	}
   2876 
   2877 	memset(kva, 0, sz);
   2878 	*physp = seg.ds_addr;
   2879 	return (void *)kva;
   2880 }
   2881 
   2882 static void
   2883 dma_free_coherent(struct device *self, size_t sz, volatile void *vaddr, dma_addr_t phys)
   2884 {
   2885 	struct wwanc_softc *sc = device_private(self);
   2886 	bus_dma_segment_t seg;
   2887 
   2888 	sz = round_page(sz);
   2889 
   2890 	bus_dmamem_unmap(sc->sc_dmat, __UNVOLATILE(vaddr), sz);
   2891 
   2892 	/* this does't need the exact seg returned by bus_dmamem_alloc() */
   2893 	memset(&seg, 0, sizeof(seg));
   2894 	seg.ds_addr = phys;
   2895 	seg.ds_len  = sz;
   2896 	bus_dmamem_free(sc->sc_dmat, &seg, 1);
   2897 }
   2898 
   2899 struct wwan_softc {
   2900 #ifdef __OpenBSD__
   2901 	struct device		sc_devx;	/* gen. device info storage */
   2902 #endif
   2903 	struct device		*sc_dev;	/* generic device */
   2904 	struct wwanc_softc	*sc_parent;	/* parent device */
   2905 	struct ifnet		sc_ifnet;	/* network-visible interface */
   2906 	struct xmm_net		sc_xmm_net;
   2907 };
   2908 
   2909 static void xmm7360_os_handle_net_frame(struct xmm_dev *xmm, const u8 *buf, size_t sz)
   2910 {
   2911 	struct wwanc_softc *sc = device_private(xmm->dev);
   2912 	struct wwan_softc *sc_if = device_private(sc->sc_net);
   2913 	struct ifnet *ifp = &sc_if->sc_ifnet;
   2914 	struct mbuf *m;
   2915 
   2916 	KASSERT(sz <= MCLBYTES);
   2917 
   2918 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   2919 	if (!m)
   2920 		return;
   2921 	if (sz > MHLEN) {
   2922 		MCLGETI(m, M_DONTWAIT, NULL, sz);
   2923 		if ((m->m_flags & M_EXT) == 0) {
   2924 			m_freem(m);
   2925 			return;
   2926 		}
   2927 	}
   2928 	m->m_len = m->m_pkthdr.len = sz;
   2929 
   2930 	/*
   2931 	 * No explicit alignment necessary - there is no ethernet header,
   2932 	 * so IP address is already aligned.
   2933 	 */
   2934 	KASSERT(m->m_pkthdr.len == sz);
   2935 	m_copyback(m, 0, sz, (const void *)buf, M_NOWAIT);
   2936 
   2937 #ifdef __OpenBSD__
   2938 	struct mbuf_list ml = MBUF_LIST_INITIALIZER();
   2939 	ml_enqueue(&ml, m);
   2940 	if_input(ifp, &ml);
   2941 #endif
   2942 #ifdef __NetBSD__
   2943 	if_percpuq_enqueue(ifp->if_percpuq, m);
   2944 #endif
   2945 }
   2946 
   2947 static void
   2948 xmm7360_os_handle_net_dequeue(struct xmm_net *xn, struct mux_frame *frame)
   2949 {
   2950 	struct wwan_softc *sc_if =
   2951 		container_of(xn, struct wwan_softc, sc_xmm_net);
   2952 	struct ifnet *ifp = &sc_if->sc_ifnet;
   2953 	struct mbuf *m;
   2954 	int ret;
   2955 
   2956 	MUTEX_ASSERT_LOCKED(&xn->lock);
   2957 
   2958 	while ((m = ifq_deq_begin(&ifp->if_snd))) {
   2959 		/*
   2960 		 * xmm7360_mux_frame_append_packet() requires single linear
   2961 		 * buffer, so try m_defrag(). Another option would be
   2962 		 * using m_copydata() into an intermediate buffer.
   2963 		 */
   2964 		if (m->m_next) {
   2965 			if (m_defrag(m, M_DONTWAIT) != 0 || m->m_next) {
   2966 				/* Can't defrag, drop and continue */
   2967 				ifq_deq_commit(&ifp->if_snd, m);
   2968 				m_freem(m);
   2969 				continue;
   2970 			}
   2971 		}
   2972 
   2973 		ret = xmm7360_mux_frame_append_packet(frame,
   2974 		    mtod(m, void *), m->m_pkthdr.len);
   2975 		if (ret) {
   2976 			/* No more space in the frame */
   2977 			ifq_deq_rollback(&ifp->if_snd, m);
   2978 			break;
   2979 		}
   2980 		ifq_deq_commit(&ifp->if_snd, m);
   2981 
   2982 		/* Send a copy of the frame to the BPF listener */
   2983 		BPF_MTAP_OUT(ifp, m);
   2984 
   2985 		m_freem(m);
   2986 	}
   2987 }
   2988 
   2989 static void xmm7360_os_handle_net_txwake(struct xmm_net *xn)
   2990 {
   2991 	struct wwan_softc *sc_if =
   2992 		container_of(xn, struct wwan_softc, sc_xmm_net);
   2993 	struct ifnet *ifp = &sc_if->sc_ifnet;
   2994 
   2995 	MUTEX_ASSERT_LOCKED(&xn->lock);
   2996 
   2997 	KASSERT(xmm7360_qp_can_write(xn->qp));
   2998 	if (ifq_is_oactive(&ifp->if_snd)) {
   2999 		ifq_clr_oactive(&ifp->if_snd);
   3000 #ifdef __OpenBSD__
   3001 		ifq_restart(&ifp->if_snd);
   3002 #endif
   3003 #ifdef __NetBSD__
   3004 		if_schedule_deferred_start(ifp);
   3005 #endif
   3006 	}
   3007 }
   3008 
   3009 #ifdef __OpenBSD__
   3010 /*
   3011  * Process received raw IPv4/IPv6 packet. There is no encapsulation.
   3012  */
   3013 static int
   3014 wwan_if_input(struct ifnet *ifp, struct mbuf *m, void *cookie)
   3015 {
   3016 	const uint8_t *data = mtod(m, uint8_t *);
   3017 	void (*input)(struct ifnet *, struct mbuf *);
   3018 	u8 ip_version;
   3019 
   3020 	ip_version = data[0] >> 4;
   3021 
   3022 	switch (ip_version) {
   3023 	case IPVERSION:
   3024 		input = ipv4_input;
   3025 		break;
   3026 	case (IPV6_VERSION >> 4):
   3027 		input = ipv6_input;
   3028 		break;
   3029 	default:
   3030 		/* Unknown protocol, just drop packet */
   3031 		m_freem(m);
   3032 		return 1;
   3033 		/* NOTREACHED */
   3034 	}
   3035 
   3036 	/* Needed for tcpdump(1) et.al */
   3037 	m->m_pkthdr.ph_rtableid = ifp->if_rdomain;
   3038 	m_adj(m, sizeof(u_int32_t));
   3039 
   3040 	(*input)(ifp, m);
   3041 	return 1;
   3042 }
   3043 #endif /* __OpenBSD__ */
   3044 
   3045 #ifdef __NetBSD__
   3046 static bool wwan_pmf_suspend(device_t, const pmf_qual_t *);
   3047 
   3048 /*
   3049  * Process received raw IPv4/IPv6 packet. There is no encapsulation.
   3050  */
   3051 static void
   3052 wwan_if_input(struct ifnet *ifp, struct mbuf *m)
   3053 {
   3054 	const uint8_t *data = mtod(m, uint8_t *);
   3055 	pktqueue_t *pktq = NULL;
   3056 	u8 ip_version;
   3057 
   3058 	KASSERT(!cpu_intr_p());
   3059 	KASSERT((m->m_flags & M_PKTHDR) != 0);
   3060 
   3061 	if ((ifp->if_flags & IFF_UP) == 0) {
   3062 		m_freem(m);
   3063 		return;
   3064 	}
   3065 
   3066 	if_statadd(ifp, if_ibytes, m->m_pkthdr.len);
   3067 
   3068 	/*
   3069 	 * The interface can't receive packets for other host, so never
   3070 	 * really IFF_PROMISC even if bpf listener is attached.
   3071 	 */
   3072 	if (pfil_run_hooks(ifp->if_pfil, &m, ifp, PFIL_IN) != 0)
   3073 		return;
   3074 	if (m == NULL)
   3075 		return;
   3076 
   3077 	ip_version = data[0] >> 4;
   3078 	switch (ip_version) {
   3079 #ifdef INET
   3080 	case IPVERSION:
   3081 #ifdef GATEWAY
   3082 		if (ipflow_fastforward(m))
   3083 			return;
   3084 #endif
   3085 		pktq = ip_pktq;
   3086 		break;
   3087 #endif /* INET */
   3088 #ifdef INET6
   3089 	case (IPV6_VERSION >> 4):
   3090 		if (__predict_false(!in6_present)) {
   3091 			m_freem(m);
   3092 			return;
   3093 		}
   3094 #ifdef GATEWAY
   3095 		if (ip6flow_fastforward(&m))
   3096 			return;
   3097 #endif
   3098 		pktq = ip6_pktq;
   3099 		break;
   3100 #endif /* INET6 */
   3101 	default:
   3102 		/* Unknown protocol, just drop packet */
   3103 		m_freem(m);
   3104 		return;
   3105 		/* NOTREACHED */
   3106 	}
   3107 
   3108 	KASSERT(pktq != NULL);
   3109 
   3110 	/* No errors.  Receive the packet. */
   3111 	m_set_rcvif(m, ifp);
   3112 
   3113 #ifdef NET_MPSAFE
   3114 	const u_int h = curcpu()->ci_index;
   3115 #else
   3116 	const uint32_t h = pktq_rps_hash(m);
   3117 #endif
   3118 	if (__predict_false(!pktq_enqueue(pktq, m, h))) {
   3119 		m_freem(m);
   3120 	}
   3121 }
   3122 #endif
   3123 
   3124 /*
   3125  * Transmit raw IPv4/IPv6 packet. No encapsulation necessary.
   3126  */
   3127 static int
   3128 wwan_if_output(struct ifnet *ifp, struct mbuf *m,
   3129     IF_OUTPUT_CONST struct sockaddr *dst, IF_OUTPUT_CONST struct rtentry *rt)
   3130 {
   3131 	// there is no ethernet frame, this means no bridge(4) handling
   3132 	return (if_enqueue(ifp, m));
   3133 }
   3134 
   3135 static int
   3136 wwan_if_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
   3137 {
   3138 	struct wwan_softc *sc_if = ifp->if_softc;
   3139 	int error = 0;
   3140 	int s;
   3141 
   3142 	s = splnet();
   3143 
   3144 	switch (cmd) {
   3145 #ifdef __NetBSD__
   3146 	case SIOCINITIFADDR:
   3147 #endif
   3148 #ifdef __OpenBSD__
   3149 	case SIOCAIFADDR:
   3150 	case SIOCAIFADDR_IN6:
   3151 	case SIOCSIFADDR:
   3152 #endif
   3153 		/* Make interface ready to run if address is assigned */
   3154 		ifp->if_flags |= IFF_UP;
   3155 		if (!(ifp->if_flags & IFF_RUNNING)) {
   3156 			ifp->if_flags |= IFF_RUNNING;
   3157 			xmm7360_mux_control(&sc_if->sc_xmm_net, 1, 0, 0, 0);
   3158 		}
   3159 		break;
   3160 	case SIOCSIFFLAGS:
   3161 	case SIOCADDMULTI:
   3162 	case SIOCDELMULTI:
   3163 		/* nothing special to do */
   3164 		break;
   3165 	case SIOCSIFMTU:
   3166 		error = ENOTTY;
   3167 		break;
   3168 	default:
   3169 #ifdef __NetBSD__
   3170 		/*
   3171 		 * Call common code for SIOCG* ioctls. In OpenBSD those ioctls
   3172 		 * are handled in ifioctl(), and the if_ioctl is not called
   3173 		 * for them at all.
   3174 		 */
   3175 		error = ifioctl_common(ifp, cmd, data);
   3176 		if (error == ENETRESET)
   3177 			error = 0;
   3178 #endif
   3179 #ifdef __OpenBSD__
   3180 		error = ENOTTY;
   3181 #endif
   3182 		break;
   3183 	}
   3184 
   3185 	splx(s);
   3186 
   3187 	return error;
   3188 }
   3189 
   3190 static void
   3191 wwan_if_start(struct ifnet *ifp)
   3192 {
   3193 	struct wwan_softc *sc = ifp->if_softc;
   3194 
   3195 	mutex_lock(&sc->sc_xmm_net.lock);
   3196 	while (!ifq_empty(&ifp->if_snd)) {
   3197 		if (!xmm7360_qp_can_write(sc->sc_xmm_net.qp)) {
   3198 			break;
   3199 		}
   3200 		xmm7360_net_flush(&sc->sc_xmm_net);
   3201 	}
   3202 	mutex_unlock(&sc->sc_xmm_net.lock);
   3203 }
   3204 
   3205 static int
   3206 wwan_match(struct device *parent, cfdata_t match, void *aux)
   3207 {
   3208 	struct wwanc_attach_args *wa = aux;
   3209 
   3210 	return (wa->aa_type == WWMC_TYPE_NET);
   3211 }
   3212 
   3213 static void
   3214 wwan_attach(struct device *parent, struct device *self, void *aux)
   3215 {
   3216 	struct wwan_softc *sc_if = device_private(self);
   3217 	struct ifnet *ifp = &sc_if->sc_ifnet;
   3218 	struct xmm_dev *xmm;
   3219 	struct xmm_net *xn;
   3220 
   3221 	sc_if->sc_dev = self;
   3222 	sc_if->sc_parent = device_private(parent);
   3223 	xmm = sc_if->sc_xmm_net.xmm = &sc_if->sc_parent->sc_xmm;
   3224 	xn = &sc_if->sc_xmm_net;
   3225 	mutex_init(&xn->lock);
   3226 
   3227 	/* QP already initialized in parent, just set pointers and start */
   3228 	xn->qp = &xmm->qp[0];
   3229 	xmm7360_qp_start(xn->qp);
   3230 	xmm->net = xn;
   3231 
   3232 	ifp->if_softc = sc_if;
   3233 	ifp->if_flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST \
   3234 		| IFF_SIMPLEX;
   3235 	ifp->if_ioctl = wwan_if_ioctl;
   3236 	ifp->if_start = wwan_if_start;
   3237 	ifp->if_mtu = 1500;
   3238 	ifp->if_hardmtu = 1500;
   3239 	ifp->if_type = IFT_OTHER;
   3240 	IFQ_SET_MAXLEN(&ifp->if_snd, xn->qp->depth);
   3241 	IFQ_SET_READY(&ifp->if_snd);
   3242 	bcopy(sc_if->sc_dev->dv_xname, ifp->if_xname, IFNAMSIZ);
   3243 
   3244 	/* Call MI attach routines. */
   3245 	if_attach(ifp);
   3246 
   3247 	/* Hook custom input and output processing, and dummy sadl */
   3248 	ifp->if_output = wwan_if_output;
   3249 	if_ih_insert(ifp, wwan_if_input, NULL);
   3250 	if_deferred_start_init(ifp, NULL);
   3251 	if_alloc_sadl(ifp);
   3252 #if NBPFILTER > 0
   3253 #ifdef __OpenBSD__
   3254 	bpfattach(&ifp->if_bpf, ifp, DLT_LOOP, sizeof(u_int32_t));
   3255 #endif
   3256 #ifdef __NetBSD__
   3257 	bpfattach(&ifp->if_bpf, ifp, DLT_RAW, 0);
   3258 #endif
   3259 #endif
   3260 
   3261 	printf("\n");
   3262 
   3263 #ifdef __NetBSD__
   3264 	if (pmf_device_register(self, wwan_pmf_suspend, NULL))
   3265 		pmf_class_network_register(self, ifp);
   3266 	else
   3267 		aprint_error_dev(self, "couldn't establish power handler\n");
   3268 #endif
   3269 }
   3270 
   3271 static int
   3272 wwan_detach(struct device *self, int flags)
   3273 {
   3274 	struct wwan_softc *sc_if = device_private(self);
   3275 	struct ifnet *ifp = &sc_if->sc_ifnet;
   3276 
   3277 	if (ifp->if_flags & (IFF_UP|IFF_RUNNING))
   3278 		ifp->if_flags &= ~(IFF_UP|IFF_RUNNING);
   3279 
   3280 	pmf_device_deregister(self);
   3281 
   3282 	if_ih_remove(ifp, wwan_if_input, NULL);
   3283 	if_detach(ifp);
   3284 
   3285 	xmm7360_qp_stop(sc_if->sc_xmm_net.qp);
   3286 
   3287 	sc_if->sc_xmm_net.xmm->net = NULL;
   3288 
   3289 	return 0;
   3290 }
   3291 
   3292 static void
   3293 wwan_suspend(struct device *self)
   3294 {
   3295 	struct wwan_softc *sc_if = device_private(self);
   3296 	struct ifnet *ifp = &sc_if->sc_ifnet;
   3297 
   3298 	/*
   3299 	 * Interface is marked down on suspend, and needs to be reconfigured
   3300 	 * after resume.
   3301 	 */
   3302 	if (ifp->if_flags & (IFF_UP|IFF_RUNNING))
   3303 		ifp->if_flags &= ~(IFF_UP|IFF_RUNNING);
   3304 
   3305 	ifq_purge(&ifp->if_snd);
   3306 }
   3307 
   3308 #ifdef __OpenBSD__
   3309 static int
   3310 wwan_activate(struct device *self, int act)
   3311 {
   3312 	switch (act) {
   3313 	case DVACT_QUIESCE:
   3314 	case DVACT_SUSPEND:
   3315 		wwan_suspend(self);
   3316 		break;
   3317 	case DVACT_RESUME:
   3318 		/* Nothing to do */
   3319 		break;
   3320 	}
   3321 
   3322 	return 0;
   3323 }
   3324 
   3325 struct cfattach wwan_ca = {
   3326         sizeof(struct wwan_softc), wwan_match, wwan_attach,
   3327         wwan_detach, wwan_activate
   3328 };
   3329 
   3330 struct cfdriver wwan_cd = {
   3331         NULL, "wwan", DV_IFNET
   3332 };
   3333 #endif /* __OpenBSD__ */
   3334 
   3335 #ifdef __NetBSD__
   3336 static bool
   3337 wwan_pmf_suspend(device_t self, const pmf_qual_t *qual)
   3338 {
   3339 	wwan_suspend(self);
   3340 	return true;
   3341 }
   3342 
   3343 CFATTACH_DECL3_NEW(wwan, sizeof(struct wwan_softc),
   3344    wwan_match, wwan_attach, wwan_detach, NULL,
   3345    NULL, NULL, DVF_DETACH_SHUTDOWN);
   3346 #endif /* __NetBSD__ */
   3347 
   3348 #endif /* __OpenBSD__ || __NetBSD__ */
   3349