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