aboutsummaryrefslogtreecommitdiffstats
path: root/extras/mini-os/tpmback.c
blob: 0601eb375d3f3f677922412d4c61256ce5e1c3cb (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
/*
 * Copyright (c) 2010-2012 United States Government, as represented by
 * the Secretary of Defense.  All rights reserved.
 *
 * This code has been derived from drivers/xen/tpmback/tpmback.c
 * from the xen 2.6.18 linux kernel
 *
 * Copyright (c) 2005, IBM Corporation
 *
 * which was itself derived from drivers/xen/netback/netback.c
 * from the xen 2.6.18 linux kernel
 *
 * Copyright (c) 2002-2004, K A Fraser
 *
 * This code has also been derived from drivers/xen/tpmback/xenbus.c
 * from the xen 2.6.18 linux kernel
 *
 * Copyright (C) 2005 IBM Corporation
 * Copyright (C) 2005 Rusty Russell <rusty@rustcorp.com.au>
 *
 * This code has also been derived from drivers/xen/tpmback/interface.c
 * from the xen 2.6.18 linux kernel
 *
 * Copyright (c) 2005, IBM Corporation
 *
 * which was itself also derived from drvivers/xen/netback/interface.c
 * from the xen 2.6.18 linux kernel
 *
 * Copyright (c) 2004, Keir Fraser
 *
 * 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
 * of the License
 */
#include <mini-os/os.h>
#include <mini-os/xenbus.h>
#include <mini-os/events.h>
#include <errno.h>
#include <mini-os/gnttab.h>
#include <xen/io/xenbus.h>
#include <xen/io/tpmif.h>
#include <xen/io/protocols.h>
#include <mini-os/xmalloc.h>
#include <time.h>
#include <mini-os/tpmback.h>
#include <mini-os/lib.h>
#include <fcntl.h>
#include <mini-os/mm.h>
#include <mini-os/posix/sys/mman.h>
#include <mini-os/semaphore.h>
#include <mini-os/wait.h>


#ifndef HAVE_LIBC
#define strtoul simple_strtoul
#endif

//#define TPMBACK_PRINT_DEBUG
#ifdef TPMBACK_PRINT_DEBUG
#define TPMBACK_DEBUG(fmt,...) printk("Tpmback:Debug("__FILE__":%d) " fmt, __LINE__, ##__VA_ARGS__)
#define TPMBACK_DEBUG_MORE(fmt,...) printk(fmt, ##__VA_ARGS__)
#else
#define TPMBACK_DEBUG(fmt,...)
#endif
#define TPMBACK_ERR(fmt,...) printk("Tpmback:Error " fmt, ##__VA_ARGS__)
#define TPMBACK_LOG(fmt,...) printk("Tpmback:Info " fmt, ##__VA_ARGS__)

#define min(a,b) (((a) < (b)) ? (a) : (b))

/* Default size of the tpmif array at initialization */
#define DEF_ARRAY_SIZE 1

/* tpmif and tpmdev flags */
#define TPMIF_CLOSED 1
#define TPMIF_REQ_READY 2

struct tpmif {
   domid_t domid;
   unsigned int handle;

   char* fe_path;
   char* fe_state_path;

   /* Locally bound event channel*/
   evtchn_port_t evtchn;

   /* Shared page */
   tpmif_shared_page_t *page;

   enum xenbus_state state;
   enum { DISCONNECTED, DISCONNECTING, CONNECTED } status;

   unsigned char uuid[16];
   void* opaque;

   /* state flags */
   int flags;
};
typedef struct tpmif tpmif_t;

struct tpmback_dev {

   tpmif_t** tpmlist;
   unsigned long num_tpms;
   unsigned long num_alloc;

   struct gntmap map;

   /* True if at least one tpmif has a request to be handled */
   int flags;

   xenbus_event_queue events;

   /* Callbacks */
   void (*open_callback)(domid_t, unsigned int);
   void (*close_callback)(domid_t, unsigned int);
};
typedef struct tpmback_dev tpmback_dev_t;

enum { EV_NONE, EV_NEWFE, EV_STCHNG } tpm_ev_enum;

/* Global objects */
static struct thread* eventthread = NULL;
static tpmback_dev_t gtpmdev = {
   .tpmlist = NULL,
   .num_tpms = 0,
   .num_alloc = 0,
   .flags = TPMIF_CLOSED,
   .events = NULL,
   .open_callback = NULL,
   .close_callback = NULL,
};
struct wait_queue_head waitq;
int globalinit = 0;

/************************************
 * TPMIF SORTED ARRAY FUNCTIONS
 * tpmback_dev_t.tpmlist is a sorted array, sorted by domid and then handle number
 * Duplicates are not allowed
 * **********************************/

inline void tpmif_req_ready(tpmif_t* tpmif) {
   tpmif->flags |= TPMIF_REQ_READY;
   gtpmdev.flags |= TPMIF_REQ_READY;
}

inline void tpmdev_check_req(void) {
   int i;
   int flags;
   local_irq_save(flags);
   for(i = 0; i < gtpmdev.num_tpms; ++i) {
      if(gtpmdev.tpmlist[i]->flags & TPMIF_REQ_READY) {
	 gtpmdev.flags |= TPMIF_REQ_READY;
	 local_irq_restore(flags);
	 return;
      }
   }
   gtpmdev.flags &= ~TPMIF_REQ_READY;
   local_irq_restore(flags);
}

inline void tpmif_req_finished(tpmif_t* tpmif) {
   tpmif->flags &= ~TPMIF_REQ_READY;
   tpmdev_check_req();
}

int __get_tpmif_index(int st, int n, domid_t domid, unsigned int handle)
{
   int i = st + n /2;
   tpmif_t* tmp;

   if( n <= 0 )
      return -1;

   tmp = gtpmdev.tpmlist[i];
   if(domid == tmp->domid && tmp->handle == handle) {
      return i;
   } else if ( (domid < tmp->domid) ||
	 (domid == tmp->domid && handle < tmp->handle)) {
      return __get_tpmif_index(st, n/2, domid, handle);
   } else {
      return __get_tpmif_index(i + 1, n/2 - ((n +1) % 2), domid, handle);
   }
}

/* Returns the array index of the tpmif domid/handle. Returns -1 if no such tpmif exists */
int get_tpmif_index(domid_t domid, unsigned int handle)
{
   int flags;
   int index;
   local_irq_save(flags);
   index = __get_tpmif_index(0, gtpmdev.num_tpms, domid, handle);
   local_irq_restore(flags);
   return index;
}

/* Returns the tpmif domid/handle or NULL if none exists */
tpmif_t* get_tpmif(domid_t domid, unsigned int handle)
{
   int flags;
   int i;
   tpmif_t* ret;
   local_irq_save(flags);
   i = get_tpmif_index(domid, handle);
   if (i < 0) {
      ret = NULL;
   } else {
      ret = gtpmdev.tpmlist[i];
   }
   local_irq_restore(flags);
   return ret;
}

/* Remove the given tpmif. Returns 0 if it was removed, -1 if it was not removed */
int remove_tpmif(tpmif_t* tpmif)
{
   int i, j;
   char* err;
   int flags;
   local_irq_save(flags);

   /* Find the index in the array if it exists */
   i = get_tpmif_index(tpmif->domid, tpmif->handle);
   if (i < 0) {
      goto error;
   }

   /* Remove the interface from the list */
   for(j = i; j < gtpmdev.num_tpms - 1; ++j) {
      gtpmdev.tpmlist[j] = gtpmdev.tpmlist[j+1];
   }
   gtpmdev.tpmlist[j] = NULL;
   --gtpmdev.num_tpms;

   /* If removed tpm was the only ready tpm, then we need to check and turn off the ready flag */
   tpmdev_check_req();

   local_irq_restore(flags);

   /* Stop listening for events on this tpm interface */
   if((err = xenbus_unwatch_path_token(XBT_NIL, tpmif->fe_state_path, tpmif->fe_state_path))) {
      TPMBACK_ERR("Unable to unwatch path token `%s' Error was %s Ignoring..\n", tpmif->fe_state_path, err);
      free(err);
   }

   return 0;
error:
   local_irq_restore(flags);
   return -1;
}

/* Insert tpmif into dev->tpmlist. Returns 0 on success and non zero on error.
 * It is an error to insert a tpmif with the same domid and handle
 * number
 * as something already in the list */
int insert_tpmif(tpmif_t* tpmif)
{
   int flags;
   unsigned int i, j;
   tpmif_t* tmp;
   char* err;
   char path[512];

   local_irq_save(flags);

   /*Check if we need to allocate more space */
   if (gtpmdev.num_tpms == gtpmdev.num_alloc) {
      gtpmdev.num_alloc *= 2;
      gtpmdev.tpmlist = realloc(gtpmdev.tpmlist, gtpmdev.num_alloc);
   }

   /*Find where to put the new interface */
   for(i = 0; i < gtpmdev.num_tpms; ++i)
   {
      tmp = gtpmdev.tpmlist[i];
      if(tpmif->domid == tmp->domid && tpmif->handle == tmp->handle) {
	 TPMBACK_ERR("Tried to insert duplicate tpm interface %u/%u\n", (unsigned int) tpmif->domid, tpmif->handle);
	 goto error;
      }
      if((tpmif->domid < tmp->domid) ||
	    (tpmif->domid == tmp->domid && tpmif->handle < tmp->handle)) {
	 break;
      }
   }

   /*Shift all the tpm pointers past i down one */
   for(j = gtpmdev.num_tpms; j > i; --j) {
      gtpmdev.tpmlist[j] = gtpmdev.tpmlist[j-1];
   }

   /*Add the new interface */
   gtpmdev.tpmlist[i] = tpmif;
   ++gtpmdev.num_tpms;

   /*Should not be needed, anything inserted with ready flag is probably an error */
   tpmdev_check_req();

   local_irq_restore(flags);

   snprintf(path, 512, "backend/vtpm/%u/%u/feature-protocol-v2", (unsigned int) tpmif->domid, tpmif->handle);
   if ((err = xenbus_write(XBT_NIL, path, "1")))
   {
      /* if we got an error here we should carefully remove the interface and then return */
      TPMBACK_ERR("Unable to write feature-protocol-v2 node: %s\n", err);
      free(err);
      remove_tpmif(tpmif);
      goto error_post_irq;
   }

   /*Listen for state changes on the new interface */
   if((err = xenbus_watch_path_token(XBT_NIL, tpmif->fe_state_path, tpmif->fe_state_path, &gtpmdev.events)))
   {
      /* if we got an error here we should carefully remove the interface and then return */
      TPMBACK_ERR("Unable to watch path token `%s' Error was %s\n", tpmif->fe_state_path, err);
      free(err);
      remove_tpmif(tpmif);
      goto error_post_irq;
   }
   return 0;
error:
   local_irq_restore(flags);
error_post_irq:
   return -1;
}


/*****************
 * CHANGE BACKEND STATE
 * *****************/
/*Attempts to change the backend state in xenstore
 * returns 0 on success and non-zero on error */
int tpmif_change_state(tpmif_t* tpmif, enum xenbus_state state)
{
   char path[512];
   char *value;
   char *err;
   enum xenbus_state readst;
   TPMBACK_DEBUG("Backend state change %u/%u from=%d to=%d\n", (unsigned int) tpmif->domid, tpmif->handle, tpmif->state, state);
   if (tpmif->state == state)
      return 0;

   snprintf(path, 512, "backend/vtpm/%u/%u/state", (unsigned int) tpmif->domid, tpmif->handle);

   if((err = xenbus_read(XBT_NIL, path, &value))) {
      TPMBACK_ERR("Unable to read backend state %s, error was %s\n", path, err);
      free(err);
      return -1;
   }
   if(sscanf(value, "%d", &readst) != 1) {
      TPMBACK_ERR("Non integer value (%s) in %s ??\n", value, path);
      free(value);
      return -1;
   }
   free(value);

   /* It's possible that the backend state got updated by hotplug or something else behind our back */
   if(readst != tpmif->state) {
      TPMBACK_DEBUG("tpm interface state was %d but xenstore state was %d!\n", tpmif->state, readst);
      tpmif->state = readst;
   }

   /*If if the state isnt changing, then we dont update xenstore b/c we dont want to fire extraneous events */
   if(tpmif->state == state) {
      return 0;
   }

   /*update xenstore*/
   snprintf(path, 512, "backend/vtpm/%u/%u", (unsigned int) tpmif->domid, tpmif->handle);
   if((err = xenbus_printf(XBT_NIL, path, "state", "%u", state))) {
      TPMBACK_ERR("Error writing to xenstore %s, error was %s new state=%d\n", path, err, state);
      free(err);
      return -1;
   }

   tpmif->state = state;

   return 0;
}
/**********************************
 * TPMIF CREATION AND DELETION
 * *******************************/
inline tpmif_t* __init_tpmif(domid_t domid, unsigned int handle)
{
   tpmif_t* tpmif;
   tpmif = malloc(sizeof(*tpmif));
   tpmif->domid = domid;
   tpmif->handle = handle;
   tpmif->fe_path = NULL;
   tpmif->fe_state_path = NULL;
   tpmif->state = XenbusStateInitialising;
   tpmif->status = DISCONNECTED;
   tpmif->page = NULL;
   tpmif->flags = 0;
   tpmif->opaque = NULL;
   memset(tpmif->uuid, 0, sizeof(tpmif->uuid));
   return tpmif;
}

void __free_tpmif(tpmif_t* tpmif)
{
   if(tpmif->fe_path) {
      free(tpmif->fe_path);
   }
   if(tpmif->fe_state_path) {
      free(tpmif->fe_state_path);
   }
   free(tpmif);
}
/* Creates a new tpm interface, adds it to the sorted array and returns it.
 * returns NULL on error
 * If the tpm interface already exists, it is returned*/
tpmif_t* new_tpmif(domid_t domid, unsigned int handle)
{
   tpmif_t* tpmif;
   char* err;
   char path[512];

   /* Make sure we haven't already created this tpm
    * Double events can occur */
   if((tpmif = get_tpmif(domid, handle)) != NULL) {
      return tpmif;
   }

   tpmif = __init_tpmif(domid, handle);

   /* Get the uuid from xenstore */
   snprintf(path, 512, "backend/vtpm/%u/%u/uuid", (unsigned int) domid, handle);
   if((!xenbus_read_uuid(path, tpmif->uuid))) {
      TPMBACK_ERR("Error reading %s\n", path);
      goto error;
   }

   if(tpmif_change_state(tpmif, XenbusStateInitWait)) {
      goto error;
   }

   snprintf(path, 512, "backend/vtpm/%u/%u/frontend", (unsigned int) domid, handle);
   if((err = xenbus_read(XBT_NIL, path, &tpmif->fe_path))) {
      TPMBACK_ERR("Error creating new tpm instance xenbus_read(%s), Error = %s", path, err);
      free(err);
      goto error;
   }

   /*Set the state path */
   tpmif->fe_state_path = malloc(strlen(tpmif->fe_path) + 7);
   strcpy(tpmif->fe_state_path, tpmif->fe_path);
   strcat(tpmif->fe_state_path, "/state");

   if(insert_tpmif(tpmif)) {
      goto error;
   }
   TPMBACK_DEBUG("New tpmif %u/%u\n", (unsigned int) tpmif->domid, tpmif->handle);
   /* Do the callback now */
   if(gtpmdev.open_callback) {
      gtpmdev.open_callback(tpmif->domid, tpmif->handle);
   }
   return tpmif;
error:
   __free_tpmif(tpmif);
   return NULL;

}

/* Removes tpmif from dev->tpmlist and frees it's memory usage */
void free_tpmif(tpmif_t* tpmif)
{
   char* err;
   char path[512];
   TPMBACK_DEBUG("Free tpmif %u/%u\n", (unsigned int) tpmif->domid, tpmif->handle);
   if(tpmif->flags & TPMIF_CLOSED) {
      TPMBACK_ERR("Tried to free an instance twice! Theres a bug somewhere!\n");
      BUG();
   }
   tpmif->flags = TPMIF_CLOSED;

   tpmif_change_state(tpmif, XenbusStateClosing);

   /* Unmap share page and unbind event channel */
   if(tpmif->status == CONNECTED) {
      tpmif->status = DISCONNECTING;
      mask_evtchn(tpmif->evtchn);

      if(gntmap_munmap(&gtpmdev.map, (unsigned long)tpmif->page, 1)) {
	 TPMBACK_ERR("%u/%u Error occured while trying to unmap shared page\n", (unsigned int) tpmif->domid, tpmif->handle);
      }

      unbind_evtchn(tpmif->evtchn);
   }
   tpmif->status = DISCONNECTED;
   tpmif_change_state(tpmif, XenbusStateClosed);

   /* Do the callback now */
   if(gtpmdev.close_callback) {
      gtpmdev.close_callback(tpmif->domid, tpmif->handle);
   }

   /* remove from array */
   remove_tpmif(tpmif);

   /* Wake up anyone possibly waiting on this interface and let them exit */
   wake_up(&waitq);
   schedule();

   /* Remove the old xenbus entries */
   snprintf(path, 512, "backend/vtpm/%u/%u", (unsigned int) tpmif->domid, tpmif->handle);
   if((err = xenbus_rm(XBT_NIL, path))) {
      TPMBACK_ERR("Error cleaning up xenbus entries path=%s error=%s\n", path, err);
      free(err);
   }

   TPMBACK_LOG("Frontend %u/%u disconnected\n", (unsigned int) tpmif->domid, tpmif->handle);

   /* free memory */
   __free_tpmif(tpmif);

}

/**********************
 * REMAINING TPMBACK FUNCTIONS
 * ********************/

/*Event channel handler */
void tpmback_handler(evtchn_port_t port, struct pt_regs *regs, void *data)
{
   tpmif_t* tpmif = (tpmif_t*) data;
   tpmif_shared_page_t *pg = tpmif->page;

   switch (pg->state)
   {
   case TPMIF_STATE_SUBMIT:
      TPMBACK_DEBUG("EVENT CHANNEL FIRE %u/%u\n", (unsigned int) tpmif->domid, tpmif->handle);
      tpmif_req_ready(tpmif);
      wake_up(&waitq);
      break;
   case TPMIF_STATE_CANCEL:
      /* If we are busy with a request, do nothing */
      if (tpmif->flags & TPMIF_REQ_READY)
         return;
      /* Acknowledge the cancellation if we are idle */
      pg->state = TPMIF_STATE_IDLE;
      wmb();
      notify_remote_via_evtchn(tpmif->evtchn);
      return;
   default:
      /* Spurious wakeup; do nothing */
      return;
   }
}

/* Connect to frontend */
int connect_fe(tpmif_t* tpmif)
{
   char path[512];
   char* err, *value;
   uint32_t domid;
   grant_ref_t ringref;
   evtchn_port_t evtchn;

   /* If already connected then quit */
   if (tpmif->status == CONNECTED) {
      TPMBACK_DEBUG("%u/%u tried to connect while it was already connected?\n", (unsigned int) tpmif->domid, tpmif->handle);
      return 0;
   }

   /* Fetch the grant reference */
   snprintf(path, 512, "%s/ring-ref", tpmif->fe_path);
   if((err = xenbus_read(XBT_NIL, path, &value))) {
      TPMBACK_ERR("Error creating new tpm instance xenbus_read(%s) Error = %s", path, err);
      free(err);
      return -1;
   }
   if(sscanf(value, "%d", &ringref) != 1) {
      TPMBACK_ERR("Non integer value (%s) in %s ??\n", value, path);
      free(value);
      return -1;
   }
   free(value);


   /* Fetch the event channel*/
   snprintf(path, 512, "%s/event-channel", tpmif->fe_path);
   if((err = xenbus_read(XBT_NIL, path, &value))) {
      TPMBACK_ERR("Error creating new tpm instance xenbus_read(%s) Error = %s", path, err);
      free(err);
      return -1;
   }
   if(sscanf(value, "%d", &evtchn) != 1) {
      TPMBACK_ERR("Non integer value (%s) in %s ??\n", value, path);
      free(value);
      return -1;
   }
   free(value);

   /* Check that protocol v2 is being used */
   snprintf(path, 512, "%s/feature-protocol-v2", tpmif->fe_path);
   if((err = xenbus_read(XBT_NIL, path, &value))) {
      TPMBACK_ERR("Unable to read %s during tpmback initialization! error = %s\n", path, err);
      free(err);
      return -1;
   }
   if(strcmp(value, "1")) {
      TPMBACK_ERR("%s has an invalid value (%s)\n", path, value);
      free(value);
      return -1;
   }
   free(value);

   domid = tpmif->domid;
   if((tpmif->page = gntmap_map_grant_refs(&gtpmdev.map, 1, &domid, 0, &ringref, PROT_READ | PROT_WRITE)) == NULL) {
      TPMBACK_ERR("Failed to map grant reference %u/%u\n", (unsigned int) tpmif->domid, tpmif->handle);
      return -1;
   }

   /*Bind the event channel */
   if((evtchn_bind_interdomain(tpmif->domid, evtchn, tpmback_handler, tpmif, &tpmif->evtchn)))
   {
      TPMBACK_ERR("%u/%u Unable to bind to interdomain event channel!\n", (unsigned int) tpmif->domid, tpmif->handle);
      goto error_post_map;
   }
   unmask_evtchn(tpmif->evtchn);

   /* Write the ready flag and change status to connected */
   snprintf(path, 512, "backend/vtpm/%u/%u", (unsigned int) tpmif->domid, tpmif->handle);
   if((err = xenbus_printf(XBT_NIL, path, "ready", "%u", 1))) {
      TPMBACK_ERR("%u/%u Unable to write ready flag on connect_fe()\n", (unsigned int) tpmif->domid, tpmif->handle);
      free(err);
      goto error_post_evtchn;
   }
   tpmif->status = CONNECTED;
   if((tpmif_change_state(tpmif, XenbusStateConnected))){
      goto error_post_evtchn;
   }

   TPMBACK_LOG("Frontend %u/%u connected\n", (unsigned int) tpmif->domid, tpmif->handle);

   return 0;
error_post_evtchn:
   mask_evtchn(tpmif->evtchn);
   unbind_evtchn(tpmif->evtchn);
error_post_map:
   gntmap_munmap(&gtpmdev.map, (unsigned long)tpmif->page, 1);
   return -1;
}

static void disconnect_fe(tpmif_t* tpmif)
{
   if (tpmif->status == CONNECTED) {
      tpmif->status = DISCONNECTING;
      mask_evtchn(tpmif->evtchn);

      if(gntmap_munmap(&gtpmdev.map, (unsigned long)tpmif->page, 1)) {
	 TPMBACK_ERR("%u/%u Error occured while trying to unmap shared page\n", (unsigned int) tpmif->domid, tpmif->handle);
      }

      unbind_evtchn(tpmif->evtchn);
   }
   tpmif->status = DISCONNECTED;
   tpmif_change_state(tpmif, XenbusStateInitWait);

   TPMBACK_LOG("Frontend %u/%u disconnected\n", (unsigned int) tpmif->domid, tpmif->handle);
}

static int frontend_changed(tpmif_t* tpmif)
{
   int state = xenbus_read_integer(tpmif->fe_state_path);
   if(state < 0) {
      state = XenbusStateUnknown;
   }

   TPMBACK_DEBUG("Frontend %u/%u state changed to %d\n", (unsigned int) tpmif->domid, tpmif->handle, state);

   switch (state) {
      case XenbusStateInitialising:
	 break;

      case XenbusStateInitialised:
      case XenbusStateConnected:
	 if(connect_fe(tpmif)) {
	    TPMBACK_ERR("Failed to connect to front end %u/%u\n", (unsigned int) tpmif->domid, tpmif->handle);
	    tpmif_change_state(tpmif, XenbusStateClosed);
	    return -1;
	 }
	 break;

      case XenbusStateClosing:
	 tpmif_change_state(tpmif, XenbusStateClosing);
	 break;

      case XenbusStateClosed:
         disconnect_fe(tpmif);
	 break;

      case XenbusStateUnknown: /* keep it here */
	 free_tpmif(tpmif);
	 break;

      default:
	 TPMBACK_DEBUG("BAD STATE CHANGE %u/%u state = %d for tpmif\n", (unsigned int) tpmif->domid, tpmif->handle, state);
	 return -1;
   }
   return 0;
}


/* parses the string that comes out of xenbus_watch_wait_return. */
static int parse_eventstr(const char* evstr, domid_t* domid, unsigned int* handle)
{
   int ret;
   char cmd[40];
   char* err;
   char* value;
   unsigned int udomid = 0;
   tpmif_t* tpmif;
   /* First check for new frontends, this occurs when /backend/vtpm/<domid>/<handle> gets created. Note we what the sscanf to fail on the last %s */
   if (sscanf(evstr, "backend/vtpm/%u/%u/%40s", &udomid, handle, cmd) == 2) {
      *domid = udomid;
      /* Make sure the entry exists, if this event triggers because the entry dissapeared then ignore it */
      if((err = xenbus_read(XBT_NIL, evstr, &value))) {
	 free(err);
	 return EV_NONE;
      }
      free(value);
      /* Make sure the tpmif entry does not already exist, this should not happen */
      if((tpmif = get_tpmif(*domid, *handle)) != NULL) {
	 TPMBACK_DEBUG("Duplicate tpm entries! %u %u\n", tpmif->domid, tpmif->handle);
	 return EV_NONE;
      }
      return EV_NEWFE;
   } else if((ret = sscanf(evstr, "/local/domain/%u/device/vtpm/%u/%40s", &udomid, handle, cmd)) == 3) {
      *domid = udomid;
      if (!strcmp(cmd, "state"))
	 return EV_STCHNG;
   }
   return EV_NONE;
}

void handle_backend_event(char* evstr) {
   tpmif_t* tpmif;
   domid_t domid;
   unsigned int handle;
   int event;

   TPMBACK_DEBUG("Xenbus Event: %s\n", evstr);

   event = parse_eventstr(evstr, &domid, &handle);

   switch(event) {
      case EV_NEWFE:
	 if(new_tpmif(domid, handle) == NULL) {
	    TPMBACK_ERR("Failed to create new tpm instance %u/%u\n", (unsigned int) domid, handle);
	 }
	 wake_up(&waitq);
	 break;
      case EV_STCHNG:
	 if((tpmif = get_tpmif(domid, handle))) {
	    frontend_changed(tpmif);
	 } else {
	    TPMBACK_DEBUG("Event Received for non-existant tpm! instance=%u/%u xenbus_event=%s\n", (unsigned int) domid, handle, evstr);
	 }
	 break;
   }
}

/* Runs through the given path and creates events recursively
 * for all of its children.
 * @path - xenstore path to scan */
static void generate_backend_events(const char* path)
{
   char* err;
   int i, len;
   char **dirs;
   char *entry;

   if((err = xenbus_ls(XBT_NIL, path, &dirs)) != NULL) {
      free(err);
      return;
   }

   for(i = 0; dirs[i] != NULL; ++i) {
      len = strlen(path) + strlen(dirs[i]) + 2;
      entry = malloc(len);
      snprintf(entry, len, "%s/%s", path, dirs[i]);

      /* Generate and handle event for the entry itself */
      handle_backend_event(entry);

      /* Do children */
      generate_backend_events(entry);

      /* Cleanup */
      free(entry);
      free(dirs[i]);
   }
   free(dirs);
   return;
}

void* tpmback_get_opaque(domid_t domid, unsigned int handle)
{
   tpmif_t* tpmif;
   if((tpmif = get_tpmif(domid, handle)) == NULL) {
      TPMBACK_DEBUG("get_opaque() failed, %u/%u is an invalid frontend\n", (unsigned int) domid, handle);
      return NULL;
   }

   return tpmif->opaque;
}

int tpmback_set_opaque(domid_t domid, unsigned int handle, void *opaque)
{
   tpmif_t* tpmif;
   if((tpmif = get_tpmif(domid, handle)) == NULL) {
      TPMBACK_DEBUG("set_opaque() failed, %u/%u is an invalid frontend\n", (unsigned int) domid, handle);
      return -1;
   }

   tpmif->opaque = opaque;
   return 0;
}

unsigned char* tpmback_get_uuid(domid_t domid, unsigned int handle)
{
   tpmif_t* tpmif;
   if((tpmif = get_tpmif(domid, handle)) == NULL) {
      TPMBACK_DEBUG("get_uuid() failed, %u/%u is an invalid frontend\n", (unsigned int) domid, handle);
      return NULL;
   }

   return tpmif->uuid;
}

int tpmback_get_peercontext(domid_t domid, unsigned int handle, void* buffer, int buflen)
{
   tpmif_t* tpmif;
   if((tpmif = get_tpmif(domid, handle)) == NULL) {
      TPMBACK_DEBUG("get_uuid() failed, %u/%u is an invalid frontend\n", (unsigned int) domid, handle);
      return -1;
   }

   return evtchn_get_peercontext(tpmif->evtchn, buffer, buflen);
}

static void event_listener(void)
{
   const char* bepath = "backend/vtpm";
   char **path;
   char* err;

   /* Setup the backend device watch */
   if((err = xenbus_watch_path_token(XBT_NIL, bepath, bepath, &gtpmdev.events)) != NULL) {
      TPMBACK_ERR("xenbus_watch_path_token(%s) failed with error %s!\n", bepath, err);
      free(err);
      goto egress;
   }

   /* Check for any frontends that connected before we set the watch.
    * This is almost guaranteed to happen if both domains are started
    * immediatly one after the other.
    * We do this by manually generating events on everything in the backend
    * path */
   generate_backend_events(bepath);

   /* Wait and listen for changes in frontend connections */
   while(1) {
      path = xenbus_wait_for_watch_return(&gtpmdev.events);

      /*If quit flag was set then exit */
      if(gtpmdev.flags & TPMIF_CLOSED) {
	 TPMBACK_DEBUG("listener thread got quit event. Exiting..\n");
	 free(path);
	 break;
      }
      handle_backend_event(*path);
      free(path);

   }

   if((err = xenbus_unwatch_path_token(XBT_NIL, bepath, bepath)) != NULL) {
      free(err);
   }
egress:
   return;
}

void event_thread(void* p) {
   event_listener();
}

void init_tpmback(void (*open_cb)(domid_t, unsigned int), void (*close_cb)(domid_t, unsigned int))
{
   if(!globalinit) {
      init_waitqueue_head(&waitq);
      globalinit = 1;
   }
   printk("============= Init TPM BACK ================\n");
   gtpmdev.tpmlist = malloc(sizeof(tpmif_t*) * DEF_ARRAY_SIZE);
   gtpmdev.num_alloc = DEF_ARRAY_SIZE;
   gtpmdev.num_tpms = 0;
   gtpmdev.flags = 0;

   gtpmdev.open_callback = open_cb;
   gtpmdev.close_callback = close_cb;

   eventthread = create_thread("tpmback-listener", event_thread, NULL);

}

void shutdown_tpmback(void)
{
   TPMBACK_LOG("Shutting down tpm backend\n");
   /* Set the quit flag */
   gtpmdev.flags = TPMIF_CLOSED;

   //printk("num tpms is %d\n", gtpmdev.num_tpms);
   /*Free all backend instances */
   while(gtpmdev.num_tpms) {
      free_tpmif(gtpmdev.tpmlist[0]);
   }
   free(gtpmdev.tpmlist);
   gtpmdev.tpmlist = NULL;
   gtpmdev.num_alloc = 0;

   /* Wake up anyone possibly waiting on the device and let them exit */
   wake_up(&waitq);
   schedule();
}

static void init_tpmcmd(tpmcmd_t* tpmcmd, domid_t domid, unsigned int handle, void *opaque)
{
   tpmcmd->domid = domid;
   tpmcmd->locality = -1;
   tpmcmd->handle = handle;
   tpmcmd->opaque = opaque;
   tpmcmd->req = NULL;
   tpmcmd->req_len = 0;
   tpmcmd->resp = NULL;
   tpmcmd->resp_len = 0;
}

tpmcmd_t* get_request(tpmif_t* tpmif) {
   tpmcmd_t* cmd;
   tpmif_shared_page_t *shr;
   unsigned int offset;
   int flags;
#ifdef TPMBACK_PRINT_DEBUG
   int i;
#endif

   local_irq_save(flags);

   /* Allocate the cmd object to hold the data */
   if((cmd = malloc(sizeof(*cmd))) == NULL) {
      goto error;
   }
   init_tpmcmd(cmd, tpmif->domid, tpmif->handle, tpmif->opaque);

   shr = tpmif->page;
   cmd->req_len = shr->length;
   cmd->locality = shr->locality;
   offset = sizeof(*shr) + 4*shr->nr_extra_pages;
   if (offset > PAGE_SIZE || offset + cmd->req_len > PAGE_SIZE) {
      TPMBACK_ERR("%u/%u Command size too long for shared page!\n", (unsigned int) tpmif->domid, tpmif->handle);
      goto error;
   }
   /* Allocate the buffer */
   if(cmd->req_len) {
      if((cmd->req = malloc(cmd->req_len)) == NULL) {
	 goto error;
      }
   }
   /* Copy the bits from the shared page(s) */
   memcpy(cmd->req, offset + (uint8_t*)shr, cmd->req_len);

#ifdef TPMBACK_PRINT_DEBUG
   TPMBACK_DEBUG("Received Tpm Command from %u/%u of size %u", (unsigned int) tpmif->domid, tpmif->handle, cmd->req_len);
   for(i = 0; i < cmd->req_len; ++i) {
      if (!(i % 30)) {
	 TPMBACK_DEBUG_MORE("\n");
      }
      TPMBACK_DEBUG_MORE("%02hhX ", cmd->req[i]);
   }
   TPMBACK_DEBUG_MORE("\n\n");
#endif

   local_irq_restore(flags);
   return cmd;
error:
   if(cmd != NULL) {
      if (cmd->req != NULL) {
	 free(cmd->req);
	 cmd->req = NULL;
      }
      free(cmd);
      cmd = NULL;
   }
   local_irq_restore(flags);
   return NULL;

}

void send_response(tpmcmd_t* cmd, tpmif_t* tpmif)
{
   tpmif_shared_page_t *shr;
   unsigned int offset;
   int flags;
#ifdef TPMBACK_PRINT_DEBUG
int i;
#endif

   local_irq_save(flags);

   shr = tpmif->page;
   shr->length = cmd->resp_len;

   offset = sizeof(*shr) + 4*shr->nr_extra_pages;
   if (offset > PAGE_SIZE || offset + cmd->resp_len > PAGE_SIZE) {
      TPMBACK_ERR("%u/%u Command size too long for shared page!\n", (unsigned int) tpmif->domid, tpmif->handle);
      goto error;
   }
   memcpy(offset + (uint8_t*)shr, cmd->resp, cmd->resp_len);

#ifdef TPMBACK_PRINT_DEBUG
   TPMBACK_DEBUG("Sent response to %u/%u of size %u", (unsigned int) tpmif->domid, tpmif->handle, cmd->resp_len);
   for(i = 0; i < cmd->resp_len; ++i) {
      if (!(i % 30)) {
	 TPMBACK_DEBUG_MORE("\n");
      }
      TPMBACK_DEBUG_MORE("%02hhX ", cmd->resp[i]);
   }
   TPMBACK_DEBUG_MORE("\n\n");
#endif
   /* clear the ready flag and send the event channel notice to the frontend */
   tpmif_req_finished(tpmif);
   barrier();
   shr->state = TPMIF_STATE_FINISH;
   wmb();
   notify_remote_via_evtchn(tpmif->evtchn);
error:
   local_irq_restore(flags);
   return;
}

tpmcmd_t* tpmback_req_any(void)
{
   int i;
   /* Block until something has a request */
   wait_event(waitq, (gtpmdev.flags & (TPMIF_REQ_READY | TPMIF_CLOSED)));

   /* Check if were shutting down */
   if(gtpmdev.flags & TPMIF_CLOSED) {
      /* if something was waiting for us to give up the queue so it can shutdown, let it finish */
      schedule();
      return NULL;
   }

   for(i = 0; i < gtpmdev.num_tpms; ++i) {
      if(gtpmdev.tpmlist[i]->flags & TPMIF_REQ_READY) {
	 return get_request(gtpmdev.tpmlist[i]);
      }
   }

   TPMBACK_ERR("backend request ready flag was set but no interfaces were actually ready\n");
   return NULL;
}

tpmcmd_t* tpmback_req(domid_t domid, unsigned int handle)
{
   tpmif_t* tpmif;
   tpmif = get_tpmif(domid, handle);
   if(tpmif == NULL) {
      return NULL;
   }

   wait_event(waitq, (tpmif->flags & (TPMIF_REQ_READY | TPMIF_CLOSED) || gtpmdev.flags & TPMIF_CLOSED));

   /* Check if were shutting down */
   if(tpmif->flags & TPMIF_CLOSED || gtpmdev.flags & TPMIF_CLOSED) {
      /* if something was waiting for us to give up the queue so it can free this instance, let it finish */
      schedule();
      return NULL;
   }

   return get_request(tpmif);
}

void tpmback_resp(tpmcmd_t* tpmcmd)
{
   tpmif_t* tpmif;

   /* Get the associated interface, if it doesnt exist then just quit */
   tpmif = get_tpmif(tpmcmd->domid, tpmcmd->handle);
   if(tpmif == NULL) {
      TPMBACK_ERR("Tried to send a reponse to non existant frontend %u/%u\n", (unsigned int) tpmcmd->domid, tpmcmd->handle);
      goto end;
   }

   if(!(tpmif->flags & TPMIF_REQ_READY)) {
      TPMBACK_ERR("Tried to send response to a frontend that was not waiting for one %u/%u\n", (unsigned int) tpmcmd->domid, tpmcmd->handle);
      goto end;
   }

   /* Send response to frontend */
   send_response(tpmcmd, tpmif);

end:
   if(tpmcmd->req != NULL) {
      free(tpmcmd->req);
   }
   free(tpmcmd);
   return;
}

int tpmback_wait_for_frontend_connect(domid_t *domid, unsigned int *handle)
{
   tpmif_t* tpmif;
   int flags;
   wait_event(waitq, ((gtpmdev.num_tpms > 0) || gtpmdev.flags & TPMIF_CLOSED));
   if(gtpmdev.flags & TPMIF_CLOSED) {
      return -1;
   }
   local_irq_save(flags);
   tpmif = gtpmdev.tpmlist[0];
   *domid = tpmif->domid;
   *handle = tpmif->handle;
   local_irq_restore(flags);

   return 0;
}

int tpmback_num_frontends(void)
{
   return gtpmdev.num_tpms;
}