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