Home | History | Annotate | Line # | Download | only in usb
if_umb.c revision 1.4.4.2
      1 /*	$NetBSD: if_umb.c,v 1.4.4.2 2018/09/06 06:56:04 pgoyette Exp $ */
      2 /*	$OpenBSD: if_umb.c,v 1.18 2018/02/19 08:59:52 mpi Exp $ */
      3 
      4 /*
      5  * Copyright (c) 2016 genua mbH
      6  * All rights reserved.
      7  *
      8  * Permission to use, copy, modify, and distribute this software for any
      9  * purpose with or without fee is hereby granted, provided that the above
     10  * copyright notice and this permission notice appear in all copies.
     11  *
     12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     19  */
     20 
     21 /*
     22  * Mobile Broadband Interface Model specification:
     23  * http://www.usb.org/developers/docs/devclass_docs/MBIM10Errata1_073013.zip
     24  * Compliance testing guide
     25  * http://www.usb.org/developers/docs/devclass_docs/MBIM-Compliance-1.0.pdf
     26  */
     27 
     28 #include <sys/cdefs.h>
     29 __KERNEL_RCSID(0, "$NetBSD: if_umb.c,v 1.4.4.2 2018/09/06 06:56:04 pgoyette Exp $");
     30 
     31 #ifdef _KERNEL_OPT
     32 #include "opt_inet.h"
     33 #endif
     34 
     35 #include <sys/param.h>
     36 #include <sys/device.h>
     37 #include <sys/endian.h>
     38 #include <sys/kauth.h>
     39 #include <sys/kernel.h>
     40 #include <sys/kmem.h>
     41 #include <sys/mbuf.h>
     42 #include <sys/rndsource.h>
     43 #include <sys/socket.h>
     44 #include <sys/syslog.h>
     45 #include <sys/systm.h>
     46 
     47 #include <net/bpf.h>
     48 #include <net/if.h>
     49 #include <net/if_media.h>
     50 #include <net/if_types.h>
     51 
     52 #ifdef INET
     53 #include <netinet/in.h>
     54 #include <netinet/if_inarp.h>
     55 #include <netinet/in_var.h>
     56 #include <netinet/ip.h>
     57 #endif
     58 
     59 #include <dev/usb/usb.h>
     60 #include <dev/usb/usbdi.h>
     61 #include <dev/usb/usbdivar.h>
     62 #include <dev/usb/usbdi_util.h>
     63 #include <dev/usb/usbdevs.h>
     64 #include <dev/usb/usbcdc.h>
     65 
     66 #include <dev/usb/mbim.h>
     67 #include <dev/usb/if_umbreg.h>
     68 
     69 #ifdef UMB_DEBUG
     70 #define DPRINTF(x...)							\
     71 		do { if (umb_debug) log(LOG_DEBUG, x); } while (0)
     72 
     73 #define DPRINTFN(n, x...)						\
     74 		do { if (umb_debug >= (n)) log(LOG_DEBUG, x); } while (0)
     75 
     76 #define DDUMPN(n, b, l)							\
     77 		do {							\
     78 			if (umb_debug >= (n))				\
     79 				umb_dump((b), (l));			\
     80 		} while (0)
     81 
     82 int	 umb_debug = 0;
     83 Static char	*umb_uuid2str(uint8_t [MBIM_UUID_LEN]);
     84 Static void	 umb_dump(void *, int);
     85 
     86 #else
     87 #define DPRINTF(x...)		do { } while (0)
     88 #define DPRINTFN(n, x...)	do { } while (0)
     89 #define DDUMPN(n, b, l)		do { } while (0)
     90 #endif
     91 
     92 #define DEVNAM(sc)		device_xname((sc)->sc_dev)
     93 
     94 #ifndef notyet
     95 #define usb_wait_task(dev, task)
     96 #endif
     97 
     98 /*
     99  * State change timeout
    100  */
    101 #define UMB_STATE_CHANGE_TIMEOUT	30
    102 
    103 /*
    104  * State change flags
    105  */
    106 #define UMB_NS_DONT_DROP	0x0001	/* do not drop below current state */
    107 #define UMB_NS_DONT_RAISE	0x0002	/* do not raise below current state */
    108 
    109 /*
    110  * Diagnostic macros
    111  */
    112 const struct umb_valdescr umb_regstates[] = MBIM_REGSTATE_DESCRIPTIONS;
    113 const struct umb_valdescr umb_dataclasses[] = MBIM_DATACLASS_DESCRIPTIONS;
    114 const struct umb_valdescr umb_simstate[] = MBIM_SIMSTATE_DESCRIPTIONS;
    115 const struct umb_valdescr umb_messages[] = MBIM_MESSAGES_DESCRIPTIONS;
    116 const struct umb_valdescr umb_status[] = MBIM_STATUS_DESCRIPTIONS;
    117 const struct umb_valdescr umb_cids[] = MBIM_CID_DESCRIPTIONS;
    118 const struct umb_valdescr umb_pktstate[] = MBIM_PKTSRV_STATE_DESCRIPTIONS;
    119 const struct umb_valdescr umb_actstate[] = MBIM_ACTIVATION_STATE_DESCRIPTIONS;
    120 const struct umb_valdescr umb_error[] = MBIM_ERROR_DESCRIPTIONS;
    121 const struct umb_valdescr umb_pintype[] = MBIM_PINTYPE_DESCRIPTIONS;
    122 const struct umb_valdescr umb_istate[] = UMB_INTERNAL_STATE_DESCRIPTIONS;
    123 
    124 #define umb_regstate(c)		umb_val2descr(umb_regstates, (c))
    125 #define umb_dataclass(c)	umb_val2descr(umb_dataclasses, (c))
    126 #define umb_simstate(s)		umb_val2descr(umb_simstate, (s))
    127 #define umb_request2str(m)	umb_val2descr(umb_messages, (m))
    128 #define umb_status2str(s)	umb_val2descr(umb_status, (s))
    129 #define umb_cid2str(c)		umb_val2descr(umb_cids, (c))
    130 #define umb_packet_state(s)	umb_val2descr(umb_pktstate, (s))
    131 #define umb_activation(s)	umb_val2descr(umb_actstate, (s))
    132 #define umb_error2str(e)	umb_val2descr(umb_error, (e))
    133 #define umb_pin_type(t)		umb_val2descr(umb_pintype, (t))
    134 #define umb_istate(s)		umb_val2descr(umb_istate, (s))
    135 
    136 Static int	 umb_match(device_t, cfdata_t, void *);
    137 Static void	 umb_attach(device_t, device_t, void *);
    138 Static int	 umb_detach(device_t, int);
    139 Static int	 umb_activate(device_t, enum devact);
    140 Static void	 umb_ncm_setup(struct umb_softc *);
    141 Static int	 umb_alloc_xfers(struct umb_softc *);
    142 Static void	 umb_free_xfers(struct umb_softc *);
    143 Static int	 umb_alloc_bulkpipes(struct umb_softc *);
    144 Static void	 umb_close_bulkpipes(struct umb_softc *);
    145 Static int	 umb_ioctl(struct ifnet *, u_long, void *);
    146 Static int	 umb_output(struct ifnet *, struct mbuf *,
    147 		    const struct sockaddr *, const struct rtentry *);
    148 Static void	 umb_input(struct ifnet *, struct mbuf *);
    149 Static void	 umb_start(struct ifnet *);
    150 Static void	 umb_watchdog(struct ifnet *);
    151 Static void	 umb_statechg_timeout(void *);
    152 
    153 Static int	 umb_mediachange(struct ifnet *);
    154 Static void	 umb_mediastatus(struct ifnet *, struct ifmediareq *);
    155 
    156 Static void	 umb_newstate(struct umb_softc *, enum umb_state, int);
    157 Static void	 umb_state_task(void *);
    158 Static void	 umb_up(struct umb_softc *);
    159 Static void	 umb_down(struct umb_softc *, int);
    160 
    161 Static void	 umb_get_response_task(void *);
    162 
    163 Static void	 umb_decode_response(struct umb_softc *, void *, int);
    164 Static void	 umb_handle_indicate_status_msg(struct umb_softc *, void *,
    165 		    int);
    166 Static void	 umb_handle_opendone_msg(struct umb_softc *, void *, int);
    167 Static void	 umb_handle_closedone_msg(struct umb_softc *, void *, int);
    168 Static int	 umb_decode_register_state(struct umb_softc *, void *, int);
    169 Static int	 umb_decode_devices_caps(struct umb_softc *, void *, int);
    170 Static int	 umb_decode_subscriber_status(struct umb_softc *, void *, int);
    171 Static int	 umb_decode_radio_state(struct umb_softc *, void *, int);
    172 Static int	 umb_decode_pin(struct umb_softc *, void *, int);
    173 Static int	 umb_decode_packet_service(struct umb_softc *, void *, int);
    174 Static int	 umb_decode_signal_state(struct umb_softc *, void *, int);
    175 Static int	 umb_decode_connect_info(struct umb_softc *, void *, int);
    176 Static int	 umb_decode_ip_configuration(struct umb_softc *, void *, int);
    177 Static void	 umb_rx(struct umb_softc *);
    178 Static void	 umb_rxeof(struct usbd_xfer *, void *, usbd_status);
    179 Static int	 umb_encap(struct umb_softc *, struct mbuf *);
    180 Static void	 umb_txeof(struct usbd_xfer *, void *, usbd_status);
    181 Static void	 umb_decap(struct umb_softc *, struct usbd_xfer *);
    182 
    183 Static usbd_status	 umb_send_encap_command(struct umb_softc *, void *, int);
    184 Static int	 umb_get_encap_response(struct umb_softc *, void *, int *);
    185 Static void	 umb_ctrl_msg(struct umb_softc *, uint32_t, void *, int);
    186 
    187 Static void	 umb_open(struct umb_softc *);
    188 Static void	 umb_close(struct umb_softc *);
    189 
    190 Static int	 umb_setpin(struct umb_softc *, int, int, void *, int, void *,
    191 		    int);
    192 Static void	 umb_setdataclass(struct umb_softc *);
    193 Static void	 umb_radio(struct umb_softc *, int);
    194 Static void	 umb_allocate_cid(struct umb_softc *);
    195 Static void	 umb_send_fcc_auth(struct umb_softc *);
    196 Static void	 umb_packet_service(struct umb_softc *, int);
    197 Static void	 umb_connect(struct umb_softc *);
    198 Static void	 umb_disconnect(struct umb_softc *);
    199 Static void	 umb_send_connect(struct umb_softc *, int);
    200 
    201 Static void	 umb_qry_ipconfig(struct umb_softc *);
    202 Static void	 umb_cmd(struct umb_softc *, int, int, const void *, int);
    203 Static void	 umb_cmd1(struct umb_softc *, int, int, const void *, int, uint8_t *);
    204 Static void	 umb_command_done(struct umb_softc *, void *, int);
    205 Static void	 umb_decode_cid(struct umb_softc *, uint32_t, void *, int);
    206 Static void	 umb_decode_qmi(struct umb_softc *, uint8_t *, int);
    207 
    208 Static void	 umb_intr(struct usbd_xfer *, void *, usbd_status);
    209 
    210 Static char	*umb_ntop(struct sockaddr *);
    211 
    212 Static const char *
    213 inet_ntop(int af, const void *src, char *dst, socklen_t size);
    214 static const char *inet_ntop4(const u_char *src, char *dst, size_t size);
    215 #ifdef INET6
    216 static const char *inet_ntop6(const u_char *src, char *dst, size_t size);
    217 #endif /* INET6 */
    218 
    219 Static int	 umb_xfer_tout = USBD_DEFAULT_TIMEOUT;
    220 
    221 Static uint8_t	 umb_uuid_basic_connect[] = MBIM_UUID_BASIC_CONNECT;
    222 Static uint8_t	 umb_uuid_context_internet[] = MBIM_UUID_CONTEXT_INTERNET;
    223 Static uint8_t	 umb_uuid_qmi_mbim[] = MBIM_UUID_QMI_MBIM;
    224 Static uint32_t	 umb_session_id = 0;
    225 
    226 CFATTACH_DECL_NEW(umb, sizeof(struct umb_softc), umb_match, umb_attach,
    227     umb_detach, umb_activate);
    228 
    229 const int umb_delay = 4000;
    230 
    231 /*
    232  * These devices require an "FCC Authentication" command.
    233  */
    234 const struct usb_devno umb_fccauth_devs[] = {
    235 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_EM7455 },
    236 };
    237 
    238 Static const uint8_t umb_qmi_alloc_cid[] = {
    239 	0x01,
    240 	0x0f, 0x00,		/* len */
    241 	0x00,			/* QMUX flags */
    242 	0x00,			/* service "ctl" */
    243 	0x00,			/* CID */
    244 	0x00,			/* QMI flags */
    245 	0x01,			/* transaction */
    246 	0x22, 0x00,		/* msg "Allocate CID" */
    247 	0x04, 0x00,		/* TLV len */
    248 	0x01, 0x01, 0x00, 0x02	/* TLV */
    249 };
    250 
    251 Static const uint8_t umb_qmi_fcc_auth[] = {
    252 	0x01,
    253 	0x0c, 0x00,		/* len */
    254 	0x00,			/* QMUX flags */
    255 	0x02,			/* service "dms" */
    256 #define UMB_QMI_CID_OFFS	5
    257 	0x00,			/* CID (filled in later) */
    258 	0x00,			/* QMI flags */
    259 	0x01, 0x00,		/* transaction */
    260 	0x5f, 0x55,		/* msg "Send FCC Authentication" */
    261 	0x00, 0x00		/* TLV len */
    262 };
    263 
    264 Static int
    265 umb_match(device_t parent, cfdata_t match, void *aux)
    266 {
    267 	struct usbif_attach_arg *uiaa = aux;
    268 	usb_interface_descriptor_t *id;
    269 
    270 	if (!uiaa->uiaa_iface)
    271 		return UMATCH_NONE;
    272 	if ((id = usbd_get_interface_descriptor(uiaa->uiaa_iface)) == NULL)
    273 		return UMATCH_NONE;
    274 
    275 	/*
    276 	 * If this function implements NCM, check if alternate setting
    277 	 * 1 implements MBIM.
    278 	 */
    279 	if (id->bInterfaceClass == UICLASS_CDC &&
    280 	    id->bInterfaceSubClass ==
    281 	    UISUBCLASS_NETWORK_CONTROL_MODEL)
    282 		id = usbd_find_idesc(uiaa->uiaa_device->ud_cdesc, uiaa->uiaa_iface->ui_index, 1);
    283 	if (id == NULL)
    284 		return UMATCH_NONE;
    285 
    286 	if (id->bInterfaceClass == UICLASS_CDC &&
    287 	    id->bInterfaceSubClass ==
    288 	    UISUBCLASS_MOBILE_BROADBAND_INTERFACE_MODEL &&
    289 	    id->bInterfaceProtocol == 0)
    290 		return UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO;
    291 
    292 	return UMATCH_NONE;
    293 }
    294 
    295 Static void
    296 umb_attach(device_t parent, device_t self, void *aux)
    297 {
    298 	struct umb_softc *sc = device_private(self);
    299 	struct usbif_attach_arg *uiaa = aux;
    300 	char *devinfop;
    301 	usbd_status status;
    302 	usbd_desc_iter_t iter;
    303 	const usb_descriptor_t *desc;
    304 	int	 v;
    305 	const usb_cdc_union_descriptor_t *ud;
    306 	const struct mbim_descriptor *md;
    307 	int	 i;
    308 	int	 ctrl_ep;
    309 	const usb_interface_descriptor_t *id;
    310 	usb_config_descriptor_t	*cd;
    311 	usb_endpoint_descriptor_t *ed;
    312 	const usb_interface_assoc_descriptor_t *ad;
    313 	int	 current_ifaceno = -1;
    314 	int	 data_ifaceno = -1;
    315 	int	 altnum;
    316 	int	 s;
    317 	struct ifnet *ifp;
    318 	int rv;
    319 
    320 	sc->sc_dev = self;
    321 	sc->sc_udev = uiaa->uiaa_device;
    322 
    323 	aprint_naive("\n");
    324 	aprint_normal("\n");
    325 
    326 	devinfop = usbd_devinfo_alloc(sc->sc_udev, 0);
    327 	aprint_normal_dev(self, "%s\n", devinfop);
    328 	usbd_devinfo_free(devinfop);
    329 
    330 	sc->sc_ctrl_ifaceno = uiaa->uiaa_ifaceno;
    331 
    332 	/*
    333 	 * Some MBIM hardware does not provide the mandatory CDC Union
    334 	 * Descriptor, so we also look at matching Interface
    335 	 * Association Descriptors to find out the MBIM Data Interface
    336 	 * number.
    337 	 */
    338 	sc->sc_ver_maj = sc->sc_ver_min = -1;
    339 	sc->sc_maxpktlen = MBIM_MAXSEGSZ_MINVAL;
    340 	usb_desc_iter_init(sc->sc_udev, &iter);
    341 	while ((desc = usb_desc_iter_next(&iter))) {
    342 		if (desc->bDescriptorType == UDESC_INTERFACE_ASSOC) {
    343 			ad = (const usb_interface_assoc_descriptor_t *)desc;
    344 			if (ad->bFirstInterface == uiaa->uiaa_ifaceno &&
    345 			    ad->bInterfaceCount > 1)
    346 				data_ifaceno = uiaa->uiaa_ifaceno + 1;
    347 			continue;
    348 		}
    349 		if (desc->bDescriptorType == UDESC_INTERFACE) {
    350 			id = (const usb_interface_descriptor_t *)desc;
    351 			current_ifaceno = id->bInterfaceNumber;
    352 			continue;
    353 		}
    354 		if (current_ifaceno != uiaa->uiaa_ifaceno)
    355 			continue;
    356 		if (desc->bDescriptorType != UDESC_CS_INTERFACE)
    357 			continue;
    358 		switch (desc->bDescriptorSubtype) {
    359 		case UDESCSUB_CDC_UNION:
    360 			ud = (const usb_cdc_union_descriptor_t *)desc;
    361 			data_ifaceno = ud->bSlaveInterface[0];
    362 			break;
    363 		case UDESCSUB_MBIM:
    364 			md = (const struct mbim_descriptor *)desc;
    365 			v = UGETW(md->bcdMBIMVersion);
    366 			sc->sc_ver_maj = MBIM_VER_MAJOR(v);
    367 			sc->sc_ver_min = MBIM_VER_MINOR(v);
    368 			sc->sc_ctrl_len = UGETW(md->wMaxControlMessage);
    369 			/* Never trust a USB device! Could try to exploit us */
    370 			if (sc->sc_ctrl_len < MBIM_CTRLMSG_MINLEN ||
    371 			    sc->sc_ctrl_len > MBIM_CTRLMSG_MAXLEN) {
    372 				DPRINTF("%s: control message len %d out of "
    373 				    "bounds [%d .. %d]\n", DEVNAM(sc),
    374 				    sc->sc_ctrl_len, MBIM_CTRLMSG_MINLEN,
    375 				    MBIM_CTRLMSG_MAXLEN);
    376 				/* cont. anyway */
    377 			}
    378 			sc->sc_maxpktlen = UGETW(md->wMaxSegmentSize);
    379 			DPRINTFN(2, "%s: ctrl_len=%d, maxpktlen=%d, cap=0x%x\n",
    380 			    DEVNAM(sc), sc->sc_ctrl_len, sc->sc_maxpktlen,
    381 			    md->bmNetworkCapabilities);
    382 			break;
    383 		default:
    384 			break;
    385 		}
    386 	}
    387 	if (sc->sc_ver_maj < 0) {
    388 		aprint_error_dev(self, "missing MBIM descriptor\n");
    389 		goto fail;
    390 	}
    391 
    392 	aprint_normal_dev(self, "version %d.%d\n", sc->sc_ver_maj,
    393 	    sc->sc_ver_min);
    394 
    395 	if (usb_lookup(umb_fccauth_devs, uiaa->uiaa_vendor, uiaa->uiaa_product)) {
    396 		sc->sc_flags |= UMBFLG_FCC_AUTH_REQUIRED;
    397 		sc->sc_cid = -1;
    398 	}
    399 
    400 	for (i = 0; i < uiaa->uiaa_nifaces; i++) {
    401 		id = usbd_get_interface_descriptor(uiaa->uiaa_ifaces[i]);
    402 		if (id != NULL && id->bInterfaceNumber == data_ifaceno) {
    403 			sc->sc_data_iface = uiaa->uiaa_ifaces[i];
    404 		}
    405 	}
    406 	if (sc->sc_data_iface == NULL) {
    407 		aprint_error_dev(self, "no data interface found\n");
    408 		goto fail;
    409 	}
    410 
    411 	/*
    412 	 * If this is a combined NCM/MBIM function, switch to
    413 	 * alternate setting one to enable MBIM.
    414 	 */
    415 	id = usbd_get_interface_descriptor(uiaa->uiaa_iface);
    416 	if (id->bInterfaceClass == UICLASS_CDC &&
    417 	    id->bInterfaceSubClass ==
    418 	    UISUBCLASS_NETWORK_CONTROL_MODEL)
    419 		usbd_set_interface(uiaa->uiaa_iface, 1);
    420 
    421 	id = usbd_get_interface_descriptor(uiaa->uiaa_iface);
    422 	ctrl_ep = -1;
    423 	for (i = 0; i < id->bNumEndpoints && ctrl_ep == -1; i++) {
    424 		ed = usbd_interface2endpoint_descriptor(uiaa->uiaa_iface, i);
    425 		if (ed == NULL)
    426 			break;
    427 		if (UE_GET_XFERTYPE(ed->bmAttributes) == UE_INTERRUPT &&
    428 		    UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN)
    429 			ctrl_ep = ed->bEndpointAddress;
    430 	}
    431 	if (ctrl_ep == -1) {
    432 		aprint_error_dev(self, "missing interrupt endpoint\n");
    433 		goto fail;
    434 	}
    435 
    436 	/*
    437 	 * For the MBIM Data Interface, select the appropriate
    438 	 * alternate setting by looking for a matching descriptor that
    439 	 * has two endpoints.
    440 	 */
    441 	cd = usbd_get_config_descriptor(sc->sc_udev);
    442 	altnum = usbd_get_no_alts(cd, data_ifaceno);
    443 	for (i = 0; i < altnum; i++) {
    444 		id = usbd_find_idesc(cd, sc->sc_data_iface->ui_index, i);
    445 		if (id == NULL)
    446 			continue;
    447 		if (id->bInterfaceClass == UICLASS_CDC_DATA &&
    448 		    id->bInterfaceSubClass == UISUBCLASS_DATA &&
    449 		    id->bInterfaceProtocol == UIPROTO_DATA_MBIM &&
    450 		    id->bNumEndpoints == 2)
    451 			break;
    452 	}
    453 	if (i == altnum || id == NULL) {
    454 		aprint_error_dev(self, "missing alt setting for interface #%d\n",
    455 		    data_ifaceno);
    456 		goto fail;
    457 	}
    458 	status = usbd_set_interface(sc->sc_data_iface, i);
    459 	if (status) {
    460 		aprint_error_dev(self, "select alt setting %d for interface #%d "
    461 		    "failed: %s\n", i, data_ifaceno, usbd_errstr(status));
    462 		goto fail;
    463 	}
    464 
    465 	id = usbd_get_interface_descriptor(sc->sc_data_iface);
    466 	sc->sc_rx_ep = sc->sc_tx_ep = -1;
    467 	for (i = 0; i < id->bNumEndpoints; i++) {
    468 		if ((ed = usbd_interface2endpoint_descriptor(sc->sc_data_iface,
    469 		    i)) == NULL)
    470 			break;
    471 		if (UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK &&
    472 		    UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN)
    473 			sc->sc_rx_ep = ed->bEndpointAddress;
    474 		else if (UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK &&
    475 		    UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT)
    476 			sc->sc_tx_ep = ed->bEndpointAddress;
    477 	}
    478 	if (sc->sc_rx_ep == -1 || sc->sc_tx_ep == -1) {
    479 		aprint_error_dev(self, "missing bulk endpoints\n");
    480 		goto fail;
    481 	}
    482 
    483 	DPRINTFN(2, "%s: ctrl-ifno#%d: ep-ctrl=%d, data-ifno#%d: ep-rx=%d, "
    484 	    "ep-tx=%d\n", DEVNAM(sc), sc->sc_ctrl_ifaceno,
    485 	    UE_GET_ADDR(ctrl_ep), data_ifaceno,
    486 	    UE_GET_ADDR(sc->sc_rx_ep), UE_GET_ADDR(sc->sc_tx_ep));
    487 
    488 	usb_init_task(&sc->sc_umb_task, umb_state_task, sc,
    489 	    0);
    490 	usb_init_task(&sc->sc_get_response_task, umb_get_response_task, sc,
    491 	    0);
    492 	callout_init(&sc->sc_statechg_timer, 0);
    493 	callout_setfunc(&sc->sc_statechg_timer, umb_statechg_timeout, sc);
    494 
    495 	if (usbd_open_pipe_intr(uiaa->uiaa_iface, ctrl_ep, USBD_SHORT_XFER_OK,
    496 	    &sc->sc_ctrl_pipe, sc, &sc->sc_intr_msg, sizeof(sc->sc_intr_msg),
    497 	    umb_intr, USBD_DEFAULT_INTERVAL)) {
    498 		aprint_error_dev(self, "failed to open control pipe\n");
    499 		goto fail;
    500 	}
    501 
    502 	sc->sc_resp_buf = kmem_alloc(sc->sc_ctrl_len, KM_SLEEP);
    503 	sc->sc_ctrl_msg = kmem_alloc(sc->sc_ctrl_len, KM_SLEEP);
    504 
    505 	sc->sc_info.regstate = MBIM_REGSTATE_UNKNOWN;
    506 	sc->sc_info.pin_attempts_left = UMB_VALUE_UNKNOWN;
    507 	sc->sc_info.rssi = UMB_VALUE_UNKNOWN;
    508 	sc->sc_info.ber = UMB_VALUE_UNKNOWN;
    509 
    510 	umb_ncm_setup(sc);
    511 	DPRINTFN(2, "%s: rx/tx size %d/%d\n", DEVNAM(sc),
    512 	    sc->sc_rx_bufsz, sc->sc_tx_bufsz);
    513 
    514 	s = splnet();
    515 
    516 	/* initialize the interface */
    517 	ifp = GET_IFP(sc);
    518 	ifp->if_softc = sc;
    519 	ifp->if_flags = IFF_SIMPLEX | IFF_MULTICAST | IFF_POINTOPOINT;
    520 	ifp->if_ioctl = umb_ioctl;
    521 	ifp->if_start = umb_start;
    522 
    523 	ifp->if_watchdog = umb_watchdog;
    524 	strlcpy(ifp->if_xname, device_xname(sc->sc_dev), IFNAMSIZ);
    525 	ifp->if_link_state = LINK_STATE_DOWN;
    526 	ifmedia_init(&sc->sc_im, 0, umb_mediachange, umb_mediastatus);
    527 
    528 	ifp->if_type = IFT_MBIM;
    529 	ifp->if_addrlen = 0;
    530 	ifp->if_hdrlen = sizeof(struct ncm_header16) +
    531 	    sizeof(struct ncm_pointer16);
    532 	ifp->if_mtu = 1500;		/* use a common default */
    533 	ifp->if_mtu = sc->sc_maxpktlen;
    534 	ifp->if_output = umb_output;
    535 	ifp->_if_input = umb_input;
    536 	IFQ_SET_READY(&ifp->if_snd);
    537 
    538 	/* attach the interface */
    539 	rv = if_initialize(ifp);
    540 	if (rv != 0) {
    541 		aprint_error_dev(self, "if_initialize failed(%d)\n", rv);
    542 		splx(s);
    543 		return;
    544 	}
    545 	if_register(ifp);
    546 	if_alloc_sadl(ifp);
    547 
    548 	bpf_attach(ifp, DLT_RAW, 0);
    549 	rnd_attach_source(&sc->sc_rnd_source, device_xname(sc->sc_dev),
    550 	    RND_TYPE_NET, RND_FLAG_DEFAULT);
    551 
    552 	/*
    553 	 * Open the device now so that we are able to query device information.
    554 	 * XXX maybe close when done?
    555 	 */
    556 	umb_open(sc);
    557 
    558 	sc->sc_attached = 1;
    559 	splx(s);
    560 
    561 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
    562 
    563 	if (!pmf_device_register(self, NULL, NULL))
    564 		aprint_error_dev(self, "couldn't establish power handler\n");
    565 
    566 	return;
    567 
    568 fail:
    569 	umb_activate(sc->sc_dev, DVACT_DEACTIVATE);
    570 	return;
    571 }
    572 
    573 Static int
    574 umb_detach(device_t self, int flags)
    575 {
    576 	struct umb_softc *sc = (struct umb_softc *)self;
    577 	struct ifnet *ifp = GET_IFP(sc);
    578 	int	 s;
    579 
    580 	pmf_device_deregister(self);
    581 
    582 	s = splnet();
    583 	if (ifp->if_flags & IFF_RUNNING)
    584 		umb_down(sc, 1);
    585 	umb_close(sc);
    586 
    587 	usb_rem_task(sc->sc_udev, &sc->sc_get_response_task);
    588 	usb_wait_task(sc->sc_udev, &sc->sc_get_response_task);
    589 	sc->sc_nresp = 0;
    590 	if (sc->sc_rx_ep != -1 && sc->sc_tx_ep != -1) {
    591 		callout_destroy(&sc->sc_statechg_timer);
    592 		usb_rem_task(sc->sc_udev, &sc->sc_umb_task);
    593 		usb_wait_task(sc->sc_udev, &sc->sc_umb_task);
    594 	}
    595 	if (sc->sc_ctrl_pipe) {
    596 		usbd_close_pipe(sc->sc_ctrl_pipe);
    597 		sc->sc_ctrl_pipe = NULL;
    598 	}
    599 	if (sc->sc_ctrl_msg) {
    600 		kmem_free(sc->sc_ctrl_msg, sc->sc_ctrl_len);
    601 		sc->sc_ctrl_msg = NULL;
    602 	}
    603 	if (sc->sc_resp_buf) {
    604 		kmem_free(sc->sc_resp_buf, sc->sc_ctrl_len);
    605 		sc->sc_resp_buf = NULL;
    606 	}
    607 	if (ifp->if_softc) {
    608 		ifmedia_delete_instance(&sc->sc_im, IFM_INST_ANY);
    609 	}
    610 	if (sc->sc_attached) {
    611 		rnd_detach_source(&sc->sc_rnd_source);
    612 		bpf_detach(ifp);
    613 		if_detach(ifp);
    614 	}
    615 
    616 	sc->sc_attached = 0;
    617 	splx(s);
    618 	return 0;
    619 }
    620 
    621 Static int
    622 umb_activate(device_t self, enum devact act)
    623 {
    624 	struct umb_softc *sc = device_private(self);
    625 
    626 	switch (act) {
    627 	case DVACT_DEACTIVATE:
    628 		if_deactivate(GET_IFP(sc));
    629 		sc->sc_dying = 1;
    630 		return 0;
    631 	default:
    632 		return EOPNOTSUPP;
    633 	}
    634 }
    635 
    636 Static void
    637 umb_ncm_setup(struct umb_softc *sc)
    638 {
    639 	usb_device_request_t req;
    640 	struct ncm_ntb_parameters np;
    641 
    642 	/* Query NTB tranfers sizes */
    643 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
    644 	req.bRequest = NCM_GET_NTB_PARAMETERS;
    645 	USETW(req.wValue, 0);
    646 	USETW(req.wIndex, sc->sc_ctrl_ifaceno);
    647 	USETW(req.wLength, sizeof(np));
    648 	if (usbd_do_request(sc->sc_udev, &req, &np) == USBD_NORMAL_COMPLETION &&
    649 	    UGETW(np.wLength) == sizeof(np)) {
    650 		sc->sc_rx_bufsz = UGETDW(np.dwNtbInMaxSize);
    651 		sc->sc_tx_bufsz = UGETDW(np.dwNtbOutMaxSize);
    652 	} else
    653 		sc->sc_rx_bufsz = sc->sc_tx_bufsz = 8 * 1024;
    654 }
    655 
    656 Static int
    657 umb_alloc_xfers(struct umb_softc *sc)
    658 {
    659 	int err = 0;
    660 
    661 	if (!sc->sc_rx_xfer) {
    662 		err |= usbd_create_xfer(sc->sc_rx_pipe,
    663 		    sc->sc_rx_bufsz,
    664 		    0, 0, &sc->sc_rx_xfer);
    665 	}
    666 	if (!sc->sc_tx_xfer) {
    667 		err |= usbd_create_xfer(sc->sc_tx_pipe,
    668 		    sc->sc_tx_bufsz,
    669 		    0, 0, &sc->sc_tx_xfer);
    670 	}
    671 	if (err)
    672 		return err;
    673 
    674 	sc->sc_rx_buf = usbd_get_buffer(sc->sc_rx_xfer);
    675 	sc->sc_tx_buf = usbd_get_buffer(sc->sc_tx_xfer);
    676 
    677 	return 0;
    678 }
    679 
    680 Static void
    681 umb_free_xfers(struct umb_softc *sc)
    682 {
    683 	if (sc->sc_rx_xfer) {
    684 		/* implicit usbd_free_buffer() */
    685 		usbd_destroy_xfer(sc->sc_rx_xfer);
    686 		sc->sc_rx_xfer = NULL;
    687 		sc->sc_rx_buf = NULL;
    688 	}
    689 	if (sc->sc_tx_xfer) {
    690 		usbd_destroy_xfer(sc->sc_tx_xfer);
    691 		sc->sc_tx_xfer = NULL;
    692 		sc->sc_tx_buf = NULL;
    693 	}
    694 	if (sc->sc_tx_m) {
    695 		m_freem(sc->sc_tx_m);
    696 		sc->sc_tx_m = NULL;
    697 	}
    698 }
    699 
    700 Static int
    701 umb_alloc_bulkpipes(struct umb_softc *sc)
    702 {
    703 	struct ifnet *ifp = GET_IFP(sc);
    704 	int rv;
    705 
    706 	if (!(ifp->if_flags & IFF_RUNNING)) {
    707 		if ((rv = usbd_open_pipe(sc->sc_data_iface, sc->sc_rx_ep,
    708 		    USBD_EXCLUSIVE_USE, &sc->sc_rx_pipe))) {
    709 			DPRINTFN(4, "usbd_open_pipe() failed (RX) %d\n", rv);
    710 			return 0;
    711 		}
    712 		if ((rv = usbd_open_pipe(sc->sc_data_iface, sc->sc_tx_ep,
    713 		    USBD_EXCLUSIVE_USE, &sc->sc_tx_pipe))) {
    714 			DPRINTFN(4, "usbd_open_pipe() failed (TX) %d\n", rv);
    715 			return 0;
    716 		}
    717 
    718 		if ((rv = umb_alloc_xfers(sc)) != 0) {
    719 			DPRINTFN(4, "umb_alloc_xfers() failed %d\n", rv);
    720 			return 0;
    721 		}
    722 
    723 		ifp->if_flags |= IFF_RUNNING;
    724 		ifp->if_flags &= ~IFF_OACTIVE;
    725 		umb_rx(sc);
    726 	}
    727 	return 1;
    728 }
    729 
    730 Static void
    731 umb_close_bulkpipes(struct umb_softc *sc)
    732 {
    733 	struct ifnet *ifp = GET_IFP(sc);
    734 
    735 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
    736 	ifp->if_timer = 0;
    737 	if (sc->sc_rx_pipe) {
    738 		usbd_close_pipe(sc->sc_rx_pipe);
    739 		sc->sc_rx_pipe = NULL;
    740 	}
    741 	if (sc->sc_tx_pipe) {
    742 		usbd_close_pipe(sc->sc_tx_pipe);
    743 		sc->sc_tx_pipe = NULL;
    744 	}
    745 }
    746 
    747 Static int
    748 umb_ioctl(struct ifnet *ifp, u_long cmd, void *data)
    749 {
    750 	struct umb_softc *sc = ifp->if_softc;
    751 	struct ifaddr *ifa = (struct ifaddr *)data;
    752 	struct ifreq *ifr = (struct ifreq *)data;
    753 	int s, error = 0;
    754 	struct umb_parameter mp;
    755 
    756 	if (sc->sc_dying)
    757 		return EIO;
    758 
    759 	s = splnet();
    760 	switch (cmd) {
    761 	case SIOCINITIFADDR:
    762 		ifp->if_flags |= IFF_UP;
    763 		usb_add_task(sc->sc_udev, &sc->sc_umb_task, USB_TASKQ_DRIVER);
    764 		switch (ifa->ifa_addr->sa_family) {
    765 #ifdef INET
    766 		case AF_INET:
    767 			break;
    768 #endif /* INET */
    769 #ifdef INET6
    770 		case AF_INET6:
    771 			break;
    772 #endif /* INET6 */
    773 		default:
    774 			error = EAFNOSUPPORT;
    775 			break;
    776 		}
    777 		ifa->ifa_rtrequest = p2p_rtrequest;
    778 		break;
    779 	case SIOCSIFFLAGS:
    780 		error = ifioctl_common(ifp, cmd, data);
    781 		if (error)
    782 			break;
    783 		usb_add_task(sc->sc_udev, &sc->sc_umb_task, USB_TASKQ_DRIVER);
    784 		break;
    785 	case SIOCGUMBINFO:
    786 		error = copyout(&sc->sc_info, ifr->ifr_data,
    787 		    sizeof(sc->sc_info));
    788 		break;
    789 	case SIOCSUMBPARAM:
    790 		error = kauth_authorize_network(curlwp->l_cred,
    791 		    KAUTH_NETWORK_INTERFACE,
    792 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, KAUTH_ARG(cmd),
    793 		    NULL);
    794 		if (error)
    795 			break;
    796 
    797 		if ((error = copyin(ifr->ifr_data, &mp, sizeof(mp))) != 0)
    798 			break;
    799 
    800 		if ((error = umb_setpin(sc, mp.op, mp.is_puk, mp.pin, mp.pinlen,
    801 		    mp.newpin, mp.newpinlen)) != 0)
    802 			break;
    803 
    804 		if (mp.apnlen < 0 || mp.apnlen > sizeof(sc->sc_info.apn)) {
    805 			error = EINVAL;
    806 			break;
    807 		}
    808 		sc->sc_roaming = mp.roaming ? 1 : 0;
    809 		memset(sc->sc_info.apn, 0, sizeof(sc->sc_info.apn));
    810 		memcpy(sc->sc_info.apn, mp.apn, mp.apnlen);
    811 		sc->sc_info.apnlen = mp.apnlen;
    812 		memset(sc->sc_info.username, 0, sizeof(sc->sc_info.username));
    813 		memcpy(sc->sc_info.username, mp.username, mp.usernamelen);
    814 		sc->sc_info.usernamelen = mp.usernamelen;
    815 		memset(sc->sc_info.password, 0, sizeof(sc->sc_info.password));
    816 		memcpy(sc->sc_info.password, mp.password, mp.passwordlen);
    817 		sc->sc_info.passwordlen = mp.passwordlen;
    818 		sc->sc_info.preferredclasses = mp.preferredclasses;
    819 		umb_setdataclass(sc);
    820 		break;
    821 	case SIOCGUMBPARAM:
    822 		memset(&mp, 0, sizeof(mp));
    823 		memcpy(mp.apn, sc->sc_info.apn, sc->sc_info.apnlen);
    824 		mp.apnlen = sc->sc_info.apnlen;
    825 		mp.roaming = sc->sc_roaming;
    826 		mp.preferredclasses = sc->sc_info.preferredclasses;
    827 		error = copyout(&mp, ifr->ifr_data, sizeof(mp));
    828 		break;
    829 	case SIOCSIFMTU:
    830 		/* Does this include the NCM headers and tail? */
    831 		if (ifr->ifr_mtu > ifp->if_mtu) {
    832 			error = EINVAL;
    833 			break;
    834 		}
    835 		ifp->if_mtu = ifr->ifr_mtu;
    836 		break;
    837 	case SIOCSIFADDR:
    838 	case SIOCAIFADDR:
    839 	case SIOCSIFDSTADDR:
    840 	case SIOCADDMULTI:
    841 	case SIOCDELMULTI:
    842 		break;
    843 	case SIOCGIFMEDIA:
    844 		error = ifmedia_ioctl(ifp, ifr, &sc->sc_im, cmd);
    845 		break;
    846 	default:
    847 		error = ifioctl_common(ifp, cmd, data);
    848 		break;
    849 	}
    850 	splx(s);
    851 	return error;
    852 }
    853 
    854 Static int
    855 umb_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
    856     const struct rtentry *rtp)
    857 {
    858 	int error;
    859 
    860 	DPRINTFN(10, "%s: %s: enter\n",
    861 		     device_xname(((struct umb_softc *)ifp->if_softc)->sc_dev),
    862 		     __func__);
    863 
    864 	/*
    865 	 * if the queueing discipline needs packet classification,
    866 	 * do it now.
    867 	 */
    868 	IFQ_CLASSIFY(&ifp->if_snd, m, dst->sa_family);
    869 
    870 	/*
    871 	 * Queue message on interface, and start output if interface
    872 	 * not yet active.
    873 	 */
    874 	error = if_transmit_lock(ifp, m);
    875 
    876 	return error;
    877 }
    878 
    879 Static void
    880 umb_input(struct ifnet *ifp, struct mbuf *m)
    881 {
    882 	size_t pktlen = m->m_len;
    883 	int s;
    884 
    885 	if ((ifp->if_flags & IFF_UP) == 0) {
    886 		m_freem(m);
    887 		return;
    888 	}
    889 	if (pktlen < sizeof(struct ip)) {
    890 		ifp->if_ierrors++;
    891 		DPRINTFN(4, "%s: dropping short packet (len %zd)\n", __func__,
    892 		    pktlen);
    893 		m_freem(m);
    894 		return;
    895 	}
    896 	s = splnet();
    897 	if (__predict_false(!pktq_enqueue(ip_pktq, m, 0))) {
    898 		ifp->if_iqdrops++;
    899 		m_freem(m);
    900 	} else {
    901 		ifp->if_ipackets++;
    902 		ifp->if_ibytes += pktlen;
    903 	}
    904 	splx(s);
    905 }
    906 
    907 Static void
    908 umb_start(struct ifnet *ifp)
    909 {
    910 	struct umb_softc *sc = ifp->if_softc;
    911 	struct mbuf *m_head = NULL;
    912 
    913 	if (sc->sc_dying || (ifp->if_flags & IFF_OACTIVE))
    914 		return;
    915 
    916 	IFQ_POLL(&ifp->if_snd, m_head);
    917 	if (m_head == NULL)
    918 		return;
    919 
    920 	if (!umb_encap(sc, m_head)) {
    921 		ifp->if_flags |= IFF_OACTIVE;
    922 		return;
    923 	}
    924 	IFQ_DEQUEUE(&ifp->if_snd, m_head);
    925 
    926 	bpf_mtap(ifp, m_head, BPF_D_OUT);
    927 
    928 	ifp->if_flags |= IFF_OACTIVE;
    929 	ifp->if_timer = (2 * umb_xfer_tout) / 1000;
    930 }
    931 
    932 Static void
    933 umb_watchdog(struct ifnet *ifp)
    934 {
    935 	struct umb_softc *sc = ifp->if_softc;
    936 
    937 	if (sc->sc_dying)
    938 		return;
    939 
    940 	ifp->if_oerrors++;
    941 	printf("%s: watchdog timeout\n", DEVNAM(sc));
    942 	usbd_abort_pipe(sc->sc_tx_pipe);
    943 	return;
    944 }
    945 
    946 Static void
    947 umb_statechg_timeout(void *arg)
    948 {
    949 	struct umb_softc *sc = arg;
    950 
    951 	if (sc->sc_info.regstate == MBIM_REGSTATE_ROAMING && !sc->sc_roaming) {
    952 		/*
    953 		 * Query the registration state until we're with the home
    954 		 * network again.
    955 		 */
    956 		umb_cmd(sc, MBIM_CID_REGISTER_STATE, MBIM_CMDOP_QRY, NULL, 0);
    957 	} else
    958 		printf("%s: state change timeout\n",DEVNAM(sc));
    959 	usb_add_task(sc->sc_udev, &sc->sc_umb_task, USB_TASKQ_DRIVER);
    960 }
    961 
    962 Static int
    963 umb_mediachange(struct ifnet * ifp)
    964 {
    965 	return 0;
    966 }
    967 
    968 Static void
    969 umb_mediastatus(struct ifnet * ifp, struct ifmediareq * imr)
    970 {
    971 	switch (ifp->if_link_state) {
    972 	case LINK_STATE_UP:
    973 		imr->ifm_status = IFM_AVALID | IFM_ACTIVE;
    974 		break;
    975 	case LINK_STATE_DOWN:
    976 		imr->ifm_status = IFM_AVALID;
    977 		break;
    978 	default:
    979 		imr->ifm_status = 0;
    980 		break;
    981 	}
    982 }
    983 
    984 Static void
    985 umb_newstate(struct umb_softc *sc, enum umb_state newstate, int flags)
    986 {
    987 	struct ifnet *ifp = GET_IFP(sc);
    988 
    989 	if (newstate == sc->sc_state)
    990 		return;
    991 	if (((flags & UMB_NS_DONT_DROP) && newstate < sc->sc_state) ||
    992 	    ((flags & UMB_NS_DONT_RAISE) && newstate > sc->sc_state))
    993 		return;
    994 	if (ifp->if_flags & IFF_DEBUG)
    995 		log(LOG_DEBUG, "%s: state going %s from '%s' to '%s'\n",
    996 		    DEVNAM(sc), newstate > sc->sc_state ? "up" : "down",
    997 		    umb_istate(sc->sc_state), umb_istate(newstate));
    998 	sc->sc_state = newstate;
    999 	usb_add_task(sc->sc_udev, &sc->sc_umb_task, USB_TASKQ_DRIVER);
   1000 }
   1001 
   1002 Static void
   1003 umb_state_task(void *arg)
   1004 {
   1005 	struct umb_softc *sc = arg;
   1006 	struct ifnet *ifp = GET_IFP(sc);
   1007 	struct ifreq ifr;
   1008 	int	 s;
   1009 	int	 state;
   1010 
   1011 	s = splnet();
   1012 	if (ifp->if_flags & IFF_UP)
   1013 		umb_up(sc);
   1014 	else
   1015 		umb_down(sc, 0);
   1016 
   1017 	state = sc->sc_state == UMB_S_UP ? LINK_STATE_UP : LINK_STATE_DOWN;
   1018 	if (ifp->if_link_state != state) {
   1019 		if (ifp->if_flags & IFF_DEBUG)
   1020 			log(LOG_DEBUG, "%s: link state changed from %s to %s\n",
   1021 			    DEVNAM(sc),
   1022 			    (ifp->if_link_state == LINK_STATE_UP)
   1023 			    ? "up" : "down",
   1024 			    (state == LINK_STATE_UP) ? "up" : "down");
   1025 		ifp->if_link_state = state;
   1026 		if (state != LINK_STATE_UP) {
   1027 			/*
   1028 			 * Purge any existing addresses
   1029 			 */
   1030 			memset(sc->sc_info.ipv4dns, 0,
   1031 			    sizeof(sc->sc_info.ipv4dns));
   1032 			if (in_control(NULL, SIOCGIFADDR, &ifr, ifp) == 0 &&
   1033 			    satosin(&ifr.ifr_addr)->sin_addr.s_addr !=
   1034 			    INADDR_ANY) {
   1035 				in_control(NULL, SIOCDIFADDR, &ifr, ifp);
   1036 			}
   1037 		}
   1038 		if_link_state_change(ifp, state);
   1039 	}
   1040 	splx(s);
   1041 }
   1042 
   1043 Static void
   1044 umb_up(struct umb_softc *sc)
   1045 {
   1046 	switch (sc->sc_state) {
   1047 	case UMB_S_DOWN:
   1048 		DPRINTF("%s: init: opening ...\n", DEVNAM(sc));
   1049 		umb_open(sc);
   1050 		break;
   1051 	case UMB_S_OPEN:
   1052 		if (sc->sc_flags & UMBFLG_FCC_AUTH_REQUIRED) {
   1053 			if (sc->sc_cid == -1) {
   1054 				DPRINTF("%s: init: allocating CID ...\n",
   1055 				    DEVNAM(sc));
   1056 				umb_allocate_cid(sc);
   1057 				break;
   1058 			} else
   1059 				umb_newstate(sc, UMB_S_CID, UMB_NS_DONT_DROP);
   1060 		} else {
   1061 			DPRINTF("%s: init: turning radio on ...\n", DEVNAM(sc));
   1062 			umb_radio(sc, 1);
   1063 			break;
   1064 		}
   1065 		/*FALLTHROUGH*/
   1066 	case UMB_S_CID:
   1067 		DPRINTF("%s: init: sending FCC auth ...\n", DEVNAM(sc));
   1068 		umb_send_fcc_auth(sc);
   1069 		break;
   1070 	case UMB_S_RADIO:
   1071 		DPRINTF("%s: init: checking SIM state ...\n", DEVNAM(sc));
   1072 		umb_cmd(sc, MBIM_CID_SUBSCRIBER_READY_STATUS, MBIM_CMDOP_QRY,
   1073 		    NULL, 0);
   1074 		break;
   1075 	case UMB_S_SIMREADY:
   1076 		DPRINTF("%s: init: attaching ...\n", DEVNAM(sc));
   1077 		umb_packet_service(sc, 1);
   1078 		break;
   1079 	case UMB_S_ATTACHED:
   1080 		sc->sc_tx_seq = 0;
   1081 		DPRINTF("%s: init: connecting ...\n", DEVNAM(sc));
   1082 		umb_connect(sc);
   1083 		break;
   1084 	case UMB_S_CONNECTED:
   1085 		DPRINTF("%s: init: getting IP config ...\n", DEVNAM(sc));
   1086 		umb_qry_ipconfig(sc);
   1087 		break;
   1088 	case UMB_S_UP:
   1089 		DPRINTF("%s: init: reached state UP\n", DEVNAM(sc));
   1090 		if (!umb_alloc_bulkpipes(sc)) {
   1091 			printf("%s: opening bulk pipes failed\n", DEVNAM(sc));
   1092 			umb_down(sc, 1);
   1093 		}
   1094 		break;
   1095 	}
   1096 	if (sc->sc_state < UMB_S_UP)
   1097 		callout_schedule(&sc->sc_statechg_timer,
   1098 		    UMB_STATE_CHANGE_TIMEOUT * hz);
   1099 	else
   1100 		callout_stop(&sc->sc_statechg_timer);
   1101 	return;
   1102 }
   1103 
   1104 Static void
   1105 umb_down(struct umb_softc *sc, int force)
   1106 {
   1107 	umb_close_bulkpipes(sc);
   1108 	if (sc->sc_state < UMB_S_CONNECTED)
   1109 		umb_free_xfers(sc);
   1110 
   1111 	switch (sc->sc_state) {
   1112 	case UMB_S_UP:
   1113 	case UMB_S_CONNECTED:
   1114 		DPRINTF("%s: stop: disconnecting ...\n", DEVNAM(sc));
   1115 		umb_disconnect(sc);
   1116 		if (!force)
   1117 			break;
   1118 		/*FALLTHROUGH*/
   1119 	case UMB_S_ATTACHED:
   1120 		DPRINTF("%s: stop: detaching ...\n", DEVNAM(sc));
   1121 		umb_packet_service(sc, 0);
   1122 		if (!force)
   1123 			break;
   1124 		/*FALLTHROUGH*/
   1125 	case UMB_S_SIMREADY:
   1126 	case UMB_S_RADIO:
   1127 		DPRINTF("%s: stop: turning radio off ...\n", DEVNAM(sc));
   1128 		umb_radio(sc, 0);
   1129 		if (!force)
   1130 			break;
   1131 		/*FALLTHROUGH*/
   1132 	case UMB_S_CID:
   1133 	case UMB_S_OPEN:
   1134 	case UMB_S_DOWN:
   1135 		/* Do not close the device */
   1136 		DPRINTF("%s: stop: reached state DOWN\n", DEVNAM(sc));
   1137 		break;
   1138 	}
   1139 	if (force)
   1140 		sc->sc_state = UMB_S_OPEN;
   1141 
   1142 	if (sc->sc_state > UMB_S_OPEN)
   1143 		callout_schedule(&sc->sc_statechg_timer,
   1144 		    UMB_STATE_CHANGE_TIMEOUT * hz);
   1145 	else
   1146 		callout_stop(&sc->sc_statechg_timer);
   1147 }
   1148 
   1149 Static void
   1150 umb_get_response_task(void *arg)
   1151 {
   1152 	struct umb_softc *sc = arg;
   1153 	int	 len;
   1154 	int	 s;
   1155 
   1156 	/*
   1157 	 * Function is required to send on RESPONSE_AVAILABLE notification for
   1158 	 * each encapsulated response that is to be processed by the host.
   1159 	 * But of course, we can receive multiple notifications before the
   1160 	 * response task is run.
   1161 	 */
   1162 	s = splusb();
   1163 	while (sc->sc_nresp > 0) {
   1164 		--sc->sc_nresp;
   1165 		len = sc->sc_ctrl_len;
   1166 		if (umb_get_encap_response(sc, sc->sc_resp_buf, &len))
   1167 			umb_decode_response(sc, sc->sc_resp_buf, len);
   1168 	}
   1169 	splx(s);
   1170 }
   1171 
   1172 Static void
   1173 umb_decode_response(struct umb_softc *sc, void *response, int len)
   1174 {
   1175 	struct mbim_msghdr *hdr = response;
   1176 	struct mbim_fragmented_msg_hdr *fraghdr;
   1177 	uint32_t type;
   1178 
   1179 	DPRINTFN(3, "%s: got response: len %d\n", DEVNAM(sc), len);
   1180 	DDUMPN(4, response, len);
   1181 
   1182 	if (len < sizeof(*hdr) || le32toh(hdr->len) != len) {
   1183 		/*
   1184 		 * We should probably cancel a transaction, but since the
   1185 		 * message is too short, we cannot decode the transaction
   1186 		 * id (tid) and hence don't know, whom to cancel. Must wait
   1187 		 * for the timeout.
   1188 		 */
   1189 		DPRINTF("%s: received short response (len %d)\n",
   1190 		    DEVNAM(sc), len);
   1191 		return;
   1192 	}
   1193 
   1194 	/*
   1195 	 * XXX FIXME: if message is fragmented, store it until last frag
   1196 	 *	is received and then re-assemble all fragments.
   1197 	 */
   1198 	type = le32toh(hdr->type);
   1199 	switch (type) {
   1200 	case MBIM_INDICATE_STATUS_MSG:
   1201 	case MBIM_COMMAND_DONE:
   1202 		fraghdr = response;
   1203 		if (le32toh(fraghdr->frag.nfrag) != 1) {
   1204 			DPRINTF("%s: discarding fragmented messages\n",
   1205 			    DEVNAM(sc));
   1206 			return;
   1207 		}
   1208 		break;
   1209 	default:
   1210 		break;
   1211 	}
   1212 
   1213 	DPRINTF("%s: <- rcv %s (tid %u)\n", DEVNAM(sc), umb_request2str(type),
   1214 	    le32toh(hdr->tid));
   1215 	switch (type) {
   1216 	case MBIM_FUNCTION_ERROR_MSG:
   1217 	case MBIM_HOST_ERROR_MSG:
   1218 	{
   1219 		struct mbim_f2h_hosterr *e;
   1220 		int	 err;
   1221 
   1222 		if (len >= sizeof(*e)) {
   1223 			e = response;
   1224 			err = le32toh(e->err);
   1225 
   1226 			DPRINTF("%s: %s message, error %s (tid %u)\n",
   1227 			    DEVNAM(sc), umb_request2str(type),
   1228 			    umb_error2str(err), le32toh(hdr->tid));
   1229 			if (err == MBIM_ERROR_NOT_OPENED)
   1230 				umb_newstate(sc, UMB_S_DOWN, 0);
   1231 		}
   1232 		break;
   1233 	}
   1234 	case MBIM_INDICATE_STATUS_MSG:
   1235 		umb_handle_indicate_status_msg(sc, response, len);
   1236 		break;
   1237 	case MBIM_OPEN_DONE:
   1238 		umb_handle_opendone_msg(sc, response, len);
   1239 		break;
   1240 	case MBIM_CLOSE_DONE:
   1241 		umb_handle_closedone_msg(sc, response, len);
   1242 		break;
   1243 	case MBIM_COMMAND_DONE:
   1244 		umb_command_done(sc, response, len);
   1245 		break;
   1246 	default:
   1247 		DPRINTF("%s: discard messsage %s\n", DEVNAM(sc),
   1248 		    umb_request2str(type));
   1249 		break;
   1250 	}
   1251 }
   1252 
   1253 Static void
   1254 umb_handle_indicate_status_msg(struct umb_softc *sc, void *data, int len)
   1255 {
   1256 	struct mbim_f2h_indicate_status *m = data;
   1257 	uint32_t infolen;
   1258 	uint32_t cid;
   1259 
   1260 	if (len < sizeof(*m)) {
   1261 		DPRINTF("%s: discard short %s messsage\n", DEVNAM(sc),
   1262 		    umb_request2str(le32toh(m->hdr.type)));
   1263 		return;
   1264 	}
   1265 	if (memcmp(m->devid, umb_uuid_basic_connect, sizeof(m->devid))) {
   1266 		DPRINTF("%s: discard %s messsage for other UUID '%s'\n",
   1267 		    DEVNAM(sc), umb_request2str(le32toh(m->hdr.type)),
   1268 		    umb_uuid2str(m->devid));
   1269 		return;
   1270 	}
   1271 	infolen = le32toh(m->infolen);
   1272 	if (len < sizeof(*m) + infolen) {
   1273 		DPRINTF("%s: discard truncated %s messsage (want %d, got %d)\n",
   1274 		    DEVNAM(sc), umb_request2str(le32toh(m->hdr.type)),
   1275 		    (int)sizeof(*m) + infolen, len);
   1276 		return;
   1277 	}
   1278 
   1279 	cid = le32toh(m->cid);
   1280 	DPRINTF("%s: indicate %s status\n", DEVNAM(sc), umb_cid2str(cid));
   1281 	umb_decode_cid(sc, cid, m->info, infolen);
   1282 }
   1283 
   1284 Static void
   1285 umb_handle_opendone_msg(struct umb_softc *sc, void *data, int len)
   1286 {
   1287 	struct mbim_f2h_openclosedone *resp = data;
   1288 	struct ifnet *ifp = GET_IFP(sc);
   1289 	uint32_t status;
   1290 
   1291 	status = le32toh(resp->status);
   1292 	if (status == MBIM_STATUS_SUCCESS) {
   1293 		if (sc->sc_maxsessions == 0) {
   1294 			umb_cmd(sc, MBIM_CID_DEVICE_CAPS, MBIM_CMDOP_QRY, NULL,
   1295 			    0);
   1296 			umb_cmd(sc, MBIM_CID_PIN, MBIM_CMDOP_QRY, NULL, 0);
   1297 			umb_cmd(sc, MBIM_CID_REGISTER_STATE, MBIM_CMDOP_QRY,
   1298 			    NULL, 0);
   1299 		}
   1300 		umb_newstate(sc, UMB_S_OPEN, UMB_NS_DONT_DROP);
   1301 	} else if (ifp->if_flags & IFF_DEBUG)
   1302 		log(LOG_ERR, "%s: open error: %s\n", DEVNAM(sc),
   1303 		    umb_status2str(status));
   1304 	return;
   1305 }
   1306 
   1307 Static void
   1308 umb_handle_closedone_msg(struct umb_softc *sc, void *data, int len)
   1309 {
   1310 	struct mbim_f2h_openclosedone *resp = data;
   1311 	uint32_t status;
   1312 
   1313 	status = le32toh(resp->status);
   1314 	if (status == MBIM_STATUS_SUCCESS)
   1315 		umb_newstate(sc, UMB_S_DOWN, 0);
   1316 	else
   1317 		DPRINTF("%s: close error: %s\n", DEVNAM(sc),
   1318 		    umb_status2str(status));
   1319 	return;
   1320 }
   1321 
   1322 static inline void
   1323 umb_getinfobuf(char *in, int inlen, uint32_t offs, uint32_t sz,
   1324     void *out, size_t outlen)
   1325 {
   1326 	offs = le32toh(offs);
   1327 	sz = le32toh(sz);
   1328 	if (inlen >= offs + sz) {
   1329 		memset(out, 0, outlen);
   1330 		memcpy(out, in + offs, MIN(sz, outlen));
   1331 	}
   1332 }
   1333 
   1334 static inline int
   1335 umb_padding(void *data, int len, size_t sz)
   1336 {
   1337 	char *p = data;
   1338 	int np = 0;
   1339 
   1340 	while (len < sz && (len % 4) != 0) {
   1341 		*p++ = '\0';
   1342 		len++;
   1343 		np++;
   1344 	}
   1345 	return np;
   1346 }
   1347 
   1348 static inline int
   1349 umb_addstr(void *buf, size_t bufsz, int *offs, void *str, int slen,
   1350     uint32_t *offsmember, uint32_t *sizemember)
   1351 {
   1352 	if (*offs + slen > bufsz)
   1353 		return 0;
   1354 
   1355 	*sizemember = htole32((uint32_t)slen);
   1356 	if (slen && str) {
   1357 		*offsmember = htole32((uint32_t)*offs);
   1358 		memcpy((char *)buf + *offs, str, slen);
   1359 		*offs += slen;
   1360 		*offs += umb_padding(buf, *offs, bufsz);
   1361 	} else
   1362 		*offsmember = htole32(0);
   1363 	return 1;
   1364 }
   1365 
   1366 static void
   1367 umb_in_len2mask(struct in_addr *mask, int len)
   1368 {
   1369 	int i;
   1370 	u_char *p;
   1371 
   1372 	p = (u_char *)mask;
   1373 	memset(mask, 0, sizeof(*mask));
   1374 	for (i = 0; i < len / 8; i++)
   1375 		p[i] = 0xff;
   1376 	if (len % 8)
   1377 		p[i] = (0xff00 >> (len % 8)) & 0xff;
   1378 }
   1379 
   1380 Static int
   1381 umb_decode_register_state(struct umb_softc *sc, void *data, int len)
   1382 {
   1383 	struct mbim_cid_registration_state_info *rs = data;
   1384 	struct ifnet *ifp = GET_IFP(sc);
   1385 
   1386 	if (len < sizeof(*rs))
   1387 		return 0;
   1388 	sc->sc_info.nwerror = le32toh(rs->nwerror);
   1389 	sc->sc_info.regstate = le32toh(rs->regstate);
   1390 	sc->sc_info.regmode = le32toh(rs->regmode);
   1391 	sc->sc_info.cellclass = le32toh(rs->curcellclass);
   1392 
   1393 	/* XXX should we remember the provider_id? */
   1394 	umb_getinfobuf(data, len, rs->provname_offs, rs->provname_size,
   1395 	    sc->sc_info.provider, sizeof(sc->sc_info.provider));
   1396 	umb_getinfobuf(data, len, rs->roamingtxt_offs, rs->roamingtxt_size,
   1397 	    sc->sc_info.roamingtxt, sizeof(sc->sc_info.roamingtxt));
   1398 
   1399 	DPRINTFN(2, "%s: %s, availclass 0x%x, class 0x%x, regmode %d\n",
   1400 	    DEVNAM(sc), umb_regstate(sc->sc_info.regstate),
   1401 	    le32toh(rs->availclasses), sc->sc_info.cellclass,
   1402 	    sc->sc_info.regmode);
   1403 
   1404 	if (sc->sc_info.regstate == MBIM_REGSTATE_ROAMING &&
   1405 	    !sc->sc_roaming &&
   1406 	    sc->sc_info.activation == MBIM_ACTIVATION_STATE_ACTIVATED) {
   1407 		if (ifp->if_flags & IFF_DEBUG)
   1408 			log(LOG_INFO,
   1409 			    "%s: disconnecting from roaming network\n",
   1410 			    DEVNAM(sc));
   1411 		umb_disconnect(sc);
   1412 	}
   1413 	return 1;
   1414 }
   1415 
   1416 Static int
   1417 umb_decode_devices_caps(struct umb_softc *sc, void *data, int len)
   1418 {
   1419 	struct mbim_cid_device_caps *dc = data;
   1420 
   1421 	if (len < sizeof(*dc))
   1422 		return 0;
   1423 	sc->sc_maxsessions = le32toh(dc->max_sessions);
   1424 	sc->sc_info.supportedclasses = le32toh(dc->dataclass);
   1425 	umb_getinfobuf(data, len, dc->devid_offs, dc->devid_size,
   1426 	    sc->sc_info.devid, sizeof(sc->sc_info.devid));
   1427 	umb_getinfobuf(data, len, dc->fwinfo_offs, dc->fwinfo_size,
   1428 	    sc->sc_info.fwinfo, sizeof(sc->sc_info.fwinfo));
   1429 	umb_getinfobuf(data, len, dc->hwinfo_offs, dc->hwinfo_size,
   1430 	    sc->sc_info.hwinfo, sizeof(sc->sc_info.hwinfo));
   1431 	DPRINTFN(2, "%s: max sessions %d, supported classes 0x%x\n",
   1432 	    DEVNAM(sc), sc->sc_maxsessions, sc->sc_info.supportedclasses);
   1433 	return 1;
   1434 }
   1435 
   1436 Static int
   1437 umb_decode_subscriber_status(struct umb_softc *sc, void *data, int len)
   1438 {
   1439 	struct mbim_cid_subscriber_ready_info *si = data;
   1440 	struct ifnet *ifp = GET_IFP(sc);
   1441 	int	npn;
   1442 
   1443 	if (len < sizeof(*si))
   1444 		return 0;
   1445 	sc->sc_info.sim_state = le32toh(si->ready);
   1446 
   1447 	umb_getinfobuf(data, len, si->sid_offs, si->sid_size,
   1448 	    sc->sc_info.sid, sizeof(sc->sc_info.sid));
   1449 	umb_getinfobuf(data, len, si->icc_offs, si->icc_size,
   1450 	    sc->sc_info.iccid, sizeof(sc->sc_info.iccid));
   1451 
   1452 	npn = le32toh(si->no_pn);
   1453 	if (npn > 0)
   1454 		umb_getinfobuf(data, len, si->pn[0].offs, si->pn[0].size,
   1455 		    sc->sc_info.pn, sizeof(sc->sc_info.pn));
   1456 	else
   1457 		memset(sc->sc_info.pn, 0, sizeof(sc->sc_info.pn));
   1458 
   1459 	if (sc->sc_info.sim_state == MBIM_SIMSTATE_LOCKED)
   1460 		sc->sc_info.pin_state = UMB_PUK_REQUIRED;
   1461 	if (ifp->if_flags & IFF_DEBUG)
   1462 		log(LOG_INFO, "%s: SIM %s\n", DEVNAM(sc),
   1463 		    umb_simstate(sc->sc_info.sim_state));
   1464 	if (sc->sc_info.sim_state == MBIM_SIMSTATE_INITIALIZED)
   1465 		umb_newstate(sc, UMB_S_SIMREADY, UMB_NS_DONT_DROP);
   1466 	return 1;
   1467 }
   1468 
   1469 Static int
   1470 umb_decode_radio_state(struct umb_softc *sc, void *data, int len)
   1471 {
   1472 	struct mbim_cid_radio_state_info *rs = data;
   1473 	struct ifnet *ifp = GET_IFP(sc);
   1474 
   1475 	if (len < sizeof(*rs))
   1476 		return 0;
   1477 
   1478 	sc->sc_info.hw_radio_on =
   1479 	    (le32toh(rs->hw_state) == MBIM_RADIO_STATE_ON) ? 1 : 0;
   1480 	sc->sc_info.sw_radio_on =
   1481 	    (le32toh(rs->sw_state) == MBIM_RADIO_STATE_ON) ? 1 : 0;
   1482 	if (!sc->sc_info.hw_radio_on) {
   1483 		printf("%s: radio is disabled by hardware switch\n",
   1484 		    DEVNAM(sc));
   1485 		/*
   1486 		 * XXX do we need a time to poll the state of the rfkill switch
   1487 		 *	or will the device send an unsolicited notification
   1488 		 *	in case the state changes?
   1489 		 */
   1490 		umb_newstate(sc, UMB_S_OPEN, 0);
   1491 	} else if (!sc->sc_info.sw_radio_on) {
   1492 		if (ifp->if_flags & IFF_DEBUG)
   1493 			log(LOG_INFO, "%s: radio is off\n", DEVNAM(sc));
   1494 		umb_newstate(sc, UMB_S_OPEN, 0);
   1495 	} else
   1496 		umb_newstate(sc, UMB_S_RADIO, UMB_NS_DONT_DROP);
   1497 	return 1;
   1498 }
   1499 
   1500 Static int
   1501 umb_decode_pin(struct umb_softc *sc, void *data, int len)
   1502 {
   1503 	struct mbim_cid_pin_info *pi = data;
   1504 	struct ifnet *ifp = GET_IFP(sc);
   1505 	uint32_t	attempts_left;
   1506 
   1507 	if (len < sizeof(*pi))
   1508 		return 0;
   1509 
   1510 	attempts_left = le32toh(pi->remaining_attempts);
   1511 	if (attempts_left != 0xffffffff)
   1512 		sc->sc_info.pin_attempts_left = attempts_left;
   1513 
   1514 	switch (le32toh(pi->state)) {
   1515 	case MBIM_PIN_STATE_UNLOCKED:
   1516 		sc->sc_info.pin_state = UMB_PIN_UNLOCKED;
   1517 		break;
   1518 	case MBIM_PIN_STATE_LOCKED:
   1519 		switch (le32toh(pi->type)) {
   1520 		case MBIM_PIN_TYPE_PIN1:
   1521 			sc->sc_info.pin_state = UMB_PIN_REQUIRED;
   1522 			break;
   1523 		case MBIM_PIN_TYPE_PUK1:
   1524 			sc->sc_info.pin_state = UMB_PUK_REQUIRED;
   1525 			break;
   1526 		case MBIM_PIN_TYPE_PIN2:
   1527 		case MBIM_PIN_TYPE_PUK2:
   1528 			/* Assume that PIN1 was accepted */
   1529 			sc->sc_info.pin_state = UMB_PIN_UNLOCKED;
   1530 			break;
   1531 		}
   1532 		break;
   1533 	}
   1534 	if (ifp->if_flags & IFF_DEBUG)
   1535 		log(LOG_INFO, "%s: %s state %s (%d attempts left)\n",
   1536 		    DEVNAM(sc), umb_pin_type(le32toh(pi->type)),
   1537 		    (le32toh(pi->state) == MBIM_PIN_STATE_UNLOCKED) ?
   1538 			"unlocked" : "locked",
   1539 		    le32toh(pi->remaining_attempts));
   1540 
   1541 	/*
   1542 	 * In case the PIN was set after IFF_UP, retrigger the state machine
   1543 	 */
   1544 	usb_add_task(sc->sc_udev, &sc->sc_umb_task, USB_TASKQ_DRIVER);
   1545 	return 1;
   1546 }
   1547 
   1548 Static int
   1549 umb_decode_packet_service(struct umb_softc *sc, void *data, int len)
   1550 {
   1551 	struct mbim_cid_packet_service_info *psi = data;
   1552 	int	 state, highestclass;
   1553 	uint64_t up_speed, down_speed;
   1554 	struct ifnet *ifp = GET_IFP(sc);
   1555 
   1556 	if (len < sizeof(*psi))
   1557 		return 0;
   1558 
   1559 	sc->sc_info.nwerror = le32toh(psi->nwerror);
   1560 	state = le32toh(psi->state);
   1561 	highestclass = le32toh(psi->highest_dataclass);
   1562 	up_speed = le64toh(psi->uplink_speed);
   1563 	down_speed = le64toh(psi->downlink_speed);
   1564 	if (sc->sc_info.packetstate  != state ||
   1565 	    sc->sc_info.uplink_speed != up_speed ||
   1566 	    sc->sc_info.downlink_speed != down_speed) {
   1567 		if (ifp->if_flags & IFF_DEBUG) {
   1568 			log(LOG_INFO, "%s: packet service ", DEVNAM(sc));
   1569 			if (sc->sc_info.packetstate  != state)
   1570 				addlog("changed from %s to ",
   1571 				    umb_packet_state(sc->sc_info.packetstate));
   1572 			addlog("%s, class %s, speed: %" PRIu64 " up / %" PRIu64 " down\n",
   1573 			    umb_packet_state(state),
   1574 			    umb_dataclass(highestclass), up_speed, down_speed);
   1575 		}
   1576 	}
   1577 	sc->sc_info.packetstate = state;
   1578 	sc->sc_info.highestclass = highestclass;
   1579 	sc->sc_info.uplink_speed = up_speed;
   1580 	sc->sc_info.downlink_speed = down_speed;
   1581 
   1582 	if (sc->sc_info.regmode == MBIM_REGMODE_AUTOMATIC) {
   1583 		/*
   1584 		 * For devices using automatic registration mode, just proceed,
   1585 		 * once registration has completed.
   1586 		 */
   1587 		if (ifp->if_flags & IFF_UP) {
   1588 			switch (sc->sc_info.regstate) {
   1589 			case MBIM_REGSTATE_HOME:
   1590 			case MBIM_REGSTATE_ROAMING:
   1591 			case MBIM_REGSTATE_PARTNER:
   1592 				umb_newstate(sc, UMB_S_ATTACHED,
   1593 				    UMB_NS_DONT_DROP);
   1594 				break;
   1595 			default:
   1596 				break;
   1597 			}
   1598 		} else
   1599 			umb_newstate(sc, UMB_S_SIMREADY, UMB_NS_DONT_RAISE);
   1600 	} else switch (sc->sc_info.packetstate) {
   1601 	case MBIM_PKTSERVICE_STATE_ATTACHED:
   1602 		umb_newstate(sc, UMB_S_ATTACHED, UMB_NS_DONT_DROP);
   1603 		break;
   1604 	case MBIM_PKTSERVICE_STATE_DETACHED:
   1605 		umb_newstate(sc, UMB_S_SIMREADY, UMB_NS_DONT_RAISE);
   1606 		break;
   1607 	}
   1608 	return 1;
   1609 }
   1610 
   1611 Static int
   1612 umb_decode_signal_state(struct umb_softc *sc, void *data, int len)
   1613 {
   1614 	struct mbim_cid_signal_state *ss = data;
   1615 	struct ifnet *ifp = GET_IFP(sc);
   1616 	int	 rssi;
   1617 
   1618 	if (len < sizeof(*ss))
   1619 		return 0;
   1620 
   1621 	if (le32toh(ss->rssi) == 99)
   1622 		rssi = UMB_VALUE_UNKNOWN;
   1623 	else {
   1624 		rssi = -113 + 2 * le32toh(ss->rssi);
   1625 		if ((ifp->if_flags & IFF_DEBUG) && sc->sc_info.rssi != rssi &&
   1626 		    sc->sc_state >= UMB_S_CONNECTED)
   1627 			log(LOG_INFO, "%s: rssi %d dBm\n", DEVNAM(sc), rssi);
   1628 	}
   1629 	sc->sc_info.rssi = rssi;
   1630 	sc->sc_info.ber = le32toh(ss->err_rate);
   1631 	if (sc->sc_info.ber == -99)
   1632 		sc->sc_info.ber = UMB_VALUE_UNKNOWN;
   1633 	return 1;
   1634 }
   1635 
   1636 Static int
   1637 umb_decode_connect_info(struct umb_softc *sc, void *data, int len)
   1638 {
   1639 	struct mbim_cid_connect_info *ci = data;
   1640 	struct ifnet *ifp = GET_IFP(sc);
   1641 	int	 act;
   1642 
   1643 	if (len < sizeof(*ci))
   1644 		return 0;
   1645 
   1646 	if (le32toh(ci->sessionid) != umb_session_id) {
   1647 		DPRINTF("%s: discard connection info for session %u\n",
   1648 		    DEVNAM(sc), le32toh(ci->sessionid));
   1649 		return 1;
   1650 	}
   1651 	if (memcmp(ci->context, umb_uuid_context_internet,
   1652 	    sizeof(ci->context))) {
   1653 		DPRINTF("%s: discard connection info for other context\n",
   1654 		    DEVNAM(sc));
   1655 		return 1;
   1656 	}
   1657 	act = le32toh(ci->activation);
   1658 	if (sc->sc_info.activation != act) {
   1659 		if (ifp->if_flags & IFF_DEBUG)
   1660 			log(LOG_INFO, "%s: connection %s\n", DEVNAM(sc),
   1661 			    umb_activation(act));
   1662 		if ((ifp->if_flags & IFF_DEBUG) &&
   1663 		    le32toh(ci->iptype) != MBIM_CONTEXT_IPTYPE_DEFAULT &&
   1664 		    le32toh(ci->iptype) != MBIM_CONTEXT_IPTYPE_IPV4)
   1665 			log(LOG_DEBUG, "%s: got iptype %d connection\n",
   1666 			    DEVNAM(sc), le32toh(ci->iptype));
   1667 
   1668 		sc->sc_info.activation = act;
   1669 		sc->sc_info.nwerror = le32toh(ci->nwerror);
   1670 
   1671 		if (sc->sc_info.activation == MBIM_ACTIVATION_STATE_ACTIVATED)
   1672 			umb_newstate(sc, UMB_S_CONNECTED, UMB_NS_DONT_DROP);
   1673 		else if (sc->sc_info.activation ==
   1674 		    MBIM_ACTIVATION_STATE_DEACTIVATED)
   1675 			umb_newstate(sc, UMB_S_ATTACHED, 0);
   1676 		/* else: other states are purely transitional */
   1677 	}
   1678 	return 1;
   1679 }
   1680 
   1681 Static int
   1682 umb_decode_ip_configuration(struct umb_softc *sc, void *data, int len)
   1683 {
   1684 	struct mbim_cid_ip_configuration_info *ic = data;
   1685 	struct ifnet *ifp = GET_IFP(sc);
   1686 	int	 s;
   1687 	uint32_t avail;
   1688 	uint32_t val;
   1689 	int	 n, i;
   1690 	int	 off;
   1691 	struct mbim_cid_ipv4_element ipv4elem;
   1692 	struct in_aliasreq ifra;
   1693 	struct sockaddr_in *sin;
   1694 	int	 state = -1;
   1695 	int	 rv;
   1696 
   1697 	if (len < sizeof(*ic))
   1698 		return 0;
   1699 	if (le32toh(ic->sessionid) != umb_session_id) {
   1700 		DPRINTF("%s: ignore IP configuration for session id %d\n",
   1701 		    DEVNAM(sc), le32toh(ic->sessionid));
   1702 		return 0;
   1703 	}
   1704 	s = splnet();
   1705 
   1706 	/*
   1707 	 * IPv4 configuation
   1708 	 */
   1709 	avail = le32toh(ic->ipv4_available);
   1710 	if (avail & MBIM_IPCONF_HAS_ADDRINFO) {
   1711 		n = le32toh(ic->ipv4_naddr);
   1712 		off = le32toh(ic->ipv4_addroffs);
   1713 
   1714 		if (n == 0 || off + sizeof(ipv4elem) > len)
   1715 			goto done;
   1716 
   1717 		/* Only pick the first one */
   1718 		memcpy(&ipv4elem, (char *)data + off, sizeof(ipv4elem));
   1719 		ipv4elem.prefixlen = le32toh(ipv4elem.prefixlen);
   1720 
   1721 		memset(&ifra, 0, sizeof(ifra));
   1722 		sin = (struct sockaddr_in *)&ifra.ifra_addr;
   1723 		sin->sin_family = AF_INET;
   1724 		sin->sin_len = sizeof(ifra.ifra_addr);
   1725 		sin->sin_addr.s_addr = ipv4elem.addr;
   1726 
   1727 		sin = (struct sockaddr_in *)&ifra.ifra_dstaddr;
   1728 		sin->sin_family = AF_INET;
   1729 		sin->sin_len = sizeof(ifra.ifra_dstaddr);
   1730 		if (avail & MBIM_IPCONF_HAS_GWINFO) {
   1731 			off = le32toh(ic->ipv4_gwoffs);
   1732 			sin->sin_addr.s_addr = *((uint32_t *)((char *)data + off));
   1733 		}
   1734 
   1735 		sin = (struct sockaddr_in *)&ifra.ifra_mask;
   1736 		sin->sin_family = AF_INET;
   1737 		sin->sin_len = sizeof(ifra.ifra_mask);
   1738 		umb_in_len2mask(&sin->sin_addr, ipv4elem.prefixlen);
   1739 
   1740 		rv = in_control(NULL, SIOCAIFADDR, &ifra, ifp);
   1741 		if (rv == 0) {
   1742 			if (ifp->if_flags & IFF_DEBUG)
   1743 				log(LOG_INFO, "%s: IPv4 addr %s, mask %s, "
   1744 				    "gateway %s\n", device_xname(sc->sc_dev),
   1745 				    umb_ntop(sintosa(&ifra.ifra_addr)),
   1746 				    umb_ntop(sintosa(&ifra.ifra_mask)),
   1747 				    umb_ntop(sintosa(&ifra.ifra_dstaddr)));
   1748 			state = UMB_S_UP;
   1749 		} else
   1750 			printf("%s: unable to set IPv4 address, error %d\n",
   1751 			    device_xname(sc->sc_dev), rv);
   1752 	}
   1753 
   1754 	memset(sc->sc_info.ipv4dns, 0, sizeof(sc->sc_info.ipv4dns));
   1755 	if (avail & MBIM_IPCONF_HAS_DNSINFO) {
   1756 		n = le32toh(ic->ipv4_ndnssrv);
   1757 		off = le32toh(ic->ipv4_dnssrvoffs);
   1758 		i = 0;
   1759 		while (n-- > 0) {
   1760 			if (off + sizeof(uint32_t) > len)
   1761 				break;
   1762 			val = *((uint32_t *)((char *)data + off));
   1763 			if (i < UMB_MAX_DNSSRV)
   1764 				sc->sc_info.ipv4dns[i++] = val;
   1765 			off += sizeof(uint32_t);
   1766 		}
   1767 	}
   1768 
   1769 	if ((avail & MBIM_IPCONF_HAS_MTUINFO)) {
   1770 		val = le32toh(ic->ipv4_mtu);
   1771 		if (ifp->if_mtu != val && val <= sc->sc_maxpktlen) {
   1772 			ifp->if_mtu = val;
   1773 			if (ifp->if_mtu > val)
   1774 				ifp->if_mtu = val;
   1775 			if (ifp->if_flags & IFF_DEBUG)
   1776 				log(LOG_INFO, "%s: MTU %d\n", DEVNAM(sc), val);
   1777 		}
   1778 	}
   1779 
   1780 	avail = le32toh(ic->ipv6_available);
   1781 	if ((ifp->if_flags & IFF_DEBUG) && avail & MBIM_IPCONF_HAS_ADDRINFO) {
   1782 		/* XXX FIXME: IPv6 configuration missing */
   1783 		log(LOG_INFO, "%s: ignoring IPv6 configuration\n", DEVNAM(sc));
   1784 	}
   1785 	if (state != -1)
   1786 		umb_newstate(sc, state, 0);
   1787 
   1788 done:
   1789 	splx(s);
   1790 	return 1;
   1791 }
   1792 
   1793 Static void
   1794 umb_rx(struct umb_softc *sc)
   1795 {
   1796 	usbd_setup_xfer(sc->sc_rx_xfer, sc, sc->sc_rx_buf,
   1797 	    sc->sc_rx_bufsz, USBD_SHORT_XFER_OK,
   1798 	    USBD_NO_TIMEOUT, umb_rxeof);
   1799 	usbd_transfer(sc->sc_rx_xfer);
   1800 }
   1801 
   1802 Static void
   1803 umb_rxeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
   1804 {
   1805 	struct umb_softc *sc = priv;
   1806 	struct ifnet *ifp = GET_IFP(sc);
   1807 
   1808 	if (sc->sc_dying || !(ifp->if_flags & IFF_RUNNING))
   1809 		return;
   1810 
   1811 	if (status != USBD_NORMAL_COMPLETION) {
   1812 		if (status == USBD_NOT_STARTED || status == USBD_CANCELLED)
   1813 			return;
   1814 		DPRINTF("%s: rx error: %s\n", DEVNAM(sc), usbd_errstr(status));
   1815 		if (status == USBD_STALLED)
   1816 			usbd_clear_endpoint_stall_async(sc->sc_rx_pipe);
   1817 		if (++sc->sc_rx_nerr > 100) {
   1818 			log(LOG_ERR, "%s: too many rx errors, disabling\n",
   1819 			    DEVNAM(sc));
   1820 			umb_activate(sc->sc_dev, DVACT_DEACTIVATE);
   1821 		}
   1822 	} else {
   1823 		sc->sc_rx_nerr = 0;
   1824 		umb_decap(sc, xfer);
   1825 	}
   1826 
   1827 	umb_rx(sc);
   1828 	return;
   1829 }
   1830 
   1831 Static int
   1832 umb_encap(struct umb_softc *sc, struct mbuf *m)
   1833 {
   1834 	struct ncm_header16 *hdr;
   1835 	struct ncm_pointer16 *ptr;
   1836 	usbd_status  err;
   1837 	int len;
   1838 
   1839 	/* All size constraints have been validated by the caller! */
   1840 	hdr = (struct ncm_header16 *)sc->sc_tx_buf;
   1841 	ptr = (struct ncm_pointer16 *)(hdr + 1);
   1842 	USETDW(hdr->dwSignature, NCM_HDR16_SIG);
   1843 	USETW(hdr->wHeaderLength, sizeof(*hdr));
   1844 	USETW(hdr->wSequence, sc->sc_tx_seq);
   1845 	sc->sc_tx_seq++;
   1846 
   1847 	len = m->m_pkthdr.len;
   1848 
   1849 	USETDW(ptr->dwSignature, MBIM_NCM_NTH16_SIG(umb_session_id));
   1850 	USETW(ptr->wLength, sizeof(*ptr));
   1851 	USETW(ptr->wNextNdpIndex, 0);
   1852 	USETW(ptr->dgram[0].wDatagramIndex, MBIM_HDR16_LEN);
   1853 	USETW(ptr->dgram[0].wDatagramLen, len);
   1854 	USETW(ptr->dgram[1].wDatagramIndex, 0);
   1855 	USETW(ptr->dgram[1].wDatagramLen, 0);
   1856 
   1857 	KASSERT(len <= sc->sc_tx_bufsz - sizeof(*hdr) - sizeof(*ptr));
   1858 	m_copydata(m, 0, len, ptr + 1);
   1859 	sc->sc_tx_m = m;
   1860 	len += MBIM_HDR16_LEN;
   1861 	USETW(hdr->wBlockLength, len);
   1862 
   1863 	DPRINTFN(3, "%s: encap %d bytes\n", DEVNAM(sc), len);
   1864 	DDUMPN(5, sc->sc_tx_buf, len);
   1865 	usbd_setup_xfer(sc->sc_tx_xfer, sc, sc->sc_tx_buf, len,
   1866 	    USBD_FORCE_SHORT_XFER, umb_xfer_tout, umb_txeof);
   1867 	err = usbd_transfer(sc->sc_tx_xfer);
   1868 	if (err != USBD_IN_PROGRESS) {
   1869 		DPRINTF("%s: start tx error: %s\n", DEVNAM(sc),
   1870 		    usbd_errstr(err));
   1871 		return 0;
   1872 	}
   1873 	return 1;
   1874 }
   1875 
   1876 Static void
   1877 umb_txeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
   1878 {
   1879 	struct umb_softc *sc = priv;
   1880 	struct ifnet *ifp = GET_IFP(sc);
   1881 	int	 s;
   1882 
   1883 	s = splnet();
   1884 	ifp->if_flags &= ~IFF_OACTIVE;
   1885 	ifp->if_timer = 0;
   1886 
   1887 	m_freem(sc->sc_tx_m);
   1888 	sc->sc_tx_m = NULL;
   1889 
   1890 	if (status != USBD_NORMAL_COMPLETION) {
   1891 		if (status != USBD_NOT_STARTED && status != USBD_CANCELLED) {
   1892 			ifp->if_oerrors++;
   1893 			DPRINTF("%s: tx error: %s\n", DEVNAM(sc),
   1894 			    usbd_errstr(status));
   1895 			if (status == USBD_STALLED)
   1896 				usbd_clear_endpoint_stall_async(sc->sc_tx_pipe);
   1897 		}
   1898 	}
   1899 	if (IFQ_IS_EMPTY(&ifp->if_snd) == 0)
   1900 		umb_start(ifp);
   1901 
   1902 	splx(s);
   1903 }
   1904 
   1905 Static void
   1906 umb_decap(struct umb_softc *sc, struct usbd_xfer *xfer)
   1907 {
   1908 	struct ifnet *ifp = GET_IFP(sc);
   1909 	int	 s;
   1910 	char	*buf;
   1911 	uint32_t len;
   1912 	char	*dp;
   1913 	struct ncm_header16 *hdr16;
   1914 	struct ncm_header32 *hdr32;
   1915 	struct ncm_pointer16 *ptr16;
   1916 	struct ncm_pointer16_dgram *dgram16;
   1917 	struct ncm_pointer32_dgram *dgram32;
   1918 	uint32_t hsig, psig;
   1919 	int	 hlen, blen;
   1920 	int	 ptrlen, ptroff, dgentryoff;
   1921 	uint32_t doff, dlen;
   1922 	struct mbuf *m;
   1923 
   1924 	usbd_get_xfer_status(xfer, NULL, (void **)&buf, &len, NULL);
   1925 	DPRINTFN(4, "%s: recv %d bytes\n", DEVNAM(sc), len);
   1926 	DDUMPN(5, buf, len);
   1927 	s = splnet();
   1928 	if (len < sizeof(*hdr16))
   1929 		goto toosmall;
   1930 
   1931 	hdr16 = (struct ncm_header16 *)buf;
   1932 	hsig = UGETDW(hdr16->dwSignature);
   1933 	hlen = UGETW(hdr16->wHeaderLength);
   1934 	if (len < hlen)
   1935 		goto toosmall;
   1936 	if (len > sc->sc_rx_bufsz) {
   1937 		DPRINTF("%s: packet too large (%d)\n", DEVNAM(sc), len);
   1938 		goto fail;
   1939 	}
   1940 	switch (hsig) {
   1941 	case NCM_HDR16_SIG:
   1942 		blen = UGETW(hdr16->wBlockLength);
   1943 		ptroff = UGETW(hdr16->wNdpIndex);
   1944 		if (hlen != sizeof(*hdr16)) {
   1945 			DPRINTF("%s: bad header len %d for NTH16 (exp %zu)\n",
   1946 			    DEVNAM(sc), hlen, sizeof(*hdr16));
   1947 			goto fail;
   1948 		}
   1949 		break;
   1950 	case NCM_HDR32_SIG:
   1951 		hdr32 = (struct ncm_header32 *)hdr16;
   1952 		blen = UGETDW(hdr32->dwBlockLength);
   1953 		ptroff = UGETDW(hdr32->dwNdpIndex);
   1954 		if (hlen != sizeof(*hdr32)) {
   1955 			DPRINTF("%s: bad header len %d for NTH32 (exp %zu)\n",
   1956 			    DEVNAM(sc), hlen, sizeof(*hdr32));
   1957 			goto fail;
   1958 		}
   1959 		break;
   1960 	default:
   1961 		DPRINTF("%s: unsupported NCM header signature (0x%08x)\n",
   1962 		    DEVNAM(sc), hsig);
   1963 		goto fail;
   1964 	}
   1965 	if (len < blen) {
   1966 		DPRINTF("%s: bad NTB len (%d) for %d bytes of data\n",
   1967 		    DEVNAM(sc), blen, len);
   1968 		goto fail;
   1969 	}
   1970 
   1971 	ptr16 = (struct ncm_pointer16 *)(buf + ptroff);
   1972 	psig = UGETDW(ptr16->dwSignature);
   1973 	ptrlen = UGETW(ptr16->wLength);
   1974 	if (len < ptrlen + ptroff)
   1975 		goto toosmall;
   1976 	if (!MBIM_NCM_NTH16_ISISG(psig) && !MBIM_NCM_NTH32_ISISG(psig)) {
   1977 		DPRINTF("%s: unsupported NCM pointer signature (0x%08x)\n",
   1978 		    DEVNAM(sc), psig);
   1979 		goto fail;
   1980 	}
   1981 
   1982 	switch (hsig) {
   1983 	case NCM_HDR16_SIG:
   1984 		dgentryoff = offsetof(struct ncm_pointer16, dgram);
   1985 		break;
   1986 	case NCM_HDR32_SIG:
   1987 		dgentryoff = offsetof(struct ncm_pointer32, dgram);
   1988 		break;
   1989 	default:
   1990 		goto fail;
   1991 	}
   1992 
   1993 	while (dgentryoff < ptrlen) {
   1994 		switch (hsig) {
   1995 		case NCM_HDR16_SIG:
   1996 			if (ptroff + dgentryoff < sizeof(*dgram16))
   1997 				goto done;
   1998 			dgram16 = (struct ncm_pointer16_dgram *)
   1999 			    (buf + ptroff + dgentryoff);
   2000 			dgentryoff += sizeof(*dgram16);
   2001 			dlen = UGETW(dgram16->wDatagramLen);
   2002 			doff = UGETW(dgram16->wDatagramIndex);
   2003 			break;
   2004 		case NCM_HDR32_SIG:
   2005 			if (ptroff + dgentryoff < sizeof(*dgram32))
   2006 				goto done;
   2007 			dgram32 = (struct ncm_pointer32_dgram *)
   2008 			    (buf + ptroff + dgentryoff);
   2009 			dgentryoff += sizeof(*dgram32);
   2010 			dlen = UGETDW(dgram32->dwDatagramLen);
   2011 			doff = UGETDW(dgram32->dwDatagramIndex);
   2012 			break;
   2013 		default:
   2014 			ifp->if_ierrors++;
   2015 			goto done;
   2016 		}
   2017 
   2018 		/* Terminating zero entry */
   2019 		if (dlen == 0 || doff == 0)
   2020 			break;
   2021 		if (len < dlen + doff) {
   2022 			/* Skip giant datagram but continue processing */
   2023 			DPRINTF("%s: datagram too large (%d @ off %d)\n",
   2024 			    DEVNAM(sc), dlen, doff);
   2025 			continue;
   2026 		}
   2027 
   2028 		dp = buf + doff;
   2029 		DPRINTFN(3, "%s: decap %d bytes\n", DEVNAM(sc), dlen);
   2030 		m = m_devget(dp, dlen, 0, ifp, NULL);
   2031 		if (m == NULL) {
   2032 			ifp->if_iqdrops++;
   2033 			continue;
   2034 		}
   2035 
   2036 		if_percpuq_enqueue((ifp)->if_percpuq, (m));
   2037 	}
   2038 done:
   2039 	splx(s);
   2040 	return;
   2041 toosmall:
   2042 	DPRINTF("%s: packet too small (%d)\n", DEVNAM(sc), len);
   2043 fail:
   2044 	ifp->if_ierrors++;
   2045 	splx(s);
   2046 }
   2047 
   2048 Static usbd_status
   2049 umb_send_encap_command(struct umb_softc *sc, void *data, int len)
   2050 {
   2051 	struct usbd_xfer *xfer;
   2052 	usb_device_request_t req;
   2053 	char *buf;
   2054 
   2055 	if (len > sc->sc_ctrl_len)
   2056 		return USBD_INVAL;
   2057 
   2058 	if (usbd_create_xfer(sc->sc_udev->ud_pipe0, len, 0, 0, &xfer) != 0)
   2059 		return USBD_NOMEM;
   2060 	buf = usbd_get_buffer(xfer);
   2061 	memcpy(buf, data, len);
   2062 
   2063 	/* XXX FIXME: if (total len > sc->sc_ctrl_len) => must fragment */
   2064 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
   2065 	req.bRequest = UCDC_SEND_ENCAPSULATED_COMMAND;
   2066 	USETW(req.wValue, 0);
   2067 	USETW(req.wIndex, sc->sc_ctrl_ifaceno);
   2068 	USETW(req.wLength, len);
   2069 	DELAY(umb_delay);
   2070 	return usbd_request_async(sc->sc_udev, xfer, &req, NULL, NULL);
   2071 }
   2072 
   2073 Static int
   2074 umb_get_encap_response(struct umb_softc *sc, void *buf, int *len)
   2075 {
   2076 	usb_device_request_t req;
   2077 	usbd_status err;
   2078 
   2079 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
   2080 	req.bRequest = UCDC_GET_ENCAPSULATED_RESPONSE;
   2081 	USETW(req.wValue, 0);
   2082 	USETW(req.wIndex, sc->sc_ctrl_ifaceno);
   2083 	USETW(req.wLength, *len);
   2084 	/* XXX FIXME: re-assemble fragments */
   2085 
   2086 	DELAY(umb_delay);
   2087 	err = usbd_do_request_flags(sc->sc_udev, &req, buf, USBD_SHORT_XFER_OK,
   2088 	    len, umb_xfer_tout);
   2089 	if (err == USBD_NORMAL_COMPLETION)
   2090 		return 1;
   2091 	DPRINTF("%s: ctrl recv: %s\n", DEVNAM(sc), usbd_errstr(err));
   2092 	return 0;
   2093 }
   2094 
   2095 Static void
   2096 umb_ctrl_msg(struct umb_softc *sc, uint32_t req, void *data, int len)
   2097 {
   2098 	struct ifnet *ifp = GET_IFP(sc);
   2099 	uint32_t tid;
   2100 	struct mbim_msghdr *hdr = data;
   2101 	usbd_status err;
   2102 	int	 s;
   2103 
   2104 	if (sc->sc_dying)
   2105 		return;
   2106 	if (len < sizeof(*hdr))
   2107 		return;
   2108 	tid = ++sc->sc_tid;
   2109 
   2110 	hdr->type = htole32(req);
   2111 	hdr->len = htole32(len);
   2112 	hdr->tid = htole32(tid);
   2113 
   2114 #ifdef UMB_DEBUG
   2115 	if (umb_debug) {
   2116 		const char *op, *str;
   2117 		if (req == MBIM_COMMAND_MSG) {
   2118 			struct mbim_h2f_cmd *c = data;
   2119 			if (le32toh(c->op) == MBIM_CMDOP_SET)
   2120 				op = "set";
   2121 			else
   2122 				op = "qry";
   2123 			str = umb_cid2str(le32toh(c->cid));
   2124 		} else {
   2125 			op = "snd";
   2126 			str = umb_request2str(req);
   2127 		}
   2128 		DPRINTF("%s: -> %s %s (tid %u)\n", DEVNAM(sc), op, str, tid);
   2129 	}
   2130 #endif
   2131 	s = splusb();
   2132 	err = umb_send_encap_command(sc, data, len);
   2133 	splx(s);
   2134 	if (err != USBD_NORMAL_COMPLETION) {
   2135 		if (ifp->if_flags & IFF_DEBUG)
   2136 			log(LOG_ERR, "%s: send %s msg (tid %u) failed: %s\n",
   2137 			    DEVNAM(sc), umb_request2str(req), tid,
   2138 			    usbd_errstr(err));
   2139 
   2140 		/* will affect other transactions, too */
   2141 		usbd_abort_pipe(sc->sc_udev->ud_pipe0);
   2142 	} else {
   2143 		DPRINTFN(2, "%s: sent %s (tid %u)\n", DEVNAM(sc),
   2144 		    umb_request2str(req), tid);
   2145 		DDUMPN(3, data, len);
   2146 	}
   2147 	return;
   2148 }
   2149 
   2150 Static void
   2151 umb_open(struct umb_softc *sc)
   2152 {
   2153 	struct mbim_h2f_openmsg msg;
   2154 
   2155 	memset(&msg, 0, sizeof(msg));
   2156 	msg.maxlen = htole32(sc->sc_ctrl_len);
   2157 	umb_ctrl_msg(sc, MBIM_OPEN_MSG, &msg, sizeof(msg));
   2158 	return;
   2159 }
   2160 
   2161 Static void
   2162 umb_close(struct umb_softc *sc)
   2163 {
   2164 	struct mbim_h2f_closemsg msg;
   2165 
   2166 	memset(&msg, 0, sizeof(msg));
   2167 	umb_ctrl_msg(sc, MBIM_CLOSE_MSG, &msg, sizeof(msg));
   2168 }
   2169 
   2170 Static int
   2171 umb_setpin(struct umb_softc *sc, int op, int is_puk, void *pin, int pinlen,
   2172     void *newpin, int newpinlen)
   2173 {
   2174 	struct mbim_cid_pin cp;
   2175 	int	 off;
   2176 
   2177 	if (pinlen == 0)
   2178 		return 0;
   2179 	if (pinlen < 0 || pinlen > MBIM_PIN_MAXLEN ||
   2180 	    newpinlen < 0 || newpinlen > MBIM_PIN_MAXLEN ||
   2181 	    op < 0 || op > MBIM_PIN_OP_CHANGE ||
   2182 	    (is_puk && op != MBIM_PIN_OP_ENTER))
   2183 		return EINVAL;
   2184 
   2185 	memset(&cp, 0, sizeof(cp));
   2186 	cp.type = htole32(is_puk ? MBIM_PIN_TYPE_PUK1 : MBIM_PIN_TYPE_PIN1);
   2187 
   2188 	off = offsetof(struct mbim_cid_pin, data);
   2189 	if (!umb_addstr(&cp, sizeof(cp), &off, pin, pinlen,
   2190 	    &cp.pin_offs, &cp.pin_size))
   2191 		return EINVAL;
   2192 
   2193 	cp.op  = htole32(op);
   2194 	if (newpinlen) {
   2195 		if (!umb_addstr(&cp, sizeof(cp), &off, newpin, newpinlen,
   2196 		    &cp.newpin_offs, &cp.newpin_size))
   2197 			return EINVAL;
   2198 	} else {
   2199 		if ((op == MBIM_PIN_OP_CHANGE) || is_puk)
   2200 			return EINVAL;
   2201 		if (!umb_addstr(&cp, sizeof(cp), &off, NULL, 0,
   2202 		    &cp.newpin_offs, &cp.newpin_size))
   2203 			return EINVAL;
   2204 	}
   2205 	umb_cmd(sc, MBIM_CID_PIN, MBIM_CMDOP_SET, &cp, off);
   2206 	return 0;
   2207 }
   2208 
   2209 Static void
   2210 umb_setdataclass(struct umb_softc *sc)
   2211 {
   2212 	struct mbim_cid_registration_state rs;
   2213 	uint32_t	 classes;
   2214 
   2215 	if (sc->sc_info.supportedclasses == MBIM_DATACLASS_NONE)
   2216 		return;
   2217 
   2218 	memset(&rs, 0, sizeof(rs));
   2219 	rs.regaction = htole32(MBIM_REGACTION_AUTOMATIC);
   2220 	classes = sc->sc_info.supportedclasses;
   2221 	if (sc->sc_info.preferredclasses != MBIM_DATACLASS_NONE)
   2222 		classes &= sc->sc_info.preferredclasses;
   2223 	rs.data_class = htole32(classes);
   2224 	umb_cmd(sc, MBIM_CID_REGISTER_STATE, MBIM_CMDOP_SET, &rs, sizeof(rs));
   2225 }
   2226 
   2227 Static void
   2228 umb_radio(struct umb_softc *sc, int on)
   2229 {
   2230 	struct mbim_cid_radio_state s;
   2231 
   2232 	DPRINTF("%s: set radio %s\n", DEVNAM(sc), on ? "on" : "off");
   2233 	memset(&s, 0, sizeof(s));
   2234 	s.state = htole32(on ? MBIM_RADIO_STATE_ON : MBIM_RADIO_STATE_OFF);
   2235 	umb_cmd(sc, MBIM_CID_RADIO_STATE, MBIM_CMDOP_SET, &s, sizeof(s));
   2236 }
   2237 
   2238 Static void
   2239 umb_allocate_cid(struct umb_softc *sc)
   2240 {
   2241 	umb_cmd1(sc, MBIM_CID_DEVICE_CAPS, MBIM_CMDOP_SET,
   2242 	    umb_qmi_alloc_cid, sizeof(umb_qmi_alloc_cid), umb_uuid_qmi_mbim);
   2243 }
   2244 
   2245 Static void
   2246 umb_send_fcc_auth(struct umb_softc *sc)
   2247 {
   2248 	uint8_t	 fccauth[sizeof(umb_qmi_fcc_auth)];
   2249 
   2250 	if (sc->sc_cid == -1) {
   2251 		DPRINTF("%s: missing CID, cannot send FCC auth\n", DEVNAM(sc));
   2252 		umb_allocate_cid(sc);
   2253 		return;
   2254 	}
   2255 	memcpy(fccauth, umb_qmi_fcc_auth, sizeof(fccauth));
   2256 	fccauth[UMB_QMI_CID_OFFS] = sc->sc_cid;
   2257 	umb_cmd1(sc, MBIM_CID_DEVICE_CAPS, MBIM_CMDOP_SET,
   2258 	    fccauth, sizeof(fccauth), umb_uuid_qmi_mbim);
   2259 }
   2260 
   2261 Static void
   2262 umb_packet_service(struct umb_softc *sc, int attach)
   2263 {
   2264 	struct mbim_cid_packet_service	s;
   2265 
   2266 	DPRINTF("%s: %s packet service\n", DEVNAM(sc),
   2267 	    attach ? "attach" : "detach");
   2268 	memset(&s, 0, sizeof(s));
   2269 	s.action = htole32(attach ?
   2270 	    MBIM_PKTSERVICE_ACTION_ATTACH : MBIM_PKTSERVICE_ACTION_DETACH);
   2271 	umb_cmd(sc, MBIM_CID_PACKET_SERVICE, MBIM_CMDOP_SET, &s, sizeof(s));
   2272 }
   2273 
   2274 Static void
   2275 umb_connect(struct umb_softc *sc)
   2276 {
   2277 	struct ifnet *ifp = GET_IFP(sc);
   2278 
   2279 	if (sc->sc_info.regstate == MBIM_REGSTATE_ROAMING && !sc->sc_roaming) {
   2280 		log(LOG_INFO, "%s: connection disabled in roaming network\n",
   2281 		    DEVNAM(sc));
   2282 		return;
   2283 	}
   2284 	if (ifp->if_flags & IFF_DEBUG)
   2285 		log(LOG_DEBUG, "%s: connecting ...\n", DEVNAM(sc));
   2286 	umb_send_connect(sc, MBIM_CONNECT_ACTIVATE);
   2287 }
   2288 
   2289 Static void
   2290 umb_disconnect(struct umb_softc *sc)
   2291 {
   2292 	struct ifnet *ifp = GET_IFP(sc);
   2293 
   2294 	if (ifp->if_flags & IFF_DEBUG)
   2295 		log(LOG_DEBUG, "%s: disconnecting ...\n", DEVNAM(sc));
   2296 	umb_send_connect(sc, MBIM_CONNECT_DEACTIVATE);
   2297 }
   2298 
   2299 Static void
   2300 umb_send_connect(struct umb_softc *sc, int command)
   2301 {
   2302 	struct mbim_cid_connect *c;
   2303 	int	 off;
   2304 
   2305 	/* Too large or the stack */
   2306 	c = kmem_zalloc(sizeof(*c), KM_SLEEP);
   2307 	c->sessionid = htole32(umb_session_id);
   2308 	c->command = htole32(command);
   2309 	off = offsetof(struct mbim_cid_connect, data);
   2310 	if (!umb_addstr(c, sizeof(*c), &off, sc->sc_info.apn,
   2311 	    sc->sc_info.apnlen, &c->access_offs, &c->access_size))
   2312 		goto done;
   2313 	if (!umb_addstr(c, sizeof(*c), &off, sc->sc_info.username,
   2314 	    sc->sc_info.usernamelen, &c->user_offs, &c->user_size))
   2315 		goto done;
   2316 	if (!umb_addstr(c, sizeof(*c), &off, sc->sc_info.password,
   2317 	    sc->sc_info.passwordlen, &c->passwd_offs, &c->passwd_size))
   2318 		goto done;
   2319 	c->authprot = htole32(MBIM_AUTHPROT_NONE);
   2320 	c->compression = htole32(MBIM_COMPRESSION_NONE);
   2321 	c->iptype = htole32(MBIM_CONTEXT_IPTYPE_IPV4);
   2322 	memcpy(c->context, umb_uuid_context_internet, sizeof(c->context));
   2323 	umb_cmd(sc, MBIM_CID_CONNECT, MBIM_CMDOP_SET, c, off);
   2324 done:
   2325 	kmem_free(c, sizeof(*c));
   2326 	return;
   2327 }
   2328 
   2329 Static void
   2330 umb_qry_ipconfig(struct umb_softc *sc)
   2331 {
   2332 	struct mbim_cid_ip_configuration_info ipc;
   2333 
   2334 	memset(&ipc, 0, sizeof(ipc));
   2335 	ipc.sessionid = htole32(umb_session_id);
   2336 	umb_cmd(sc, MBIM_CID_IP_CONFIGURATION, MBIM_CMDOP_QRY,
   2337 	    &ipc, sizeof(ipc));
   2338 }
   2339 
   2340 Static void
   2341 umb_cmd(struct umb_softc *sc, int cid, int op, const void *data, int len)
   2342 {
   2343 	umb_cmd1(sc, cid, op, data, len, umb_uuid_basic_connect);
   2344 }
   2345 
   2346 Static void
   2347 umb_cmd1(struct umb_softc *sc, int cid, int op, const void *data, int len,
   2348     uint8_t *uuid)
   2349 {
   2350 	struct mbim_h2f_cmd *cmd;
   2351 	int	totlen;
   2352 
   2353 	/* XXX FIXME support sending fragments */
   2354 	if (sizeof(*cmd) + len > sc->sc_ctrl_len) {
   2355 		DPRINTF("%s: set %s msg too long: cannot send\n",
   2356 		    DEVNAM(sc), umb_cid2str(cid));
   2357 		return;
   2358 	}
   2359 	cmd = sc->sc_ctrl_msg;
   2360 	memset(cmd, 0, sizeof(*cmd));
   2361 	cmd->frag.nfrag = htole32(1);
   2362 	memcpy(cmd->devid, uuid, sizeof(cmd->devid));
   2363 	cmd->cid = htole32(cid);
   2364 	cmd->op = htole32(op);
   2365 	cmd->infolen = htole32(len);
   2366 	totlen = sizeof(*cmd);
   2367 	if (len > 0) {
   2368 		memcpy(cmd + 1, data, len);
   2369 		totlen += len;
   2370 	}
   2371 	umb_ctrl_msg(sc, MBIM_COMMAND_MSG, cmd, totlen);
   2372 }
   2373 
   2374 Static void
   2375 umb_command_done(struct umb_softc *sc, void *data, int len)
   2376 {
   2377 	struct mbim_f2h_cmddone *cmd = data;
   2378 	struct ifnet *ifp = GET_IFP(sc);
   2379 	uint32_t status;
   2380 	uint32_t cid;
   2381 	uint32_t infolen;
   2382 	int	 qmimsg = 0;
   2383 
   2384 	if (len < sizeof(*cmd)) {
   2385 		DPRINTF("%s: discard short %s messsage\n", DEVNAM(sc),
   2386 		    umb_request2str(le32toh(cmd->hdr.type)));
   2387 		return;
   2388 	}
   2389 	cid = le32toh(cmd->cid);
   2390 	if (memcmp(cmd->devid, umb_uuid_basic_connect, sizeof(cmd->devid))) {
   2391 		if (memcmp(cmd->devid, umb_uuid_qmi_mbim,
   2392 		    sizeof(cmd->devid))) {
   2393 			DPRINTF("%s: discard %s messsage for other UUID '%s'\n",
   2394 			    DEVNAM(sc), umb_request2str(le32toh(cmd->hdr.type)),
   2395 			    umb_uuid2str(cmd->devid));
   2396 			return;
   2397 		} else
   2398 			qmimsg = 1;
   2399 	}
   2400 
   2401 	status = le32toh(cmd->status);
   2402 	switch (status) {
   2403 	case MBIM_STATUS_SUCCESS:
   2404 		break;
   2405 	case MBIM_STATUS_NOT_INITIALIZED:
   2406 		if (ifp->if_flags & IFF_DEBUG)
   2407 			log(LOG_ERR, "%s: SIM not initialized (PIN missing)\n",
   2408 			    DEVNAM(sc));
   2409 		return;
   2410 	case MBIM_STATUS_PIN_REQUIRED:
   2411 		sc->sc_info.pin_state = UMB_PIN_REQUIRED;
   2412 		/*FALLTHROUGH*/
   2413 	default:
   2414 		if (ifp->if_flags & IFF_DEBUG)
   2415 			log(LOG_ERR, "%s: set/qry %s failed: %s\n", DEVNAM(sc),
   2416 			    umb_cid2str(cid), umb_status2str(status));
   2417 		return;
   2418 	}
   2419 
   2420 	infolen = le32toh(cmd->infolen);
   2421 	if (len < sizeof(*cmd) + infolen) {
   2422 		DPRINTF("%s: discard truncated %s messsage (want %d, got %d)\n",
   2423 		    DEVNAM(sc), umb_cid2str(cid),
   2424 		    (int)sizeof(*cmd) + infolen, len);
   2425 		return;
   2426 	}
   2427 	if (qmimsg) {
   2428 		if (sc->sc_flags & UMBFLG_FCC_AUTH_REQUIRED)
   2429 			umb_decode_qmi(sc, cmd->info, infolen);
   2430 	} else {
   2431 		DPRINTFN(2, "%s: set/qry %s done\n", DEVNAM(sc),
   2432 		    umb_cid2str(cid));
   2433 		umb_decode_cid(sc, cid, cmd->info, infolen);
   2434 	}
   2435 }
   2436 
   2437 Static void
   2438 umb_decode_cid(struct umb_softc *sc, uint32_t cid, void *data, int len)
   2439 {
   2440 	int	 ok = 1;
   2441 
   2442 	switch (cid) {
   2443 	case MBIM_CID_DEVICE_CAPS:
   2444 		ok = umb_decode_devices_caps(sc, data, len);
   2445 		break;
   2446 	case MBIM_CID_SUBSCRIBER_READY_STATUS:
   2447 		ok = umb_decode_subscriber_status(sc, data, len);
   2448 		break;
   2449 	case MBIM_CID_RADIO_STATE:
   2450 		ok = umb_decode_radio_state(sc, data, len);
   2451 		break;
   2452 	case MBIM_CID_PIN:
   2453 		ok = umb_decode_pin(sc, data, len);
   2454 		break;
   2455 	case MBIM_CID_REGISTER_STATE:
   2456 		ok = umb_decode_register_state(sc, data, len);
   2457 		break;
   2458 	case MBIM_CID_PACKET_SERVICE:
   2459 		ok = umb_decode_packet_service(sc, data, len);
   2460 		break;
   2461 	case MBIM_CID_SIGNAL_STATE:
   2462 		ok = umb_decode_signal_state(sc, data, len);
   2463 		break;
   2464 	case MBIM_CID_CONNECT:
   2465 		ok = umb_decode_connect_info(sc, data, len);
   2466 		break;
   2467 	case MBIM_CID_IP_CONFIGURATION:
   2468 		ok = umb_decode_ip_configuration(sc, data, len);
   2469 		break;
   2470 	default:
   2471 		/*
   2472 		 * Note: the above list is incomplete and only contains
   2473 		 *	mandatory CIDs from the BASIC_CONNECT set.
   2474 		 *	So alternate values are not unusual.
   2475 		 */
   2476 		DPRINTFN(4, "%s: ignore %s\n", DEVNAM(sc), umb_cid2str(cid));
   2477 		break;
   2478 	}
   2479 	if (!ok)
   2480 		DPRINTF("%s: discard %s with bad info length %d\n",
   2481 		    DEVNAM(sc), umb_cid2str(cid), len);
   2482 	return;
   2483 }
   2484 
   2485 Static void
   2486 umb_decode_qmi(struct umb_softc *sc, uint8_t *data, int len)
   2487 {
   2488 	uint8_t	srv;
   2489 	uint16_t msg, tlvlen;
   2490 	uint32_t val;
   2491 
   2492 #define UMB_QMI_QMUXLEN		6
   2493 	if (len < UMB_QMI_QMUXLEN)
   2494 		goto tooshort;
   2495 
   2496 	srv = data[4];
   2497 	data += UMB_QMI_QMUXLEN;
   2498 	len -= UMB_QMI_QMUXLEN;
   2499 
   2500 #define UMB_GET16(p)	((uint16_t)*p | (uint16_t)*(p + 1) << 8)
   2501 #define UMB_GET32(p)	((uint32_t)*p | (uint32_t)*(p + 1) << 8 | \
   2502 			    (uint32_t)*(p + 2) << 16 |(uint32_t)*(p + 3) << 24)
   2503 	switch (srv) {
   2504 	case 0:	/* ctl */
   2505 #define UMB_QMI_CTLLEN		6
   2506 		if (len < UMB_QMI_CTLLEN)
   2507 			goto tooshort;
   2508 		msg = UMB_GET16(&data[2]);
   2509 		tlvlen = UMB_GET16(&data[4]);
   2510 		data += UMB_QMI_CTLLEN;
   2511 		len -= UMB_QMI_CTLLEN;
   2512 		break;
   2513 	case 2:	/* dms  */
   2514 #define UMB_QMI_DMSLEN		7
   2515 		if (len < UMB_QMI_DMSLEN)
   2516 			goto tooshort;
   2517 		msg = UMB_GET16(&data[3]);
   2518 		tlvlen = UMB_GET16(&data[5]);
   2519 		data += UMB_QMI_DMSLEN;
   2520 		len -= UMB_QMI_DMSLEN;
   2521 		break;
   2522 	default:
   2523 		DPRINTF("%s: discard QMI message for unknown service type %d\n",
   2524 		    DEVNAM(sc), srv);
   2525 		return;
   2526 	}
   2527 
   2528 	if (len < tlvlen)
   2529 		goto tooshort;
   2530 
   2531 #define UMB_QMI_TLVLEN		3
   2532 	while (len > 0) {
   2533 		if (len < UMB_QMI_TLVLEN)
   2534 			goto tooshort;
   2535 		tlvlen = UMB_GET16(&data[1]);
   2536 		if (len < UMB_QMI_TLVLEN + tlvlen)
   2537 			goto tooshort;
   2538 		switch (data[0]) {
   2539 		case 1:	/* allocation info */
   2540 			if (msg == 0x0022) {	/* Allocate CID */
   2541 				if (tlvlen != 2 || data[3] != 2) /* dms */
   2542 					break;
   2543 				sc->sc_cid = data[4];
   2544 				DPRINTF("%s: QMI CID %d allocated\n",
   2545 				    DEVNAM(sc), sc->sc_cid);
   2546 				umb_newstate(sc, UMB_S_CID, UMB_NS_DONT_DROP);
   2547 			}
   2548 			break;
   2549 		case 2:	/* response */
   2550 			if (tlvlen != sizeof(val))
   2551 				break;
   2552 			val = UMB_GET32(&data[3]);
   2553 			switch (msg) {
   2554 			case 0x0022:	/* Allocate CID */
   2555 				if (val != 0) {
   2556 					log(LOG_ERR, "%s: allocation of QMI CID"
   2557 					    " failed, error 0x%x\n", DEVNAM(sc),
   2558 					    val);
   2559 					/* XXX how to proceed? */
   2560 					return;
   2561 				}
   2562 				break;
   2563 			case 0x555f:	/* Send FCC Authentication */
   2564 				if (val == 0)
   2565 					log(LOG_INFO, "%s: send FCC "
   2566 					    "Authentication succeeded\n",
   2567 					    DEVNAM(sc));
   2568 				else if (val == 0x001a0001)
   2569 					log(LOG_INFO, "%s: FCC Authentication "
   2570 					    "not required\n", DEVNAM(sc));
   2571 				else
   2572 					log(LOG_INFO, "%s: send FCC "
   2573 					    "Authentication failed, "
   2574 					    "error 0x%x\n", DEVNAM(sc), val);
   2575 
   2576 				/* FCC Auth is needed only once after power-on*/
   2577 				sc->sc_flags &= ~UMBFLG_FCC_AUTH_REQUIRED;
   2578 
   2579 				/* Try to proceed anyway */
   2580 				DPRINTF("%s: init: turning radio on ...\n",
   2581 				    DEVNAM(sc));
   2582 				umb_radio(sc, 1);
   2583 				break;
   2584 			default:
   2585 				break;
   2586 			}
   2587 			break;
   2588 		default:
   2589 			break;
   2590 		}
   2591 		data += UMB_QMI_TLVLEN + tlvlen;
   2592 		len -= UMB_QMI_TLVLEN + tlvlen;
   2593 	}
   2594 	return;
   2595 
   2596 tooshort:
   2597 	DPRINTF("%s: discard short QMI message\n", DEVNAM(sc));
   2598 	return;
   2599 }
   2600 
   2601 Static void
   2602 umb_intr(struct usbd_xfer *xfer, void *priv, usbd_status status)
   2603 {
   2604 	struct umb_softc *sc = priv;
   2605 	struct ifnet *ifp = GET_IFP(sc);
   2606 	int	 total_len;
   2607 
   2608 	if (status != USBD_NORMAL_COMPLETION) {
   2609 		DPRINTF("%s: notification error: %s\n", DEVNAM(sc),
   2610 		    usbd_errstr(status));
   2611 		if (status == USBD_STALLED)
   2612 			usbd_clear_endpoint_stall_async(sc->sc_ctrl_pipe);
   2613 		return;
   2614 	}
   2615 	usbd_get_xfer_status(xfer, NULL, NULL, &total_len, NULL);
   2616 	if (total_len < UCDC_NOTIFICATION_LENGTH) {
   2617 		DPRINTF("%s: short notification (%d<%d)\n", DEVNAM(sc),
   2618 		    total_len, UCDC_NOTIFICATION_LENGTH);
   2619 		    return;
   2620 	}
   2621 	if (sc->sc_intr_msg.bmRequestType != UCDC_NOTIFICATION) {
   2622 		DPRINTF("%s: unexpected notification (type=0x%02x)\n",
   2623 		    DEVNAM(sc), sc->sc_intr_msg.bmRequestType);
   2624 		return;
   2625 	}
   2626 
   2627 	switch (sc->sc_intr_msg.bNotification) {
   2628 	case UCDC_N_NETWORK_CONNECTION:
   2629 		if (ifp->if_flags & IFF_DEBUG)
   2630 			log(LOG_DEBUG, "%s: network %sconnected\n", DEVNAM(sc),
   2631 			    UGETW(sc->sc_intr_msg.wValue) ? "" : "dis");
   2632 		break;
   2633 	case UCDC_N_RESPONSE_AVAILABLE:
   2634 		DPRINTFN(2, "%s: umb_intr: response available\n", DEVNAM(sc));
   2635 		++sc->sc_nresp;
   2636 		usb_add_task(sc->sc_udev, &sc->sc_get_response_task, USB_TASKQ_DRIVER);
   2637 		break;
   2638 	case UCDC_N_CONNECTION_SPEED_CHANGE:
   2639 		DPRINTFN(2, "%s: umb_intr: connection speed changed\n",
   2640 		    DEVNAM(sc));
   2641 		break;
   2642 	default:
   2643 		DPRINTF("%s: unexpected notifiation (0x%02x)\n",
   2644 		    DEVNAM(sc), sc->sc_intr_msg.bNotification);
   2645 		break;
   2646 	}
   2647 }
   2648 
   2649 /*
   2650  * Diagnostic routines
   2651  */
   2652 Static char *
   2653 umb_ntop(struct sockaddr *sa)
   2654 {
   2655 #define NUMBUFS		4
   2656 	static char astr[NUMBUFS][INET_ADDRSTRLEN];
   2657 	static unsigned nbuf = 0;
   2658 	char	*s;
   2659 
   2660 	s = astr[nbuf++];
   2661 	if (nbuf >= NUMBUFS)
   2662 		nbuf = 0;
   2663 
   2664 	switch (sa->sa_family) {
   2665 	case AF_INET:
   2666 	default:
   2667 		inet_ntop(AF_INET, &satosin(sa)->sin_addr, s, sizeof(astr[0]));
   2668 		break;
   2669 	case AF_INET6:
   2670 		inet_ntop(AF_INET6, &satosin6(sa)->sin6_addr, s,
   2671 		    sizeof(astr[0]));
   2672 		break;
   2673 	}
   2674 	return s;
   2675 }
   2676 
   2677 #ifdef UMB_DEBUG
   2678 Static char *
   2679 umb_uuid2str(uint8_t uuid[MBIM_UUID_LEN])
   2680 {
   2681 	static char uuidstr[2 * MBIM_UUID_LEN + 5];
   2682 
   2683 #define UUID_BFMT	"%02X"
   2684 #define UUID_SEP	"-"
   2685 	snprintf(uuidstr, sizeof(uuidstr),
   2686 	    UUID_BFMT UUID_BFMT UUID_BFMT UUID_BFMT UUID_SEP
   2687 	    UUID_BFMT UUID_BFMT UUID_SEP
   2688 	    UUID_BFMT UUID_BFMT UUID_SEP
   2689 	    UUID_BFMT UUID_BFMT UUID_SEP
   2690 	    UUID_BFMT UUID_BFMT UUID_BFMT UUID_BFMT UUID_BFMT UUID_BFMT,
   2691 	    uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5],
   2692 	    uuid[6], uuid[7], uuid[8], uuid[9], uuid[10], uuid[11],
   2693 	    uuid[12], uuid[13], uuid[14], uuid[15]);
   2694 	return uuidstr;
   2695 }
   2696 
   2697 Static void
   2698 umb_dump(void *buf, int len)
   2699 {
   2700 	int	 i = 0;
   2701 	uint8_t	*c = buf;
   2702 
   2703 	if (len == 0)
   2704 		return;
   2705 	while (i < len) {
   2706 		if ((i % 16) == 0) {
   2707 			if (i > 0)
   2708 				addlog("\n");
   2709 			log(LOG_DEBUG, "%4d:  ", i);
   2710 		}
   2711 		addlog(" %02x", *c);
   2712 		c++;
   2713 		i++;
   2714 	}
   2715 	addlog("\n");
   2716 }
   2717 #endif /* UMB_DEBUG */
   2718 
   2719 /* char *
   2720  * inet_ntop(af, src, dst, size)
   2721  *	convert a network format address to presentation format.
   2722  * return:
   2723  *	pointer to presentation format address (`dst'), or NULL (see errno).
   2724  * author:
   2725  *	Paul Vixie, 1996.
   2726  */
   2727 Static const char *
   2728 inet_ntop(int af, const void *src, char *dst, socklen_t size)
   2729 {
   2730 	switch (af) {
   2731 	case AF_INET:
   2732 		return inet_ntop4(src, dst, (size_t)size);
   2733 #ifdef INET6
   2734 	case AF_INET6:
   2735 		return inet_ntop6(src, dst, (size_t)size);
   2736 #endif /* INET6 */
   2737 	default:
   2738 		return NULL;
   2739 	}
   2740 	/* NOTREACHED */
   2741 }
   2742 
   2743 /* const char *
   2744  * inet_ntop4(src, dst, size)
   2745  *	format an IPv4 address, more or less like inet_ntoa()
   2746  * return:
   2747  *	`dst' (as a const)
   2748  * notes:
   2749  *	(1) uses no statics
   2750  *	(2) takes a u_char* not an in_addr as input
   2751  * author:
   2752  *	Paul Vixie, 1996.
   2753  */
   2754 Static const char *
   2755 inet_ntop4(const u_char *src, char *dst, size_t size)
   2756 {
   2757 	char tmp[sizeof "255.255.255.255"];
   2758 	int l;
   2759 
   2760 	l = snprintf(tmp, sizeof(tmp), "%u.%u.%u.%u",
   2761 	    src[0], src[1], src[2], src[3]);
   2762 	if (l <= 0 || l >= size) {
   2763 		return NULL;
   2764 	}
   2765 	strlcpy(dst, tmp, size);
   2766 	return dst;
   2767 }
   2768 
   2769 #ifdef INET6
   2770 /* const char *
   2771  * inet_ntop6(src, dst, size)
   2772  *	convert IPv6 binary address into presentation (printable) format
   2773  * author:
   2774  *	Paul Vixie, 1996.
   2775  */
   2776 Static const char *
   2777 inet_ntop6(const u_char *src, char *dst, size_t size)
   2778 {
   2779 	/*
   2780 	 * Note that int32_t and int16_t need only be "at least" large enough
   2781 	 * to contain a value of the specified size.  On some systems, like
   2782 	 * Crays, there is no such thing as an integer variable with 16 bits.
   2783 	 * Keep this in mind if you think this function should have been coded
   2784 	 * to use pointer overlays.  All the world's not a VAX.
   2785 	 */
   2786 	char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"];
   2787 	char *tp, *ep;
   2788 	struct { int base, len; } best, cur;
   2789 #define IN6ADDRSZ	16
   2790 #define INT16SZ		2
   2791 	u_int words[IN6ADDRSZ / INT16SZ];
   2792 	int i;
   2793 	int advance;
   2794 
   2795 	/*
   2796 	 * Preprocess:
   2797 	 *	Copy the input (bytewise) array into a wordwise array.
   2798 	 *	Find the longest run of 0x00's in src[] for :: shorthanding.
   2799 	 */
   2800 	memset(words, '\0', sizeof words);
   2801 	for (i = 0; i < IN6ADDRSZ; i++)
   2802 		words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
   2803 	best.base = -1;
   2804 	best.len = 0;
   2805 	cur.base = -1;
   2806 	cur.len = 0;
   2807 	for (i = 0; i < (IN6ADDRSZ / INT16SZ); i++) {
   2808 		if (words[i] == 0) {
   2809 			if (cur.base == -1)
   2810 				cur.base = i, cur.len = 1;
   2811 			else
   2812 				cur.len++;
   2813 		} else {
   2814 			if (cur.base != -1) {
   2815 				if (best.base == -1 || cur.len > best.len)
   2816 					best = cur;
   2817 				cur.base = -1;
   2818 			}
   2819 		}
   2820 	}
   2821 	if (cur.base != -1) {
   2822 		if (best.base == -1 || cur.len > best.len)
   2823 			best = cur;
   2824 	}
   2825 	if (best.base != -1 && best.len < 2)
   2826 		best.base = -1;
   2827 
   2828 	/*
   2829 	 * Format the result.
   2830 	 */
   2831 	tp = tmp;
   2832 	ep = tmp + sizeof(tmp);
   2833 	for (i = 0; i < (IN6ADDRSZ / INT16SZ) && tp < ep; i++) {
   2834 		/* Are we inside the best run of 0x00's? */
   2835 		if (best.base != -1 && i >= best.base &&
   2836 		    i < (best.base + best.len)) {
   2837 			if (i == best.base) {
   2838 				if (tp + 1 >= ep)
   2839 					return NULL;
   2840 				*tp++ = ':';
   2841 			}
   2842 			continue;
   2843 		}
   2844 		/* Are we following an initial run of 0x00s or any real hex? */
   2845 		if (i != 0) {
   2846 			if (tp + 1 >= ep)
   2847 				return NULL;
   2848 			*tp++ = ':';
   2849 		}
   2850 		/* Is this address an encapsulated IPv4? */
   2851 		if (i == 6 && best.base == 0 &&
   2852 		    (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) {
   2853 			if (!inet_ntop4(src+12, tp, (size_t)(ep - tp)))
   2854 				return NULL;
   2855 			tp += strlen(tp);
   2856 			break;
   2857 		}
   2858 		advance = snprintf(tp, ep - tp, "%x", words[i]);
   2859 		if (advance <= 0 || advance >= ep - tp)
   2860 			return NULL;
   2861 		tp += advance;
   2862 	}
   2863 	/* Was it a trailing run of 0x00's? */
   2864 	if (best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / INT16SZ)) {
   2865 		if (tp + 1 >= ep)
   2866 			return NULL;
   2867 		*tp++ = ':';
   2868 	}
   2869 	if (tp + 1 >= ep)
   2870 		return NULL;
   2871 	*tp++ = '\0';
   2872 
   2873 	/*
   2874 	 * Check for overflow, copy, and we're done.
   2875 	 */
   2876 	if ((size_t)(tp - tmp) > size) {
   2877 		return NULL;
   2878 	}
   2879 	strlcpy(dst, tmp, size);
   2880 	return dst;
   2881 }
   2882 #endif /* INET6 */
   2883