libm: Fix misleading indent.
[dragonfly.git] / sys / emulation / ndis / kern_ndis.c
blobb10282af4bb1d1cd9da6eb26133072abd42d896b
1 /*-
2 * Copyright (c) 2003
3 * Bill Paul <wpaul@windriver.com>. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by Bill Paul.
16 * 4. Neither the name of the author nor the names of any co-contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30 * THE POSSIBILITY OF SUCH DAMAGE.
32 * $FreeBSD: src/sys/compat/ndis/kern_ndis.c,v 1.111 2011/02/23 21:45:28 brucec Exp $
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/unistd.h>
38 #include <sys/types.h>
39 #include <sys/errno.h>
40 #include <sys/callout.h>
41 #include <sys/socket.h>
42 #include <sys/queue.h>
43 #include <sys/sysctl.h>
44 #include <sys/proc.h>
45 #include <sys/malloc.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/conf.h>
50 #include <sys/kernel.h>
51 #include <sys/module.h>
52 #include <sys/kthread.h>
53 #include <sys/bus.h>
54 #include <sys/rman.h>
55 #include <sys/mplock2.h>
57 #include <net/if.h>
58 #include <net/if_arp.h>
59 #include <net/ethernet.h>
60 #include <net/if_dl.h>
61 #include <net/if_media.h>
63 #include <netproto/802_11/ieee80211_var.h>
64 #include <netproto/802_11/ieee80211_ioctl.h>
66 #include <bus/u4b/usb.h>
67 #include <bus/u4b/usbdi.h>
69 #include <emulation/ndis/pe_var.h>
70 #include <emulation/ndis/cfg_var.h>
71 #include <emulation/ndis/resource_var.h>
72 #include <emulation/ndis/ntoskrnl_var.h>
73 #include <emulation/ndis/ndis_var.h>
74 #include <emulation/ndis/hal_var.h>
75 #include <emulation/ndis/u4bd_var.h>
76 #include <dev/netif/ndis/if_ndisvar.h>
78 #define NDIS_DUMMY_PATH "\\\\some\\bogus\\path"
80 static void ndis_status_func(ndis_handle, ndis_status, void *, uint32_t);
81 static void ndis_statusdone_func(ndis_handle);
82 static void ndis_setdone_func(ndis_handle, ndis_status);
83 static void ndis_getdone_func(ndis_handle, ndis_status);
84 static void ndis_resetdone_func(ndis_handle, ndis_status, uint8_t);
85 static void ndis_sendrsrcavail_func(ndis_handle);
86 static void ndis_intrsetup(kdpc *, device_object *,
87 irp *, struct ndis_softc *);
88 static void ndis_return(device_object *, void *);
90 static image_patch_table kernndis_functbl[] = {
91 IMPORT_SFUNC(ndis_status_func, 4),
92 IMPORT_SFUNC(ndis_statusdone_func, 1),
93 IMPORT_SFUNC(ndis_setdone_func, 2),
94 IMPORT_SFUNC(ndis_getdone_func, 2),
95 IMPORT_SFUNC(ndis_resetdone_func, 3),
96 IMPORT_SFUNC(ndis_sendrsrcavail_func, 1),
97 IMPORT_SFUNC(ndis_intrsetup, 4),
98 IMPORT_SFUNC(ndis_return, 1),
100 { NULL, NULL, NULL }
103 static struct nd_head ndis_devhead;
106 * This allows us to export our symbols to other modules.
108 * Note: some of the subsystems depend on each other, so the
109 * order in which they're started is important. The order of
110 * importance is:
112 * HAL - spinlocks and IRQL manipulation
113 * ntoskrnl - DPC and workitem threads, object waiting
114 * windrv - driver/device registration
116 * The HAL should also be the last thing shut down, since
117 * the ntoskrnl subsystem will use spinlocks right up until
118 * the DPC and workitem threads are terminated.
121 static int
122 ndis_modevent(module_t mod, int cmd, void *arg)
124 int error = 0;
125 image_patch_table *patch;
127 switch (cmd) {
128 case MOD_LOAD:
129 /* Initialize subsystems */
130 hal_libinit();
131 ntoskrnl_libinit();
132 windrv_libinit();
133 ndis_libinit();
134 usbd_libinit();
136 patch = kernndis_functbl;
137 while (patch->ipt_func != NULL) {
138 windrv_wrap((funcptr)patch->ipt_func,
139 (funcptr *)&patch->ipt_wrap,
140 patch->ipt_argcnt, patch->ipt_ftype);
141 patch++;
144 TAILQ_INIT(&ndis_devhead);
145 break;
146 case MOD_SHUTDOWN:
147 if (TAILQ_FIRST(&ndis_devhead) == NULL) {
148 /* Shut down subsystems */
149 ndis_libfini();
150 usbd_libfini();
151 windrv_libfini();
152 ntoskrnl_libfini();
153 hal_libfini();
155 patch = kernndis_functbl;
156 while (patch->ipt_func != NULL) {
157 windrv_unwrap(patch->ipt_wrap);
158 patch++;
161 break;
162 case MOD_UNLOAD:
163 /* Shut down subsystems */
164 ndis_libfini();
165 usbd_libfini();
166 windrv_libfini();
167 ntoskrnl_libfini();
168 hal_libfini();
170 patch = kernndis_functbl;
171 while (patch->ipt_func != NULL) {
172 windrv_unwrap(patch->ipt_wrap);
173 patch++;
176 break;
177 default:
178 error = EINVAL;
179 break;
182 return (error);
184 DEV_MODULE(ndis, ndis_modevent, NULL);
185 MODULE_VERSION(ndis, 1);
187 static void
188 ndis_sendrsrcavail_func(ndis_handle adapter)
192 static void
193 ndis_status_func(ndis_handle adapter, ndis_status status, void *sbuf,
194 uint32_t slen)
196 ndis_miniport_block *block;
197 struct ndis_softc *sc;
198 struct ifnet *ifp;
200 block = adapter;
201 sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
202 ifp = sc->ifp;
203 if (ifp->if_flags & IFF_DEBUG)
204 device_printf(sc->ndis_dev, "status: %x\n", status);
207 static void
208 ndis_statusdone_func(ndis_handle adapter)
210 ndis_miniport_block *block;
211 struct ndis_softc *sc;
212 struct ifnet *ifp;
214 block = adapter;
215 sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
216 ifp = sc->ifp;
217 if (ifp->if_flags & IFF_DEBUG)
218 device_printf(sc->ndis_dev, "status complete\n");
221 static void
222 ndis_setdone_func(ndis_handle adapter, ndis_status status)
224 ndis_miniport_block *block;
225 block = adapter;
227 block->nmb_setstat = status;
228 KeSetEvent(&block->nmb_setevent, IO_NO_INCREMENT, FALSE);
231 static void
232 ndis_getdone_func(ndis_handle adapter, ndis_status status)
234 ndis_miniport_block *block;
235 block = adapter;
237 block->nmb_getstat = status;
238 KeSetEvent(&block->nmb_getevent, IO_NO_INCREMENT, FALSE);
241 static void
242 ndis_resetdone_func(ndis_handle adapter, ndis_status status,
243 uint8_t addressingreset)
245 ndis_miniport_block *block;
246 struct ndis_softc *sc;
247 struct ifnet *ifp;
249 block = adapter;
250 sc = device_get_softc(block->nmb_physdeviceobj->do_devext);
251 ifp = sc->ifp;
253 if (ifp->if_flags & IFF_DEBUG)
254 device_printf(sc->ndis_dev, "reset done...\n");
255 KeSetEvent(&block->nmb_resetevent, IO_NO_INCREMENT, FALSE);
259 ndis_create_sysctls(void *arg)
261 struct ndis_softc *sc;
262 ndis_cfg *vals;
263 char buf[256];
264 struct sysctl_oid *oidp;
265 struct sysctl_ctx_entry *e;
267 if (arg == NULL)
268 return (EINVAL);
270 sc = arg;
271 vals = sc->ndis_regvals;
273 TAILQ_INIT(&sc->ndis_cfglist_head);
275 /* Add the driver-specific registry keys. */
277 while(1) {
278 if (vals->nc_cfgkey == NULL)
279 break;
281 if (vals->nc_idx != sc->ndis_devidx) {
282 vals++;
283 continue;
286 /* See if we already have a sysctl with this name */
288 oidp = NULL;
289 TAILQ_FOREACH(e, device_get_sysctl_ctx(sc->ndis_dev), link) {
290 oidp = e->entry;
291 if (strcasecmp(oidp->oid_name, vals->nc_cfgkey) == 0)
292 break;
293 oidp = NULL;
296 if (oidp != NULL) {
297 vals++;
298 continue;
301 ndis_add_sysctl(sc, vals->nc_cfgkey, vals->nc_cfgdesc,
302 vals->nc_val, CTLFLAG_RW);
303 vals++;
306 /* Now add a couple of builtin keys. */
309 * Environment can be either Windows (0) or WindowsNT (1).
310 * We qualify as the latter.
312 ndis_add_sysctl(sc, "Environment",
313 "Windows environment", "1", CTLFLAG_RD);
315 /* NDIS version should be 5.1. */
316 ndis_add_sysctl(sc, "NdisVersion",
317 "NDIS API Version", "0x00050001", CTLFLAG_RD);
320 * Some miniport drivers rely on the existence of the SlotNumber,
321 * NetCfgInstanceId and DriverDesc keys.
323 ndis_add_sysctl(sc, "SlotNumber", "Slot Number", "01", CTLFLAG_RD);
324 ndis_add_sysctl(sc, "NetCfgInstanceId", "NetCfgInstanceId",
325 "{12345678-1234-5678-CAFE0-123456789ABC}", CTLFLAG_RD);
326 ndis_add_sysctl(sc, "DriverDesc", "Driver Description",
327 "NDIS Network Adapter", CTLFLAG_RD);
329 /* Bus type (PCI, PCMCIA, etc...) */
330 ksprintf(buf, "%d", (int)sc->ndis_iftype);
331 ndis_add_sysctl(sc, "BusType", "Bus Type", buf, CTLFLAG_RD);
333 if (sc->ndis_res_io != NULL) {
334 ksprintf(buf, "0x%lx", rman_get_start(sc->ndis_res_io));
335 ndis_add_sysctl(sc, "IOBaseAddress",
336 "Base I/O Address", buf, CTLFLAG_RD);
339 if (sc->ndis_irq != NULL) {
340 ksprintf(buf, "%lu", rman_get_start(sc->ndis_irq));
341 ndis_add_sysctl(sc, "InterruptNumber",
342 "Interrupt Number", buf, CTLFLAG_RD);
345 return (0);
349 ndis_add_sysctl(void *arg, char *key, char *desc, char *val, int flag)
351 struct ndis_softc *sc;
352 struct ndis_cfglist *cfg;
353 char descstr[256];
355 sc = arg;
357 cfg = kmalloc(sizeof(struct ndis_cfglist), M_DEVBUF, M_WAITOK|M_ZERO);
358 cfg->ndis_cfg.nc_cfgkey = kstrdup(key, M_DEVBUF);
359 if (desc == NULL) {
360 ksnprintf(descstr, sizeof(descstr), "%s (dynamic)", key);
361 cfg->ndis_cfg.nc_cfgdesc = kstrdup(descstr, M_DEVBUF);
362 } else
363 cfg->ndis_cfg.nc_cfgdesc = kstrdup(desc, M_DEVBUF);
364 strcpy(cfg->ndis_cfg.nc_val, val);
366 TAILQ_INSERT_TAIL(&sc->ndis_cfglist_head, cfg, link);
368 cfg->ndis_oid =
369 SYSCTL_ADD_STRING(device_get_sysctl_ctx(sc->ndis_dev),
370 SYSCTL_CHILDREN(device_get_sysctl_tree(sc->ndis_dev)),
371 OID_AUTO, cfg->ndis_cfg.nc_cfgkey, flag,
372 cfg->ndis_cfg.nc_val, sizeof(cfg->ndis_cfg.nc_val),
373 cfg->ndis_cfg.nc_cfgdesc);
375 return (0);
379 * Somewhere, somebody decided "hey, let's automatically create
380 * a sysctl tree for each device instance as it's created -- it'll
381 * make life so much easier!" Lies. Why must they turn the kernel
382 * into a house of lies?
386 ndis_flush_sysctls(void *arg)
388 struct ndis_softc *sc;
389 struct ndis_cfglist *cfg;
390 struct sysctl_ctx_list *clist;
392 sc = arg;
394 clist = device_get_sysctl_ctx(sc->ndis_dev);
396 while (!TAILQ_EMPTY(&sc->ndis_cfglist_head)) {
397 cfg = TAILQ_FIRST(&sc->ndis_cfglist_head);
398 TAILQ_REMOVE(&sc->ndis_cfglist_head, cfg, link);
399 sysctl_ctx_entry_del(clist, cfg->ndis_oid);
400 sysctl_remove_oid(cfg->ndis_oid, 1, 0);
401 kfree(cfg->ndis_cfg.nc_cfgkey, M_DEVBUF);
402 kfree(cfg->ndis_cfg.nc_cfgdesc, M_DEVBUF);
403 kfree(cfg, M_DEVBUF);
406 return (0);
409 void *
410 ndis_get_routine_address(struct image_patch_table *functbl, char *name)
412 int i;
414 for (i = 0; functbl[i].ipt_name != NULL; i++)
415 if (strcmp(name, functbl[i].ipt_name) == 0)
416 return (functbl[i].ipt_wrap);
417 return (NULL);
420 static void
421 ndis_return(device_object *dobj, void *arg)
423 ndis_miniport_block *block;
424 ndis_miniport_characteristics *ch;
425 ndis_return_handler returnfunc;
426 ndis_handle adapter;
427 ndis_packet *p;
428 uint8_t irql;
429 list_entry *l;
431 block = arg;
432 ch = IoGetDriverObjectExtension(dobj->do_drvobj, (void *)1);
434 p = arg;
435 adapter = block->nmb_miniportadapterctx;
437 if (adapter == NULL)
438 return;
440 returnfunc = ch->nmc_return_packet_func;
442 KeAcquireSpinLock(&block->nmb_returnlock, &irql);
443 while (!IsListEmpty(&block->nmb_returnlist)) {
444 l = RemoveHeadList((&block->nmb_returnlist));
445 p = CONTAINING_RECORD(l, ndis_packet, np_list);
446 InitializeListHead((&p->np_list));
447 KeReleaseSpinLock(&block->nmb_returnlock, irql);
448 MSCALL2(returnfunc, adapter, p);
449 KeAcquireSpinLock(&block->nmb_returnlock, &irql);
451 KeReleaseSpinLock(&block->nmb_returnlock, irql);
454 static void
455 ndis_reference_packet(void *arg)
457 ndis_packet *p;
459 if (arg == NULL)
460 return;
462 p = arg;
464 /* Increment refcount. */
465 atomic_add_int(&p->np_refcnt, 1);
468 void
469 ndis_return_packet(void *arg)
471 ndis_packet *p;
472 ndis_miniport_block *block;
474 if (arg == NULL)
475 return;
477 p = arg;
479 /* Release packet when refcount hits zero, otherwise return. */
480 if (atomic_fetchadd_int(&p->np_refcnt, -1) > 1)
481 return;
483 block = ((struct ndis_softc *)p->np_softc)->ndis_block;
485 KeAcquireSpinLockAtDpcLevel(&block->nmb_returnlock);
486 InitializeListHead((&p->np_list));
487 InsertHeadList((&block->nmb_returnlist), (&p->np_list));
488 KeReleaseSpinLockFromDpcLevel(&block->nmb_returnlock);
490 IoQueueWorkItem(block->nmb_returnitem,
491 (io_workitem_func)kernndis_functbl[7].ipt_wrap,
492 WORKQUEUE_CRITICAL, block);
495 void
496 ndis_free_bufs(ndis_buffer *b0)
498 ndis_buffer *next;
500 if (b0 == NULL)
501 return;
503 while(b0 != NULL) {
504 next = b0->mdl_next;
505 IoFreeMdl(b0);
506 b0 = next;
510 void
511 ndis_free_packet(ndis_packet *p)
513 if (p == NULL)
514 return;
516 ndis_free_bufs(p->np_private.npp_head);
517 NdisFreePacket(p);
521 ndis_convert_res(void *arg)
523 struct ndis_softc *sc;
524 ndis_resource_list *rl = NULL;
525 cm_partial_resource_desc *prd = NULL;
526 ndis_miniport_block *block;
527 device_t dev;
528 struct resource_list *brl;
529 struct resource_list_entry *brle;
530 struct resource_list brl_rev;
531 struct resource_list_entry *n;
532 int error = 0;
534 sc = arg;
535 block = sc->ndis_block;
536 dev = sc->ndis_dev;
538 SLIST_INIT(&brl_rev);
540 rl = kmalloc(sizeof(ndis_resource_list) +
541 (sizeof(cm_partial_resource_desc) * (sc->ndis_rescnt - 1)),
542 M_DEVBUF, M_WAITOK|M_NULLOK|M_ZERO);
544 if (rl == NULL)
545 return (ENOMEM);
547 rl->cprl_version = 5;
548 rl->cprl_revision = 1;
549 rl->cprl_count = sc->ndis_rescnt;
550 prd = rl->cprl_partial_descs;
552 brl = BUS_GET_RESOURCE_LIST(dev, dev);
554 if (brl != NULL) {
557 * We have a small problem. Some PCI devices have
558 * multiple I/O ranges. Windows orders them starting
559 * from lowest numbered BAR to highest. We discover
560 * them in that order too, but insert them into a singly
561 * linked list head first, which means when time comes
562 * to traverse the list, we enumerate them in reverse
563 * order. This screws up some drivers which expect the
564 * BARs to be in ascending order so that they can choose
565 * the "first" one as their register space. Unfortunately,
566 * in order to fix this, we have to create our own
567 * temporary list with the entries in reverse order.
570 SLIST_FOREACH(brle, brl, link) {
571 n = kmalloc(sizeof(struct resource_list_entry),
572 M_TEMP, M_WAITOK|M_NULLOK);
573 if (n == NULL) {
574 error = ENOMEM;
575 goto bad;
577 bcopy((char *)brle, (char *)n,
578 sizeof(struct resource_list_entry));
579 SLIST_INSERT_HEAD(&brl_rev, n, link);
582 SLIST_FOREACH(brle, &brl_rev, link) {
583 switch (brle->type) {
584 case SYS_RES_IOPORT:
585 prd->cprd_type = CmResourceTypePort;
586 prd->cprd_flags = CM_RESOURCE_PORT_IO;
587 prd->cprd_sharedisp =
588 CmResourceShareDeviceExclusive;
589 prd->u.cprd_port.cprd_start.np_quad =
590 brle->start;
591 prd->u.cprd_port.cprd_len = brle->count;
592 break;
593 case SYS_RES_MEMORY:
594 prd->cprd_type = CmResourceTypeMemory;
595 prd->cprd_flags =
596 CM_RESOURCE_MEMORY_READ_WRITE;
597 prd->cprd_sharedisp =
598 CmResourceShareDeviceExclusive;
599 prd->u.cprd_mem.cprd_start.np_quad =
600 brle->start;
601 prd->u.cprd_mem.cprd_len = brle->count;
602 break;
603 case SYS_RES_IRQ:
604 prd->cprd_type = CmResourceTypeInterrupt;
605 prd->cprd_flags = 0;
607 * Always mark interrupt resources as
608 * shared, since in our implementation,
609 * they will be.
611 prd->cprd_sharedisp =
612 CmResourceShareShared;
613 prd->u.cprd_intr.cprd_level = brle->start;
614 prd->u.cprd_intr.cprd_vector = brle->start;
615 prd->u.cprd_intr.cprd_affinity = 0;
616 break;
617 default:
618 break;
620 prd++;
624 block->nmb_rlist = rl;
626 bad:
628 while (!SLIST_EMPTY(&brl_rev)) {
629 n = SLIST_FIRST(&brl_rev);
630 SLIST_REMOVE_HEAD(&brl_rev, link);
631 kfree (n, M_TEMP);
634 return (error);
638 * Map an NDIS packet to an mbuf list. When an NDIS driver receives a
639 * packet, it will hand it to us in the form of an ndis_packet,
640 * which we need to convert to an mbuf that is then handed off
641 * to the stack. Note: we configure the mbuf list so that it uses
642 * the memory regions specified by the ndis_buffer structures in
643 * the ndis_packet as external storage. In most cases, this will
644 * point to a memory region allocated by the driver (either by
645 * ndis_malloc_withtag() or ndis_alloc_sharedmem()). We expect
646 * the driver to handle kfree()ing this region for is, so we set up
647 * a dummy no-op free handler for it.
651 ndis_ptom(struct mbuf **m0, ndis_packet *p)
653 struct mbuf *m = NULL, *prev = NULL;
654 ndis_buffer *buf;
655 ndis_packet_private *priv;
656 uint32_t totlen = 0;
657 struct ifnet *ifp;
658 struct ether_header *eh;
659 int diff;
661 if (p == NULL || m0 == NULL)
662 return (EINVAL);
664 priv = &p->np_private;
665 buf = priv->npp_head;
666 p->np_refcnt = 0;
668 for (buf = priv->npp_head; buf != NULL; buf = buf->mdl_next) {
669 if (buf == priv->npp_head) {
670 /* XXX swildner: why not MT_HEADER? (see FreeBSD) */
671 MGETHDR(m, M_NOWAIT, MT_DATA);
672 } else {
673 MGET(m, M_NOWAIT, MT_DATA);
675 if (m == NULL) {
676 m_freem(*m0);
677 *m0 = NULL;
678 return (ENOBUFS);
680 m->m_len = MmGetMdlByteCount(buf);
681 m->m_data = MmGetMdlVirtualAddress(buf);
682 m_extadd(m, m->m_data, m->m_len, ndis_reference_packet,
683 ndis_return_packet, p);
684 // p->np_refcnt++;
686 totlen += m->m_len;
687 if (m->m_flags & M_PKTHDR)
688 *m0 = m;
689 else
690 prev->m_next = m;
691 prev = m;
695 * This is a hack to deal with the Marvell 8335 driver
696 * which, when associated with an AP in WPA-PSK mode,
697 * seems to overpad its frames by 8 bytes. I don't know
698 * that the extra 8 bytes are for, and they're not there
699 * in open mode, so for now clamp the frame size at 1514
700 * until I can figure out how to deal with this properly,
701 * otherwise if_ethersubr() will spank us by discarding
702 * the 'oversize' frames.
705 eh = mtod((*m0), struct ether_header *);
706 ifp = ((struct ndis_softc *)p->np_softc)->ifp;
707 if (totlen > ETHER_MAX_FRAME(ifp, eh->ether_type, FALSE)) {
708 diff = totlen - ETHER_MAX_FRAME(ifp, eh->ether_type, FALSE);
709 totlen -= diff;
710 m->m_len -= diff;
712 (*m0)->m_pkthdr.len = totlen;
714 return (0);
718 * Create an NDIS packet from an mbuf chain.
719 * This is used mainly when transmitting packets, where we need
720 * to turn an mbuf off an interface's send queue and transform it
721 * into an NDIS packet which will be fed into the NDIS driver's
722 * send routine.
724 * NDIS packets consist of two parts: an ndis_packet structure,
725 * which is vaguely analagous to the pkthdr portion of an mbuf,
726 * and one or more ndis_buffer structures, which define the
727 * actual memory segments in which the packet data resides.
728 * We need to allocate one ndis_buffer for each mbuf in a chain,
729 * plus one ndis_packet as the header.
733 ndis_mtop(struct mbuf *m0, ndis_packet **p)
735 struct mbuf *m;
736 ndis_buffer *buf = NULL, *prev = NULL;
737 ndis_packet_private *priv;
739 if (p == NULL || *p == NULL || m0 == NULL)
740 return (EINVAL);
742 priv = &(*p)->np_private;
743 priv->npp_totlen = m0->m_pkthdr.len;
745 for (m = m0; m != NULL; m = m->m_next) {
746 if (m->m_len == 0)
747 continue;
748 buf = IoAllocateMdl(m->m_data, m->m_len, FALSE, FALSE, NULL);
749 if (buf == NULL) {
750 ndis_free_packet(*p);
751 *p = NULL;
752 return (ENOMEM);
754 MmBuildMdlForNonPagedPool(buf);
756 if (priv->npp_head == NULL)
757 priv->npp_head = buf;
758 else
759 prev->mdl_next = buf;
760 prev = buf;
763 priv->npp_tail = buf;
765 return (0);
769 ndis_get_supported_oids(void *arg, ndis_oid **oids, int *oidcnt)
771 int len, rval;
772 ndis_oid *o;
774 if (arg == NULL || oids == NULL || oidcnt == NULL)
775 return (EINVAL);
776 len = 0;
777 ndis_get_info(arg, OID_GEN_SUPPORTED_LIST, NULL, &len);
779 o = kmalloc(len, M_DEVBUF, M_WAITOK);
781 rval = ndis_get_info(arg, OID_GEN_SUPPORTED_LIST, o, &len);
783 if (rval) {
784 kfree(o, M_DEVBUF);
785 return (rval);
788 *oids = o;
789 *oidcnt = len / 4;
791 return (0);
795 ndis_set_info(void *arg, ndis_oid oid, void *buf, int *buflen)
797 struct ndis_softc *sc;
798 ndis_status rval;
799 ndis_handle adapter;
800 ndis_setinfo_handler setfunc;
801 uint32_t byteswritten = 0, bytesneeded = 0;
802 uint8_t irql;
803 uint64_t duetime;
806 * According to the NDIS spec, MiniportQueryInformation()
807 * and MiniportSetInformation() requests are handled serially:
808 * once one request has been issued, we must wait for it to
809 * finish before allowing another request to proceed.
812 sc = arg;
814 KeResetEvent(&sc->ndis_block->nmb_setevent);
816 KeAcquireSpinLock(&sc->ndis_block->nmb_lock, &irql);
818 if (sc->ndis_block->nmb_pendingreq != NULL) {
819 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
820 panic("ndis_set_info() called while other request pending");
821 } else
822 sc->ndis_block->nmb_pendingreq = (ndis_request *)sc;
824 setfunc = sc->ndis_chars->nmc_setinfo_func;
825 adapter = sc->ndis_block->nmb_miniportadapterctx;
827 if (adapter == NULL || setfunc == NULL ||
828 sc->ndis_block->nmb_devicectx == NULL) {
829 sc->ndis_block->nmb_pendingreq = NULL;
830 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
831 return (ENXIO);
834 rval = MSCALL6(setfunc, adapter, oid, buf, *buflen,
835 &byteswritten, &bytesneeded);
837 sc->ndis_block->nmb_pendingreq = NULL;
839 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
841 if (rval == NDIS_STATUS_PENDING) {
842 /* Wait up to 5 seconds. */
843 duetime = (5 * 1000000) * -10;
844 KeWaitForSingleObject(&sc->ndis_block->nmb_setevent,
845 0, 0, FALSE, &duetime);
846 rval = sc->ndis_block->nmb_setstat;
849 if (byteswritten)
850 *buflen = byteswritten;
851 if (bytesneeded)
852 *buflen = bytesneeded;
854 if (rval == NDIS_STATUS_INVALID_LENGTH)
855 return (ENOSPC);
857 if (rval == NDIS_STATUS_INVALID_OID)
858 return (EINVAL);
860 if (rval == NDIS_STATUS_NOT_SUPPORTED ||
861 rval == NDIS_STATUS_NOT_ACCEPTED)
862 return (ENOTSUP);
864 if (rval != NDIS_STATUS_SUCCESS)
865 return (ENODEV);
867 return (0);
870 typedef void (*ndis_senddone_func)(ndis_handle, ndis_packet *, ndis_status);
873 ndis_send_packets(void *arg, ndis_packet **packets, int cnt)
875 struct ndis_softc *sc;
876 ndis_handle adapter;
877 ndis_sendmulti_handler sendfunc;
878 ndis_senddone_func senddonefunc;
879 int i;
880 ndis_packet *p;
881 uint8_t irql = 0;
883 sc = arg;
884 adapter = sc->ndis_block->nmb_miniportadapterctx;
885 if (adapter == NULL)
886 return (ENXIO);
887 sendfunc = sc->ndis_chars->nmc_sendmulti_func;
888 senddonefunc = sc->ndis_block->nmb_senddone_func;
890 if (NDIS_SERIALIZED(sc->ndis_block))
891 KeAcquireSpinLock(&sc->ndis_block->nmb_lock, &irql);
893 MSCALL3(sendfunc, adapter, packets, cnt);
895 for (i = 0; i < cnt; i++) {
896 p = packets[i];
898 * Either the driver already handed the packet to
899 * ndis_txeof() due to a failure, or it wants to keep
900 * it and release it asynchronously later. Skip to the
901 * next one.
903 if (p == NULL || p->np_oob.npo_status == NDIS_STATUS_PENDING)
904 continue;
905 MSCALL3(senddonefunc, sc->ndis_block, p, p->np_oob.npo_status);
908 if (NDIS_SERIALIZED(sc->ndis_block))
909 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
911 return(0);
915 ndis_send_packet(void *arg, ndis_packet *packet)
917 struct ndis_softc *sc;
918 ndis_handle adapter;
919 ndis_status status;
920 ndis_sendsingle_handler sendfunc;
921 ndis_senddone_func senddonefunc;
922 uint8_t irql = 0;
924 sc = arg;
925 adapter = sc->ndis_block->nmb_miniportadapterctx;
926 if (adapter == NULL)
927 return (ENXIO);
928 sendfunc = sc->ndis_chars->nmc_sendsingle_func;
929 senddonefunc = sc->ndis_block->nmb_senddone_func;
931 if (NDIS_SERIALIZED(sc->ndis_block))
932 KeAcquireSpinLock(&sc->ndis_block->nmb_lock, &irql);
933 status = MSCALL3(sendfunc, adapter, packet,
934 packet->np_private.npp_flags);
936 if (status == NDIS_STATUS_PENDING) {
937 if (NDIS_SERIALIZED(sc->ndis_block))
938 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
939 return (0);
942 MSCALL3(senddonefunc, sc->ndis_block, packet, status);
944 if (NDIS_SERIALIZED(sc->ndis_block))
945 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
947 return (0);
951 ndis_init_dma(void *arg)
953 struct ndis_softc *sc;
954 int i, error;
956 sc = arg;
958 sc->ndis_tmaps = kmalloc(sizeof(bus_dmamap_t) * sc->ndis_maxpkts,
959 M_DEVBUF, M_WAITOK|M_ZERO);
961 for (i = 0; i < sc->ndis_maxpkts; i++) {
962 error = bus_dmamap_create(sc->ndis_ttag, 0,
963 &sc->ndis_tmaps[i]);
964 if (error) {
965 kfree(sc->ndis_tmaps, M_DEVBUF);
966 return (ENODEV);
970 return (0);
974 ndis_destroy_dma(void *arg)
976 struct ndis_softc *sc;
977 struct mbuf *m;
978 ndis_packet *p = NULL;
979 int i;
981 sc = arg;
983 for (i = 0; i < sc->ndis_maxpkts; i++) {
984 if (sc->ndis_txarray[i] != NULL) {
985 p = sc->ndis_txarray[i];
986 m = (struct mbuf *)p->np_rsvd[1];
987 if (m != NULL)
988 m_freem(m);
989 ndis_free_packet(sc->ndis_txarray[i]);
991 bus_dmamap_destroy(sc->ndis_ttag, sc->ndis_tmaps[i]);
994 kfree(sc->ndis_tmaps, M_DEVBUF);
996 bus_dma_tag_destroy(sc->ndis_ttag);
998 return (0);
1002 ndis_reset_nic(void *arg)
1004 struct ndis_softc *sc;
1005 ndis_handle adapter;
1006 ndis_reset_handler resetfunc;
1007 uint8_t addressing_reset;
1008 int rval;
1009 uint8_t irql = 0;
1011 sc = arg;
1013 NDIS_LOCK(sc);
1014 adapter = sc->ndis_block->nmb_miniportadapterctx;
1015 resetfunc = sc->ndis_chars->nmc_reset_func;
1017 if (adapter == NULL || resetfunc == NULL ||
1018 sc->ndis_block->nmb_devicectx == NULL) {
1019 NDIS_UNLOCK(sc);
1020 return(EIO);
1023 NDIS_UNLOCK(sc);
1025 KeResetEvent(&sc->ndis_block->nmb_resetevent);
1027 if (NDIS_SERIALIZED(sc->ndis_block))
1028 KeAcquireSpinLock(&sc->ndis_block->nmb_lock, &irql);
1030 rval = MSCALL2(resetfunc, &addressing_reset, adapter);
1032 if (NDIS_SERIALIZED(sc->ndis_block))
1033 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
1035 if (rval == NDIS_STATUS_PENDING)
1036 KeWaitForSingleObject(&sc->ndis_block->nmb_resetevent,
1037 0, 0, FALSE, NULL);
1039 return (0);
1043 ndis_halt_nic(void *arg)
1045 struct ndis_softc *sc;
1046 ndis_handle adapter;
1047 ndis_halt_handler haltfunc;
1048 ndis_miniport_block *block;
1049 int empty = 0;
1050 uint8_t irql;
1052 sc = arg;
1053 block = sc->ndis_block;
1055 if (!cold)
1056 KeFlushQueuedDpcs();
1059 * Wait for all packets to be returned.
1062 while (1) {
1063 KeAcquireSpinLock(&block->nmb_returnlock, &irql);
1064 empty = IsListEmpty(&block->nmb_returnlist);
1065 KeReleaseSpinLock(&block->nmb_returnlock, irql);
1066 if (empty)
1067 break;
1068 NdisMSleep(1000);
1071 NDIS_LOCK(sc);
1072 adapter = sc->ndis_block->nmb_miniportadapterctx;
1073 if (adapter == NULL) {
1074 NDIS_UNLOCK(sc);
1075 return (EIO);
1078 sc->ndis_block->nmb_devicectx = NULL;
1081 * The adapter context is only valid after the init
1082 * handler has been called, and is invalid once the
1083 * halt handler has been called.
1086 haltfunc = sc->ndis_chars->nmc_halt_func;
1087 NDIS_UNLOCK(sc);
1089 MSCALL1(haltfunc, adapter);
1091 NDIS_LOCK(sc);
1092 sc->ndis_block->nmb_miniportadapterctx = NULL;
1093 NDIS_UNLOCK(sc);
1095 return (0);
1099 ndis_shutdown_nic(void *arg)
1101 struct ndis_softc *sc;
1102 ndis_handle adapter;
1103 ndis_shutdown_handler shutdownfunc;
1105 sc = arg;
1106 NDIS_LOCK(sc);
1107 adapter = sc->ndis_block->nmb_miniportadapterctx;
1108 shutdownfunc = sc->ndis_chars->nmc_shutdown_handler;
1109 NDIS_UNLOCK(sc);
1110 if (adapter == NULL || shutdownfunc == NULL)
1111 return (EIO);
1113 if (sc->ndis_chars->nmc_rsvd0 == NULL)
1114 MSCALL1(shutdownfunc, adapter);
1115 else
1116 MSCALL1(shutdownfunc, sc->ndis_chars->nmc_rsvd0);
1118 TAILQ_REMOVE(&ndis_devhead, sc->ndis_block, link);
1120 return(0);
1124 ndis_pnpevent_nic(void *arg, int type)
1126 device_t dev;
1127 struct ndis_softc *sc;
1128 ndis_handle adapter;
1129 ndis_pnpevent_handler pnpeventfunc;
1131 dev = arg;
1132 sc = device_get_softc(dev);
1133 NDIS_LOCK(sc);
1134 adapter = sc->ndis_block->nmb_miniportadapterctx;
1135 pnpeventfunc = sc->ndis_chars->nmc_pnpevent_handler;
1136 NDIS_UNLOCK(sc);
1137 if (adapter == NULL || pnpeventfunc == NULL)
1138 return (EIO);
1140 if (sc->ndis_chars->nmc_rsvd0 == NULL)
1141 MSCALL4(pnpeventfunc, adapter, type, NULL, 0);
1142 else
1143 MSCALL4(pnpeventfunc, sc->ndis_chars->nmc_rsvd0, type, NULL, 0);
1145 return (0);
1149 ndis_init_nic(void *arg)
1151 struct ndis_softc *sc;
1152 ndis_miniport_block *block;
1153 ndis_init_handler initfunc;
1154 ndis_status status, openstatus = 0;
1155 ndis_medium mediumarray[NdisMediumMax];
1156 uint32_t chosenmedium, i;
1158 if (arg == NULL)
1159 return (EINVAL);
1161 sc = arg;
1162 NDIS_LOCK(sc);
1163 block = sc->ndis_block;
1164 initfunc = sc->ndis_chars->nmc_init_func;
1165 NDIS_UNLOCK(sc);
1167 sc->ndis_block->nmb_timerlist = NULL;
1169 for (i = 0; i < NdisMediumMax; i++)
1170 mediumarray[i] = i;
1172 status = MSCALL6(initfunc, &openstatus, &chosenmedium,
1173 mediumarray, NdisMediumMax, block, block);
1176 * If the init fails, blow away the other exported routines
1177 * we obtained from the driver so we can't call them later.
1178 * If the init failed, none of these will work.
1180 if (status != NDIS_STATUS_SUCCESS) {
1181 NDIS_LOCK(sc);
1182 sc->ndis_block->nmb_miniportadapterctx = NULL;
1183 NDIS_UNLOCK(sc);
1184 return (ENXIO);
1188 * This may look really goofy, but apparently it is possible
1189 * to halt a miniport too soon after it's been initialized.
1190 * After MiniportInitialize() finishes, pause for 1 second
1191 * to give the chip a chance to handle any short-lived timers
1192 * that were set in motion. If we call MiniportHalt() too soon,
1193 * some of the timers may not be cancelled, because the driver
1194 * expects them to fire before the halt is called.
1197 tsleep(arg, 0, "ndwait", hz);
1199 NDIS_LOCK(sc);
1200 sc->ndis_block->nmb_devicectx = sc;
1201 NDIS_UNLOCK(sc);
1203 return (0);
1206 static void
1207 ndis_intrsetup(kdpc *dpc, device_object *dobj, irp *ip, struct ndis_softc *sc)
1209 ndis_miniport_interrupt *intr;
1211 intr = sc->ndis_block->nmb_interrupt;
1213 /* Sanity check. */
1215 if (intr == NULL)
1216 return;
1218 KeAcquireSpinLockAtDpcLevel(&intr->ni_dpccountlock);
1219 KeResetEvent(&intr->ni_dpcevt);
1220 if (KeInsertQueueDpc(&intr->ni_dpc, NULL, NULL) == TRUE)
1221 intr->ni_dpccnt++;
1222 KeReleaseSpinLockFromDpcLevel(&intr->ni_dpccountlock);
1226 ndis_get_info(void *arg, ndis_oid oid, void *buf, int *buflen)
1228 struct ndis_softc *sc;
1229 ndis_status rval;
1230 ndis_handle adapter;
1231 ndis_queryinfo_handler queryfunc;
1232 uint32_t byteswritten = 0, bytesneeded = 0;
1233 uint8_t irql;
1234 uint64_t duetime;
1236 sc = arg;
1238 KeResetEvent(&sc->ndis_block->nmb_getevent);
1240 KeAcquireSpinLock(&sc->ndis_block->nmb_lock, &irql);
1242 if (sc->ndis_block->nmb_pendingreq != NULL) {
1243 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
1244 panic("ndis_get_info() called while other request pending");
1245 } else
1246 sc->ndis_block->nmb_pendingreq = (ndis_request *)sc;
1248 queryfunc = sc->ndis_chars->nmc_queryinfo_func;
1249 adapter = sc->ndis_block->nmb_miniportadapterctx;
1251 if (adapter == NULL || queryfunc == NULL ||
1252 sc->ndis_block->nmb_devicectx == NULL) {
1253 sc->ndis_block->nmb_pendingreq = NULL;
1254 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
1255 return (ENXIO);
1258 rval = MSCALL6(queryfunc, adapter, oid, buf, *buflen,
1259 &byteswritten, &bytesneeded);
1261 sc->ndis_block->nmb_pendingreq = NULL;
1263 KeReleaseSpinLock(&sc->ndis_block->nmb_lock, irql);
1265 /* Wait for requests that block. */
1267 if (rval == NDIS_STATUS_PENDING) {
1268 /* Wait up to 5 seconds. */
1269 duetime = (5 * 1000000) * -10;
1270 KeWaitForSingleObject(&sc->ndis_block->nmb_getevent,
1271 0, 0, FALSE, &duetime);
1272 rval = sc->ndis_block->nmb_getstat;
1275 if (byteswritten)
1276 *buflen = byteswritten;
1277 if (bytesneeded)
1278 *buflen = bytesneeded;
1280 if (rval == NDIS_STATUS_INVALID_LENGTH ||
1281 rval == NDIS_STATUS_BUFFER_TOO_SHORT)
1282 return (ENOSPC);
1284 if (rval == NDIS_STATUS_INVALID_OID)
1285 return (EINVAL);
1287 if (rval == NDIS_STATUS_NOT_SUPPORTED ||
1288 rval == NDIS_STATUS_NOT_ACCEPTED)
1289 return (ENOTSUP);
1291 if (rval != NDIS_STATUS_SUCCESS)
1292 return (ENODEV);
1294 return (0);
1297 uint32_t
1298 NdisAddDevice(driver_object *drv, device_object *pdo)
1300 device_object *fdo;
1301 ndis_miniport_block *block;
1302 struct ndis_softc *sc;
1303 uint32_t status;
1304 int error;
1306 sc = device_get_softc(pdo->do_devext);
1308 if (sc->ndis_iftype == PCMCIABus || sc->ndis_iftype == PCIBus) {
1309 error = bus_setup_intr(sc->ndis_dev, sc->ndis_irq,
1310 INTR_MPSAFE,
1311 ntoskrnl_intr, sc, &sc->ndis_intrhand, NULL);
1312 if (error)
1313 return (NDIS_STATUS_FAILURE);
1316 status = IoCreateDevice(drv, sizeof(ndis_miniport_block), NULL,
1317 FILE_DEVICE_UNKNOWN, 0, FALSE, &fdo);
1319 if (status != STATUS_SUCCESS)
1320 return (status);
1322 block = fdo->do_devext;
1324 block->nmb_filterdbs.nf_ethdb = block;
1325 block->nmb_deviceobj = fdo;
1326 block->nmb_physdeviceobj = pdo;
1327 block->nmb_nextdeviceobj = IoAttachDeviceToDeviceStack(fdo, pdo);
1328 KeInitializeSpinLock(&block->nmb_lock);
1329 KeInitializeSpinLock(&block->nmb_returnlock);
1330 KeInitializeEvent(&block->nmb_getevent, EVENT_TYPE_NOTIFY, TRUE);
1331 KeInitializeEvent(&block->nmb_setevent, EVENT_TYPE_NOTIFY, TRUE);
1332 KeInitializeEvent(&block->nmb_resetevent, EVENT_TYPE_NOTIFY, TRUE);
1333 InitializeListHead(&block->nmb_parmlist);
1334 InitializeListHead(&block->nmb_returnlist);
1335 block->nmb_returnitem = IoAllocateWorkItem(fdo);
1338 * Stash pointers to the miniport block and miniport
1339 * characteristics info in the if_ndis softc so the
1340 * UNIX wrapper driver can get to them later.
1342 sc->ndis_block = block;
1343 sc->ndis_chars = IoGetDriverObjectExtension(drv, (void *)1);
1346 * If the driver has a MiniportTransferData() function,
1347 * we should allocate a private RX packet pool.
1350 if (sc->ndis_chars->nmc_transferdata_func != NULL) {
1351 NdisAllocatePacketPool(&status, &block->nmb_rxpool,
1352 32, PROTOCOL_RESERVED_SIZE_IN_PACKET);
1353 if (status != NDIS_STATUS_SUCCESS) {
1354 IoDetachDevice(block->nmb_nextdeviceobj);
1355 IoDeleteDevice(fdo);
1356 return (status);
1358 InitializeListHead((&block->nmb_packetlist));
1361 /* Give interrupt handling priority over timers. */
1362 IoInitializeDpcRequest(fdo, kernndis_functbl[6].ipt_wrap);
1363 KeSetImportanceDpc(&fdo->do_dpc, KDPC_IMPORTANCE_HIGH);
1365 /* Finish up BSD-specific setup. */
1367 block->nmb_signature = (void *)0xcafebabe;
1368 block->nmb_status_func = kernndis_functbl[0].ipt_wrap;
1369 block->nmb_statusdone_func = kernndis_functbl[1].ipt_wrap;
1370 block->nmb_setdone_func = kernndis_functbl[2].ipt_wrap;
1371 block->nmb_querydone_func = kernndis_functbl[3].ipt_wrap;
1372 block->nmb_resetdone_func = kernndis_functbl[4].ipt_wrap;
1373 block->nmb_sendrsrc_func = kernndis_functbl[5].ipt_wrap;
1374 block->nmb_pendingreq = NULL;
1376 TAILQ_INSERT_TAIL(&ndis_devhead, block, link);
1378 return (STATUS_SUCCESS);
1382 ndis_unload_driver(void *arg)
1384 struct ndis_softc *sc;
1385 device_object *fdo;
1387 sc = arg;
1389 if (sc->ndis_intrhand)
1390 bus_teardown_intr(sc->ndis_dev,
1391 sc->ndis_irq, sc->ndis_intrhand);
1393 if (sc->ndis_block->nmb_rlist != NULL)
1394 kfree(sc->ndis_block->nmb_rlist, M_DEVBUF);
1396 ndis_flush_sysctls(sc);
1398 TAILQ_REMOVE(&ndis_devhead, sc->ndis_block, link);
1400 if (sc->ndis_chars->nmc_transferdata_func != NULL)
1401 NdisFreePacketPool(sc->ndis_block->nmb_rxpool);
1402 fdo = sc->ndis_block->nmb_deviceobj;
1403 IoFreeWorkItem(sc->ndis_block->nmb_returnitem);
1404 IoDetachDevice(sc->ndis_block->nmb_nextdeviceobj);
1405 IoDeleteDevice(fdo);
1407 return (0);