netdev-dpdk: fix mbuf leaks
[cascardo/ovs.git] / datapath-windows / ovsext / Datapath.c
1 /*
2  * Copyright (c) 2014 VMware, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * XXX: OVS_USE_NL_INTERFACE is being used to keep the legacy DPIF interface
19  * alive while we transition over to the netlink based interface.
20  * OVS_USE_NL_INTERFACE = 0 => legacy inteface to use with dpif-windows.c
21  * OVS_USE_NL_INTERFACE = 1 => netlink inteface to use with ported dpif-linux.c
22  */
23
24 #include "precomp.h"
25 #include "Switch.h"
26 #include "User.h"
27 #include "Datapath.h"
28 #include "Jhash.h"
29 #include "Vport.h"
30 #include "Event.h"
31 #include "User.h"
32 #include "PacketIO.h"
33 #include "NetProto.h"
34 #include "Flow.h"
35 #include "User.h"
36 #include "Vxlan.h"
37
38 #ifdef OVS_DBG_MOD
39 #undef OVS_DBG_MOD
40 #endif
41 #define OVS_DBG_MOD OVS_DBG_DATAPATH
42 #include "Debug.h"
43
44 #define NETLINK_FAMILY_NAME_LEN 48
45
46
47 /*
48  * Netlink messages are grouped by family (aka type), and each family supports
49  * a set of commands, and can be passed both from kernel -> userspace or
50  * vice-versa. To call into the kernel, userspace uses a device operation which
51  * is outside of a netlink message.
52  *
53  * Each command results in the invocation of a handler function to implement the
54  * request functionality.
55  *
56  * Expectedly, only certain combinations of (device operation, netlink family,
57  * command) are valid.
58  *
59  * Here, we implement the basic infrastructure to perform validation on the
60  * incoming message, version checking, and also to invoke the corresponding
61  * handler to do the heavy-lifting.
62  */
63
64 /*
65  * Handler for a given netlink command. Not all the parameters are used by all
66  * the handlers.
67  */
68 typedef NTSTATUS(NetlinkCmdHandler)(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
69                                     UINT32 *replyLen);
70
71 typedef struct _NETLINK_CMD {
72     UINT16 cmd;
73     NetlinkCmdHandler *handler;
74     UINT32 supportedDevOp;      /* Supported device operations. */
75     BOOLEAN validateDpIndex;    /* Does command require a valid DP argument. */
76 } NETLINK_CMD, *PNETLINK_CMD;
77
78 /* A netlink family is a group of commands. */
79 typedef struct _NETLINK_FAMILY {
80     CHAR *name;
81     UINT16 id;
82     UINT8 version;
83     UINT8 pad1;
84     UINT16 maxAttr;
85     UINT16 pad2;
86     NETLINK_CMD *cmds;          /* Array of netlink commands and handlers. */
87     UINT16 opsCount;
88 } NETLINK_FAMILY, *PNETLINK_FAMILY;
89
90 /* Handlers for the various netlink commands. */
91 static NetlinkCmdHandler OvsPendEventCmdHandler,
92                          OvsSubscribeEventCmdHandler,
93                          OvsReadEventCmdHandler,
94                          OvsNewDpCmdHandler,
95                          OvsGetDpCmdHandler,
96                          OvsSetDpCmdHandler;
97
98 NetlinkCmdHandler        OvsGetNetdevCmdHandler,
99                          OvsGetVportCmdHandler,
100                          OvsSetVportCmdHandler,
101                          OvsNewVportCmdHandler,
102                          OvsDeleteVportCmdHandler,
103                          OvsPendPacketCmdHandler,
104                          OvsSubscribePacketCmdHandler,
105                          OvsReadPacketCmdHandler;
106
107 static NTSTATUS HandleGetDpTransaction(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
108                                        UINT32 *replyLen);
109 static NTSTATUS HandleGetDpDump(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
110                                 UINT32 *replyLen);
111 static NTSTATUS HandleDpTransactionCommon(
112                     POVS_USER_PARAMS_CONTEXT usrParamsCtx, UINT32 *replyLen);
113 static NTSTATUS OvsGetPidHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
114                                     UINT32 *replyLen);
115
116 /*
117  * The various netlink families, along with the supported commands. Most of
118  * these families and commands are part of the openvswitch specification for a
119  * netlink datapath. In addition, each platform can implement a few families
120  * and commands as extensions.
121  */
122
123 /* Netlink control family: this is a Windows specific family. */
124 NETLINK_CMD nlControlFamilyCmdOps[] = {
125     { .cmd = OVS_CTRL_CMD_WIN_PEND_REQ,
126       .handler = OvsPendEventCmdHandler,
127       .supportedDevOp = OVS_WRITE_DEV_OP,
128       .validateDpIndex = TRUE,
129     },
130     { .cmd = OVS_CTRL_CMD_WIN_PEND_PACKET_REQ,
131       .handler = OvsPendPacketCmdHandler,
132       .supportedDevOp = OVS_WRITE_DEV_OP,
133       .validateDpIndex = TRUE,
134     },
135     { .cmd = OVS_CTRL_CMD_MC_SUBSCRIBE_REQ,
136       .handler = OvsSubscribeEventCmdHandler,
137       .supportedDevOp = OVS_WRITE_DEV_OP,
138       .validateDpIndex = TRUE,
139     },
140     { .cmd = OVS_CTRL_CMD_PACKET_SUBSCRIBE_REQ,
141       .handler = OvsSubscribePacketCmdHandler,
142       .supportedDevOp = OVS_WRITE_DEV_OP,
143       .validateDpIndex = TRUE,
144     },
145     { .cmd = OVS_CTRL_CMD_EVENT_NOTIFY,
146       .handler = OvsReadEventCmdHandler,
147       .supportedDevOp = OVS_READ_DEV_OP,
148       .validateDpIndex = FALSE,
149     },
150     { .cmd = OVS_CTRL_CMD_READ_NOTIFY,
151       .handler = OvsReadPacketCmdHandler,
152       .supportedDevOp = OVS_READ_DEV_OP,
153       .validateDpIndex = FALSE,
154     }
155 };
156
157 NETLINK_FAMILY nlControlFamilyOps = {
158     .name     = OVS_WIN_CONTROL_FAMILY,
159     .id       = OVS_WIN_NL_CTRL_FAMILY_ID,
160     .version  = OVS_WIN_CONTROL_VERSION,
161     .maxAttr  = OVS_WIN_CONTROL_ATTR_MAX,
162     .cmds     = nlControlFamilyCmdOps,
163     .opsCount = ARRAY_SIZE(nlControlFamilyCmdOps)
164 };
165
166 /* Netlink datapath family. */
167 NETLINK_CMD nlDatapathFamilyCmdOps[] = {
168     { .cmd             = OVS_DP_CMD_NEW,
169       .handler         = OvsNewDpCmdHandler,
170       .supportedDevOp  = OVS_TRANSACTION_DEV_OP,
171       .validateDpIndex = FALSE
172     },
173     { .cmd             = OVS_DP_CMD_GET,
174       .handler         = OvsGetDpCmdHandler,
175       .supportedDevOp  = OVS_WRITE_DEV_OP | OVS_READ_DEV_OP |
176                          OVS_TRANSACTION_DEV_OP,
177       .validateDpIndex = FALSE
178     },
179     { .cmd             = OVS_DP_CMD_SET,
180       .handler         = OvsSetDpCmdHandler,
181       .supportedDevOp  = OVS_WRITE_DEV_OP | OVS_READ_DEV_OP |
182                          OVS_TRANSACTION_DEV_OP,
183       .validateDpIndex = TRUE
184     }
185 };
186
187 NETLINK_FAMILY nlDatapathFamilyOps = {
188     .name     = OVS_DATAPATH_FAMILY,
189     .id       = OVS_WIN_NL_DATAPATH_FAMILY_ID,
190     .version  = OVS_DATAPATH_VERSION,
191     .maxAttr  = OVS_DP_ATTR_MAX,
192     .cmds     = nlDatapathFamilyCmdOps,
193     .opsCount = ARRAY_SIZE(nlDatapathFamilyCmdOps)
194 };
195
196 /* Netlink packet family. */
197
198 NETLINK_CMD nlPacketFamilyCmdOps[] = {
199     { .cmd             = OVS_PACKET_CMD_EXECUTE,
200       .handler         = OvsNlExecuteCmdHandler,
201       .supportedDevOp  = OVS_TRANSACTION_DEV_OP,
202       .validateDpIndex = TRUE
203     }
204 };
205
206 NETLINK_FAMILY nlPacketFamilyOps = {
207     .name     = OVS_PACKET_FAMILY,
208     .id       = OVS_WIN_NL_PACKET_FAMILY_ID,
209     .version  = OVS_PACKET_VERSION,
210     .maxAttr  = OVS_PACKET_ATTR_MAX,
211     .cmds     = nlPacketFamilyCmdOps,
212     .opsCount = ARRAY_SIZE(nlPacketFamilyCmdOps)
213 };
214
215 /* Netlink vport family. */
216 NETLINK_CMD nlVportFamilyCmdOps[] = {
217     { .cmd = OVS_VPORT_CMD_GET,
218       .handler = OvsGetVportCmdHandler,
219       .supportedDevOp = OVS_WRITE_DEV_OP | OVS_READ_DEV_OP |
220                         OVS_TRANSACTION_DEV_OP,
221       .validateDpIndex = TRUE
222     },
223     { .cmd = OVS_VPORT_CMD_NEW,
224       .handler = OvsNewVportCmdHandler,
225       .supportedDevOp = OVS_TRANSACTION_DEV_OP,
226       .validateDpIndex = TRUE
227     },
228     { .cmd = OVS_VPORT_CMD_SET,
229       .handler = OvsSetVportCmdHandler,
230       .supportedDevOp = OVS_TRANSACTION_DEV_OP,
231       .validateDpIndex = TRUE
232     },
233     { .cmd = OVS_VPORT_CMD_DEL,
234       .handler = OvsDeleteVportCmdHandler,
235       .supportedDevOp = OVS_TRANSACTION_DEV_OP,
236       .validateDpIndex = TRUE
237     },
238 };
239
240 NETLINK_FAMILY nlVportFamilyOps = {
241     .name     = OVS_VPORT_FAMILY,
242     .id       = OVS_WIN_NL_VPORT_FAMILY_ID,
243     .version  = OVS_VPORT_VERSION,
244     .maxAttr  = OVS_VPORT_ATTR_MAX,
245     .cmds     = nlVportFamilyCmdOps,
246     .opsCount = ARRAY_SIZE(nlVportFamilyCmdOps)
247 };
248
249 /* Netlink flow family. */
250
251 NETLINK_CMD nlFlowFamilyCmdOps[] = {
252     { .cmd              = OVS_FLOW_CMD_NEW,
253       .handler          = OvsFlowNlCmdHandler,
254       .supportedDevOp   = OVS_TRANSACTION_DEV_OP,
255       .validateDpIndex  = TRUE
256     },
257     { .cmd              = OVS_FLOW_CMD_SET,
258       .handler          = OvsFlowNlCmdHandler,
259       .supportedDevOp   = OVS_TRANSACTION_DEV_OP,
260       .validateDpIndex  = TRUE
261     },
262     { .cmd              = OVS_FLOW_CMD_DEL,
263       .handler          = OvsFlowNlCmdHandler,
264       .supportedDevOp   = OVS_TRANSACTION_DEV_OP,
265       .validateDpIndex  = TRUE
266     },
267     { .cmd              = OVS_FLOW_CMD_GET,
268       .handler          = OvsFlowNlGetCmdHandler,
269       .supportedDevOp   = OVS_TRANSACTION_DEV_OP |
270                           OVS_WRITE_DEV_OP | OVS_READ_DEV_OP,
271       .validateDpIndex  = TRUE
272     },
273 };
274
275 NETLINK_FAMILY nlFLowFamilyOps = {
276     .name     = OVS_FLOW_FAMILY,
277     .id       = OVS_WIN_NL_FLOW_FAMILY_ID,
278     .version  = OVS_FLOW_VERSION,
279     .maxAttr  = OVS_FLOW_ATTR_MAX,
280     .cmds     = nlFlowFamilyCmdOps,
281     .opsCount = ARRAY_SIZE(nlFlowFamilyCmdOps)
282 };
283
284 /* Netlink netdev family. */
285 NETLINK_CMD nlNetdevFamilyCmdOps[] = {
286     { .cmd = OVS_WIN_NETDEV_CMD_GET,
287       .handler = OvsGetNetdevCmdHandler,
288       .supportedDevOp = OVS_TRANSACTION_DEV_OP,
289       .validateDpIndex = FALSE
290     },
291 };
292
293 NETLINK_FAMILY nlNetdevFamilyOps = {
294     .name     = OVS_WIN_NETDEV_FAMILY,
295     .id       = OVS_WIN_NL_NETDEV_FAMILY_ID,
296     .version  = OVS_WIN_NETDEV_VERSION,
297     .maxAttr  = OVS_WIN_NETDEV_ATTR_MAX,
298     .cmds     = nlNetdevFamilyCmdOps,
299     .opsCount = ARRAY_SIZE(nlNetdevFamilyCmdOps)
300 };
301
302 static NTSTATUS MapIrpOutputBuffer(PIRP irp,
303                                    UINT32 bufferLength,
304                                    UINT32 requiredLength,
305                                    PVOID *buffer);
306 static NTSTATUS ValidateNetlinkCmd(UINT32 devOp,
307                                    POVS_OPEN_INSTANCE instance,
308                                    POVS_MESSAGE ovsMsg,
309                                    NETLINK_FAMILY *nlFamilyOps);
310 static NTSTATUS InvokeNetlinkCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
311                                         NETLINK_FAMILY *nlFamilyOps,
312                                         UINT32 *replyLen);
313
314 /* Handles to the device object for communication with userspace. */
315 NDIS_HANDLE gOvsDeviceHandle;
316 PDEVICE_OBJECT gOvsDeviceObject;
317
318 _Dispatch_type_(IRP_MJ_CREATE)
319 _Dispatch_type_(IRP_MJ_CLOSE)
320 DRIVER_DISPATCH OvsOpenCloseDevice;
321
322 _Dispatch_type_(IRP_MJ_CLEANUP)
323 DRIVER_DISPATCH OvsCleanupDevice;
324
325 _Dispatch_type_(IRP_MJ_DEVICE_CONTROL)
326 DRIVER_DISPATCH OvsDeviceControl;
327
328 #ifdef ALLOC_PRAGMA
329 #pragma alloc_text(INIT, OvsCreateDeviceObject)
330 #pragma alloc_text(PAGE, OvsOpenCloseDevice)
331 #pragma alloc_text(PAGE, OvsCleanupDevice)
332 #pragma alloc_text(PAGE, OvsDeviceControl)
333 #endif // ALLOC_PRAGMA
334
335 /*
336  * We might hit this limit easily since userspace opens a netlink descriptor for
337  * each thread, and at least one descriptor per vport. Revisit this later.
338  */
339 #define OVS_MAX_OPEN_INSTANCES 512
340 #define OVS_SYSTEM_DP_NAME     "ovs-system"
341
342 POVS_OPEN_INSTANCE ovsOpenInstanceArray[OVS_MAX_OPEN_INSTANCES];
343 UINT32 ovsNumberOfOpenInstances;
344 extern POVS_SWITCH_CONTEXT gOvsSwitchContext;
345
346 NDIS_SPIN_LOCK ovsCtrlLockObj;
347 PNDIS_SPIN_LOCK gOvsCtrlLock;
348
349 NTSTATUS
350 InitUserDumpState(POVS_OPEN_INSTANCE instance,
351                   POVS_MESSAGE ovsMsg)
352 {
353     /* Clear the dumpState from a previous dump sequence. */
354     ASSERT(instance->dumpState.ovsMsg == NULL);
355     ASSERT(ovsMsg);
356
357     instance->dumpState.ovsMsg =
358         (POVS_MESSAGE)OvsAllocateMemoryWithTag(sizeof(OVS_MESSAGE),
359                                                OVS_DATAPATH_POOL_TAG);
360     if (instance->dumpState.ovsMsg == NULL) {
361         return STATUS_NO_MEMORY;
362     }
363     RtlCopyMemory(instance->dumpState.ovsMsg, ovsMsg,
364                   sizeof *instance->dumpState.ovsMsg);
365     RtlZeroMemory(instance->dumpState.index,
366                   sizeof instance->dumpState.index);
367
368     return STATUS_SUCCESS;
369 }
370
371 VOID
372 FreeUserDumpState(POVS_OPEN_INSTANCE instance)
373 {
374     if (instance->dumpState.ovsMsg != NULL) {
375         OvsFreeMemoryWithTag(instance->dumpState.ovsMsg,
376                              OVS_DATAPATH_POOL_TAG);
377         RtlZeroMemory(&instance->dumpState, sizeof instance->dumpState);
378     }
379 }
380
381 VOID
382 OvsInit()
383 {
384     gOvsCtrlLock = &ovsCtrlLockObj;
385     NdisAllocateSpinLock(gOvsCtrlLock);
386     OvsInitEventQueue();
387 }
388
389 VOID
390 OvsCleanup()
391 {
392     OvsCleanupEventQueue();
393     if (gOvsCtrlLock) {
394         NdisFreeSpinLock(gOvsCtrlLock);
395         gOvsCtrlLock = NULL;
396     }
397 }
398
399 VOID
400 OvsAcquireCtrlLock()
401 {
402     NdisAcquireSpinLock(gOvsCtrlLock);
403 }
404
405 VOID
406 OvsReleaseCtrlLock()
407 {
408     NdisReleaseSpinLock(gOvsCtrlLock);
409 }
410
411
412 /*
413  * --------------------------------------------------------------------------
414  * Creates the communication device between user and kernel, and also
415  * initializes the data associated data structures.
416  * --------------------------------------------------------------------------
417  */
418 NDIS_STATUS
419 OvsCreateDeviceObject(NDIS_HANDLE ovsExtDriverHandle)
420 {
421     NDIS_STATUS status = NDIS_STATUS_SUCCESS;
422     UNICODE_STRING deviceName;
423     UNICODE_STRING symbolicDeviceName;
424     PDRIVER_DISPATCH dispatchTable[IRP_MJ_MAXIMUM_FUNCTION+1];
425     NDIS_DEVICE_OBJECT_ATTRIBUTES deviceAttributes;
426     OVS_LOG_TRACE("ovsExtDriverHandle: %p", ovsExtDriverHandle);
427
428     RtlZeroMemory(dispatchTable,
429                   (IRP_MJ_MAXIMUM_FUNCTION + 1) * sizeof (PDRIVER_DISPATCH));
430     dispatchTable[IRP_MJ_CREATE] = OvsOpenCloseDevice;
431     dispatchTable[IRP_MJ_CLOSE] = OvsOpenCloseDevice;
432     dispatchTable[IRP_MJ_CLEANUP] = OvsCleanupDevice;
433     dispatchTable[IRP_MJ_DEVICE_CONTROL] = OvsDeviceControl;
434
435     NdisInitUnicodeString(&deviceName, OVS_DEVICE_NAME_NT);
436     NdisInitUnicodeString(&symbolicDeviceName, OVS_DEVICE_NAME_DOS);
437
438     RtlZeroMemory(&deviceAttributes, sizeof (NDIS_DEVICE_OBJECT_ATTRIBUTES));
439
440     OVS_INIT_OBJECT_HEADER(&deviceAttributes.Header,
441                            NDIS_OBJECT_TYPE_DEVICE_OBJECT_ATTRIBUTES,
442                            NDIS_DEVICE_OBJECT_ATTRIBUTES_REVISION_1,
443                            sizeof (NDIS_DEVICE_OBJECT_ATTRIBUTES));
444
445     deviceAttributes.DeviceName = &deviceName;
446     deviceAttributes.SymbolicName = &symbolicDeviceName;
447     deviceAttributes.MajorFunctions = dispatchTable;
448     deviceAttributes.ExtensionSize = sizeof (OVS_DEVICE_EXTENSION);
449
450     status = NdisRegisterDeviceEx(ovsExtDriverHandle,
451                                   &deviceAttributes,
452                                   &gOvsDeviceObject,
453                                   &gOvsDeviceHandle);
454     if (status != NDIS_STATUS_SUCCESS) {
455         POVS_DEVICE_EXTENSION ovsExt =
456             (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(gOvsDeviceObject);
457         ASSERT(gOvsDeviceObject != NULL);
458         ASSERT(gOvsDeviceHandle != NULL);
459
460         if (ovsExt) {
461             ovsExt->numberOpenInstance = 0;
462         }
463     } else {
464         OvsRegisterSystemProvider((PVOID)gOvsDeviceObject);
465     }
466
467     OVS_LOG_TRACE("DeviceObject: %p", gOvsDeviceObject);
468     return status;
469 }
470
471
472 VOID
473 OvsDeleteDeviceObject()
474 {
475     if (gOvsDeviceHandle) {
476 #ifdef DBG
477         POVS_DEVICE_EXTENSION ovsExt = (POVS_DEVICE_EXTENSION)
478                     NdisGetDeviceReservedExtension(gOvsDeviceObject);
479         if (ovsExt) {
480             ASSERT(ovsExt->numberOpenInstance == 0);
481         }
482 #endif
483
484         ASSERT(gOvsDeviceObject);
485         NdisDeregisterDeviceEx(gOvsDeviceHandle);
486         gOvsDeviceHandle = NULL;
487         gOvsDeviceObject = NULL;
488
489         OvsUnregisterSystemProvider();
490     }
491 }
492
493 POVS_OPEN_INSTANCE
494 OvsGetOpenInstance(PFILE_OBJECT fileObject,
495                    UINT32 dpNo)
496 {
497     POVS_OPEN_INSTANCE instance = (POVS_OPEN_INSTANCE)fileObject->FsContext;
498     ASSERT(instance);
499     ASSERT(instance->fileObject == fileObject);
500     if (gOvsSwitchContext->dpNo != dpNo) {
501         return NULL;
502     }
503     return instance;
504 }
505
506
507 POVS_OPEN_INSTANCE
508 OvsFindOpenInstance(PFILE_OBJECT fileObject)
509 {
510     UINT32 i, j;
511     for (i = 0, j = 0; i < OVS_MAX_OPEN_INSTANCES &&
512                        j < ovsNumberOfOpenInstances; i++) {
513         if (ovsOpenInstanceArray[i]) {
514             if (ovsOpenInstanceArray[i]->fileObject == fileObject) {
515                 return ovsOpenInstanceArray[i];
516             }
517             j++;
518         }
519     }
520     return NULL;
521 }
522
523 NTSTATUS
524 OvsAddOpenInstance(POVS_DEVICE_EXTENSION ovsExt,
525                    PFILE_OBJECT fileObject)
526 {
527     POVS_OPEN_INSTANCE instance =
528         (POVS_OPEN_INSTANCE)OvsAllocateMemoryWithTag(sizeof(OVS_OPEN_INSTANCE),
529                                                      OVS_DATAPATH_POOL_TAG);
530     UINT32 i;
531
532     if (instance == NULL) {
533         return STATUS_NO_MEMORY;
534     }
535     OvsAcquireCtrlLock();
536     ASSERT(OvsFindOpenInstance(fileObject) == NULL);
537
538     if (ovsNumberOfOpenInstances >= OVS_MAX_OPEN_INSTANCES) {
539         OvsReleaseCtrlLock();
540         OvsFreeMemoryWithTag(instance, OVS_DATAPATH_POOL_TAG);
541         return STATUS_INSUFFICIENT_RESOURCES;
542     }
543     RtlZeroMemory(instance, sizeof (OVS_OPEN_INSTANCE));
544
545     for (i = 0; i < OVS_MAX_OPEN_INSTANCES; i++) {
546         if (ovsOpenInstanceArray[i] == NULL) {
547             ovsOpenInstanceArray[i] = instance;
548             ovsNumberOfOpenInstances++;
549             instance->cookie = i;
550             break;
551         }
552     }
553     ASSERT(i < OVS_MAX_OPEN_INSTANCES);
554     instance->fileObject = fileObject;
555     ASSERT(fileObject->FsContext == NULL);
556     instance->pid = (UINT32)InterlockedIncrement((LONG volatile *)&ovsExt->pidCount);
557     if (instance->pid == 0) {
558         /* XXX: check for rollover. */
559     }
560     fileObject->FsContext = instance;
561     OvsReleaseCtrlLock();
562     return STATUS_SUCCESS;
563 }
564
565 static VOID
566 OvsCleanupOpenInstance(PFILE_OBJECT fileObject)
567 {
568     POVS_OPEN_INSTANCE instance = (POVS_OPEN_INSTANCE)fileObject->FsContext;
569     ASSERT(instance);
570     ASSERT(fileObject == instance->fileObject);
571     OvsCleanupEvent(instance);
572     OvsCleanupPacketQueue(instance);
573 }
574
575 VOID
576 OvsRemoveOpenInstance(PFILE_OBJECT fileObject)
577 {
578     POVS_OPEN_INSTANCE instance;
579     ASSERT(fileObject->FsContext);
580     instance = (POVS_OPEN_INSTANCE)fileObject->FsContext;
581     ASSERT(instance->cookie < OVS_MAX_OPEN_INSTANCES);
582
583     OvsAcquireCtrlLock();
584     fileObject->FsContext = NULL;
585     ASSERT(ovsOpenInstanceArray[instance->cookie] == instance);
586     ovsOpenInstanceArray[instance->cookie] = NULL;
587     ovsNumberOfOpenInstances--;
588     OvsReleaseCtrlLock();
589     ASSERT(instance->eventQueue == NULL);
590     ASSERT (instance->packetQueue == NULL);
591     FreeUserDumpState(instance);
592     OvsFreeMemoryWithTag(instance, OVS_DATAPATH_POOL_TAG);
593 }
594
595 NTSTATUS
596 OvsCompleteIrpRequest(PIRP irp,
597                       ULONG_PTR infoPtr,
598                       NTSTATUS status)
599 {
600     irp->IoStatus.Information = infoPtr;
601     irp->IoStatus.Status = status;
602     IoCompleteRequest(irp, IO_NO_INCREMENT);
603     return status;
604 }
605
606
607 NTSTATUS
608 OvsOpenCloseDevice(PDEVICE_OBJECT deviceObject,
609                    PIRP irp)
610 {
611     PIO_STACK_LOCATION irpSp;
612     NTSTATUS status = STATUS_SUCCESS;
613     PFILE_OBJECT fileObject;
614     POVS_DEVICE_EXTENSION ovsExt =
615         (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(deviceObject);
616
617     ASSERT(deviceObject == gOvsDeviceObject);
618     ASSERT(ovsExt != NULL);
619
620     irpSp = IoGetCurrentIrpStackLocation(irp);
621     fileObject = irpSp->FileObject;
622     OVS_LOG_TRACE("DeviceObject: %p, fileObject:%p, instance: %u",
623                   deviceObject, fileObject,
624                   ovsExt->numberOpenInstance);
625
626     switch (irpSp->MajorFunction) {
627     case IRP_MJ_CREATE:
628         status = OvsAddOpenInstance(ovsExt, fileObject);
629         if (STATUS_SUCCESS == status) {
630             InterlockedIncrement((LONG volatile *)&ovsExt->numberOpenInstance);
631         }
632         break;
633     case IRP_MJ_CLOSE:
634         ASSERT(ovsExt->numberOpenInstance > 0);
635         OvsRemoveOpenInstance(fileObject);
636         InterlockedDecrement((LONG volatile *)&ovsExt->numberOpenInstance);
637         break;
638     default:
639         ASSERT(0);
640     }
641     return OvsCompleteIrpRequest(irp, (ULONG_PTR)0, status);
642 }
643
644 _Use_decl_annotations_
645 NTSTATUS
646 OvsCleanupDevice(PDEVICE_OBJECT deviceObject,
647                  PIRP irp)
648 {
649
650     PIO_STACK_LOCATION irpSp;
651     PFILE_OBJECT fileObject;
652
653     NTSTATUS status = STATUS_SUCCESS;
654 #ifdef DBG
655     POVS_DEVICE_EXTENSION ovsExt =
656         (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(deviceObject);
657     if (ovsExt) {
658         ASSERT(ovsExt->numberOpenInstance > 0);
659     }
660 #else
661     UNREFERENCED_PARAMETER(deviceObject);
662 #endif
663     ASSERT(deviceObject == gOvsDeviceObject);
664     irpSp = IoGetCurrentIrpStackLocation(irp);
665     fileObject = irpSp->FileObject;
666
667     ASSERT(irpSp->MajorFunction == IRP_MJ_CLEANUP);
668
669     OvsCleanupOpenInstance(fileObject);
670
671     return OvsCompleteIrpRequest(irp, (ULONG_PTR)0, status);
672 }
673
674 /*
675  * --------------------------------------------------------------------------
676  * IOCTL function handler for the device.
677  * --------------------------------------------------------------------------
678  */
679 NTSTATUS
680 OvsDeviceControl(PDEVICE_OBJECT deviceObject,
681                  PIRP irp)
682 {
683     PIO_STACK_LOCATION irpSp;
684     NTSTATUS status = STATUS_SUCCESS;
685     PFILE_OBJECT fileObject;
686     PVOID inputBuffer = NULL;
687     PVOID outputBuffer = NULL;
688     UINT32 inputBufferLen, outputBufferLen;
689     UINT32 code, replyLen = 0;
690     POVS_OPEN_INSTANCE instance;
691     UINT32 devOp;
692     OVS_MESSAGE ovsMsgReadOp;
693     POVS_MESSAGE ovsMsg;
694     NETLINK_FAMILY *nlFamilyOps;
695     OVS_USER_PARAMS_CONTEXT usrParamsCtx;
696
697 #ifdef DBG
698     POVS_DEVICE_EXTENSION ovsExt =
699         (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(deviceObject);
700     ASSERT(deviceObject == gOvsDeviceObject);
701     ASSERT(ovsExt);
702     ASSERT(ovsExt->numberOpenInstance > 0);
703 #else
704     UNREFERENCED_PARAMETER(deviceObject);
705 #endif
706
707     irpSp = IoGetCurrentIrpStackLocation(irp);
708
709     ASSERT(irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL);
710     ASSERT(irpSp->FileObject != NULL);
711
712     fileObject = irpSp->FileObject;
713     instance = (POVS_OPEN_INSTANCE)fileObject->FsContext;
714     code = irpSp->Parameters.DeviceIoControl.IoControlCode;
715     inputBufferLen = irpSp->Parameters.DeviceIoControl.InputBufferLength;
716     outputBufferLen = irpSp->Parameters.DeviceIoControl.OutputBufferLength;
717     inputBuffer = irp->AssociatedIrp.SystemBuffer;
718
719     /* Check if the extension is enabled. */
720     if (NULL == gOvsSwitchContext) {
721         status = STATUS_NOT_FOUND;
722         goto exit;
723     }
724
725     if (!OvsAcquireSwitchContext()) {
726         status = STATUS_NOT_FOUND;
727         goto exit;
728     }
729
730     /*
731      * Validate the input/output buffer arguments depending on the type of the
732      * operation.
733      */
734     switch (code) {
735     case OVS_IOCTL_GET_PID:
736         /* Both input buffer and output buffer use the same location. */
737         outputBuffer = irp->AssociatedIrp.SystemBuffer;
738         if (outputBufferLen != 0) {
739             InitUserParamsCtx(irp, instance, 0, NULL,
740                               inputBuffer, inputBufferLen,
741                               outputBuffer, outputBufferLen,
742                               &usrParamsCtx);
743
744             ASSERT(outputBuffer);
745         } else {
746             status = STATUS_NDIS_INVALID_LENGTH;
747             goto done;
748         }
749
750         status = OvsGetPidHandler(&usrParamsCtx, &replyLen);
751         goto done;
752
753     case OVS_IOCTL_TRANSACT:
754         /* Both input buffer and output buffer are mandatory. */
755         if (outputBufferLen != 0) {
756             status = MapIrpOutputBuffer(irp, outputBufferLen,
757                                         sizeof *ovsMsg, &outputBuffer);
758             if (status != STATUS_SUCCESS) {
759                 goto done;
760             }
761             ASSERT(outputBuffer);
762         } else {
763             status = STATUS_NDIS_INVALID_LENGTH;
764             goto done;
765         }
766
767         if (inputBufferLen < sizeof (*ovsMsg)) {
768             status = STATUS_NDIS_INVALID_LENGTH;
769             goto done;
770         }
771
772         ovsMsg = inputBuffer;
773         devOp = OVS_TRANSACTION_DEV_OP;
774         break;
775
776     case OVS_IOCTL_READ_EVENT:
777     case OVS_IOCTL_READ_PACKET:
778         /*
779          * Output buffer is mandatory. These IOCTLs are used to read events and
780          * packets respectively. It is convenient to have separate ioctls.
781          */
782         if (outputBufferLen != 0) {
783             status = MapIrpOutputBuffer(irp, outputBufferLen,
784                                         sizeof *ovsMsg, &outputBuffer);
785             if (status != STATUS_SUCCESS) {
786                 goto done;
787             }
788             ASSERT(outputBuffer);
789         } else {
790             status = STATUS_NDIS_INVALID_LENGTH;
791             goto done;
792         }
793         inputBuffer = NULL;
794         inputBufferLen = 0;
795
796         ovsMsg = &ovsMsgReadOp;
797         RtlZeroMemory(ovsMsg, sizeof *ovsMsg);
798         ovsMsg->nlMsg.nlmsgLen = sizeof *ovsMsg;
799         ovsMsg->nlMsg.nlmsgType = nlControlFamilyOps.id;
800         ovsMsg->nlMsg.nlmsgPid = instance->pid;
801
802         /* An "artificial" command so we can use NL family function table*/
803         ovsMsg->genlMsg.cmd = (code == OVS_IOCTL_READ_EVENT) ?
804                               OVS_CTRL_CMD_EVENT_NOTIFY :
805                               OVS_CTRL_CMD_READ_NOTIFY;
806         ovsMsg->genlMsg.version = nlControlFamilyOps.version;
807
808         devOp = OVS_READ_DEV_OP;
809         break;
810
811     case OVS_IOCTL_READ:
812         /* Output buffer is mandatory. */
813         if (outputBufferLen != 0) {
814             status = MapIrpOutputBuffer(irp, outputBufferLen,
815                                         sizeof *ovsMsg, &outputBuffer);
816             if (status != STATUS_SUCCESS) {
817                 goto done;
818             }
819             ASSERT(outputBuffer);
820         } else {
821             status = STATUS_NDIS_INVALID_LENGTH;
822             goto done;
823         }
824
825         /*
826          * Operate in the mode that read ioctl is similar to ReadFile(). This
827          * might change as the userspace code gets implemented.
828          */
829         inputBuffer = NULL;
830         inputBufferLen = 0;
831
832         /*
833          * For implementing read (ioctl or otherwise), we need to store some
834          * state in the instance to indicate the command that started the dump
835          * operation. The state can setup 'ovsMsgReadOp' appropriately. Note
836          * that 'ovsMsgReadOp' is needed only in this function to call into the
837          * appropriate handler. The handler itself can access the state in the
838          * instance.
839          *
840          * In the absence of a dump start, return 0 bytes.
841          */
842         if (instance->dumpState.ovsMsg == NULL) {
843             replyLen = 0;
844             status = STATUS_SUCCESS;
845             goto done;
846         }
847         RtlCopyMemory(&ovsMsgReadOp, instance->dumpState.ovsMsg,
848                       sizeof (ovsMsgReadOp));
849
850         /* Create an NL message for consumption. */
851         ovsMsg = &ovsMsgReadOp;
852         devOp = OVS_READ_DEV_OP;
853
854         break;
855
856     case OVS_IOCTL_WRITE:
857         /* Input buffer is mandatory. */
858         if (inputBufferLen < sizeof (*ovsMsg)) {
859             status = STATUS_NDIS_INVALID_LENGTH;
860             goto done;
861         }
862
863         ovsMsg = inputBuffer;
864         devOp = OVS_WRITE_DEV_OP;
865         break;
866
867     default:
868         status = STATUS_INVALID_DEVICE_REQUEST;
869         goto done;
870     }
871
872     ASSERT(ovsMsg);
873     switch (ovsMsg->nlMsg.nlmsgType) {
874     case OVS_WIN_NL_CTRL_FAMILY_ID:
875         nlFamilyOps = &nlControlFamilyOps;
876         break;
877     case OVS_WIN_NL_DATAPATH_FAMILY_ID:
878         nlFamilyOps = &nlDatapathFamilyOps;
879         break;
880     case OVS_WIN_NL_FLOW_FAMILY_ID:
881          nlFamilyOps = &nlFLowFamilyOps;
882          break;
883     case OVS_WIN_NL_PACKET_FAMILY_ID:
884          nlFamilyOps = &nlPacketFamilyOps;
885          break;
886     case OVS_WIN_NL_VPORT_FAMILY_ID:
887         nlFamilyOps = &nlVportFamilyOps;
888         break;
889     case OVS_WIN_NL_NETDEV_FAMILY_ID:
890         nlFamilyOps = &nlNetdevFamilyOps;
891         break;
892     default:
893         status = STATUS_INVALID_PARAMETER;
894         goto done;
895     }
896
897     /*
898      * For read operation, avoid duplicate validation since 'ovsMsg' is either
899      * "artificial" or was copied from a previously validated 'ovsMsg'.
900      */
901     if (devOp != OVS_READ_DEV_OP) {
902         status = ValidateNetlinkCmd(devOp, instance, ovsMsg, nlFamilyOps);
903         if (status != STATUS_SUCCESS) {
904             goto done;
905         }
906     }
907
908     InitUserParamsCtx(irp, instance, devOp, ovsMsg,
909                       inputBuffer, inputBufferLen,
910                       outputBuffer, outputBufferLen,
911                       &usrParamsCtx);
912
913     status = InvokeNetlinkCmdHandler(&usrParamsCtx, nlFamilyOps, &replyLen);
914
915 done:
916     OvsReleaseSwitchContext(gOvsSwitchContext);
917
918 exit:
919     /* Should not complete a pending IRP unless proceesing is completed. */
920     if (status == STATUS_PENDING) {
921         return status;
922     }
923     return OvsCompleteIrpRequest(irp, (ULONG_PTR)replyLen, status);
924 }
925
926
927 /*
928  * --------------------------------------------------------------------------
929  * Function to validate a netlink command. Only certain combinations of
930  * (device operation, netlink family, command) are valid.
931  * --------------------------------------------------------------------------
932  */
933 static NTSTATUS
934 ValidateNetlinkCmd(UINT32 devOp,
935                    POVS_OPEN_INSTANCE instance,
936                    POVS_MESSAGE ovsMsg,
937                    NETLINK_FAMILY *nlFamilyOps)
938 {
939     NTSTATUS status = STATUS_INVALID_PARAMETER;
940     UINT16 i;
941
942     for (i = 0; i < nlFamilyOps->opsCount; i++) {
943         if (nlFamilyOps->cmds[i].cmd == ovsMsg->genlMsg.cmd) {
944             /* Validate if the command is valid for the device operation. */
945             if ((devOp & nlFamilyOps->cmds[i].supportedDevOp) == 0) {
946                 status = STATUS_INVALID_PARAMETER;
947                 goto done;
948             }
949
950             /* Validate the version. */
951             if (nlFamilyOps->version > ovsMsg->genlMsg.version) {
952                 status = STATUS_INVALID_PARAMETER;
953                 goto done;
954             }
955
956             /* Validate the DP for commands that require a DP. */
957             if (nlFamilyOps->cmds[i].validateDpIndex == TRUE) {
958                 if (ovsMsg->ovsHdr.dp_ifindex !=
959                                           (INT)gOvsSwitchContext->dpNo) {
960                     status = STATUS_INVALID_PARAMETER;
961                     goto done;
962                 }
963             }
964
965             /* Validate the PID. */
966             if (ovsMsg->nlMsg.nlmsgPid != instance->pid) {
967                 status = STATUS_INVALID_PARAMETER;
968                 goto done;
969             }
970
971             status = STATUS_SUCCESS;
972             break;
973         }
974     }
975
976 done:
977     return status;
978 }
979
980 /*
981  * --------------------------------------------------------------------------
982  * Function to invoke the netlink command handler. The function also stores
983  * the return value of the handler function to construct a 'NL_ERROR' message,
984  * and in turn returns success to the caller.
985  * --------------------------------------------------------------------------
986  */
987 static NTSTATUS
988 InvokeNetlinkCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
989                         NETLINK_FAMILY *nlFamilyOps,
990                         UINT32 *replyLen)
991 {
992     NTSTATUS status = STATUS_INVALID_PARAMETER;
993     UINT16 i;
994
995     for (i = 0; i < nlFamilyOps->opsCount; i++) {
996         if (nlFamilyOps->cmds[i].cmd == usrParamsCtx->ovsMsg->genlMsg.cmd) {
997             NetlinkCmdHandler *handler = nlFamilyOps->cmds[i].handler;
998             ASSERT(handler);
999             if (handler) {
1000                 status = handler(usrParamsCtx, replyLen);
1001             }
1002             break;
1003         }
1004     }
1005
1006     /*
1007      * Netlink socket semantics dictate that the return value of the netlink
1008      * function should be an error ONLY under fatal conditions. If the message
1009      * made it all the way to the handler function, it is not a fatal condition.
1010      * Absorb the error returned by the handler function into a 'struct
1011      * NL_ERROR' and populate the 'output buffer' to return to userspace.
1012      *
1013      * This behavior is obviously applicable only to netlink commands that
1014      * specify an 'output buffer'. For other commands, we return the error as
1015      * is.
1016      *
1017      * 'STATUS_PENDING' is a special return value and userspace is equipped to
1018      * handle it.
1019      */
1020     if (status != STATUS_SUCCESS && status != STATUS_PENDING) {
1021         if (usrParamsCtx->devOp != OVS_WRITE_DEV_OP && *replyLen == 0) {
1022             NL_ERROR nlError = NlMapStatusToNlErr(status);
1023             OVS_MESSAGE msgInTmp = { 0 };
1024             POVS_MESSAGE msgIn = NULL;
1025             POVS_MESSAGE_ERROR msgError = (POVS_MESSAGE_ERROR)
1026                 usrParamsCtx->outputBuffer;
1027
1028             if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_CTRL_CMD_EVENT_NOTIFY ||
1029                 usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_CTRL_CMD_READ_NOTIFY) {
1030                 /* There's no input buffer associated with such requests. */
1031                 NL_BUFFER nlBuffer;
1032                 msgIn = &msgInTmp;
1033                 NlBufInit(&nlBuffer, (PCHAR)msgIn, sizeof *msgIn);
1034                 NlFillNlHdr(&nlBuffer, nlFamilyOps->id, 0, 0,
1035                             usrParamsCtx->ovsInstance->pid);
1036             } else {
1037                 msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1038             }
1039
1040             ASSERT(msgIn);
1041             ASSERT(msgError);
1042             NlBuildErrorMsg(msgIn, msgError, nlError);
1043             *replyLen = msgError->nlMsg.nlmsgLen;
1044         }
1045
1046         if (*replyLen != 0) {
1047             status = STATUS_SUCCESS;
1048         }
1049     }
1050
1051 #ifdef DBG
1052     if (usrParamsCtx->devOp != OVS_WRITE_DEV_OP) {
1053         ASSERT(status == STATUS_PENDING || *replyLen != 0 || status == STATUS_SUCCESS);
1054     }
1055 #endif
1056
1057     return status;
1058 }
1059
1060 /*
1061  * --------------------------------------------------------------------------
1062  *  Handler for 'OVS_IOCTL_GET_PID'.
1063  *
1064  *  Each handle on the device is assigned a unique PID when the handle is
1065  *  created. This function passes the PID to userspace using METHOD_BUFFERED
1066  *  method.
1067  * --------------------------------------------------------------------------
1068  */
1069 static NTSTATUS
1070 OvsGetPidHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1071                  UINT32 *replyLen)
1072 {
1073     NTSTATUS status = STATUS_SUCCESS;
1074     PUINT32 msgOut = (PUINT32)usrParamsCtx->outputBuffer;
1075
1076     if (usrParamsCtx->outputLength >= sizeof *msgOut) {
1077         POVS_OPEN_INSTANCE instance =
1078             (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1079
1080         RtlZeroMemory(msgOut, sizeof *msgOut);
1081         RtlCopyMemory(msgOut, &instance->pid, sizeof(*msgOut));
1082         *replyLen = sizeof *msgOut;
1083     } else {
1084         *replyLen = sizeof *msgOut;
1085         status = STATUS_NDIS_INVALID_LENGTH;
1086     }
1087
1088     return status;
1089 }
1090
1091 /*
1092  * --------------------------------------------------------------------------
1093  * Utility function to fill up information about the datapath in a reply to
1094  * userspace.
1095  * --------------------------------------------------------------------------
1096  */
1097 static NTSTATUS
1098 OvsDpFillInfo(POVS_SWITCH_CONTEXT ovsSwitchContext,
1099               POVS_MESSAGE msgIn,
1100               PNL_BUFFER nlBuf)
1101 {
1102     BOOLEAN writeOk;
1103     OVS_MESSAGE msgOutTmp;
1104     OVS_DATAPATH *datapath = &ovsSwitchContext->datapath;
1105     PNL_MSG_HDR nlMsg;
1106
1107     ASSERT(NlBufAt(nlBuf, 0, 0) != 0 && NlBufRemLen(nlBuf) >= sizeof *msgIn);
1108
1109     msgOutTmp.nlMsg.nlmsgType = OVS_WIN_NL_DATAPATH_FAMILY_ID;
1110     msgOutTmp.nlMsg.nlmsgFlags = 0;  /* XXX: ? */
1111     msgOutTmp.nlMsg.nlmsgSeq = msgIn->nlMsg.nlmsgSeq;
1112     msgOutTmp.nlMsg.nlmsgPid = msgIn->nlMsg.nlmsgPid;
1113
1114     msgOutTmp.genlMsg.cmd = OVS_DP_CMD_GET;
1115     msgOutTmp.genlMsg.version = nlDatapathFamilyOps.version;
1116     msgOutTmp.genlMsg.reserved = 0;
1117
1118     msgOutTmp.ovsHdr.dp_ifindex = ovsSwitchContext->dpNo;
1119
1120     writeOk = NlMsgPutHead(nlBuf, (PCHAR)&msgOutTmp, sizeof msgOutTmp);
1121     if (writeOk) {
1122         writeOk = NlMsgPutTailString(nlBuf, OVS_DP_ATTR_NAME,
1123                                      OVS_SYSTEM_DP_NAME);
1124     }
1125     if (writeOk) {
1126         OVS_DP_STATS dpStats;
1127
1128         dpStats.n_hit = datapath->hits;
1129         dpStats.n_missed = datapath->misses;
1130         dpStats.n_lost = datapath->lost;
1131         dpStats.n_flows = datapath->nFlows;
1132         writeOk = NlMsgPutTailUnspec(nlBuf, OVS_DP_ATTR_STATS,
1133                                      (PCHAR)&dpStats, sizeof dpStats);
1134     }
1135     nlMsg = (PNL_MSG_HDR)NlBufAt(nlBuf, 0, 0);
1136     nlMsg->nlmsgLen = NlBufSize(nlBuf);
1137
1138     return writeOk ? STATUS_SUCCESS : STATUS_INVALID_BUFFER_SIZE;
1139 }
1140
1141 /*
1142  * --------------------------------------------------------------------------
1143  * Handler for queueing an IRP used for event notification. The IRP is
1144  * completed when a port state changes. STATUS_PENDING is returned on
1145  * success. User mode keep a pending IRP at all times.
1146  * --------------------------------------------------------------------------
1147  */
1148 static NTSTATUS
1149 OvsPendEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1150                        UINT32 *replyLen)
1151 {
1152     NDIS_STATUS status;
1153
1154     UNREFERENCED_PARAMETER(replyLen);
1155
1156     POVS_OPEN_INSTANCE instance =
1157         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1158     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1159     OVS_EVENT_POLL poll;
1160
1161     poll.dpNo = msgIn->ovsHdr.dp_ifindex;
1162     status = OvsWaitEventIoctl(usrParamsCtx->irp, instance->fileObject,
1163                                &poll, sizeof poll);
1164     return status;
1165 }
1166
1167 /*
1168  * --------------------------------------------------------------------------
1169  *  Handler for the subscription for the event queue
1170  * --------------------------------------------------------------------------
1171  */
1172 static NTSTATUS
1173 OvsSubscribeEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1174                             UINT32 *replyLen)
1175 {
1176     NDIS_STATUS status;
1177     OVS_EVENT_SUBSCRIBE request;
1178     BOOLEAN rc;
1179     UINT8 join;
1180     PNL_ATTR attrs[2];
1181     const NL_POLICY policy[] =  {
1182         [OVS_NL_ATTR_MCAST_GRP] = {.type = NL_A_U32 },
1183         [OVS_NL_ATTR_MCAST_JOIN] = {.type = NL_A_U8 },
1184         };
1185
1186     UNREFERENCED_PARAMETER(replyLen);
1187
1188     POVS_OPEN_INSTANCE instance =
1189         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1190     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1191
1192     rc = NlAttrParse(&msgIn->nlMsg, sizeof (*msgIn),
1193          NlMsgAttrsLen((PNL_MSG_HDR)msgIn), policy, ARRAY_SIZE(policy),
1194                        attrs, ARRAY_SIZE(attrs));
1195     if (!rc) {
1196         status = STATUS_INVALID_PARAMETER;
1197         goto done;
1198     }
1199
1200     /* XXX Ignore the MC group for now */
1201     join = NlAttrGetU8(attrs[OVS_NL_ATTR_MCAST_JOIN]);
1202     request.dpNo = msgIn->ovsHdr.dp_ifindex;
1203     request.subscribe = join;
1204     request.mask = OVS_EVENT_MASK_ALL;
1205
1206     status = OvsSubscribeEventIoctl(instance->fileObject, &request,
1207                                     sizeof request);
1208 done:
1209     return status;
1210 }
1211
1212 /*
1213  * --------------------------------------------------------------------------
1214  *  Command Handler for 'OVS_DP_CMD_NEW'.
1215  * --------------------------------------------------------------------------
1216  */
1217 static NTSTATUS
1218 OvsNewDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1219                    UINT32 *replyLen)
1220 {
1221     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1222 }
1223
1224 /*
1225  * --------------------------------------------------------------------------
1226  *  Command Handler for 'OVS_DP_CMD_GET'.
1227  *
1228  *  The function handles both the dump based as well as the transaction based
1229  *  'OVS_DP_CMD_GET' command. In the dump command, it handles the initial
1230  *  call to setup dump state, as well as subsequent calls to continue dumping
1231  *  data.
1232  * --------------------------------------------------------------------------
1233  */
1234 static NTSTATUS
1235 OvsGetDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1236                    UINT32 *replyLen)
1237 {
1238     if (usrParamsCtx->devOp == OVS_TRANSACTION_DEV_OP) {
1239         return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1240     } else {
1241         return HandleGetDpDump(usrParamsCtx, replyLen);
1242     }
1243 }
1244
1245 /*
1246  * --------------------------------------------------------------------------
1247  *  Function for handling the transaction based 'OVS_DP_CMD_GET' command.
1248  * --------------------------------------------------------------------------
1249  */
1250 static NTSTATUS
1251 HandleGetDpTransaction(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1252                        UINT32 *replyLen)
1253 {
1254     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1255 }
1256
1257
1258 /*
1259  * --------------------------------------------------------------------------
1260  *  Function for handling the dump-based 'OVS_DP_CMD_GET' command.
1261  * --------------------------------------------------------------------------
1262  */
1263 static NTSTATUS
1264 HandleGetDpDump(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1265                 UINT32 *replyLen)
1266 {
1267     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1268     POVS_OPEN_INSTANCE instance =
1269         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1270
1271     if (usrParamsCtx->devOp == OVS_WRITE_DEV_OP) {
1272         *replyLen = 0;
1273         OvsSetupDumpStart(usrParamsCtx);
1274     } else {
1275         NL_BUFFER nlBuf;
1276         NTSTATUS status;
1277         POVS_MESSAGE msgIn = instance->dumpState.ovsMsg;
1278
1279         ASSERT(usrParamsCtx->devOp == OVS_READ_DEV_OP);
1280
1281         if (instance->dumpState.ovsMsg == NULL) {
1282             ASSERT(FALSE);
1283             return STATUS_INVALID_DEVICE_STATE;
1284         }
1285
1286         /* Dump state must have been deleted after previous dump operation. */
1287         ASSERT(instance->dumpState.index[0] == 0);
1288
1289         /* Output buffer has been validated while validating read dev op. */
1290         ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1291
1292         NlBufInit(&nlBuf, usrParamsCtx->outputBuffer,
1293                   usrParamsCtx->outputLength);
1294
1295         status = OvsDpFillInfo(gOvsSwitchContext, msgIn, &nlBuf);
1296
1297         if (status != STATUS_SUCCESS) {
1298             *replyLen = 0;
1299             FreeUserDumpState(instance);
1300             return status;
1301         }
1302
1303         /* Increment the dump index. */
1304         instance->dumpState.index[0] = 1;
1305         *replyLen = msgOut->nlMsg.nlmsgLen;
1306
1307         /* Free up the dump state, since there's no more data to continue. */
1308         FreeUserDumpState(instance);
1309     }
1310
1311     return STATUS_SUCCESS;
1312 }
1313
1314
1315 /*
1316  * --------------------------------------------------------------------------
1317  *  Command Handler for 'OVS_DP_CMD_SET'.
1318  * --------------------------------------------------------------------------
1319  */
1320 static NTSTATUS
1321 OvsSetDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1322                    UINT32 *replyLen)
1323 {
1324     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1325 }
1326
1327 /*
1328  * --------------------------------------------------------------------------
1329  *  Function for handling transaction based 'OVS_DP_CMD_NEW', 'OVS_DP_CMD_GET'
1330  *  and 'OVS_DP_CMD_SET' commands.
1331  *
1332  * 'OVS_DP_CMD_NEW' is implemented to keep userspace code happy. Creation of a
1333  * new datapath is not supported currently.
1334  * --------------------------------------------------------------------------
1335  */
1336 static NTSTATUS
1337 HandleDpTransactionCommon(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1338                           UINT32 *replyLen)
1339 {
1340     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1341     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1342     NTSTATUS status = STATUS_SUCCESS;
1343     NL_BUFFER nlBuf;
1344     NL_ERROR nlError = NL_ERROR_SUCCESS;
1345     static const NL_POLICY ovsDatapathSetPolicy[] = {
1346         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .maxLen = IFNAMSIZ },
1347         [OVS_DP_ATTR_UPCALL_PID] = { .type = NL_A_U32, .optional = TRUE },
1348         [OVS_DP_ATTR_USER_FEATURES] = { .type = NL_A_U32, .optional = TRUE },
1349     };
1350     PNL_ATTR dpAttrs[ARRAY_SIZE(ovsDatapathSetPolicy)];
1351
1352     UNREFERENCED_PARAMETER(msgOut);
1353
1354     /* input buffer has been validated while validating write dev op. */
1355     ASSERT(msgIn != NULL && usrParamsCtx->inputLength >= sizeof *msgIn);
1356
1357     /* Parse any attributes in the request. */
1358     if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_SET ||
1359         usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_NEW) {
1360         if (!NlAttrParse((PNL_MSG_HDR)msgIn,
1361                         NLMSG_HDRLEN + GENL_HDRLEN + OVS_HDRLEN,
1362                         NlMsgAttrsLen((PNL_MSG_HDR)msgIn),
1363                         ovsDatapathSetPolicy,
1364                         ARRAY_SIZE(ovsDatapathSetPolicy),
1365                         dpAttrs, ARRAY_SIZE(dpAttrs))) {
1366             return STATUS_INVALID_PARAMETER;
1367         }
1368
1369         /*
1370         * XXX: Not clear at this stage if there's any role for the
1371         * OVS_DP_ATTR_UPCALL_PID and OVS_DP_ATTR_USER_FEATURES attributes passed
1372         * from userspace.
1373         */
1374
1375     } else {
1376         RtlZeroMemory(dpAttrs, sizeof dpAttrs);
1377     }
1378
1379     /* Output buffer has been validated while validating transact dev op. */
1380     ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1381
1382     NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength);
1383
1384     if (dpAttrs[OVS_DP_ATTR_NAME] != NULL) {
1385         if (!OvsCompareString(NlAttrGet(dpAttrs[OVS_DP_ATTR_NAME]),
1386                               OVS_SYSTEM_DP_NAME)) {
1387
1388             /* Creation of new datapaths is not supported. */
1389             if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_SET) {
1390                 nlError = NL_ERROR_NOTSUPP;
1391                 goto cleanup;
1392             }
1393
1394             nlError = NL_ERROR_NODEV;
1395             goto cleanup;
1396         }
1397     } else if ((UINT32)msgIn->ovsHdr.dp_ifindex != gOvsSwitchContext->dpNo) {
1398         nlError = NL_ERROR_NODEV;
1399         goto cleanup;
1400     }
1401
1402     if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_NEW) {
1403         nlError = NL_ERROR_EXIST;
1404         goto cleanup;
1405     }
1406
1407     status = OvsDpFillInfo(gOvsSwitchContext, msgIn, &nlBuf);
1408
1409     *replyLen = NlBufSize(&nlBuf);
1410
1411 cleanup:
1412     if (nlError != NL_ERROR_SUCCESS) {
1413         POVS_MESSAGE_ERROR msgError = (POVS_MESSAGE_ERROR)
1414             usrParamsCtx->outputBuffer;
1415
1416         NlBuildErrorMsg(msgIn, msgError, nlError);
1417         *replyLen = msgError->nlMsg.nlmsgLen;
1418     }
1419
1420     return STATUS_SUCCESS;
1421 }
1422
1423
1424 NTSTATUS
1425 OvsSetupDumpStart(POVS_USER_PARAMS_CONTEXT usrParamsCtx)
1426 {
1427     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1428     POVS_OPEN_INSTANCE instance =
1429         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1430
1431     /* input buffer has been validated while validating write dev op. */
1432     ASSERT(msgIn != NULL && usrParamsCtx->inputLength >= sizeof *msgIn);
1433
1434     /* A write operation that does not indicate dump start is invalid. */
1435     if ((msgIn->nlMsg.nlmsgFlags & NLM_F_DUMP) != NLM_F_DUMP) {
1436         return STATUS_INVALID_PARAMETER;
1437     }
1438     /* XXX: Handle other NLM_F_* flags in the future. */
1439
1440     /*
1441      * This operation should be setting up the dump state. If there's any
1442      * previous state, clear it up so as to set it up afresh.
1443      */
1444     FreeUserDumpState(instance);
1445
1446     return InitUserDumpState(instance, msgIn);
1447 }
1448
1449
1450 /*
1451  * --------------------------------------------------------------------------
1452  *  Utility function to map the output buffer in an IRP. The buffer is assumed
1453  *  to have been passed down using METHOD_OUT_DIRECT (Direct I/O).
1454  * --------------------------------------------------------------------------
1455  */
1456 static NTSTATUS
1457 MapIrpOutputBuffer(PIRP irp,
1458                    UINT32 bufferLength,
1459                    UINT32 requiredLength,
1460                    PVOID *buffer)
1461 {
1462     ASSERT(irp);
1463     ASSERT(buffer);
1464     ASSERT(bufferLength);
1465     ASSERT(requiredLength);
1466     if (!buffer || !irp || bufferLength == 0 || requiredLength == 0) {
1467         return STATUS_INVALID_PARAMETER;
1468     }
1469
1470     if (bufferLength < requiredLength) {
1471         return STATUS_NDIS_INVALID_LENGTH;
1472     }
1473     if (irp->MdlAddress == NULL) {
1474         return STATUS_INVALID_PARAMETER;
1475     }
1476     *buffer = MmGetSystemAddressForMdlSafe(irp->MdlAddress,
1477                                            NormalPagePriority);
1478     if (*buffer == NULL) {
1479         return STATUS_INSUFFICIENT_RESOURCES;
1480     }
1481
1482     return STATUS_SUCCESS;
1483 }
1484
1485 /*
1486  * --------------------------------------------------------------------------
1487  * Utility function to fill up information about the state of a port in a reply
1488  * to* userspace.
1489  * --------------------------------------------------------------------------
1490  */
1491 static NTSTATUS
1492 OvsPortFillInfo(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1493                 POVS_EVENT_ENTRY eventEntry,
1494                 PNL_BUFFER nlBuf)
1495 {
1496     NTSTATUS status;
1497     BOOLEAN ok;
1498     OVS_MESSAGE msgOutTmp;
1499     PNL_MSG_HDR nlMsg;
1500
1501     ASSERT(NlBufAt(nlBuf, 0, 0) != 0 && nlBuf->bufRemLen >= sizeof msgOutTmp);
1502
1503     msgOutTmp.nlMsg.nlmsgType = OVS_WIN_NL_VPORT_FAMILY_ID;
1504     msgOutTmp.nlMsg.nlmsgFlags = 0;  /* XXX: ? */
1505
1506     /* driver intiated messages should have zerp seq number*/
1507     msgOutTmp.nlMsg.nlmsgSeq = 0;
1508     msgOutTmp.nlMsg.nlmsgPid = usrParamsCtx->ovsInstance->pid;
1509
1510     msgOutTmp.genlMsg.version = nlVportFamilyOps.version;
1511     msgOutTmp.genlMsg.reserved = 0;
1512
1513     /* we don't have netdev yet, treat link up/down a adding/removing a port*/
1514     if (eventEntry->type & (OVS_EVENT_LINK_UP | OVS_EVENT_CONNECT)) {
1515         msgOutTmp.genlMsg.cmd = OVS_VPORT_CMD_NEW;
1516     } else if (eventEntry->type &
1517              (OVS_EVENT_LINK_DOWN | OVS_EVENT_DISCONNECT)) {
1518         msgOutTmp.genlMsg.cmd = OVS_VPORT_CMD_DEL;
1519     } else {
1520         ASSERT(FALSE);
1521         return STATUS_UNSUCCESSFUL;
1522     }
1523     msgOutTmp.ovsHdr.dp_ifindex = gOvsSwitchContext->dpNo;
1524
1525     ok = NlMsgPutHead(nlBuf, (PCHAR)&msgOutTmp, sizeof msgOutTmp);
1526     if (!ok) {
1527         status = STATUS_INVALID_BUFFER_SIZE;
1528         goto cleanup;
1529     }
1530
1531     ok = NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_PORT_NO, eventEntry->portNo) &&
1532          NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_TYPE, eventEntry->ovsType) &&
1533          NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_UPCALL_PID,
1534                          eventEntry->upcallPid) &&
1535          NlMsgPutTailString(nlBuf, OVS_VPORT_ATTR_NAME, eventEntry->ovsName);
1536     if (!ok) {
1537         status = STATUS_INVALID_BUFFER_SIZE;
1538         goto cleanup;
1539     }
1540
1541     /* XXXX Should we add the port stats attributes?*/
1542     nlMsg = (PNL_MSG_HDR)NlBufAt(nlBuf, 0, 0);
1543     nlMsg->nlmsgLen = NlBufSize(nlBuf);
1544     status = STATUS_SUCCESS;
1545
1546 cleanup:
1547     return status;
1548 }
1549
1550
1551 /*
1552  * --------------------------------------------------------------------------
1553  * Handler for reading events from the driver event queue. This handler is
1554  * executed when user modes issues a socket receive on a socket assocaited
1555  * with the MC group for events.
1556  * XXX user mode should read multiple events in one system call
1557  * --------------------------------------------------------------------------
1558  */
1559 static NTSTATUS
1560 OvsReadEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1561                        UINT32 *replyLen)
1562 {
1563 #ifdef DBG
1564     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1565     POVS_OPEN_INSTANCE instance =
1566         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1567 #endif
1568     NL_BUFFER nlBuf;
1569     NTSTATUS status;
1570     OVS_EVENT_ENTRY eventEntry;
1571
1572     ASSERT(usrParamsCtx->devOp == OVS_READ_DEV_OP);
1573
1574     /* Should never read events with a dump socket */
1575     ASSERT(instance->dumpState.ovsMsg == NULL);
1576
1577     /* Must have an event queue */
1578     ASSERT(instance->eventQueue != NULL);
1579
1580     /* Output buffer has been validated while validating read dev op. */
1581     ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1582
1583     NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength);
1584
1585     /* remove an event entry from the event queue */
1586     status = OvsRemoveEventEntry(usrParamsCtx->ovsInstance, &eventEntry);
1587     if (status != STATUS_SUCCESS) {
1588         /* If there were not elements, read should return no data. */
1589         status = STATUS_SUCCESS;
1590         *replyLen = 0;
1591         goto cleanup;
1592     }
1593
1594     status = OvsPortFillInfo(usrParamsCtx, &eventEntry, &nlBuf);
1595     if (status == NDIS_STATUS_SUCCESS) {
1596         *replyLen = NlBufSize(&nlBuf);
1597     }
1598
1599 cleanup:
1600     return status;
1601 }