datapath-windows: Return pending for IRPs completed later
[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                          OvsPendPacketCmdHandler,
93                          OvsSubscribeEventCmdHandler,
94                          OvsSubscribePacketCmdHandler,
95                          OvsReadEventCmdHandler,
96                          OvsReadPacketCmdHandler,
97                          OvsNewDpCmdHandler,
98                          OvsGetDpCmdHandler,
99                          OvsSetDpCmdHandler;
100
101 NetlinkCmdHandler        OvsGetNetdevCmdHandler,
102                          OvsGetVportCmdHandler,
103                          OvsSetVportCmdHandler,
104                          OvsNewVportCmdHandler,
105                          OvsDeleteVportCmdHandler;
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     OvsFreeMemoryWithTag(instance, OVS_DATAPATH_POOL_TAG);
592 }
593
594 NTSTATUS
595 OvsCompleteIrpRequest(PIRP irp,
596                       ULONG_PTR infoPtr,
597                       NTSTATUS status)
598 {
599     irp->IoStatus.Information = infoPtr;
600     irp->IoStatus.Status = status;
601     IoCompleteRequest(irp, IO_NO_INCREMENT);
602     return status;
603 }
604
605
606 NTSTATUS
607 OvsOpenCloseDevice(PDEVICE_OBJECT deviceObject,
608                    PIRP irp)
609 {
610     PIO_STACK_LOCATION irpSp;
611     NTSTATUS status = STATUS_SUCCESS;
612     PFILE_OBJECT fileObject;
613     POVS_DEVICE_EXTENSION ovsExt =
614         (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(deviceObject);
615
616     ASSERT(deviceObject == gOvsDeviceObject);
617     ASSERT(ovsExt != NULL);
618
619     irpSp = IoGetCurrentIrpStackLocation(irp);
620     fileObject = irpSp->FileObject;
621     OVS_LOG_TRACE("DeviceObject: %p, fileObject:%p, instance: %u",
622                   deviceObject, fileObject,
623                   ovsExt->numberOpenInstance);
624
625     switch (irpSp->MajorFunction) {
626     case IRP_MJ_CREATE:
627         status = OvsAddOpenInstance(ovsExt, fileObject);
628         if (STATUS_SUCCESS == status) {
629             InterlockedIncrement((LONG volatile *)&ovsExt->numberOpenInstance);
630         }
631         break;
632     case IRP_MJ_CLOSE:
633         ASSERT(ovsExt->numberOpenInstance > 0);
634         OvsRemoveOpenInstance(fileObject);
635         InterlockedDecrement((LONG volatile *)&ovsExt->numberOpenInstance);
636         break;
637     default:
638         ASSERT(0);
639     }
640     return OvsCompleteIrpRequest(irp, (ULONG_PTR)0, status);
641 }
642
643 _Use_decl_annotations_
644 NTSTATUS
645 OvsCleanupDevice(PDEVICE_OBJECT deviceObject,
646                  PIRP irp)
647 {
648
649     PIO_STACK_LOCATION irpSp;
650     PFILE_OBJECT fileObject;
651
652     NTSTATUS status = STATUS_SUCCESS;
653 #ifdef DBG
654     POVS_DEVICE_EXTENSION ovsExt =
655         (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(deviceObject);
656     if (ovsExt) {
657         ASSERT(ovsExt->numberOpenInstance > 0);
658     }
659 #else
660     UNREFERENCED_PARAMETER(deviceObject);
661 #endif
662     ASSERT(deviceObject == gOvsDeviceObject);
663     irpSp = IoGetCurrentIrpStackLocation(irp);
664     fileObject = irpSp->FileObject;
665
666     ASSERT(irpSp->MajorFunction == IRP_MJ_CLEANUP);
667
668     OvsCleanupOpenInstance(fileObject);
669
670     return OvsCompleteIrpRequest(irp, (ULONG_PTR)0, status);
671 }
672
673 /*
674  * --------------------------------------------------------------------------
675  * IOCTL function handler for the device.
676  * --------------------------------------------------------------------------
677  */
678 NTSTATUS
679 OvsDeviceControl(PDEVICE_OBJECT deviceObject,
680                  PIRP irp)
681 {
682     PIO_STACK_LOCATION irpSp;
683     NTSTATUS status = STATUS_SUCCESS;
684     PFILE_OBJECT fileObject;
685     PVOID inputBuffer = NULL;
686     PVOID outputBuffer = NULL;
687     UINT32 inputBufferLen, outputBufferLen;
688     UINT32 code, replyLen = 0;
689     POVS_OPEN_INSTANCE instance;
690     UINT32 devOp;
691     OVS_MESSAGE ovsMsgReadOp;
692     POVS_MESSAGE ovsMsg;
693     NETLINK_FAMILY *nlFamilyOps;
694     OVS_USER_PARAMS_CONTEXT usrParamsCtx;
695
696 #ifdef DBG
697     POVS_DEVICE_EXTENSION ovsExt =
698         (POVS_DEVICE_EXTENSION)NdisGetDeviceReservedExtension(deviceObject);
699     ASSERT(deviceObject == gOvsDeviceObject);
700     ASSERT(ovsExt);
701     ASSERT(ovsExt->numberOpenInstance > 0);
702 #else
703     UNREFERENCED_PARAMETER(deviceObject);
704 #endif
705
706     irpSp = IoGetCurrentIrpStackLocation(irp);
707
708     ASSERT(irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL);
709     ASSERT(irpSp->FileObject != NULL);
710
711     fileObject = irpSp->FileObject;
712     instance = (POVS_OPEN_INSTANCE)fileObject->FsContext;
713     code = irpSp->Parameters.DeviceIoControl.IoControlCode;
714     inputBufferLen = irpSp->Parameters.DeviceIoControl.InputBufferLength;
715     outputBufferLen = irpSp->Parameters.DeviceIoControl.OutputBufferLength;
716     inputBuffer = irp->AssociatedIrp.SystemBuffer;
717
718     /* Check if the extension is enabled. */
719     if (NULL == gOvsSwitchContext) {
720         status = STATUS_NOT_FOUND;
721         goto exit;
722     }
723
724     if (!OvsAcquireSwitchContext()) {
725         status = STATUS_NOT_FOUND;
726         goto exit;
727     }
728
729     /*
730      * Validate the input/output buffer arguments depending on the type of the
731      * operation.
732      */
733     switch (code) {
734     case OVS_IOCTL_GET_PID:
735         /* Both input buffer and output buffer use the same location. */
736         outputBuffer = irp->AssociatedIrp.SystemBuffer;
737         if (outputBufferLen != 0) {
738             InitUserParamsCtx(irp, instance, 0, NULL,
739                               inputBuffer, inputBufferLen,
740                               outputBuffer, outputBufferLen,
741                               &usrParamsCtx);
742
743             ASSERT(outputBuffer);
744         } else {
745             status = STATUS_NDIS_INVALID_LENGTH;
746             goto done;
747         }
748
749         status = OvsGetPidHandler(&usrParamsCtx, &replyLen);
750         goto done;
751
752     case OVS_IOCTL_TRANSACT:
753         /* Both input buffer and output buffer are mandatory. */
754         if (outputBufferLen != 0) {
755             status = MapIrpOutputBuffer(irp, outputBufferLen,
756                                         sizeof *ovsMsg, &outputBuffer);
757             if (status != STATUS_SUCCESS) {
758                 goto done;
759             }
760             ASSERT(outputBuffer);
761         } else {
762             status = STATUS_NDIS_INVALID_LENGTH;
763             goto done;
764         }
765
766         if (inputBufferLen < sizeof (*ovsMsg)) {
767             status = STATUS_NDIS_INVALID_LENGTH;
768             goto done;
769         }
770
771         ovsMsg = inputBuffer;
772         devOp = OVS_TRANSACTION_DEV_OP;
773         break;
774
775     case OVS_IOCTL_READ_EVENT:
776     case OVS_IOCTL_READ_PACKET:
777         /*
778          * Output buffer is mandatory. These IOCTLs are used to read events and
779          * packets respectively. It is convenient to have separate ioctls.
780          */
781         if (outputBufferLen != 0) {
782             status = MapIrpOutputBuffer(irp, outputBufferLen,
783                                         sizeof *ovsMsg, &outputBuffer);
784             if (status != STATUS_SUCCESS) {
785                 goto done;
786             }
787             ASSERT(outputBuffer);
788         } else {
789             status = STATUS_NDIS_INVALID_LENGTH;
790             goto done;
791         }
792         inputBuffer = NULL;
793         inputBufferLen = 0;
794
795         ovsMsg = &ovsMsgReadOp;
796         RtlZeroMemory(ovsMsg, sizeof *ovsMsg);
797         ovsMsg->nlMsg.nlmsgLen = sizeof *ovsMsg;
798         ovsMsg->nlMsg.nlmsgType = nlControlFamilyOps.id;
799         ovsMsg->nlMsg.nlmsgPid = instance->pid;
800
801         /* An "artificial" command so we can use NL family function table*/
802         ovsMsg->genlMsg.cmd = (code == OVS_IOCTL_READ_EVENT) ?
803                               OVS_CTRL_CMD_EVENT_NOTIFY :
804                               OVS_CTRL_CMD_READ_NOTIFY;
805         ovsMsg->genlMsg.version = nlControlFamilyOps.version;
806
807         devOp = OVS_READ_DEV_OP;
808         break;
809
810     case OVS_IOCTL_READ:
811         /* Output buffer is mandatory. */
812         if (outputBufferLen != 0) {
813             status = MapIrpOutputBuffer(irp, outputBufferLen,
814                                         sizeof *ovsMsg, &outputBuffer);
815             if (status != STATUS_SUCCESS) {
816                 goto done;
817             }
818             ASSERT(outputBuffer);
819         } else {
820             status = STATUS_NDIS_INVALID_LENGTH;
821             goto done;
822         }
823
824         /*
825          * Operate in the mode that read ioctl is similar to ReadFile(). This
826          * might change as the userspace code gets implemented.
827          */
828         inputBuffer = NULL;
829         inputBufferLen = 0;
830
831         /*
832          * For implementing read (ioctl or otherwise), we need to store some
833          * state in the instance to indicate the command that started the dump
834          * operation. The state can setup 'ovsMsgReadOp' appropriately. Note
835          * that 'ovsMsgReadOp' is needed only in this function to call into the
836          * appropriate handler. The handler itself can access the state in the
837          * instance.
838          *
839          * In the absence of a dump start, return 0 bytes.
840          */
841         if (instance->dumpState.ovsMsg == NULL) {
842             replyLen = 0;
843             status = STATUS_SUCCESS;
844             goto done;
845         }
846         RtlCopyMemory(&ovsMsgReadOp, instance->dumpState.ovsMsg,
847                       sizeof (ovsMsgReadOp));
848
849         /* Create an NL message for consumption. */
850         ovsMsg = &ovsMsgReadOp;
851         devOp = OVS_READ_DEV_OP;
852
853         break;
854
855     case OVS_IOCTL_WRITE:
856         /* Input buffer is mandatory. */
857         if (inputBufferLen < sizeof (*ovsMsg)) {
858             status = STATUS_NDIS_INVALID_LENGTH;
859             goto done;
860         }
861
862         ovsMsg = inputBuffer;
863         devOp = OVS_WRITE_DEV_OP;
864         break;
865
866     default:
867         status = STATUS_INVALID_DEVICE_REQUEST;
868         goto done;
869     }
870
871     ASSERT(ovsMsg);
872     switch (ovsMsg->nlMsg.nlmsgType) {
873     case OVS_WIN_NL_CTRL_FAMILY_ID:
874         nlFamilyOps = &nlControlFamilyOps;
875         break;
876     case OVS_WIN_NL_DATAPATH_FAMILY_ID:
877         nlFamilyOps = &nlDatapathFamilyOps;
878         break;
879     case OVS_WIN_NL_FLOW_FAMILY_ID:
880          nlFamilyOps = &nlFLowFamilyOps;
881          break;
882     case OVS_WIN_NL_PACKET_FAMILY_ID:
883          nlFamilyOps = &nlPacketFamilyOps;
884          break;
885     case OVS_WIN_NL_VPORT_FAMILY_ID:
886         nlFamilyOps = &nlVportFamilyOps;
887         break;
888     case OVS_WIN_NL_NETDEV_FAMILY_ID:
889         nlFamilyOps = &nlNetdevFamilyOps;
890         break;
891     default:
892         status = STATUS_INVALID_PARAMETER;
893         goto done;
894     }
895
896     /*
897      * For read operation, avoid duplicate validation since 'ovsMsg' is either
898      * "artificial" or was copied from a previously validated 'ovsMsg'.
899      */
900     if (devOp != OVS_READ_DEV_OP) {
901         status = ValidateNetlinkCmd(devOp, instance, ovsMsg, nlFamilyOps);
902         if (status != STATUS_SUCCESS) {
903             goto done;
904         }
905     }
906
907     InitUserParamsCtx(irp, instance, devOp, ovsMsg,
908                       inputBuffer, inputBufferLen,
909                       outputBuffer, outputBufferLen,
910                       &usrParamsCtx);
911
912     status = InvokeNetlinkCmdHandler(&usrParamsCtx, nlFamilyOps, &replyLen);
913
914 done:
915     OvsReleaseSwitchContext(gOvsSwitchContext);
916
917 exit:
918     /* Should not complete a pending IRP unless proceesing is completed. */
919     if (status == STATUS_PENDING) {
920         /* STATUS_PENDING is returned by the NL handler when the request is
921          * to be processed later, so we mark the IRP as pending and complete
922          * it in another thread when the request is processed. */
923         IoMarkIrpPending(irp);
924         return status;
925     }
926     return OvsCompleteIrpRequest(irp, (ULONG_PTR)replyLen, status);
927 }
928
929
930 /*
931  * --------------------------------------------------------------------------
932  * Function to validate a netlink command. Only certain combinations of
933  * (device operation, netlink family, command) are valid.
934  * --------------------------------------------------------------------------
935  */
936 static NTSTATUS
937 ValidateNetlinkCmd(UINT32 devOp,
938                    POVS_OPEN_INSTANCE instance,
939                    POVS_MESSAGE ovsMsg,
940                    NETLINK_FAMILY *nlFamilyOps)
941 {
942     NTSTATUS status = STATUS_INVALID_PARAMETER;
943     UINT16 i;
944
945     for (i = 0; i < nlFamilyOps->opsCount; i++) {
946         if (nlFamilyOps->cmds[i].cmd == ovsMsg->genlMsg.cmd) {
947             /* Validate if the command is valid for the device operation. */
948             if ((devOp & nlFamilyOps->cmds[i].supportedDevOp) == 0) {
949                 status = STATUS_INVALID_PARAMETER;
950                 goto done;
951             }
952
953             /* Validate the version. */
954             if (nlFamilyOps->version > ovsMsg->genlMsg.version) {
955                 status = STATUS_INVALID_PARAMETER;
956                 goto done;
957             }
958
959             /* Validate the DP for commands that require a DP. */
960             if (nlFamilyOps->cmds[i].validateDpIndex == TRUE) {
961                 if (ovsMsg->ovsHdr.dp_ifindex !=
962                                           (INT)gOvsSwitchContext->dpNo) {
963                     status = STATUS_INVALID_PARAMETER;
964                     goto done;
965                 }
966             }
967
968             /* Validate the PID. */
969             if (ovsMsg->nlMsg.nlmsgPid != instance->pid) {
970                 status = STATUS_INVALID_PARAMETER;
971                 goto done;
972             }
973
974             status = STATUS_SUCCESS;
975             break;
976         }
977     }
978
979 done:
980     return status;
981 }
982
983 /*
984  * --------------------------------------------------------------------------
985  * Function to invoke the netlink command handler. The function also stores
986  * the return value of the handler function to construct a 'NL_ERROR' message,
987  * and in turn returns success to the caller.
988  * --------------------------------------------------------------------------
989  */
990 static NTSTATUS
991 InvokeNetlinkCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
992                         NETLINK_FAMILY *nlFamilyOps,
993                         UINT32 *replyLen)
994 {
995     NTSTATUS status = STATUS_INVALID_PARAMETER;
996     UINT16 i;
997
998     for (i = 0; i < nlFamilyOps->opsCount; i++) {
999         if (nlFamilyOps->cmds[i].cmd == usrParamsCtx->ovsMsg->genlMsg.cmd) {
1000             NetlinkCmdHandler *handler = nlFamilyOps->cmds[i].handler;
1001             ASSERT(handler);
1002             if (handler) {
1003                 status = handler(usrParamsCtx, replyLen);
1004             }
1005             break;
1006         }
1007     }
1008
1009     /*
1010      * Netlink socket semantics dictate that the return value of the netlink
1011      * function should be an error ONLY under fatal conditions. If the message
1012      * made it all the way to the handler function, it is not a fatal condition.
1013      * Absorb the error returned by the handler function into a 'struct
1014      * NL_ERROR' and populate the 'output buffer' to return to userspace.
1015      *
1016      * This behavior is obviously applicable only to netlink commands that
1017      * specify an 'output buffer'. For other commands, we return the error as
1018      * is.
1019      *
1020      * 'STATUS_PENDING' is a special return value and userspace is equipped to
1021      * handle it.
1022      */
1023     if (status != STATUS_SUCCESS && status != STATUS_PENDING) {
1024         if (usrParamsCtx->devOp != OVS_WRITE_DEV_OP && *replyLen == 0) {
1025             NL_ERROR nlError = NlMapStatusToNlErr(status);
1026             POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1027             POVS_MESSAGE_ERROR msgError = (POVS_MESSAGE_ERROR)
1028                 usrParamsCtx->outputBuffer;
1029
1030             ASSERT(msgError);
1031             NlBuildErrorMsg(msgIn, msgError, nlError);
1032             *replyLen = msgError->nlMsg.nlmsgLen;
1033         }
1034
1035         if (*replyLen != 0) {
1036             status = STATUS_SUCCESS;
1037         }
1038     }
1039
1040 #ifdef DBG
1041     if (usrParamsCtx->devOp != OVS_WRITE_DEV_OP) {
1042         ASSERT(status == STATUS_PENDING || *replyLen != 0 || status == STATUS_SUCCESS);
1043     }
1044 #endif
1045
1046     return status;
1047 }
1048
1049 /*
1050  * --------------------------------------------------------------------------
1051  *  Handler for 'OVS_IOCTL_GET_PID'.
1052  *
1053  *  Each handle on the device is assigned a unique PID when the handle is
1054  *  created. This function passes the PID to userspace using METHOD_BUFFERED
1055  *  method.
1056  * --------------------------------------------------------------------------
1057  */
1058 static NTSTATUS
1059 OvsGetPidHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1060                  UINT32 *replyLen)
1061 {
1062     NTSTATUS status = STATUS_SUCCESS;
1063     PUINT32 msgOut = (PUINT32)usrParamsCtx->outputBuffer;
1064
1065     if (usrParamsCtx->outputLength >= sizeof *msgOut) {
1066         POVS_OPEN_INSTANCE instance =
1067             (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1068
1069         RtlZeroMemory(msgOut, sizeof *msgOut);
1070         RtlCopyMemory(msgOut, &instance->pid, sizeof(*msgOut));
1071         *replyLen = sizeof *msgOut;
1072     } else {
1073         *replyLen = sizeof *msgOut;
1074         status = STATUS_NDIS_INVALID_LENGTH;
1075     }
1076
1077     return status;
1078 }
1079
1080 /*
1081  * --------------------------------------------------------------------------
1082  * Utility function to fill up information about the datapath in a reply to
1083  * userspace.
1084  * --------------------------------------------------------------------------
1085  */
1086 static NTSTATUS
1087 OvsDpFillInfo(POVS_SWITCH_CONTEXT ovsSwitchContext,
1088               POVS_MESSAGE msgIn,
1089               PNL_BUFFER nlBuf)
1090 {
1091     BOOLEAN writeOk;
1092     OVS_MESSAGE msgOutTmp;
1093     OVS_DATAPATH *datapath = &ovsSwitchContext->datapath;
1094     PNL_MSG_HDR nlMsg;
1095
1096     ASSERT(NlBufAt(nlBuf, 0, 0) != 0 && NlBufRemLen(nlBuf) >= sizeof *msgIn);
1097
1098     msgOutTmp.nlMsg.nlmsgType = OVS_WIN_NL_DATAPATH_FAMILY_ID;
1099     msgOutTmp.nlMsg.nlmsgFlags = 0;  /* XXX: ? */
1100     msgOutTmp.nlMsg.nlmsgSeq = msgIn->nlMsg.nlmsgSeq;
1101     msgOutTmp.nlMsg.nlmsgPid = msgIn->nlMsg.nlmsgPid;
1102
1103     msgOutTmp.genlMsg.cmd = OVS_DP_CMD_GET;
1104     msgOutTmp.genlMsg.version = nlDatapathFamilyOps.version;
1105     msgOutTmp.genlMsg.reserved = 0;
1106
1107     msgOutTmp.ovsHdr.dp_ifindex = ovsSwitchContext->dpNo;
1108
1109     writeOk = NlMsgPutHead(nlBuf, (PCHAR)&msgOutTmp, sizeof msgOutTmp);
1110     if (writeOk) {
1111         writeOk = NlMsgPutTailString(nlBuf, OVS_DP_ATTR_NAME,
1112                                      OVS_SYSTEM_DP_NAME);
1113     }
1114     if (writeOk) {
1115         OVS_DP_STATS dpStats;
1116
1117         dpStats.n_hit = datapath->hits;
1118         dpStats.n_missed = datapath->misses;
1119         dpStats.n_lost = datapath->lost;
1120         dpStats.n_flows = datapath->nFlows;
1121         writeOk = NlMsgPutTailUnspec(nlBuf, OVS_DP_ATTR_STATS,
1122                                      (PCHAR)&dpStats, sizeof dpStats);
1123     }
1124     nlMsg = (PNL_MSG_HDR)NlBufAt(nlBuf, 0, 0);
1125     nlMsg->nlmsgLen = NlBufSize(nlBuf);
1126
1127     return writeOk ? STATUS_SUCCESS : STATUS_INVALID_BUFFER_SIZE;
1128 }
1129
1130 /*
1131  * --------------------------------------------------------------------------
1132  * Handler for queueing an IRP used for event notification. The IRP is
1133  * completed when a port state changes. STATUS_PENDING is returned on
1134  * success. User mode keep a pending IRP at all times.
1135  * --------------------------------------------------------------------------
1136  */
1137 static NTSTATUS
1138 OvsPendEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1139                        UINT32 *replyLen)
1140 {
1141     NDIS_STATUS status;
1142
1143     UNREFERENCED_PARAMETER(replyLen);
1144
1145     POVS_OPEN_INSTANCE instance =
1146         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1147     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1148     OVS_EVENT_POLL poll;
1149
1150     poll.dpNo = msgIn->ovsHdr.dp_ifindex;
1151     status = OvsWaitEventIoctl(usrParamsCtx->irp, instance->fileObject,
1152                                &poll, sizeof poll);
1153     return status;
1154 }
1155
1156 /*
1157  * --------------------------------------------------------------------------
1158  *  Handler for the subscription for the event queue
1159  * --------------------------------------------------------------------------
1160  */
1161 static NTSTATUS
1162 OvsSubscribeEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1163                             UINT32 *replyLen)
1164 {
1165     NDIS_STATUS status;
1166     OVS_EVENT_SUBSCRIBE request;
1167     BOOLEAN rc;
1168     UINT8 join;
1169     PNL_ATTR attrs[2];
1170     const NL_POLICY policy[] =  {
1171         [OVS_NL_ATTR_MCAST_GRP] = {.type = NL_A_U32 },
1172         [OVS_NL_ATTR_MCAST_JOIN] = {.type = NL_A_U8 },
1173         };
1174
1175     UNREFERENCED_PARAMETER(replyLen);
1176
1177     POVS_OPEN_INSTANCE instance =
1178         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1179     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1180
1181     rc = NlAttrParse(&msgIn->nlMsg, sizeof (*msgIn),
1182          NlMsgAttrsLen((PNL_MSG_HDR)msgIn), policy, attrs, ARRAY_SIZE(attrs));
1183     if (!rc) {
1184         status = STATUS_INVALID_PARAMETER;
1185         goto done;
1186     }
1187
1188     /* XXX Ignore the MC group for now */
1189     join = NlAttrGetU8(attrs[OVS_NL_ATTR_MCAST_JOIN]);
1190     request.dpNo = msgIn->ovsHdr.dp_ifindex;
1191     request.subscribe = join;
1192     request.mask = OVS_EVENT_MASK_ALL;
1193
1194     status = OvsSubscribeEventIoctl(instance->fileObject, &request,
1195                                     sizeof request);
1196 done:
1197     return status;
1198 }
1199
1200 /*
1201  * --------------------------------------------------------------------------
1202  *  Command Handler for 'OVS_DP_CMD_NEW'.
1203  * --------------------------------------------------------------------------
1204  */
1205 static NTSTATUS
1206 OvsNewDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1207                    UINT32 *replyLen)
1208 {
1209     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1210 }
1211
1212 /*
1213  * --------------------------------------------------------------------------
1214  *  Command Handler for 'OVS_DP_CMD_GET'.
1215  *
1216  *  The function handles both the dump based as well as the transaction based
1217  *  'OVS_DP_CMD_GET' command. In the dump command, it handles the initial
1218  *  call to setup dump state, as well as subsequent calls to continue dumping
1219  *  data.
1220  * --------------------------------------------------------------------------
1221  */
1222 static NTSTATUS
1223 OvsGetDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1224                    UINT32 *replyLen)
1225 {
1226     if (usrParamsCtx->devOp == OVS_TRANSACTION_DEV_OP) {
1227         return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1228     } else {
1229         return HandleGetDpDump(usrParamsCtx, replyLen);
1230     }
1231 }
1232
1233 /*
1234  * --------------------------------------------------------------------------
1235  *  Function for handling the transaction based 'OVS_DP_CMD_GET' command.
1236  * --------------------------------------------------------------------------
1237  */
1238 static NTSTATUS
1239 HandleGetDpTransaction(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1240                        UINT32 *replyLen)
1241 {
1242     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1243 }
1244
1245
1246 /*
1247  * --------------------------------------------------------------------------
1248  *  Function for handling the dump-based 'OVS_DP_CMD_GET' command.
1249  * --------------------------------------------------------------------------
1250  */
1251 static NTSTATUS
1252 HandleGetDpDump(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1253                 UINT32 *replyLen)
1254 {
1255     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1256     POVS_OPEN_INSTANCE instance =
1257         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1258
1259     if (usrParamsCtx->devOp == OVS_WRITE_DEV_OP) {
1260         *replyLen = 0;
1261         OvsSetupDumpStart(usrParamsCtx);
1262     } else {
1263         NL_BUFFER nlBuf;
1264         NTSTATUS status;
1265         POVS_MESSAGE msgIn = instance->dumpState.ovsMsg;
1266
1267         ASSERT(usrParamsCtx->devOp == OVS_READ_DEV_OP);
1268
1269         if (instance->dumpState.ovsMsg == NULL) {
1270             ASSERT(FALSE);
1271             return STATUS_INVALID_DEVICE_STATE;
1272         }
1273
1274         /* Dump state must have been deleted after previous dump operation. */
1275         ASSERT(instance->dumpState.index[0] == 0);
1276
1277         /* Output buffer has been validated while validating read dev op. */
1278         ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1279
1280         NlBufInit(&nlBuf, usrParamsCtx->outputBuffer,
1281                   usrParamsCtx->outputLength);
1282
1283         status = OvsDpFillInfo(gOvsSwitchContext, msgIn, &nlBuf);
1284
1285         if (status != STATUS_SUCCESS) {
1286             *replyLen = 0;
1287             FreeUserDumpState(instance);
1288             return status;
1289         }
1290
1291         /* Increment the dump index. */
1292         instance->dumpState.index[0] = 1;
1293         *replyLen = msgOut->nlMsg.nlmsgLen;
1294
1295         /* Free up the dump state, since there's no more data to continue. */
1296         FreeUserDumpState(instance);
1297     }
1298
1299     return STATUS_SUCCESS;
1300 }
1301
1302
1303 /*
1304  * --------------------------------------------------------------------------
1305  *  Command Handler for 'OVS_DP_CMD_SET'.
1306  * --------------------------------------------------------------------------
1307  */
1308 static NTSTATUS
1309 OvsSetDpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1310                    UINT32 *replyLen)
1311 {
1312     return HandleDpTransactionCommon(usrParamsCtx, replyLen);
1313 }
1314
1315 /*
1316  * --------------------------------------------------------------------------
1317  *  Function for handling transaction based 'OVS_DP_CMD_NEW', 'OVS_DP_CMD_GET'
1318  *  and 'OVS_DP_CMD_SET' commands.
1319  *
1320  * 'OVS_DP_CMD_NEW' is implemented to keep userspace code happy. Creation of a
1321  * new datapath is not supported currently.
1322  * --------------------------------------------------------------------------
1323  */
1324 static NTSTATUS
1325 HandleDpTransactionCommon(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1326                           UINT32 *replyLen)
1327 {
1328     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1329     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1330     NTSTATUS status = STATUS_SUCCESS;
1331     NL_BUFFER nlBuf;
1332     NL_ERROR nlError = NL_ERROR_SUCCESS;
1333     static const NL_POLICY ovsDatapathSetPolicy[] = {
1334         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .maxLen = IFNAMSIZ },
1335         [OVS_DP_ATTR_UPCALL_PID] = { .type = NL_A_U32, .optional = TRUE },
1336         [OVS_DP_ATTR_USER_FEATURES] = { .type = NL_A_U32, .optional = TRUE },
1337     };
1338     PNL_ATTR dpAttrs[ARRAY_SIZE(ovsDatapathSetPolicy)];
1339
1340     UNREFERENCED_PARAMETER(msgOut);
1341
1342     /* input buffer has been validated while validating write dev op. */
1343     ASSERT(msgIn != NULL && usrParamsCtx->inputLength >= sizeof *msgIn);
1344
1345     /* Parse any attributes in the request. */
1346     if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_SET ||
1347         usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_NEW) {
1348         if (!NlAttrParse((PNL_MSG_HDR)msgIn,
1349                         NLMSG_HDRLEN + GENL_HDRLEN + OVS_HDRLEN,
1350                         NlMsgAttrsLen((PNL_MSG_HDR)msgIn),
1351                         ovsDatapathSetPolicy, dpAttrs, ARRAY_SIZE(dpAttrs))) {
1352             return STATUS_INVALID_PARAMETER;
1353         }
1354
1355         /*
1356         * XXX: Not clear at this stage if there's any role for the
1357         * OVS_DP_ATTR_UPCALL_PID and OVS_DP_ATTR_USER_FEATURES attributes passed
1358         * from userspace.
1359         */
1360
1361     } else {
1362         RtlZeroMemory(dpAttrs, sizeof dpAttrs);
1363     }
1364
1365     /* Output buffer has been validated while validating transact dev op. */
1366     ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1367
1368     NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength);
1369
1370     if (dpAttrs[OVS_DP_ATTR_NAME] != NULL) {
1371         if (!OvsCompareString(NlAttrGet(dpAttrs[OVS_DP_ATTR_NAME]),
1372                               OVS_SYSTEM_DP_NAME)) {
1373
1374             /* Creation of new datapaths is not supported. */
1375             if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_SET) {
1376                 nlError = NL_ERROR_NOTSUPP;
1377                 goto cleanup;
1378             }
1379
1380             nlError = NL_ERROR_NODEV;
1381             goto cleanup;
1382         }
1383     } else if ((UINT32)msgIn->ovsHdr.dp_ifindex != gOvsSwitchContext->dpNo) {
1384         nlError = NL_ERROR_NODEV;
1385         goto cleanup;
1386     }
1387
1388     if (usrParamsCtx->ovsMsg->genlMsg.cmd == OVS_DP_CMD_NEW) {
1389         nlError = NL_ERROR_EXIST;
1390         goto cleanup;
1391     }
1392
1393     status = OvsDpFillInfo(gOvsSwitchContext, msgIn, &nlBuf);
1394
1395     *replyLen = NlBufSize(&nlBuf);
1396
1397 cleanup:
1398     if (nlError != NL_ERROR_SUCCESS) {
1399         POVS_MESSAGE_ERROR msgError = (POVS_MESSAGE_ERROR)
1400             usrParamsCtx->outputBuffer;
1401
1402         NlBuildErrorMsg(msgIn, msgError, nlError);
1403         *replyLen = msgError->nlMsg.nlmsgLen;
1404     }
1405
1406     return STATUS_SUCCESS;
1407 }
1408
1409
1410 NTSTATUS
1411 OvsSetupDumpStart(POVS_USER_PARAMS_CONTEXT usrParamsCtx)
1412 {
1413     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1414     POVS_OPEN_INSTANCE instance =
1415         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1416
1417     /* input buffer has been validated while validating write dev op. */
1418     ASSERT(msgIn != NULL && usrParamsCtx->inputLength >= sizeof *msgIn);
1419
1420     /* A write operation that does not indicate dump start is invalid. */
1421     if ((msgIn->nlMsg.nlmsgFlags & NLM_F_DUMP) != NLM_F_DUMP) {
1422         return STATUS_INVALID_PARAMETER;
1423     }
1424     /* XXX: Handle other NLM_F_* flags in the future. */
1425
1426     /*
1427      * This operation should be setting up the dump state. If there's any
1428      * previous state, clear it up so as to set it up afresh.
1429      */
1430     FreeUserDumpState(instance);
1431
1432     return InitUserDumpState(instance, msgIn);
1433 }
1434
1435
1436 /*
1437  * --------------------------------------------------------------------------
1438  *  Utility function to map the output buffer in an IRP. The buffer is assumed
1439  *  to have been passed down using METHOD_OUT_DIRECT (Direct I/O).
1440  * --------------------------------------------------------------------------
1441  */
1442 static NTSTATUS
1443 MapIrpOutputBuffer(PIRP irp,
1444                    UINT32 bufferLength,
1445                    UINT32 requiredLength,
1446                    PVOID *buffer)
1447 {
1448     ASSERT(irp);
1449     ASSERT(buffer);
1450     ASSERT(bufferLength);
1451     ASSERT(requiredLength);
1452     if (!buffer || !irp || bufferLength == 0 || requiredLength == 0) {
1453         return STATUS_INVALID_PARAMETER;
1454     }
1455
1456     if (bufferLength < requiredLength) {
1457         return STATUS_NDIS_INVALID_LENGTH;
1458     }
1459     if (irp->MdlAddress == NULL) {
1460         return STATUS_INVALID_PARAMETER;
1461     }
1462     *buffer = MmGetSystemAddressForMdlSafe(irp->MdlAddress,
1463                                            NormalPagePriority);
1464     if (*buffer == NULL) {
1465         return STATUS_INSUFFICIENT_RESOURCES;
1466     }
1467
1468     return STATUS_SUCCESS;
1469 }
1470
1471 /*
1472  * --------------------------------------------------------------------------
1473  * Utility function to fill up information about the state of a port in a reply
1474  * to* userspace.
1475  * --------------------------------------------------------------------------
1476  */
1477 static NTSTATUS
1478 OvsPortFillInfo(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1479                 POVS_EVENT_ENTRY eventEntry,
1480                 PNL_BUFFER nlBuf)
1481 {
1482     NTSTATUS status;
1483     BOOLEAN ok;
1484     OVS_MESSAGE msgOutTmp;
1485     PNL_MSG_HDR nlMsg;
1486     POVS_VPORT_ENTRY vport;
1487
1488     ASSERT(NlBufAt(nlBuf, 0, 0) != 0 && nlBuf->bufRemLen >= sizeof msgOutTmp);
1489
1490     msgOutTmp.nlMsg.nlmsgType = OVS_WIN_NL_VPORT_FAMILY_ID;
1491     msgOutTmp.nlMsg.nlmsgFlags = 0;  /* XXX: ? */
1492
1493     /* driver intiated messages should have zerp seq number*/
1494     msgOutTmp.nlMsg.nlmsgSeq = 0;
1495     msgOutTmp.nlMsg.nlmsgPid = usrParamsCtx->ovsInstance->pid;
1496
1497     msgOutTmp.genlMsg.version = nlVportFamilyOps.version;
1498     msgOutTmp.genlMsg.reserved = 0;
1499
1500     /* we don't have netdev yet, treat link up/down a adding/removing a port*/
1501     if (eventEntry->status & (OVS_EVENT_LINK_UP | OVS_EVENT_CONNECT)) {
1502         msgOutTmp.genlMsg.cmd = OVS_VPORT_CMD_NEW;
1503     } else if (eventEntry->status &
1504              (OVS_EVENT_LINK_DOWN | OVS_EVENT_DISCONNECT)) {
1505         msgOutTmp.genlMsg.cmd = OVS_VPORT_CMD_DEL;
1506     } else {
1507         ASSERT(FALSE);
1508         return STATUS_UNSUCCESSFUL;
1509     }
1510     msgOutTmp.ovsHdr.dp_ifindex = gOvsSwitchContext->dpNo;
1511
1512     ok = NlMsgPutHead(nlBuf, (PCHAR)&msgOutTmp, sizeof msgOutTmp);
1513     if (!ok) {
1514         status = STATUS_INVALID_BUFFER_SIZE;
1515         goto cleanup;
1516     }
1517
1518     vport = OvsFindVportByPortNo(gOvsSwitchContext, eventEntry->portNo);
1519     if (!vport) {
1520         status = STATUS_DEVICE_DOES_NOT_EXIST;
1521         goto cleanup;
1522     }
1523
1524     ok = NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_PORT_NO, eventEntry->portNo) &&
1525          NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_TYPE, vport->ovsType) &&
1526          NlMsgPutTailU32(nlBuf, OVS_VPORT_ATTR_UPCALL_PID,
1527                          vport->upcallPid) &&
1528          NlMsgPutTailString(nlBuf, OVS_VPORT_ATTR_NAME, vport->ovsName);
1529     if (!ok) {
1530         status = STATUS_INVALID_BUFFER_SIZE;
1531         goto cleanup;
1532     }
1533
1534     /* XXXX Should we add the port stats attributes?*/
1535     nlMsg = (PNL_MSG_HDR)NlBufAt(nlBuf, 0, 0);
1536     nlMsg->nlmsgLen = NlBufSize(nlBuf);
1537     status = STATUS_SUCCESS;
1538
1539 cleanup:
1540     return status;
1541 }
1542
1543
1544 /*
1545  * --------------------------------------------------------------------------
1546  * Handler for reading events from the driver event queue. This handler is
1547  * executed when user modes issues a socket receive on a socket assocaited
1548  * with the MC group for events.
1549  * XXX user mode should read multiple events in one system call
1550  * --------------------------------------------------------------------------
1551  */
1552 static NTSTATUS
1553 OvsReadEventCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1554                        UINT32 *replyLen)
1555 {
1556 #ifdef DBG
1557     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1558     POVS_OPEN_INSTANCE instance =
1559         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1560 #endif
1561     NL_BUFFER nlBuf;
1562     NTSTATUS status;
1563     OVS_EVENT_ENTRY eventEntry;
1564
1565     ASSERT(usrParamsCtx->devOp == OVS_READ_DEV_OP);
1566
1567     /* Should never read events with a dump socket */
1568     ASSERT(instance->dumpState.ovsMsg == NULL);
1569
1570     /* Must have an event queue */
1571     ASSERT(instance->eventQueue != NULL);
1572
1573     /* Output buffer has been validated while validating read dev op. */
1574     ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1575
1576     NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength);
1577
1578     /* remove an event entry from the event queue */
1579     status = OvsRemoveEventEntry(usrParamsCtx->ovsInstance, &eventEntry);
1580     if (status != STATUS_SUCCESS) {
1581         /* If there were not elements, read should return no data. */
1582         status = STATUS_SUCCESS;
1583         *replyLen = 0;
1584         goto cleanup;
1585     }
1586
1587     status = OvsPortFillInfo(usrParamsCtx, &eventEntry, &nlBuf);
1588     if (status == NDIS_STATUS_SUCCESS) {
1589         *replyLen = NlBufSize(&nlBuf);
1590     }
1591
1592 cleanup:
1593     return status;
1594 }
1595
1596 /*
1597  * --------------------------------------------------------------------------
1598  * Handler for reading missed pacckets from the driver event queue. This
1599  * handler is executed when user modes issues a socket receive on a socket
1600  * --------------------------------------------------------------------------
1601  */
1602 static NTSTATUS
1603 OvsReadPacketCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1604                        UINT32 *replyLen)
1605 {
1606 #ifdef DBG
1607     POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer;
1608 #endif
1609     POVS_OPEN_INSTANCE instance =
1610         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1611     NTSTATUS status;
1612
1613     ASSERT(usrParamsCtx->devOp == OVS_READ_DEV_OP);
1614
1615     /* Should never read events with a dump socket */
1616     ASSERT(instance->dumpState.ovsMsg == NULL);
1617
1618     /* Must have an packet queue */
1619     ASSERT(instance->packetQueue != NULL);
1620
1621     /* Output buffer has been validated while validating read dev op. */
1622     ASSERT(msgOut != NULL && usrParamsCtx->outputLength >= sizeof *msgOut);
1623
1624     /* Read a packet from the instance queue */
1625     status = OvsReadDpIoctl(instance->fileObject, usrParamsCtx->outputBuffer,
1626                             usrParamsCtx->outputLength, replyLen);
1627     return status;
1628 }
1629
1630 /*
1631  * --------------------------------------------------------------------------
1632  *  Handler for the subscription for a packet queue
1633  * --------------------------------------------------------------------------
1634  */
1635 static NTSTATUS
1636 OvsSubscribePacketCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1637                             UINT32 *replyLen)
1638 {
1639     NDIS_STATUS status;
1640     BOOLEAN rc;
1641     UINT8 join;
1642     UINT32 pid;
1643     const NL_POLICY policy[] =  {
1644         [OVS_NL_ATTR_PACKET_PID] = {.type = NL_A_U32 },
1645         [OVS_NL_ATTR_PACKET_SUBSCRIBE] = {.type = NL_A_U8 }
1646         };
1647     PNL_ATTR attrs[ARRAY_SIZE(policy)];
1648
1649     UNREFERENCED_PARAMETER(replyLen);
1650
1651     POVS_OPEN_INSTANCE instance =
1652         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1653     POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer;
1654
1655     rc = NlAttrParse(&msgIn->nlMsg, sizeof (*msgIn),
1656          NlMsgAttrsLen((PNL_MSG_HDR)msgIn), policy, attrs, ARRAY_SIZE(attrs));
1657     if (!rc) {
1658         status = STATUS_INVALID_PARAMETER;
1659         goto done;
1660     }
1661
1662     join = NlAttrGetU8(attrs[OVS_NL_ATTR_PACKET_PID]);
1663     pid = NlAttrGetU32(attrs[OVS_NL_ATTR_PACKET_PID]);
1664
1665     /* The socket subscribed with must be the same socket we perform receive*/
1666     ASSERT(pid == instance->pid);
1667
1668     status = OvsSubscribeDpIoctl(instance, pid, join);
1669
1670     /*
1671      * XXX Need to add this instance to a global data structure
1672      * which hold all packet based instances. The data structure (hash)
1673      * should be searched through the pid field of the instance for
1674      * placing the missed packet into the correct queue
1675      */
1676 done:
1677     return status;
1678 }
1679
1680 /*
1681  * --------------------------------------------------------------------------
1682  * Handler for queueing an IRP used for missed packet notification. The IRP is
1683  * completed when a packet received and mismatched. STATUS_PENDING is returned
1684  * on success. User mode keep a pending IRP at all times.
1685  * --------------------------------------------------------------------------
1686  */
1687 static NTSTATUS
1688 OvsPendPacketCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx,
1689                        UINT32 *replyLen)
1690 {
1691     UNREFERENCED_PARAMETER(replyLen);
1692
1693     POVS_OPEN_INSTANCE instance =
1694         (POVS_OPEN_INSTANCE)usrParamsCtx->ovsInstance;
1695
1696     /*
1697      * XXX access to packet queue must be through acquiring a lock as user mode
1698      * could unsubscribe and the instnace will be freed.
1699      */
1700     return OvsWaitDpIoctl(usrParamsCtx->irp, instance->fileObject);
1701 }