summaryrefslogtreecommitdiff
path: root/open-vm-tools/modules/linux/vmci/common/vmciDoorbell.c
blob: 5a3fbfd5e333467de52cf112b781812cbdd6d8cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
/*********************************************************
 * Copyright (C) 2010 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation version 2 and no later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 *
 *********************************************************/

/*
 * vmciDoorbell.c --
 *
 *    This file implements the VMCI doorbell API on the host.
 */

#include "vmci_kernel_if.h"
#include "vm_assert.h"
#include "vmci_defs.h"
#include "vmci_infrastructure.h"
#include "vmciCommonInt.h"
#include "vmciDatagram.h"
#include "vmciDoorbell.h"
#include "vmciDriver.h"
#include "vmciKernelAPI.h"
#include "vmciResource.h"
#include "vmciRoute.h"
#if defined(VMKERNEL)
#  include "vmciVmkInt.h"
#  include "vm_libc.h"
#  include "helper_ext.h"
#endif

#define LGPFX "VMCIDoorbell: "

#if !defined(__APPLE__)

#define VMCI_DOORBELL_INDEX_TABLE_SIZE 64
#define VMCI_DOORBELL_HASH(_idx) \
   VMCI_HashId((_idx), VMCI_DOORBELL_INDEX_TABLE_SIZE)


/*
 * DoorbellEntry describes the a doorbell notification handle allocated by the
 * host.
 */

typedef struct VMCIDoorbellEntry {
   VMCIResource        resource;
   uint32              idx;
   VMCIListItem        idxListItem;
   VMCIPrivilegeFlags  privFlags;
   Bool                isDoorbell;
   Bool                runDelayed;
   VMCICallback        notifyCB;
   void                *clientData;
   VMCIEvent           destroyEvent;
   Atomic_uint32       active;       // Only used by guest personality
} VMCIDoorbellEntry;

typedef struct VMCIDoorbellIndexTable {
   VMCILock lock;
   VMCIList entries[VMCI_DOORBELL_INDEX_TABLE_SIZE];
} VMCIDoorbellIndexTable;


/* The VMCI index table keeps track of currently registered doorbells. */
static VMCIDoorbellIndexTable vmciDoorbellIT;


/*
 * The maxNotifyIdx is one larger than the currently known bitmap index in
 * use, and is used to determine how much of the bitmap needs to be scanned.
 */

static uint32 maxNotifyIdx;

/*
 * The notifyIdxCount is used for determining whether there are free entries
 * within the bitmap (if notifyIdxCount + 1 < maxNotifyIdx).
 */

static uint32 notifyIdxCount;

/*
 * The lastNotifyIdxReserved is used to track the last index handed out - in
 * the case where multiple handles share a notification index, we hand out
 * indexes round robin based on lastNotifyIdxReserved.
 */

static uint32 lastNotifyIdxReserved;

/* This is a one entry cache used to by the index allocation. */
static uint32 lastNotifyIdxReleased = PAGE_SIZE;


static void VMCIDoorbellFreeCB(void *clientData);
static int VMCIDoorbellReleaseCB(void *clientData);
static void VMCIDoorbellDelayedDispatchCB(void *data);


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbell_Init --
 *
 *    General init code.
 *
 * Result:
 *    VMCI_SUCCESS on success, lock allocation error otherwise.
 *
 * Side effects:
 *    None.
 *
 *------------------------------------------------------------------------------
 */

int
VMCIDoorbell_Init(void)
{
   uint32 bucket;

   for (bucket = 0; bucket < ARRAYSIZE(vmciDoorbellIT.entries); ++bucket) {
      VMCIList_Init(&vmciDoorbellIT.entries[bucket]);
   }

   return VMCI_InitLock(&vmciDoorbellIT.lock, "VMCIDoorbellIndexTableLock",
                        VMCI_LOCK_RANK_DOORBELL);
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbell_Exit --
 *
 *    General init code.
 *
 * Result:
 *    None.
 *
 * Side effects:
 *    None.
 *
 *------------------------------------------------------------------------------
 */

void
VMCIDoorbell_Exit(void)
{
   VMCI_CleanupLock(&vmciDoorbellIT.lock);
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbellFreeCB --
 *
 *    Callback to free doorbell entry structure when resource is no longer used,
 *    ie. the reference count reached 0.  The entry is freed in
 *    VMCIDoorbell_Destroy(), which is waiting on the signal that gets fired
 *    here.
 *
 * Result:
 *    None.
 *
 * Side effects:
 *    Signals VMCI event.
 *
 *------------------------------------------------------------------------------
 */

static void
VMCIDoorbellFreeCB(void *clientData)  // IN
{
   VMCIDoorbellEntry *entry = (VMCIDoorbellEntry *)clientData;
   ASSERT(entry);
   VMCI_SignalEvent(&entry->destroyEvent);
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbellReleaseCB --
 *
 *     Callback to release the resource reference. It is called by the
 *     VMCI_WaitOnEvent function before it blocks.
 *
 * Result:
 *     Always 0.
 *
 * Side effects:
 *     None.
 *
 *------------------------------------------------------------------------------
 */

static int
VMCIDoorbellReleaseCB(void *clientData) // IN: doorbell entry
{
   VMCIDoorbellEntry *entry = (VMCIDoorbellEntry *)clientData;
   ASSERT(entry);
   VMCIResource_Release(&entry->resource);
   return 0;
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbellGetPrivFlags --
 *
 *    Utility function that retrieves the privilege flags associated
 *    with a given doorbell handle. For guest endpoints, the
 *    privileges are determined by the context ID, but for host
 *    endpoints privileges are associated with the complete
 *    handle. Hypervisor endpoints are not yet supported.
 *
 * Result:
 *    VMCI_SUCCESS on success,
 *    VMCI_ERROR_NOT_FOUND if handle isn't found,
 *    VMCI_ERROR_INVALID_ARGS if handle is invalid.
 *
 * Side effects:
 *    None.
 *
 *------------------------------------------------------------------------------
 */

int
VMCIDoorbellGetPrivFlags(VMCIHandle handle,             // IN
                         VMCIPrivilegeFlags *privFlags) // OUT
{
   if (privFlags == NULL || handle.context == VMCI_INVALID_ID) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   if (handle.context == VMCI_HOST_CONTEXT_ID) {
      VMCIDoorbellEntry *entry;
      VMCIResource *resource;

      resource = VMCIResource_Get(handle, VMCI_RESOURCE_TYPE_DOORBELL);
      if (resource == NULL) {
         return VMCI_ERROR_NOT_FOUND;
      }
      entry = RESOURCE_CONTAINER(resource, VMCIDoorbellEntry, resource);
      *privFlags = entry->privFlags;
      VMCIResource_Release(resource);
   } else if (handle.context == VMCI_HYPERVISOR_CONTEXT_ID) {
       /* Hypervisor endpoints for notifications are not supported (yet). */
      return VMCI_ERROR_INVALID_ARGS;
   } else {
      *privFlags = vmci_context_get_priv_flags(handle.context);
   }

   return VMCI_SUCCESS;
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCIDoorbellIndexTableFind --
 *
 *    Find doorbell entry by bitmap index.
 *
 * Results:
 *    Entry if found, NULL if not.
 *
 * Side effects:
 *    None.
 *
 *-----------------------------------------------------------------------------
 */

static VMCIDoorbellEntry *
VMCIDoorbellIndexTableFind(uint32 idx) // IN
{
   uint32 bucket = VMCI_DOORBELL_HASH(idx);
   VMCIListItem *iter;

   ASSERT(VMCI_GuestPersonalityActive());

   VMCIList_Scan(iter, &vmciDoorbellIT.entries[bucket]) {
      VMCIDoorbellEntry *cur =
         VMCIList_Entry(iter, VMCIDoorbellEntry, idxListItem);

      ASSERT(cur);

      if (idx == cur->idx) {
         return cur;
      }
   }

   return NULL;
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbellIndexTableAdd --
 *
 *    Add the given entry to the index table.  This will hold() the entry's
 *    resource so that the entry is not deleted before it is removed from the
 *    table.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    None.
 *
 *------------------------------------------------------------------------------
 */

static void
VMCIDoorbellIndexTableAdd(VMCIDoorbellEntry *entry) // IN/OUT
{
   uint32 bucket;
   uint32 newNotifyIdx;
   VMCILockFlags flags;

   ASSERT(entry);
   ASSERT(VMCI_GuestPersonalityActive());

   VMCIResource_Hold(&entry->resource);

   VMCI_GrabLock_BH(&vmciDoorbellIT.lock, &flags);

   /*
    * Below we try to allocate an index in the notification bitmap with "not
    * too much" sharing between resources. If we use less that the full bitmap,
    * we either add to the end if there are no unused flags within the
    * currently used area, or we search for unused ones. If we use the full
    * bitmap, we allocate the index round robin.
    */

   if (maxNotifyIdx < PAGE_SIZE || notifyIdxCount < PAGE_SIZE) {
      if (lastNotifyIdxReleased < maxNotifyIdx &&
          !VMCIDoorbellIndexTableFind(lastNotifyIdxReleased)) {
         newNotifyIdx = lastNotifyIdxReleased;
         lastNotifyIdxReleased = PAGE_SIZE;
      } else {
         Bool reused = FALSE;
         newNotifyIdx = lastNotifyIdxReserved;
         if (notifyIdxCount + 1 < maxNotifyIdx) {
            do {
               if (!VMCIDoorbellIndexTableFind(newNotifyIdx)) {
                  reused = TRUE;
                  break;
               }
               newNotifyIdx = (newNotifyIdx + 1) % maxNotifyIdx;
            } while(newNotifyIdx != lastNotifyIdxReleased);
         }
         if (!reused) {
            newNotifyIdx = maxNotifyIdx;
            maxNotifyIdx++;
         }
      }
   } else {
      newNotifyIdx = (lastNotifyIdxReserved + 1) % PAGE_SIZE;
   }
   lastNotifyIdxReserved = newNotifyIdx;
   notifyIdxCount++;

   entry->idx = newNotifyIdx;
   bucket = VMCI_DOORBELL_HASH(entry->idx);
   VMCIList_Insert(&entry->idxListItem, &vmciDoorbellIT.entries[bucket]);

   VMCI_ReleaseLock_BH(&vmciDoorbellIT.lock, flags);
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbellIndexTableRemove --
 *
 *    Remove the given entry from the index table.  This will release() the
 *    entry's resource.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    None.
 *
 *------------------------------------------------------------------------------
 */

static void
VMCIDoorbellIndexTableRemove(VMCIDoorbellEntry *entry) // IN/OUT
{
   VMCILockFlags flags;

   ASSERT(entry);
   ASSERT(VMCI_GuestPersonalityActive());

   VMCI_GrabLock_BH(&vmciDoorbellIT.lock, &flags);

   VMCIList_Remove(&entry->idxListItem);

   notifyIdxCount--;
   if (entry->idx == maxNotifyIdx - 1) {
      /*
       * If we delete an entry with the maximum known notification index, we
       * take the opportunity to prune the current max. As there might be other
       * unused indices immediately below, we lower the maximum until we hit an
       * index in use.
       */

      while (maxNotifyIdx > 0 &&
             !VMCIDoorbellIndexTableFind(maxNotifyIdx - 1)) {
         maxNotifyIdx--;
      }
   }
   lastNotifyIdxReleased = entry->idx;

   VMCI_ReleaseLock_BH(&vmciDoorbellIT.lock, flags);

   VMCIResource_Release(&entry->resource);
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbellLink --
 *
 *    Creates a link between the given doorbell handle and the given
 *    index in the bitmap in the device backend.
 *
 * Results:
 *    VMCI_SUCCESS if success, appropriate error code otherwise.
 *
 * Side effects:
 *    Notification state is created in hypervisor.
 *
 *------------------------------------------------------------------------------
 */

static int
VMCIDoorbellLink(VMCIHandle handle, // IN
                 Bool isDoorbell,   // IN
                 uint32 notifyIdx)  // IN
{
#if defined(VMKERNEL)
   VMCI_WARNING((LGPFX"Cannot send down to host from VMKERNEL.\n"));
   return VMCI_ERROR_DST_UNREACHABLE;
#else // VMKERNEL
   VMCIId resourceID;
   VMCIDoorbellLinkMsg linkMsg;

   ASSERT(!VMCI_HANDLE_INVALID(handle));
   ASSERT(VMCI_GuestPersonalityActive());

   if (isDoorbell) {
      resourceID = VMCI_DOORBELL_LINK;
   } else {
      ASSERT(FALSE);
      return VMCI_ERROR_UNAVAILABLE;
   }

   linkMsg.hdr.dst = VMCI_MAKE_HANDLE(VMCI_HYPERVISOR_CONTEXT_ID, resourceID);
   linkMsg.hdr.src = VMCI_ANON_SRC_HANDLE;
   linkMsg.hdr.payloadSize = sizeof linkMsg - VMCI_DG_HEADERSIZE;
   linkMsg.handle = handle;
   linkMsg.notifyIdx = notifyIdx;

   return VMCI_SendDatagram((VMCIDatagram *)&linkMsg);
#endif // VMKERNEL
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbellUnlink --
 *
 *    Unlinks the given doorbell handle from an index in the bitmap in
 *    the device backend.
 *
 * Results:
 *      VMCI_SUCCESS if success, appropriate error code otherwise.
 *
 * Side effects:
 *      Notification state is destroyed in hypervisor.
 *
 *------------------------------------------------------------------------------
 */

static int
VMCIDoorbellUnlink(VMCIHandle handle, // IN
                   Bool isDoorbell)   // IN
{
#if defined(VMKERNEL)
   VMCI_WARNING((LGPFX"Cannot send down to host from VMKERNEL.\n"));
   return VMCI_ERROR_DST_UNREACHABLE;
#else // VMKERNEL
   VMCIId resourceID;
   VMCIDoorbellUnlinkMsg unlinkMsg;

   ASSERT(!VMCI_HANDLE_INVALID(handle));
   ASSERT(VMCI_GuestPersonalityActive());

   if (isDoorbell) {
      resourceID = VMCI_DOORBELL_UNLINK;
   } else {
      ASSERT(FALSE);
      return VMCI_ERROR_UNAVAILABLE;
   }

   unlinkMsg.hdr.dst = VMCI_MAKE_HANDLE(VMCI_HYPERVISOR_CONTEXT_ID, resourceID);
   unlinkMsg.hdr.src = VMCI_ANON_SRC_HANDLE;
   unlinkMsg.hdr.payloadSize = sizeof unlinkMsg - VMCI_DG_HEADERSIZE;
   unlinkMsg.handle = handle;

   return VMCI_SendDatagram((VMCIDatagram *)&unlinkMsg);
#endif // VMKERNEL
}


/*
 *------------------------------------------------------------------------------
 *
 * vmci_doorbell_create --
 *
 *    Creates a doorbell with the given callback. If the handle is
 *    VMCI_INVALID_HANDLE, a free handle will be assigned, if
 *    possible. The callback can be run immediately (potentially with
 *    locks held - the default) or delayed (in a kernel thread) by
 *    specifying the flag VMCI_FLAG_DELAYED_CB. If delayed execution
 *    is selected, a given callback may not be run if the kernel is
 *    unable to allocate memory for the delayed execution (highly
 *    unlikely).
 *
 * Results:
 *    VMCI_SUCCESS on success, appropriate error code otherwise.
 *
 * Side effects:
 *    None.
 *
 *------------------------------------------------------------------------------
 */

VMCI_EXPORT_SYMBOL(vmci_doorbell_create)
int
vmci_doorbell_create(VMCIHandle *handle,            // IN/OUT
                     uint32 flags,                  // IN
                     VMCIPrivilegeFlags privFlags,  // IN
                     VMCICallback notifyCB,         // IN
                     void *clientData)              // IN
{
   VMCIDoorbellEntry *entry;
   VMCIHandle newHandle;
   int result;

   if (!handle || !notifyCB || flags & ~VMCI_FLAG_DELAYED_CB ||
       privFlags & ~VMCI_PRIVILEGE_ALL_FLAGS) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   entry = VMCI_AllocKernelMem(sizeof *entry, VMCI_MEMORY_NONPAGED);
   if (entry == NULL) {
      VMCI_WARNING((LGPFX"Failed allocating memory for datagram entry.\n"));
      return VMCI_ERROR_NO_MEM;
   }

   if (!VMCI_CanScheduleDelayedWork() && (flags & VMCI_FLAG_DELAYED_CB)) {
      result = VMCI_ERROR_INVALID_ARGS;
      goto freeMem;
   }

   if (VMCI_HANDLE_INVALID(*handle)) {
      VMCIId contextID = vmci_get_context_id();
      VMCIId resourceID = VMCIResource_GetID(contextID);
      if (resourceID == VMCI_INVALID_ID) {
         result = VMCI_ERROR_NO_HANDLE;
         goto freeMem;
      }
      newHandle = VMCI_MAKE_HANDLE(contextID, resourceID);
   } else {
      Bool validContext;

      /*
       * Validate the handle.  We must do both of the checks below
       * because we can be acting as both a host and a guest at the
       * same time. We always allow the host context ID, since the
       * host functionality is in practice always there with the
       * unified driver.
       */

      validContext = FALSE;
      if (VMCI_HOST_CONTEXT_ID == handle->context) {
         validContext = TRUE;
      }
      if (VMCI_GuestPersonalityActive() &&
          vmci_get_context_id() == handle->context) {
         validContext = TRUE;
      }

      if (!validContext || VMCI_INVALID_ID == handle->resource) {
         VMCI_DEBUG_LOG(4, (LGPFX"Invalid argument (handle=0x%x:0x%x).\n",
                            handle->context, handle->resource));
         result = VMCI_ERROR_INVALID_ARGS;
         goto freeMem;
      }

      newHandle = *handle;
   }

   entry->idx = 0;
   VMCIList_Init(&entry->idxListItem);
   entry->privFlags = privFlags;
   entry->isDoorbell = TRUE;
   entry->runDelayed = (flags & VMCI_FLAG_DELAYED_CB) ? TRUE : FALSE;
   entry->notifyCB = notifyCB;
   entry->clientData = clientData;
   Atomic_Write(&entry->active, 0);
   VMCI_CreateEvent(&entry->destroyEvent);

   result = VMCIResource_Add(&entry->resource, VMCI_RESOURCE_TYPE_DOORBELL,
                             newHandle, VMCIDoorbellFreeCB, entry);
   if (result != VMCI_SUCCESS) {
      VMCI_WARNING((LGPFX"Failed to add new resource (handle=0x%x:0x%x).\n",
                    newHandle.context, newHandle.resource));
      if (result == VMCI_ERROR_DUPLICATE_ENTRY) {
         result = VMCI_ERROR_ALREADY_EXISTS;
      }
      goto destroy;
   }

   if (VMCI_GuestPersonalityActive()) {
      VMCIDoorbellIndexTableAdd(entry);
      result = VMCIDoorbellLink(newHandle, entry->isDoorbell, entry->idx);
      if (VMCI_SUCCESS != result) {
         goto destroyResource;
     }
      Atomic_Write(&entry->active, 1);
   }

   if (VMCI_HANDLE_INVALID(*handle)) {
      *handle = newHandle;
   }

   return result;

destroyResource:
   VMCIDoorbellIndexTableRemove(entry);
   VMCIResource_Remove(newHandle, VMCI_RESOURCE_TYPE_DOORBELL);
destroy:
   VMCI_DestroyEvent(&entry->destroyEvent);
freeMem:
   VMCI_FreeKernelMem(entry, sizeof *entry);
   return result;
}


/*
 *------------------------------------------------------------------------------
 *
 * vmci_doorbell_destroy --
 *
 *    Destroys a doorbell previously created with
 *    vmci_doorbell_create. This operation may block waiting for a
 *    callback to finish.
 *
 * Results:
 *    VMCI_SUCCESS on success, appropriate error code otherwise.
 *
 * Side effects:
 *    May block.
 *
 *------------------------------------------------------------------------------
 */

VMCI_EXPORT_SYMBOL(vmci_doorbell_destroy)
int
vmci_doorbell_destroy(VMCIHandle handle)  // IN
{
   VMCIDoorbellEntry *entry;
   VMCIResource *resource;

   if (VMCI_HANDLE_INVALID(handle)) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   resource = VMCIResource_Get(handle, VMCI_RESOURCE_TYPE_DOORBELL);
   if (resource == NULL) {
      VMCI_DEBUG_LOG(4, (LGPFX"Failed to destroy doorbell (handle=0x%x:0x%x).\n",
                         handle.context, handle.resource));
      return VMCI_ERROR_NOT_FOUND;
   }
   entry = RESOURCE_CONTAINER(resource, VMCIDoorbellEntry, resource);

   if (VMCI_GuestPersonalityActive()) {
      int result;

      VMCIDoorbellIndexTableRemove(entry);

      result = VMCIDoorbellUnlink(handle, entry->isDoorbell);
      if (VMCI_SUCCESS != result) {

         /*
          * The only reason this should fail would be an inconsistency between
          * guest and hypervisor state, where the guest believes it has an
          * active registration whereas the hypervisor doesn't. One case where
          * this may happen is if a doorbell is unregistered following a
          * hibernation at a time where the doorbell state hasn't been restored
          * on the hypervisor side yet. Since the handle has now been removed
          * in the guest, we just print a warning and return success.
          */

         VMCI_DEBUG_LOG(4, (LGPFX"Unlink of %s (handle=0x%x:0x%x) unknown by "
                            "hypervisor (error=%d).\n",
                            entry->isDoorbell ? "doorbell" : "queuepair",
                            handle.context, handle.resource, result));
      }
   }

   /*
    * Now remove the resource from the table.  It might still be in use
    * after this, in a callback or still on the delayed work queue.
    */

   VMCIResource_Remove(handle, VMCI_RESOURCE_TYPE_DOORBELL);

   /*
    * We now wait on the destroyEvent and release the reference we got
    * above.
    */

   VMCI_WaitOnEvent(&entry->destroyEvent, VMCIDoorbellReleaseCB, entry);

   /*
    * We know that we are now the only reference to the above entry so
    * can safely free it.
    */

   VMCI_DestroyEvent(&entry->destroyEvent);
   VMCI_FreeKernelMem(entry, sizeof *entry);

   return VMCI_SUCCESS;
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbellNotifyAsGuest --
 *
 *    Notify another guest or the host.  We send a datagram down to the
 *    host via the hypervisor with the notification info.
 *
 * Results:
 *    VMCI_SUCCESS on success, appropriate error code otherwise.
 *
 * Side effects:
 *    May do a hypercall.
 *
 *------------------------------------------------------------------------------
 */

static int
VMCIDoorbellNotifyAsGuest(VMCIHandle handle,            // IN
                          VMCIPrivilegeFlags privFlags) // IN
{
#if defined(VMKERNEL)
   VMCI_WARNING((LGPFX"Cannot send down to host from VMKERNEL.\n"));
   return VMCI_ERROR_DST_UNREACHABLE;
#else // VMKERNEL
   VMCIDoorbellNotifyMsg notifyMsg;

   ASSERT(VMCI_GuestPersonalityActive());

   notifyMsg.hdr.dst = VMCI_MAKE_HANDLE(VMCI_HYPERVISOR_CONTEXT_ID,
                                        VMCI_DOORBELL_NOTIFY);
   notifyMsg.hdr.src = VMCI_ANON_SRC_HANDLE;
   notifyMsg.hdr.payloadSize = sizeof notifyMsg - VMCI_DG_HEADERSIZE;
   notifyMsg.handle = handle;

   return VMCI_SendDatagram((VMCIDatagram *)&notifyMsg);
#endif // VMKERNEL
}


/*
 *------------------------------------------------------------------------------
 *
 * vmci_doorbell_notify --
 *
 *    Generates a notification on the doorbell identified by the
 *    handle. For host side generation of notifications, the caller
 *    can specify what the privilege of the calling side is.
 *
 * Results:
 *    VMCI_SUCCESS on success, appropriate error code otherwise.
 *
 * Side effects:
 *    May do a hypercall.
 *
 *------------------------------------------------------------------------------
 */

VMCI_EXPORT_SYMBOL(vmci_doorbell_notify)
int
vmci_doorbell_notify(VMCIHandle dst,               // IN
                     VMCIPrivilegeFlags privFlags) // IN
{
   int retval;
   VMCIRoute route;
   VMCIHandle src;

   if (VMCI_HANDLE_INVALID(dst) || (privFlags & ~VMCI_PRIVILEGE_ALL_FLAGS)) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   src = VMCI_INVALID_HANDLE;
   retval = VMCI_Route(&src, &dst, FALSE, &route);
   if (retval < VMCI_SUCCESS) {
      return retval;
   }

   if (VMCI_ROUTE_AS_HOST == route) {
      return VMCIContext_NotifyDoorbell(VMCI_HOST_CONTEXT_ID, dst, privFlags);
   }

   if (VMCI_ROUTE_AS_GUEST == route) {
      return VMCIDoorbellNotifyAsGuest(dst, privFlags);
   }

   VMCI_WARNING((LGPFX"Unknown route (%d) for doorbell.\n", route));
   return VMCI_ERROR_DST_UNREACHABLE;
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbellDelayedDispatchCB --
 *
 *    Calls the specified callback in a delayed context.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    None.
 *
 *------------------------------------------------------------------------------
 */

static void
VMCIDoorbellDelayedDispatchCB(void *data) // IN
{
   VMCIDoorbellEntry *entry = (VMCIDoorbellEntry *)data;

   ASSERT(data);

   entry->notifyCB(entry->clientData);

   VMCIResource_Release(&entry->resource);
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbellHostContextNotify --
 *
 *    Dispatches a doorbell notification to the host context.
 *
 * Results:
 *    VMCI_SUCCESS on success. Appropriate error code otherwise.
 *
 * Side effects:
 *    None.
 *
 *------------------------------------------------------------------------------
 */

int
VMCIDoorbellHostContextNotify(VMCIId srcCID,     // IN
                              VMCIHandle handle) // IN
{
   VMCIDoorbellEntry *entry;
   VMCIResource *resource;
   int result;

   ASSERT(VMCI_HostPersonalityActive());

   if (VMCI_HANDLE_INVALID(handle)) {
      VMCI_DEBUG_LOG(4,
                     (LGPFX"Notifying an invalid doorbell (handle=0x%x:0x%x).\n",
                      handle.context, handle.resource));
      return VMCI_ERROR_INVALID_ARGS;
   }

   resource = VMCIResource_Get(handle, VMCI_RESOURCE_TYPE_DOORBELL);
   if (resource == NULL) {
      VMCI_DEBUG_LOG(4,
                     (LGPFX"Notifying an unknown doorbell (handle=0x%x:0x%x).\n",
                      handle.context, handle.resource));
      return VMCI_ERROR_NOT_FOUND;
   }
   entry = RESOURCE_CONTAINER(resource, VMCIDoorbellEntry, resource);

   if (entry->runDelayed) {
      result = VMCI_ScheduleDelayedWork(VMCIDoorbellDelayedDispatchCB, entry);
      if (result < VMCI_SUCCESS) {
         /*
          * If we failed to schedule the delayed work, we need to
          * release the resource immediately. Otherwise, the resource
          * will be released once the delayed callback has been
          * completed.
          */

         VMCI_DEBUG_LOG(10, (LGPFX"Failed to schedule delayed doorbell "
                             "notification (result=%d).\n", result));
         VMCIResource_Release(resource);
      }
   } else {
      entry->notifyCB(entry->clientData);
      VMCIResource_Release(resource);
      result = VMCI_SUCCESS;
   }
   return result;
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbell_Hibernate --
 *
 *      When a guest leaves hibernation, the device driver state is out of sync
 *      with the device state, since the driver state has doorbells registered
 *      that aren't known to the device.  This function takes care of
 *      reregistering any doorbells. In case an error occurs during
 *      reregistration (this is highly unlikely since 1) it succeeded the first
 *      time 2) the device driver is the only source of doorbell registrations),
 *      we simply log the error.  The doorbell can still be destroyed using
 *      VMCIDoorbell_Destroy.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *------------------------------------------------------------------------------
 */

void
VMCIDoorbell_Hibernate(Bool enterHibernate)
{
   uint32 bucket;
   VMCIListItem *iter;
   VMCILockFlags flags;

   if (!VMCI_GuestPersonalityActive() || enterHibernate) {
      return;
   }

   VMCI_GrabLock_BH(&vmciDoorbellIT.lock, &flags);

   for (bucket = 0; bucket < ARRAYSIZE(vmciDoorbellIT.entries); bucket++) {
      VMCIList_Scan(iter, &vmciDoorbellIT.entries[bucket]) {
         int result;
         VMCIHandle h;
         VMCIDoorbellEntry *cur;

         cur = VMCIList_Entry(iter, VMCIDoorbellEntry, idxListItem);
         h = VMCIResource_Handle(&cur->resource);
         result = VMCIDoorbellLink(h, cur->isDoorbell, cur->idx);
         if (result != VMCI_SUCCESS && result != VMCI_ERROR_DUPLICATE_ENTRY) {
            VMCI_WARNING((LGPFX"Failed to reregister doorbell "
                          "(handle=0x%x:0x%x) of resource %s to index "
                          "(error=%d).\n",
                          h.context, h.resource,
                          cur->isDoorbell ? "doorbell" : "queue pair", result));
         }
      }
   }

   VMCI_ReleaseLock_BH(&vmciDoorbellIT.lock, flags);
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCIDoorbell_Sync --
 *
 *      Use this as a synchronization point when setting globals, for example,
 *      during device shutdown.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *------------------------------------------------------------------------------
 */

void
VMCIDoorbell_Sync(void)
{
   VMCILockFlags flags;
   VMCI_GrabLock_BH(&vmciDoorbellIT.lock, &flags);
   VMCI_ReleaseLock_BH(&vmciDoorbellIT.lock, flags);
   VMCIResource_Sync();
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCI_RegisterNotificationBitmap --
 *
 *      Register the notification bitmap with the host.
 *
 * Results:
 *      TRUE if the bitmap is registered successfully with the device, FALSE
 *      otherwise.
 *
 * Side effects:
 *      None.
 *
 *------------------------------------------------------------------------------
 */

Bool
VMCI_RegisterNotificationBitmap(PPN bitmapPPN)
{
   int result;
   VMCINotifyBitmapSetMsg bitmapSetMsg;

   /*
    * Do not ASSERT() on the guest device here.  This function can get called
    * during device initialization, so the ASSERT() will fail even though
    * the device is (almost) up.
    */

   bitmapSetMsg.hdr.dst = VMCI_MAKE_HANDLE(VMCI_HYPERVISOR_CONTEXT_ID,
                                           VMCI_SET_NOTIFY_BITMAP);
   bitmapSetMsg.hdr.src = VMCI_ANON_SRC_HANDLE;
   bitmapSetMsg.hdr.payloadSize = sizeof bitmapSetMsg - VMCI_DG_HEADERSIZE;
   bitmapSetMsg.bitmapPPN = bitmapPPN;

   result = VMCI_SendDatagram((VMCIDatagram *)&bitmapSetMsg);
   if (result != VMCI_SUCCESS) {
      VMCI_DEBUG_LOG(4, (LGPFX"Failed to register (PPN=%u) as "
                         "notification bitmap (error=%d).\n",
                         bitmapPPN, result));
      return FALSE;
   }
   return TRUE;
}


/*
 *-------------------------------------------------------------------------
 *
 * VMCIDoorbellFireEntries --
 *
 *     Executes or schedules the handlers for a given notify index.
 *
 * Result:
 *     Notification hash entry if found. NULL otherwise.
 *
 * Side effects:
 *     Whatever the side effects of the handlers are.
 *
 *-------------------------------------------------------------------------
 */

static void
VMCIDoorbellFireEntries(uint32 notifyIdx) // IN
{
   uint32 bucket = VMCI_DOORBELL_HASH(notifyIdx);
   VMCIListItem *iter;
   VMCILockFlags flags;

   ASSERT(VMCI_GuestPersonalityActive());

   VMCI_GrabLock_BH(&vmciDoorbellIT.lock, &flags);

   VMCIList_Scan(iter, &vmciDoorbellIT.entries[bucket]) {
      VMCIDoorbellEntry *cur =
         VMCIList_Entry(iter, VMCIDoorbellEntry, idxListItem);

      ASSERT(cur);

      if (cur->idx == notifyIdx && Atomic_Read(&cur->active) == 1) {
         ASSERT(cur->notifyCB);
         if (cur->runDelayed) {
            int err;

            VMCIResource_Hold(&cur->resource);
            err = VMCI_ScheduleDelayedWork(VMCIDoorbellDelayedDispatchCB, cur);
            if (err != VMCI_SUCCESS) {
               VMCIResource_Release(&cur->resource);
               goto out;
            }
         } else {
            cur->notifyCB(cur->clientData);
         }
      }
   }

out:
   VMCI_ReleaseLock_BH(&vmciDoorbellIT.lock, flags);
}


/*
 *------------------------------------------------------------------------------
 *
 * VMCI_ScanNotificationBitmap --
 *
 *      Scans the notification bitmap, collects pending notifications,
 *      resets the bitmap and invokes appropriate callbacks.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      May schedule tasks, allocate memory and run callbacks.
 *
 *------------------------------------------------------------------------------
 */

void
VMCI_ScanNotificationBitmap(uint8 *bitmap)
{
   uint32 idx;

   ASSERT(bitmap);
   ASSERT(VMCI_GuestPersonalityActive());

   for (idx = 0; idx < maxNotifyIdx; idx++) {
      if (bitmap[idx] & 0x1) {
         bitmap[idx] &= ~1;
         VMCIDoorbellFireEntries(idx);
      }
   }
}


#else // __APPLE__

/*
 *-----------------------------------------------------------------------------
 *
 * VMCIDoorbell_Create/VMCIDoorbell_Destroy/VMCIDoorbell_Notify/
 * VMCIDoorbellHostContextNotify/VMCIDoorbellGetPrivFlags/
 * VMCIDoorbell_Init/VMCIDoorbell_Exit --
 *
 *      The doorbell functions have yet to be implemented for Solaris
 *      and Mac OS X guest drivers.
 *
 * Results:
 *      VMCI_ERROR_UNAVAILABLE.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

VMCI_EXPORT_SYMBOL(VMCIDoorbell_Create)
int
VMCIDoorbell_Create(VMCIHandle *handle,            // IN
                    uint32 flags,                  // IN
                    VMCIPrivilegeFlags privFlags,  // IN
                    VMCICallback notifyCB,         // IN
                    void *clientData)              // IN
{
   return VMCI_ERROR_UNAVAILABLE;
}


VMCI_EXPORT_SYMBOL(VMCIDoorbell_Destroy)
int
VMCIDoorbell_Destroy(VMCIHandle handle)  // IN
{
   return VMCI_ERROR_UNAVAILABLE;
}


VMCI_EXPORT_SYMBOL(VMCIDoorbell_Notify)
int
VMCIDoorbell_Notify(VMCIHandle handle,             // IN
                    VMCIPrivilegeFlags privFlags)  // IN
{
   return VMCI_ERROR_UNAVAILABLE;
}


int
VMCIDoorbellHostContextNotify(VMCIId srcCID,     // IN
                              VMCIHandle handle) // IN
{
   return VMCI_ERROR_UNAVAILABLE;
}


int
VMCIDoorbellGetPrivFlags(VMCIHandle handle,             // IN
                         VMCIPrivilegeFlags *privFlags) // OUT
{
   return VMCI_ERROR_UNAVAILABLE;
}


int
VMCIDoorbell_Init(void)
{
   return VMCI_SUCCESS;
}


void
VMCIDoorbell_Exit(void)
{
}

#endif // __APPLE__