win-pvdrivers

view xennet/xennet.c @ 77:b9b4b731f890

Tidyups and work on getting xennet at least as functional as it was before I started messing with it :)
author James Harper <james.harper@bendigoit.com.au>
date Fri Dec 28 23:21:49 2007 +1100 (2007-12-28)
parents dfa772949c6e
children 63da9239cfe2
line source
1 /*
2 PV Net Driver for Windows Xen HVM Domains
3 Copyright (C) 2007 James Harper
4 Copyright (C) 2007 Andrew Grover <andy.grover@oracle.com>
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 */
21 #include <stdlib.h>
22 #include <io/xenbus.h>
23 #include "xennet.h"
25 /* Xen macros use these, so they need to be redefined to Win equivs */
26 #define wmb() KeMemoryBarrier()
27 #define mb() KeMemoryBarrier()
29 #if !defined (NDIS51_MINIPORT)
30 #error requires NDIS 5.1 compilation environment
31 #endif
33 #define GRANT_INVALID_REF 0
35 /* couldn't get regular xen ring macros to work...*/
36 #define __NET_RING_SIZE(type, _sz) \
37 (__RD32( \
38 (_sz - sizeof(struct type##_sring) + sizeof(union type##_sring_entry)) \
39 / sizeof(union type##_sring_entry)))
41 #define NET_TX_RING_SIZE __NET_RING_SIZE(netif_tx, PAGE_SIZE)
42 #define NET_RX_RING_SIZE __NET_RING_SIZE(netif_rx, PAGE_SIZE)
44 #pragma warning(disable: 4127) // conditional expression is constant
46 struct xennet_info
47 {
48 PDEVICE_OBJECT pdo;
49 PDEVICE_OBJECT fdo;
50 PDEVICE_OBJECT lower_do;
51 WDFDEVICE wdf_device;
52 PXENPCI_XEN_DEVICE_DATA pdoData;
54 WCHAR name[NAME_SIZE];
55 NDIS_HANDLE adapter_handle;
56 ULONG packet_filter;
57 int connected;
58 UINT8 perm_mac_addr[ETH_ALEN];
59 UINT8 curr_mac_addr[ETH_ALEN];
61 // char Path[128];
62 char BackendPath[128];
63 XEN_IFACE XenInterface;
65 /* ring control structures */
66 struct netif_tx_front_ring tx;
67 struct netif_rx_front_ring rx;
69 /* ptrs to the actual rings themselvves */
70 struct netif_tx_sring *tx_pgs;
71 struct netif_rx_sring *rx_pgs;
73 /* MDLs for the above */
74 PMDL tx_mdl;
75 PMDL rx_mdl;
77 /* Outstanding packets. The first entry in tx_pkts
78 * is an index into a chain of free entries. */
79 PNDIS_PACKET tx_pkts[NET_TX_RING_SIZE];
80 PNDIS_PACKET rx_pkts[NET_RX_RING_SIZE];
82 grant_ref_t gref_tx_head;
83 grant_ref_t grant_tx_ref[NET_TX_RING_SIZE];
84 grant_ref_t gref_rx_head;
85 grant_ref_t grant_rx_ref[NET_TX_RING_SIZE];
87 UINT irq;
88 evtchn_port_t event_channel;
90 grant_ref_t tx_ring_ref;
91 grant_ref_t rx_ring_ref;
93 /* Receive-ring batched refills. */
94 #define RX_MIN_TARGET 8
95 #define RX_DFL_MIN_TARGET 64
96 #define RX_MAX_TARGET min(NET_RX_RING_SIZE, 256)
97 ULONG rx_target;
98 ULONG rx_max_target;
99 ULONG rx_min_target;
101 NDIS_HANDLE packet_pool;
102 NDIS_HANDLE buffer_pool;
104 /* stats */
105 ULONG64 stat_tx_ok;
106 ULONG64 stat_rx_ok;
107 ULONG64 stat_tx_error;
108 ULONG64 stat_rx_error;
109 ULONG64 stat_rx_no_buffer;
111 KEVENT backend_ready_event;
112 };
114 /* This function copied from linux's lib/vsprintf.c, see it for attribution */
115 static unsigned long
116 simple_strtoul(const char *cp,char **endp,unsigned int base)
117 {
118 unsigned long result = 0,value;
120 if (!base) {
121 base = 10;
122 if (*cp == '0') {
123 base = 8;
124 cp++;
125 if ((toupper(*cp) == 'X') && isxdigit(cp[1])) {
126 cp++;
127 base = 16;
128 }
129 }
130 } else if (base == 16) {
131 if (cp[0] == '0' && toupper(cp[1]) == 'X')
132 cp += 2;
133 }
134 while (isxdigit(*cp) &&
135 (value = isdigit(*cp) ? *cp-'0' : toupper(*cp)-'A'+10) < base) {
136 result = result*base + value;
137 cp++;
138 }
139 if (endp)
140 *endp = (char *)cp;
141 return result;
142 }
144 static void
145 add_id_to_freelist(NDIS_PACKET **list, unsigned short id)
146 {
147 list[id] = list[0];
148 list[0] = (void *)(unsigned long)id;
149 }
151 static unsigned short
152 get_id_from_freelist(NDIS_PACKET **list)
153 {
154 unsigned short id = (unsigned short)(unsigned long)list[0];
155 list[0] = list[id];
156 return id;
157 }
159 static NDIS_STATUS
160 XenNet_TxBufferGC(struct xennet_info *xi)
161 {
162 RING_IDX cons, prod;
163 unsigned short id;
164 PNDIS_PACKET pkt;
165 PMDL pmdl;
167 ASSERT(xi->connected);
169 do {
170 prod = xi->tx.sring->rsp_prod;
171 KeMemoryBarrier(); /* Ensure we see responses up to 'rp'. */
173 for (cons = xi->tx.rsp_cons; cons != prod; cons++) {
174 struct netif_tx_response *txrsp;
176 txrsp = RING_GET_RESPONSE(&xi->tx, cons);
177 if (txrsp->status == NETIF_RSP_NULL)
178 continue;
180 id = txrsp->id;
181 pkt = xi->tx_pkts[id];
182 xi->XenInterface.GntTbl_EndAccess(xi->XenInterface.InterfaceHeader.Context,
183 xi->grant_tx_ref[id]);
184 xi->grant_tx_ref[id] = GRANT_INVALID_REF;
185 add_id_to_freelist(xi->tx_pkts, id);
187 /* free linearized data page */
188 pmdl = *(PMDL *)pkt->MiniportReservedEx;
189 NdisFreeMemory(MmGetMdlVirtualAddress(pmdl), 0, 0);
190 IoFreeMdl(pmdl);
192 xi->stat_tx_ok++;
193 NdisMSendComplete(xi->adapter_handle, pkt, NDIS_STATUS_SUCCESS);
194 }
196 xi->tx.rsp_cons = prod;
198 /*
199 * Set a new event, then check for race with update of tx_cons.
200 * Note that it is essential to schedule a callback, no matter
201 * how few buffers are pending. Even if there is space in the
202 * transmit ring, higher layers may be blocked because too much
203 * data is outstanding: in such cases notification from Xen is
204 * likely to be the only kick that we'll get.
205 */
206 xi->tx.sring->rsp_event =
207 prod + ((xi->tx.sring->req_prod - prod) >> 1) + 1;
208 KeMemoryBarrier();
209 } while ((cons == prod) && (prod != xi->tx.sring->rsp_prod));
211 /* if queued packets, send them now?
212 network_maybe_wake_tx(dev); */
214 return NDIS_STATUS_SUCCESS;
215 }
217 static NDIS_STATUS
218 XenNet_AllocRXBuffers(struct xennet_info *xi)
219 {
220 unsigned short id;
221 PNDIS_PACKET packet;
222 PNDIS_BUFFER buffer;
223 int i, batch_target, notify;
224 RING_IDX req_prod = xi->rx.req_prod_pvt;
225 grant_ref_t ref;
226 netif_rx_request_t *req;
227 NDIS_STATUS status;
228 PVOID start;
230 batch_target = xi->rx_target - (req_prod - xi->rx.rsp_cons);
231 for (i = 0; i < batch_target; i++)
232 {
233 /*
234 * Allocate a packet, page, and buffer. Hook them up.
235 */
236 status = NdisAllocateMemoryWithTag(&start, PAGE_SIZE, XENNET_POOL_TAG);
237 if (status != NDIS_STATUS_SUCCESS)
238 {
239 KdPrint(("NdisAllocateMemoryWithTag Failed! status = 0x%x\n", status));
240 break;
241 }
242 NdisAllocateBuffer(&status, &buffer, xi->buffer_pool, start, PAGE_SIZE);
243 if (status != NDIS_STATUS_SUCCESS)
244 {
245 KdPrint(("NdisAllocateBuffer Failed! status = 0x%x\n", status));
246 NdisFreeMemory(start, 0, 0);
247 break;
248 }
249 NdisAllocatePacket(&status, &packet, xi->packet_pool);
250 if (status != NDIS_STATUS_SUCCESS)
251 {
252 KdPrint(("NdisAllocatePacket Failed! status = 0x%x\n", status));
253 NdisFreeMemory(start, 0, 0);
254 NdisFreeBuffer(buffer);
255 break;
256 }
257 NdisChainBufferAtBack(packet, buffer);
258 NDIS_SET_PACKET_HEADER_SIZE(packet, XN_HDR_SIZE);
260 /* Give to netback */
261 id = (unsigned short)(req_prod + i) & (NET_RX_RING_SIZE - 1);
262 ASSERT(!xi->rx_pkts[id]);
263 xi->rx_pkts[id] = packet;
264 req = RING_GET_REQUEST(&xi->rx, req_prod + i);
265 /* an NDIS_BUFFER is just a MDL, so we can get its pfn array */
266 ref = xi->XenInterface.GntTbl_GrantAccess(
267 xi->XenInterface.InterfaceHeader.Context, 0,
268 *MmGetMdlPfnArray(buffer), FALSE);
269 ASSERT((signed short)ref >= 0);
270 xi->grant_rx_ref[id] = ref;
272 req->id = id;
273 req->gref = ref;
274 }
276 xi->rx.req_prod_pvt = req_prod + i;
277 RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&xi->rx, notify);
278 if (notify)
279 {
280 xi->XenInterface.EvtChn_Notify(xi->XenInterface.InterfaceHeader.Context,
281 xi->event_channel);
282 }
284 return NDIS_STATUS_SUCCESS;
285 }
287 static NDIS_STATUS
288 XenNet_RxBufferCheck(struct xennet_info *xi)
289 {
290 RING_IDX cons, prod;
292 PNDIS_PACKET pkt;
293 PNDIS_BUFFER buffer;
294 PVOID buff_va;
295 UINT buff_len;
296 UINT tot_buff_len;
298 ASSERT(xi->connected);
300 do {
301 prod = xi->rx.sring->rsp_prod;
302 KeMemoryBarrier(); /* Ensure we see responses up to 'rp'. */
304 for (cons = xi->rx.rsp_cons; cons != prod; cons++) {
305 struct netif_rx_response *rxrsp;
307 rxrsp = RING_GET_RESPONSE(&xi->rx, cons);
308 if (rxrsp->status == NETIF_RSP_NULL)
309 continue;
311 pkt = xi->rx_pkts[rxrsp->id];
312 xi->rx_pkts[rxrsp->id] = NULL;
313 xi->XenInterface.GntTbl_EndAccess(xi->XenInterface.InterfaceHeader.Context,
314 xi->grant_rx_ref[rxrsp->id]);
315 xi->grant_rx_ref[rxrsp->id] = GRANT_INVALID_REF;
317 NdisGetFirstBufferFromPacketSafe(pkt, &buffer, &buff_va, &buff_len,
318 &tot_buff_len, NormalPagePriority);
319 ASSERT(rxrsp->offset == 0);
320 ASSERT(rxrsp->status > 0);
321 NdisAdjustBufferLength(buffer, rxrsp->status);
323 xi->stat_rx_ok++;
324 NDIS_SET_PACKET_STATUS(pkt, NDIS_STATUS_SUCCESS);
326 /* just indicate 1 packet for now */
327 NdisMIndicateReceivePacket(xi->adapter_handle, &pkt, 1);
328 }
330 xi->rx.rsp_cons = prod;
332 /*
333 * Set a new event, then check for race with update of rx_cons.
334 * Note that it is essential to schedule a callback, no matter
335 * how few buffers are pending. Even if there is space in the
336 * transmit ring, higher layers may be blocked because too much
337 * data is outstanding: in such cases notification from Xen is
338 * likely to be the only kick that we'll get.
339 */
340 xi->rx.sring->rsp_event =
341 prod + ((xi->rx.sring->req_prod - prod) >> 1) + 1;
342 KeMemoryBarrier();
343 } while ((cons == prod) && (prod != xi->rx.sring->rsp_prod));
345 /* Give netback more buffers */
346 XenNet_AllocRXBuffers(xi);
348 return NDIS_STATUS_SUCCESS;
349 }
351 static BOOLEAN
352 XenNet_Interrupt(
353 PKINTERRUPT Interrupt,
354 PVOID ServiceContext
355 )
356 {
357 struct xennet_info *xi = ServiceContext;
358 // KIRQL KIrql;
360 UNREFERENCED_PARAMETER(Interrupt);
362 //KdPrint((__DRIVER_NAME " ***XenNet Interrupt***\n"));
364 if (xi->connected)
365 {
366 XenNet_TxBufferGC(xi);
367 XenNet_RxBufferCheck(xi);
368 }
369 // KeAcquireSpinLock(&ChildDeviceData->Lock, &KIrql);
370 // KdPrint((__DRIVER_NAME " --> Setting Dpc Event\n"));
371 // KeSetEvent(&ChildDeviceData->DpcThreadEvent, 1, FALSE);
372 // KeReleaseSpinLock(&ChildDeviceData->Lock, KIrql);
373 // KdPrint((__DRIVER_NAME " --> Dpc Event Set\n"));
375 return TRUE;
376 }
378 static VOID
379 XenNet_BackEndStateHandler(char *Path, PVOID Data)
380 {
381 struct xennet_info *xi = Data;
382 char *Value;
383 int be_state;
384 char TmpPath[128];
385 xenbus_transaction_t xbt = 0;
386 int retry = 0;
387 char *err;
388 int i;
390 struct set_params {
391 char *name;
392 int value;
393 } params[] = {
394 {"tx-ring-ref", 0},
395 {"rx-ring-ref", 0},
396 {"event-channel", 0},
397 {"request-rx-copy", 1},
398 {"feature-rx-notify", 1},
399 {"feature-no-csum-offload", 1},
400 {"feature-sg", 1},
401 {"feature-gso-tcpv4", 0},
402 {NULL, 0},
403 };
405 xi->XenInterface.XenBus_Read(xi->XenInterface.InterfaceHeader.Context,
406 XBT_NIL, Path, &Value);
407 be_state = atoi(Value);
408 xi->XenInterface.FreeMem(Value);
410 switch (be_state)
411 {
412 case XenbusStateUnknown:
413 KdPrint((__DRIVER_NAME " Backend State Changed to Unknown\n"));
414 break;
416 case XenbusStateInitialising:
417 KdPrint((__DRIVER_NAME " Backend State Changed to Initialising\n"));
418 break;
420 case XenbusStateInitWait:
421 KdPrint((__DRIVER_NAME " Backend State Changed to InitWait\n"));
423 xi->event_channel = xi->XenInterface.EvtChn_AllocUnbound(
424 xi->XenInterface.InterfaceHeader.Context, 0);
425 xi->XenInterface.EvtChn_Bind(xi->XenInterface.InterfaceHeader.Context,
426 xi->event_channel, XenNet_Interrupt, xi);
428 /* TODO: must free pages in MDL as well as MDL using MmFreePagesFromMdl and ExFreePool */
429 // or, allocate mem and then get mdl, then free mdl
430 xi->tx_mdl = AllocatePage();
431 xi->tx_pgs = MmGetMdlVirtualAddress(xi->tx_mdl); //MmMapLockedPagesSpecifyCache(xi->tx_mdl, KernelMode, MmNonCached, NULL, FALSE, NormalPagePriority);
432 SHARED_RING_INIT(xi->tx_pgs);
433 FRONT_RING_INIT(&xi->tx, xi->tx_pgs, PAGE_SIZE);
434 xi->tx_ring_ref = xi->XenInterface.GntTbl_GrantAccess(
435 xi->XenInterface.InterfaceHeader.Context, 0,
436 *MmGetMdlPfnArray(xi->tx_mdl), FALSE);
438 xi->rx_mdl = AllocatePage();
439 xi->rx_pgs = MmGetMdlVirtualAddress(xi->rx_mdl); //MmMapLockedPagesSpecifyCache(xi->rx_mdl, KernelMode, MmNonCached, NULL, FALSE, NormalPagePriority);
440 SHARED_RING_INIT(xi->rx_pgs);
441 FRONT_RING_INIT(&xi->rx, xi->rx_pgs, PAGE_SIZE);
442 xi->rx_ring_ref = xi->XenInterface.GntTbl_GrantAccess(
443 xi->XenInterface.InterfaceHeader.Context, 0,
444 *MmGetMdlPfnArray(xi->rx_mdl), FALSE);
446 /* fixup array for dynamic values */
447 params[0].value = xi->tx_ring_ref;
448 params[1].value = xi->rx_ring_ref;
449 params[2].value = xi->event_channel;
451 xi->XenInterface.XenBus_StartTransaction(
452 xi->XenInterface.InterfaceHeader.Context, &xbt);
454 for (i = 0; params[i].name; i++)
455 {
456 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath), "%s/%s",
457 xi->pdoData->Path, params[i].name);
458 err = xi->XenInterface.XenBus_Printf(xi->XenInterface.InterfaceHeader.Context,
459 XBT_NIL, TmpPath, "%d", params[i].value);
460 if (err)
461 {
462 KdPrint(("setting %s failed, err = %s\n", params[i].name, err));
463 goto trouble;
464 }
465 }
467 /* commit transaction */
468 xi->XenInterface.XenBus_EndTransaction(xi->XenInterface.InterfaceHeader.Context,
469 xbt, 0, &retry);
471 XenNet_AllocRXBuffers(xi);
473 KdPrint((__DRIVER_NAME " Set Frontend state to Connected\n"));
474 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath), "%s/state", xi->pdoData->Path);
475 xi->XenInterface.XenBus_Printf(xi->XenInterface.InterfaceHeader.Context,
476 XBT_NIL, TmpPath, "%d", XenbusStateConnected);
478 /* send fake arp? */
480 xi->connected = TRUE;
482 break;
484 case XenbusStateInitialised:
485 KdPrint((__DRIVER_NAME " Backend State Changed to Initialised\n"));
486 break;
488 case XenbusStateConnected:
489 KdPrint((__DRIVER_NAME " Backend State Changed to Connected\n"));
490 KeSetEvent(&xi->backend_ready_event, 1, FALSE);
491 break;
493 case XenbusStateClosing:
494 KdPrint((__DRIVER_NAME " Backend State Changed to Closing\n"));
495 break;
497 case XenbusStateClosed:
498 KdPrint((__DRIVER_NAME " Backend State Changed to Closed\n"));
499 break;
501 default:
502 KdPrint((__DRIVER_NAME " Backend State Changed to Undefined = %d\n", be_state));
503 break;
504 }
506 return;
508 trouble:
509 KdPrint((__DRIVER_NAME __FUNCTION__ ": Should never happen!\n"));
510 xi->XenInterface.XenBus_EndTransaction(xi->XenInterface.InterfaceHeader.Context,
511 xbt, 1, &retry);
513 }
515 VOID
516 XenNet_Halt(
517 IN NDIS_HANDLE MiniportAdapterContext
518 )
519 {
520 UNREFERENCED_PARAMETER(MiniportAdapterContext);
521 }
523 static NDIS_STATUS
524 XenNet_Init(
525 OUT PNDIS_STATUS OpenErrorStatus,
526 OUT PUINT SelectedMediumIndex,
527 IN PNDIS_MEDIUM MediumArray,
528 IN UINT MediumArraySize,
529 IN NDIS_HANDLE MiniportAdapterHandle,
530 IN NDIS_HANDLE WrapperConfigurationContext
531 )
532 {
533 NDIS_STATUS status;
534 UINT i;
535 BOOLEAN medium_found = FALSE;
536 struct xennet_info *xi = NULL;
537 ULONG length;
538 WDF_OBJECT_ATTRIBUTES wdf_attrs;
539 char *msg;
540 char *Value;
541 char TmpPath[128];
543 UNREFERENCED_PARAMETER(OpenErrorStatus);
544 UNREFERENCED_PARAMETER(WrapperConfigurationContext);
546 /* deal with medium stuff */
547 for (i = 0; i < MediumArraySize; i++)
548 {
549 if (MediumArray[i] == NdisMedium802_3)
550 {
551 medium_found = TRUE;
552 break;
553 }
554 }
555 if (!medium_found)
556 {
557 KdPrint(("NIC_MEDIA_TYPE not in MediumArray\n"));
558 return NDIS_STATUS_UNSUPPORTED_MEDIA;
559 }
560 *SelectedMediumIndex = i;
562 /* Alloc memory for adapter private info */
563 status = NdisAllocateMemoryWithTag(&xi, sizeof(*xi), XENNET_POOL_TAG);
564 if (!NT_SUCCESS(status))
565 {
566 KdPrint(("NdisAllocateMemoryWithTag failed with 0x%x\n", status));
567 status = NDIS_STATUS_RESOURCES;
568 goto err;
569 }
570 RtlZeroMemory(xi, sizeof(*xi));
572 /* init xennet_info */
573 xi->adapter_handle = MiniportAdapterHandle;
574 xi->rx_target = RX_DFL_MIN_TARGET;
575 xi->rx_min_target = RX_DFL_MIN_TARGET;
576 xi->rx_max_target = RX_MAX_TARGET;
578 NdisAllocatePacketPool(&status, &xi->packet_pool, NET_RX_RING_SIZE,
579 PROTOCOL_RESERVED_SIZE_IN_PACKET);
580 if (status != NDIS_STATUS_SUCCESS)
581 {
582 KdPrint(("NdisAllocatePacketPool failed with 0x%x\n", status));
583 status = NDIS_STATUS_RESOURCES;
584 goto err;
585 }
587 NdisAllocateBufferPool(&status, &xi->buffer_pool, NET_RX_RING_SIZE);
588 if (status != NDIS_STATUS_SUCCESS)
589 {
590 KdPrint(("NdisAllocateBufferPool failed with 0x%x\n", status));
591 status = NDIS_STATUS_RESOURCES;
592 goto err;
593 }
595 NdisMGetDeviceProperty(MiniportAdapterHandle, &xi->pdo, &xi->fdo,
596 &xi->lower_do, NULL, NULL);
597 xi->pdoData = (PXENPCI_XEN_DEVICE_DATA)xi->pdo->DeviceExtension;
599 /* Initialize tx_pkts as a free chain containing every entry. */
600 for (i = 0; i <= NET_TX_RING_SIZE; i++) {
601 xi->tx_pkts[i] = (void *)((unsigned long) i+1);
602 xi->grant_tx_ref[i] = GRANT_INVALID_REF;
603 }
605 for (i = 0; i < NET_RX_RING_SIZE; i++) {
606 xi->rx_pkts[i] = NULL;
607 xi->grant_rx_ref[i] = GRANT_INVALID_REF;
608 }
610 status = IoGetDeviceProperty(xi->pdo, DevicePropertyDeviceDescription,
611 NAME_SIZE, xi->name, &length);
612 if (!NT_SUCCESS(status))
613 {
614 KdPrint(("IoGetDeviceProperty failed with 0x%x\n", status));
615 status = NDIS_STATUS_FAILURE;
616 goto err;
617 }
619 NdisMSetAttributesEx(xi->adapter_handle, (NDIS_HANDLE) xi,
620 0, (NDIS_ATTRIBUTE_DESERIALIZE /*| NDIS_ATTRIBUTE_BUS_MASTER*/),
621 NdisInterfaceInternal);
623 WDF_OBJECT_ATTRIBUTES_INIT(&wdf_attrs);
625 status = WdfDeviceMiniportCreate(WdfGetDriver(), &wdf_attrs, xi->fdo,
626 xi->lower_do, xi->pdo, &xi->wdf_device);
627 if (!NT_SUCCESS(status))
628 {
629 KdPrint(("WdfDeviceMiniportCreate failed with 0x%x\n", status));
630 status = NDIS_STATUS_FAILURE;
631 goto err;
632 }
634 /* get lower (Xen) interfaces */
636 status = WdfFdoQueryForInterface(xi->wdf_device, &GUID_XEN_IFACE,
637 (PINTERFACE) &xi->XenInterface, sizeof(XEN_IFACE), 1, NULL);
638 if(!NT_SUCCESS(status))
639 {
640 KdPrint(("WdfFdoQueryForInterface failed with status 0x%08x\n", status));
641 status = NDIS_STATUS_FAILURE;
642 goto err;
643 }
645 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath),
646 "%s/backend", xi->pdoData->Path);
647 KdPrint(("About to read %s to get backend path\n", TmpPath));
648 xi->XenInterface.XenBus_Read(xi->XenInterface.InterfaceHeader.Context,
649 XBT_NIL, TmpPath, &Value);
650 if (!Value)
651 {
652 KdPrint((__DRIVER_NAME " Failed to read backend path\n"));
653 status = NDIS_STATUS_FAILURE;
654 goto err;
655 }
656 // Check for Value == NULL here
657 RtlStringCbCopyA(xi->BackendPath, ARRAY_SIZE(xi->BackendPath), Value);
658 KdPrint((__DRIVER_NAME "backend path = %s\n", xi->BackendPath));
660 KeInitializeEvent(&xi->backend_ready_event, SynchronizationEvent, FALSE);
662 /* Add watch on backend state */
663 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath), "%s/state", xi->BackendPath);
664 xi->XenInterface.XenBus_AddWatch(xi->XenInterface.InterfaceHeader.Context,
665 XBT_NIL, TmpPath, XenNet_BackEndStateHandler, xi);
667 // wait here for signal that we are all set up
668 KeWaitForSingleObject(&xi->backend_ready_event, Executive, KernelMode, FALSE, NULL);
670 /* get mac address */
671 RtlStringCbPrintfA(TmpPath, ARRAY_SIZE(TmpPath), "%s/mac", xi->BackendPath);
672 xi->XenInterface.XenBus_Read(xi->XenInterface.InterfaceHeader.Context,
673 XBT_NIL, TmpPath, &Value);
674 if (!Value)
675 {
676 KdPrint((__DRIVER_NAME " mac Read Failed\n"));
677 status = NDIS_STATUS_FAILURE;
678 goto err;
679 }
680 else
681 {
682 char *s, *e;
683 int i;
684 s = Value;
685 for (i = 0; i < ETH_ALEN; i++) {
686 xi->perm_mac_addr[i] = (UINT8)simple_strtoul(s, &e, 16);
687 if ((s == e) || (*e != ((i == ETH_ALEN-1) ? '\0' : ':'))) {
688 KdPrint((__DRIVER_NAME "Error parsing MAC address\n"));
689 xi->XenInterface.FreeMem(Value);
690 status = NDIS_STATUS_FAILURE;
691 goto err;
692 }
693 s = e + 1;
694 }
695 memcpy(xi->curr_mac_addr, xi->perm_mac_addr, ETH_ALEN);
696 xi->XenInterface.FreeMem(Value);
697 }
699 return NDIS_STATUS_SUCCESS;
701 err:
702 NdisFreeMemory(xi, 0, 0);
703 return status;
704 }
706 NDIS_OID supported_oids[] =
707 {
708 /* general OIDs */
709 OID_GEN_SUPPORTED_LIST,
710 OID_GEN_HARDWARE_STATUS,
711 OID_GEN_MEDIA_SUPPORTED,
712 OID_GEN_MEDIA_IN_USE,
713 OID_GEN_MAXIMUM_LOOKAHEAD,
714 OID_GEN_MAXIMUM_FRAME_SIZE,
715 OID_GEN_LINK_SPEED,
716 OID_GEN_TRANSMIT_BUFFER_SPACE,
717 OID_GEN_RECEIVE_BUFFER_SPACE,
718 OID_GEN_TRANSMIT_BLOCK_SIZE,
719 OID_GEN_RECEIVE_BLOCK_SIZE,
720 OID_GEN_VENDOR_ID,
721 OID_GEN_VENDOR_DESCRIPTION,
722 OID_GEN_CURRENT_PACKET_FILTER,
723 OID_GEN_CURRENT_LOOKAHEAD,
724 OID_GEN_DRIVER_VERSION,
725 OID_GEN_MAXIMUM_TOTAL_SIZE,
726 OID_GEN_MAC_OPTIONS,
727 OID_GEN_MEDIA_CONNECT_STATUS,
728 OID_GEN_MAXIMUM_SEND_PACKETS,
729 /* stats */
730 OID_GEN_XMIT_OK,
731 OID_GEN_RCV_OK,
732 OID_GEN_XMIT_ERROR,
733 OID_GEN_RCV_ERROR,
734 OID_GEN_RCV_NO_BUFFER,
735 /* media-specific OIDs */
736 OID_802_3_PERMANENT_ADDRESS,
737 OID_802_3_CURRENT_ADDRESS,
738 OID_802_3_MULTICAST_LIST,
739 OID_802_3_MAXIMUM_LIST_SIZE,
740 };
742 NDIS_STATUS
743 XenNet_QueryInformation(
744 IN NDIS_HANDLE MiniportAdapterContext,
745 IN NDIS_OID Oid,
746 IN PVOID InformationBuffer,
747 IN ULONG InformationBufferLength,
748 OUT PULONG BytesWritten,
749 OUT PULONG BytesNeeded)
750 {
751 struct xennet_info *xi = MiniportAdapterContext;
752 UCHAR vendor_desc[] = XN_VENDOR_DESC;
753 ULONG64 temp_data;
754 PVOID data = &temp_data;
755 UINT len = 4;
756 NDIS_STATUS status = NDIS_STATUS_SUCCESS;
758 switch(Oid)
759 {
760 case OID_GEN_SUPPORTED_LIST:
761 data = supported_oids;
762 len = sizeof(supported_oids);
763 break;
764 case OID_GEN_HARDWARE_STATUS:
765 if (!xi->connected)
766 temp_data = NdisHardwareStatusInitializing;
767 else
768 temp_data = NdisHardwareStatusReady;
769 break;
770 case OID_GEN_MEDIA_SUPPORTED:
771 temp_data = NdisMedium802_3;
772 break;
773 case OID_GEN_MEDIA_IN_USE:
774 temp_data = NdisMedium802_3;
775 break;
776 case OID_GEN_MAXIMUM_LOOKAHEAD:
777 temp_data = XN_DATA_SIZE;
778 break;
779 case OID_GEN_MAXIMUM_FRAME_SIZE:
780 temp_data = XN_MAX_PKT_SIZE;
781 break;
782 case OID_GEN_LINK_SPEED:
783 temp_data = 10000000; /* 1Gb */
784 break;
785 case OID_GEN_TRANSMIT_BUFFER_SPACE:
786 /* pkts times sizeof ring, maybe? */
787 temp_data = XN_MAX_PKT_SIZE * NET_TX_RING_SIZE;
788 break;
789 case OID_GEN_RECEIVE_BUFFER_SPACE:
790 /* pkts times sizeof ring, maybe? */
791 temp_data = XN_MAX_PKT_SIZE * NET_TX_RING_SIZE;
792 break;
793 case OID_GEN_TRANSMIT_BLOCK_SIZE:
794 temp_data = XN_MAX_PKT_SIZE;
795 break;
796 case OID_GEN_RECEIVE_BLOCK_SIZE:
797 temp_data = XN_MAX_PKT_SIZE;
798 break;
799 case OID_GEN_VENDOR_ID:
800 temp_data = XENSOURCE_MAC_HDR;
801 break;
802 case OID_GEN_VENDOR_DESCRIPTION:
803 data = vendor_desc;
804 len = sizeof(vendor_desc);
805 break;
806 case OID_GEN_CURRENT_PACKET_FILTER:
807 temp_data = xi->packet_filter;
808 break;
809 case OID_GEN_CURRENT_LOOKAHEAD:
810 temp_data = XN_MAX_PKT_SIZE;
811 break;
812 case OID_GEN_DRIVER_VERSION:
813 temp_data = (NDIS_MAJOR_VER << 8) | NDIS_MINOR_VER;
814 len = 2;
815 break;
816 case OID_GEN_MAXIMUM_TOTAL_SIZE:
817 temp_data = XN_MAX_PKT_SIZE;
818 break;
819 case OID_GEN_MAC_OPTIONS:
820 temp_data = NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA |
821 NDIS_MAC_OPTION_TRANSFERS_NOT_PEND |
822 NDIS_MAC_OPTION_NO_LOOPBACK;
823 break;
824 case OID_GEN_MEDIA_CONNECT_STATUS:
825 if (xi->connected)
826 temp_data = NdisMediaStateConnected;
827 else
828 temp_data = NdisMediaStateDisconnected;
829 break;
830 case OID_GEN_MAXIMUM_SEND_PACKETS:
831 temp_data = XN_MAX_SEND_PKTS;
832 break;
833 case OID_GEN_XMIT_OK:
834 temp_data = xi->stat_tx_ok;
835 len = sizeof(ULONG64);
836 break;
837 case OID_GEN_RCV_OK:
838 temp_data = xi->stat_rx_ok;
839 len = sizeof(ULONG64);
840 break;
841 case OID_GEN_XMIT_ERROR:
842 temp_data = xi->stat_tx_error;
843 len = sizeof(ULONG64);
844 break;
845 case OID_GEN_RCV_ERROR:
846 temp_data = xi->stat_rx_error;
847 len = sizeof(ULONG64);
848 break;
849 case OID_GEN_RCV_NO_BUFFER:
850 temp_data = xi->stat_rx_no_buffer;
851 len = sizeof(ULONG64);
852 break;
853 case OID_802_3_PERMANENT_ADDRESS:
854 data = xi->perm_mac_addr;
855 len = ETH_ALEN;
856 break;
857 case OID_802_3_CURRENT_ADDRESS:
858 data = xi->curr_mac_addr;
859 len = ETH_ALEN;
860 break;
861 case OID_802_3_MULTICAST_LIST:
862 data = NULL;
863 len = 0;
864 case OID_802_3_MAXIMUM_LIST_SIZE:
865 temp_data = 0; /* no mcast support */
866 break;
867 default:
868 //KdPrint(("Unknown OID 0x%x\n", Oid));
869 status = NDIS_STATUS_NOT_SUPPORTED;
870 }
872 if (!NT_SUCCESS(status))
873 {
874 return status;
875 }
877 if (len > InformationBufferLength)
878 {
879 *BytesNeeded = len;
880 return NDIS_STATUS_BUFFER_TOO_SHORT;
881 }
883 *BytesWritten = len;
884 if (len)
885 {
886 NdisMoveMemory(InformationBuffer, data, len);
887 }
889 //KdPrint(("Got OID 0x%x\n", Oid));
891 return status;
892 }
894 NDIS_STATUS
895 XenNet_SetInformation(
896 IN NDIS_HANDLE MiniportAdapterContext,
897 IN NDIS_OID Oid,
898 IN PVOID InformationBuffer,
899 IN ULONG InformationBufferLength,
900 OUT PULONG BytesRead,
901 OUT PULONG BytesNeeded
902 )
903 {
904 UNREFERENCED_PARAMETER(MiniportAdapterContext);
905 UNREFERENCED_PARAMETER(Oid);
906 UNREFERENCED_PARAMETER(InformationBuffer);
907 UNREFERENCED_PARAMETER(InformationBufferLength);
908 UNREFERENCED_PARAMETER(BytesRead);
909 UNREFERENCED_PARAMETER(BytesNeeded);
911 KdPrint((__FUNCTION__ " called with OID=0x%x\n", Oid));
912 return NDIS_STATUS_SUCCESS;
913 }
915 VOID
916 XenNet_ReturnPacket(
917 IN NDIS_HANDLE MiniportAdapterContext,
918 IN PNDIS_PACKET Packet
919 )
920 {
921 PNDIS_BUFFER buffer;
922 PVOID buff_va;
923 UINT buff_len;
924 UINT tot_buff_len;
926 UNREFERENCED_PARAMETER(MiniportAdapterContext);
928 NdisGetFirstBufferFromPacketSafe(Packet, &buffer, &buff_va, &buff_len,
929 &tot_buff_len, NormalPagePriority);
930 ASSERT(buff_len == tot_buff_len);
932 NdisFreeMemory(buff_va, 0, 0);
933 NdisFreeBuffer(buffer);
934 NdisFreePacket(Packet);
936 //KdPrint((__FUNCTION__ " called\n"));
937 }
939 PMDL
940 XenNet_Linearize(PNDIS_PACKET Packet)
941 {
942 NDIS_STATUS status;
943 PMDL pmdl;
944 char *start;
945 PNDIS_BUFFER buffer;
946 PVOID buff_va;
947 UINT buff_len;
948 UINT tot_buff_len;
950 NdisGetFirstBufferFromPacketSafe(Packet, &buffer, &buff_va, &buff_len,
951 &tot_buff_len, NormalPagePriority);
952 ASSERT(tot_buff_len <= XN_MAX_PKT_SIZE);
954 status = NdisAllocateMemoryWithTag(&start, tot_buff_len, XENNET_POOL_TAG);
955 if (!NT_SUCCESS(status))
956 {
957 KdPrint(("Could not allocate memory for linearization\n"));
958 return NULL;
959 }
960 pmdl = IoAllocateMdl(start, tot_buff_len, FALSE, FALSE, FALSE);
961 if (!pmdl)
962 {
963 KdPrint(("Could not allocate MDL for linearization\n"));
964 NdisFreeMemory(start, 0, 0);
965 return NULL;
966 }
967 MmBuildMdlForNonPagedPool(pmdl);
969 while (buffer)
970 {
971 NdisQueryBufferSafe(buffer, &buff_va, &buff_len, NormalPagePriority);
972 RtlCopyMemory(start, buff_va, buff_len);
973 start += buff_len;
974 NdisGetNextBuffer(buffer, &buffer);
975 }
977 return pmdl;
978 }
980 VOID
981 XenNet_SendPackets(
982 IN NDIS_HANDLE MiniportAdapterContext,
983 IN PPNDIS_PACKET PacketArray,
984 IN UINT NumberOfPackets
985 )
986 {
987 struct xennet_info *xi = MiniportAdapterContext;
988 PNDIS_PACKET curr_packet;
989 UINT i;
990 struct netif_tx_request *tx;
991 unsigned short id;
992 int notify;
993 PMDL pmdl;
994 UINT pkt_size;
996 for (i = 0; i < NumberOfPackets; i++)
997 {
998 curr_packet = PacketArray[i];
999 ASSERT(curr_packet);
1001 NdisQueryPacket(curr_packet, NULL, NULL, NULL, &pkt_size);
1003 //KdPrint(("sending pkt, len %d\n", pkt_size));
1005 pmdl = XenNet_Linearize(curr_packet);
1006 if (!pmdl)
1008 KdPrint((__DRIVER_NAME "Couldn't linearize packet!\n"));
1009 NdisMSendComplete(xi, curr_packet, NDIS_STATUS_FAILURE);
1010 break;
1012 *((PMDL *)curr_packet->MiniportReservedEx) = pmdl;
1014 id = get_id_from_freelist(xi->tx_pkts);
1015 xi->tx_pkts[id] = curr_packet;
1017 tx = RING_GET_REQUEST(&xi->tx, xi->tx.req_prod_pvt);
1018 tx->id = id;
1019 tx->gref = xi->XenInterface.GntTbl_GrantAccess(
1020 xi->XenInterface.InterfaceHeader.Context,
1021 0,
1022 *MmGetMdlPfnArray(pmdl),
1023 TRUE);
1024 xi->grant_tx_ref[id] = tx->gref;
1025 tx->offset = (uint16_t)MmGetMdlByteOffset(pmdl);
1026 tx->size = (UINT16)pkt_size;
1027 tx->flags = NETTXF_csum_blank;
1029 xi->tx.req_prod_pvt++;
1031 // NDIS_SET_PACKET_STATUS(curr_packet, NDIS_STATUS_SUCCESS);
1032 // NdisMSendComplete(xi, curr_packet, NDIS_STATUS_SUCCESS);
1035 RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&xi->tx, notify);
1036 if (notify)
1038 xi->XenInterface.EvtChn_Notify(xi->XenInterface.InterfaceHeader.Context,
1039 xi->event_channel);
1043 VOID
1044 XenNet_PnPEventNotify(
1045 IN NDIS_HANDLE MiniportAdapterContext,
1046 IN NDIS_DEVICE_PNP_EVENT PnPEvent,
1047 IN PVOID InformationBuffer,
1048 IN ULONG InformationBufferLength
1051 UNREFERENCED_PARAMETER(MiniportAdapterContext);
1052 UNREFERENCED_PARAMETER(PnPEvent);
1053 UNREFERENCED_PARAMETER(InformationBuffer);
1054 UNREFERENCED_PARAMETER(InformationBufferLength);
1056 KdPrint((__FUNCTION__ " called\n"));
1059 VOID
1060 XenNet_Shutdown(
1061 IN NDIS_HANDLE MiniportAdapterContext
1064 UNREFERENCED_PARAMETER(MiniportAdapterContext);
1066 KdPrint((__FUNCTION__ " called\n"));
1069 NTSTATUS
1070 DriverEntry(
1071 PDRIVER_OBJECT DriverObject,
1072 PUNICODE_STRING RegistryPath
1075 NTSTATUS status;
1076 WDF_DRIVER_CONFIG config;
1077 NDIS_HANDLE ndis_wrapper_handle;
1078 NDIS_MINIPORT_CHARACTERISTICS mini_chars;
1080 RtlZeroMemory(&mini_chars, sizeof(mini_chars));
1082 WDF_DRIVER_CONFIG_INIT(&config, WDF_NO_EVENT_CALLBACK);
1083 config.DriverInitFlags |= WdfDriverInitNoDispatchOverride;
1085 status = WdfDriverCreate(DriverObject, RegistryPath, WDF_NO_OBJECT_ATTRIBUTES,
1086 &config, WDF_NO_HANDLE);
1087 if (!NT_SUCCESS(status))
1089 KdPrint(("WdfDriverCreate failed err = 0x%x\n", status));
1090 return status;
1093 NdisMInitializeWrapper(&ndis_wrapper_handle, DriverObject, RegistryPath, NULL);
1094 if (!ndis_wrapper_handle)
1096 KdPrint(("NdisMInitializeWrapper failed\n"));
1097 return NDIS_STATUS_FAILURE;
1100 /* NDIS 5.1 driver */
1101 mini_chars.MajorNdisVersion = NDIS_MAJOR_VER;
1102 mini_chars.MinorNdisVersion = NDIS_MINOR_VER;
1104 mini_chars.HaltHandler = XenNet_Halt;
1105 mini_chars.InitializeHandler = XenNet_Init;
1106 mini_chars.ISRHandler = NULL; // needed if we register interrupt?
1107 mini_chars.QueryInformationHandler = XenNet_QueryInformation;
1108 mini_chars.ResetHandler = NULL; //TODO: fill in
1109 mini_chars.SetInformationHandler = XenNet_SetInformation;
1110 /* added in v.4 -- use multiple pkts interface */
1111 mini_chars.ReturnPacketHandler = XenNet_ReturnPacket;
1112 mini_chars.SendPacketsHandler = XenNet_SendPackets;
1113 /* added in v.5.1 */
1114 mini_chars.PnPEventNotifyHandler = XenNet_PnPEventNotify;
1115 mini_chars.AdapterShutdownHandler = XenNet_Shutdown;
1117 /* TODO: we don't have hardware, but we have "resources", so do we need to implement fns to handle this? */
1119 /* set up upper-edge interface */
1120 status = NdisMRegisterMiniport(ndis_wrapper_handle, &mini_chars, sizeof(mini_chars));
1121 if (!NT_SUCCESS(status))
1123 KdPrint(("NdisMRegisterMiniport failed, status = 0x%x\n", status));
1124 NdisTerminateWrapper(ndis_wrapper_handle, NULL);
1125 return status;
1128 return status;