summaryrefslogtreecommitdiff
path: root/security/tf_driver/tf_conn.c
blob: 3148fec46358d7c6ba6131bf41a9505ddfe68943 (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
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
/**
 * Copyright (c) 2011 Trusted Logic S.A.
 * 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
 * version 2 as published by the Free Software Foundation.
 *
 * 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., 59 Temple Place, Suite 330, Boston,
 * MA 02111-1307 USA
 */

#include <linux/atomic.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/list.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/stddef.h>
#include <linux/types.h>

#include "s_version.h"

#include "tf_protocol.h"
#include "tf_defs.h"
#include "tf_util.h"
#include "tf_comm.h"
#include "tf_conn.h"

#ifdef CONFIG_TF_ZEBRA
#include "tf_crypto.h"
#endif

#ifdef CONFIG_ANDROID
#define TF_PRIVILEGED_UID_GID 1000 /* Android system AID */
#else
#define TF_PRIVILEGED_UID_GID 0
#endif

/*----------------------------------------------------------------------------
 * Management of the shared memory blocks.
 *
 * Shared memory blocks are the blocks registered through
 * the commands REGISTER_SHARED_MEMORY and POWER_MANAGEMENT
 *----------------------------------------------------------------------------*/

/**
 * Unmaps a shared memory
 **/
void tf_unmap_shmem(
		struct tf_connection *connection,
		struct tf_shmem_desc *shmem_desc,
		u32 full_cleanup)
{
	/* check shmem_desc contains a descriptor */
	if (shmem_desc == NULL)
		return;

	dprintk(KERN_DEBUG "tf_unmap_shmem(%p)\n", shmem_desc);

retry:
	mutex_lock(&(connection->shmem_mutex));
	if (atomic_read(&shmem_desc->ref_count) > 1) {
		/*
		 * Shared mem still in use, wait for other operations completion
		 * before actually unmapping it.
		 */
		dprintk(KERN_INFO "Descriptor in use\n");
		mutex_unlock(&(connection->shmem_mutex));
		schedule();
		goto retry;
	}

	tf_cleanup_shared_memory(
			&(connection->cpt_alloc_context),
			shmem_desc,
			full_cleanup);

	list_del(&(shmem_desc->list));

	if ((shmem_desc->type == TF_SHMEM_TYPE_REGISTERED_SHMEM) ||
			(full_cleanup != 0)) {
		internal_kfree(shmem_desc);

		atomic_dec(&(connection->shmem_count));
	} else {
		/*
		 * This is a preallocated shared memory, add to free list
		 * Since the device context is unmapped last, it is
		 * always the first element of the free list if no
		 * device context has been created
		 */
		shmem_desc->block_identifier = 0;
		list_add(&(shmem_desc->list), &(connection->free_shmem_list));
	}

	mutex_unlock(&(connection->shmem_mutex));
}


/**
 * Find the first available slot for a new block of shared memory
 * and map the user buffer.
 * Update the descriptors to L1 descriptors
 * Update the buffer_start_offset and buffer_size fields
 * shmem_desc is updated to the mapped shared memory descriptor
 **/
int tf_map_shmem(
		struct tf_connection *connection,
		u32 buffer,
		/* flags for read-write access rights on the memory */
		u32 flags,
		bool in_user_space,
		u32 descriptors[TF_MAX_COARSE_PAGES],
		u32 *buffer_start_offset,
		u32 buffer_size,
		struct tf_shmem_desc **shmem_desc,
		u32 *descriptor_count)
{
	struct tf_shmem_desc *desc = NULL;
	int error;

	dprintk(KERN_INFO "tf_map_shmem(%p, %p, flags = 0x%08x)\n",
					connection,
					(void *) buffer,
					flags);

	mutex_lock(&(connection->shmem_mutex));

	/*
	 * Check the list of free shared memory
	 * is not empty
	 */
	if (list_empty(&(connection->free_shmem_list))) {
		if (atomic_read(&(connection->shmem_count)) ==
				TF_SHMEM_MAX_COUNT) {
			printk(KERN_ERR "tf_map_shmem(%p):"
				" maximum shared memories already registered\n",
				connection);
			error = -ENOMEM;
			goto error;
		}

		/* no descriptor available, allocate a new one */

		desc = (struct tf_shmem_desc *) internal_kmalloc(
			sizeof(*desc), GFP_KERNEL);
		if (desc == NULL) {
			printk(KERN_ERR "tf_map_shmem(%p):"
				" failed to allocate descriptor\n",
				connection);
			error = -ENOMEM;
			goto error;
		}

		/* Initialize the structure */
		desc->type = TF_SHMEM_TYPE_REGISTERED_SHMEM;
		atomic_set(&desc->ref_count, 1);
		INIT_LIST_HEAD(&(desc->list));

		atomic_inc(&(connection->shmem_count));
	} else {
		/* take the first free shared memory descriptor */
		desc = list_first_entry(&(connection->free_shmem_list),
			struct tf_shmem_desc, list);
		list_del(&(desc->list));
	}

	/* Add the descriptor to the used list */
	list_add(&(desc->list), &(connection->used_shmem_list));

	error = tf_fill_descriptor_table(
			&(connection->cpt_alloc_context),
			desc,
			buffer,
			connection->vmas,
			descriptors,
			buffer_size,
			buffer_start_offset,
			in_user_space,
			flags,
			descriptor_count);

	if (error != 0) {
		dprintk(KERN_ERR "tf_map_shmem(%p):"
			" tf_fill_descriptor_table failed with error "
			"code %d!\n",
			connection,
			error);
		goto error;
	}
	desc->client_buffer = (u8 *) buffer;

	/*
	 * Successful completion.
	 */
	*shmem_desc = desc;
	mutex_unlock(&(connection->shmem_mutex));
	dprintk(KERN_DEBUG "tf_map_shmem: success\n");
	return 0;


	/*
	 * Error handling.
	 */
error:
	mutex_unlock(&(connection->shmem_mutex));
	dprintk(KERN_ERR "tf_map_shmem: failure with error code %d\n",
		error);

	tf_unmap_shmem(
			connection,
			desc,
			0);

	return error;
}



/* This function is a copy of the find_vma() function
in linux kernel 2.6.15 version with some fixes :
	- memory block may end on vm_end
	- check the full memory block is in the memory area
	- guarantee NULL is returned if no memory area is found */
struct vm_area_struct *tf_find_vma(struct mm_struct *mm,
	unsigned long addr, unsigned long size)
{
	struct vm_area_struct *vma = NULL;

	dprintk(KERN_INFO
		"tf_find_vma addr=0x%lX size=0x%lX\n", addr, size);

	if (mm) {
		/* Check the cache first. */
		/* (Cache hit rate is typically around 35%.) */
		vma = mm->mmap_cache;
		if (!(vma && vma->vm_end >= (addr+size) &&
				vma->vm_start <= addr))	{
			struct rb_node *rb_node;

			rb_node = mm->mm_rb.rb_node;
			vma = NULL;

			while (rb_node) {
				struct vm_area_struct *vma_tmp;

				vma_tmp = rb_entry(rb_node,
					struct vm_area_struct, vm_rb);

				dprintk(KERN_INFO
					"vma_tmp->vm_start=0x%lX"
					"vma_tmp->vm_end=0x%lX\n",
					vma_tmp->vm_start,
					vma_tmp->vm_end);

				if (vma_tmp->vm_end >= (addr+size)) {
					vma = vma_tmp;
					if (vma_tmp->vm_start <= addr)
						break;

					rb_node = rb_node->rb_left;
				} else {
					rb_node = rb_node->rb_right;
				}
			}

			if (vma)
				mm->mmap_cache = vma;
			if (rb_node == NULL)
				vma = NULL;
		}
	}
	return vma;
}

int tf_validate_shmem_and_flags(
	u32 shmem,
	u32 shmem_size,
	u32 flags)
{
	struct vm_area_struct *vma;
	u32 chunk;

	if (shmem_size == 0)
		/* This is always valid */
		return 0;

	if ((shmem + shmem_size) < shmem)
		/* Overflow */
		return -EINVAL;

	down_read(&current->mm->mmap_sem);

	/*
	 *  When looking for a memory address, split buffer into chunks of
	 *  size=PAGE_SIZE.
	 */
	chunk = PAGE_SIZE - (shmem & (PAGE_SIZE-1));
	if (chunk > shmem_size)
		chunk = shmem_size;

	do {
		vma = tf_find_vma(current->mm, shmem, chunk);

		if (vma == NULL) {
			dprintk(KERN_ERR "%s: area not found\n", __func__);
			goto error;
		}

		if (flags & TF_SHMEM_TYPE_READ)
			if (!(vma->vm_flags & VM_READ)) {
				dprintk(KERN_ERR "%s: no read permission\n",
					__func__);
				goto error;
			}
		if (flags & TF_SHMEM_TYPE_WRITE)
			if (!(vma->vm_flags & VM_WRITE)) {
				dprintk(KERN_ERR "%s: no write permission\n",
					__func__);
				goto error;
			}

		shmem_size -= chunk;
		shmem += chunk;
		chunk = (shmem_size <= PAGE_SIZE ?
				shmem_size : PAGE_SIZE);
	} while (shmem_size != 0);

	up_read(&current->mm->mmap_sem);
	return 0;

error:
	up_read(&current->mm->mmap_sem);
	return -EFAULT;
}


static int tf_map_temp_shmem(struct tf_connection *connection,
	 struct tf_command_param_temp_memref *temp_memref,
	 u32 param_type,
	 struct tf_shmem_desc **shmem_desc)
{
	u32 flags;
	u32 error = S_SUCCESS;
	bool in_user_space = connection->owner != TF_CONNECTION_OWNER_KERNEL;

	dprintk(KERN_INFO "tf_map_temp_shmem(%p, "
		"0x%08x[size=0x%08x], offset=0x%08x)\n",
		connection,
		temp_memref->descriptor,
		temp_memref->size,
		temp_memref->offset);

	switch (param_type) {
	case TF_PARAM_TYPE_MEMREF_TEMP_INPUT:
		flags = TF_SHMEM_TYPE_READ;
		break;
	case TF_PARAM_TYPE_MEMREF_TEMP_OUTPUT:
		flags = TF_SHMEM_TYPE_WRITE;
		break;
	case TF_PARAM_TYPE_MEMREF_TEMP_INOUT:
		flags = TF_SHMEM_TYPE_WRITE | TF_SHMEM_TYPE_READ;
		break;
	default:
		error = -EINVAL;
		goto error;
	}

	if (temp_memref->descriptor == 0) {
		/* NULL tmpref */
		temp_memref->offset = 0;
		*shmem_desc = NULL;
	} else if ((temp_memref->descriptor != 0) &&
			(temp_memref->size == 0)) {
		/* Empty tmpref */
		temp_memref->offset = temp_memref->descriptor;
		temp_memref->descriptor = 0;
		temp_memref->size = 0;
		*shmem_desc = NULL;
	} else {
		/* Map the temp shmem block */

		u32 shared_mem_descriptors[TF_MAX_COARSE_PAGES];
		u32 descriptor_count;

		if (in_user_space) {
			error = tf_validate_shmem_and_flags(
				temp_memref->descriptor,
				temp_memref->size,
				flags);
			if (error != 0)
				goto error;
		}

		error = tf_map_shmem(
				connection,
				temp_memref->descriptor,
				flags,
				in_user_space,
				shared_mem_descriptors,
				&(temp_memref->offset),
				temp_memref->size,
				shmem_desc,
				&descriptor_count);
		temp_memref->descriptor = shared_mem_descriptors[0];
	 }

error:
	 return error;
}

/*
 * Clean up a list of shared memory descriptors.
 */
static void tf_shared_memory_cleanup_list(
		struct tf_connection *connection,
		struct list_head *shmem_desc_list)
{
	while (!list_empty(shmem_desc_list)) {
		struct tf_shmem_desc *shmem_desc;

		shmem_desc = list_first_entry(shmem_desc_list,
			struct tf_shmem_desc, list);

		tf_unmap_shmem(connection, shmem_desc, 1);
	}
}


/*
 * Clean up the shared memory information in the connection.
 * Releases all allocated pages.
 */
static void tf_cleanup_shared_memories(struct tf_connection *connection)
{
	/* clean up the list of used and free descriptors.
	 * done outside the mutex, because tf_unmap_shmem already
	 * mutex()ed
	 */
	tf_shared_memory_cleanup_list(connection,
		&connection->used_shmem_list);
	tf_shared_memory_cleanup_list(connection,
		&connection->free_shmem_list);

	mutex_lock(&(connection->shmem_mutex));

	/* Free the Vmas page */
	if (connection->vmas) {
		internal_free_page((unsigned long) connection->vmas);
		connection->vmas = NULL;
	}

	tf_release_coarse_page_table_allocator(
		&(connection->cpt_alloc_context));

	mutex_unlock(&(connection->shmem_mutex));
}


/*
 * Initialize the shared memory in a connection.
 * Allocates the minimum memory to be provided
 * for shared memory management
 */
int tf_init_shared_memory(struct tf_connection *connection)
{
	int error;
	int i;
	int coarse_page_index;

	/*
	 * We only need to initialize special elements and attempt to allocate
	 * the minimum shared memory descriptors we want to support
	 */

	mutex_init(&(connection->shmem_mutex));
	INIT_LIST_HEAD(&(connection->free_shmem_list));
	INIT_LIST_HEAD(&(connection->used_shmem_list));
	atomic_set(&(connection->shmem_count), 0);

	tf_init_coarse_page_table_allocator(
		&(connection->cpt_alloc_context));


	/*
	 * Preallocate 3 pages to increase the chances that a connection
	 * succeeds in allocating shared mem
	 */
	for (i = 0;
	     i < 3;
	     i++) {
		struct tf_shmem_desc *shmem_desc =
			(struct tf_shmem_desc *) internal_kmalloc(
				sizeof(*shmem_desc), GFP_KERNEL);

		if (shmem_desc == NULL) {
			printk(KERN_ERR "tf_init_shared_memory(%p):"
				" failed to pre allocate descriptor %d\n",
				connection,
				i);
			error = -ENOMEM;
			goto error;
		}

		for (coarse_page_index = 0;
		     coarse_page_index < TF_MAX_COARSE_PAGES;
		     coarse_page_index++) {
			struct tf_coarse_page_table *coarse_pg_table;

			coarse_pg_table = tf_alloc_coarse_page_table(
				&(connection->cpt_alloc_context),
				TF_PAGE_DESCRIPTOR_TYPE_PREALLOCATED);

			if (coarse_pg_table == NULL) {
				printk(KERN_ERR "tf_init_shared_memory(%p)"
					": descriptor %d coarse page %d - "
					"tf_alloc_coarse_page_table() "
					"failed\n",
					connection,
					i,
					coarse_page_index);
				error = -ENOMEM;
				goto error;
			}

			shmem_desc->coarse_pg_table[coarse_page_index] =
				coarse_pg_table;
		}
		shmem_desc->coarse_pg_table_count = 0;

		shmem_desc->type = TF_SHMEM_TYPE_PREALLOC_REGISTERED_SHMEM;
		atomic_set(&shmem_desc->ref_count, 1);

		/*
		 * add this preallocated descriptor to the list of free
		 * descriptors Keep the device context specific one at the
		 * beginning of the list
		 */
		INIT_LIST_HEAD(&(shmem_desc->list));
		list_add_tail(&(shmem_desc->list),
			&(connection->free_shmem_list));
	}

	/* allocate memory for the vmas structure */
	connection->vmas =
		(struct vm_area_struct **) internal_get_zeroed_page(GFP_KERNEL);
	if (connection->vmas == NULL) {
		printk(KERN_ERR "tf_init_shared_memory(%p):"
			" vmas - failed to get_zeroed_page\n",
			connection);
		error = -ENOMEM;
		goto error;
	}

	return 0;

error:
	tf_cleanup_shared_memories(connection);
	return error;
}

/*----------------------------------------------------------------------------
 * Connection operations to the Secure World
 *----------------------------------------------------------------------------*/

int tf_create_device_context(
	struct tf_connection *connection)
{
	union tf_command command;
	union tf_answer  answer;
	int error = 0;

	dprintk(KERN_INFO "tf_create_device_context(%p)\n",
			connection);

	command.create_device_context.message_type =
		TF_MESSAGE_TYPE_CREATE_DEVICE_CONTEXT;
	command.create_device_context.message_size =
		(sizeof(struct tf_command_create_device_context)
			- sizeof(struct tf_command_header))/sizeof(u32);
	command.create_device_context.operation_id = (u32) &answer;
	command.create_device_context.device_context_id = (u32) connection;

	error = tf_send_receive(
		&connection->dev->sm,
		&command,
		&answer,
		connection,
		true);

	if ((error != 0) ||
		(answer.create_device_context.error_code != S_SUCCESS))
		goto error;

	/*
	 * CREATE_DEVICE_CONTEXT succeeded,
	 * store device context handler and update connection status
	 */
	connection->device_context =
		answer.create_device_context.device_context;
	spin_lock(&(connection->state_lock));
	connection->state = TF_CONN_STATE_VALID_DEVICE_CONTEXT;
	spin_unlock(&(connection->state_lock));

	/* successful completion */
	dprintk(KERN_INFO "tf_create_device_context(%p):"
		" device_context=0x%08x\n",
		connection,
		answer.create_device_context.device_context);
	return 0;

error:
	if (error != 0) {
		dprintk(KERN_ERR "tf_create_device_context failed with "
			"error %d\n", error);
	} else {
		/*
		 * We sent a DeviceCreateContext. The state is now
		 * TF_CONN_STATE_CREATE_DEVICE_CONTEXT_SENT It has to be
		 * reset if we ever want to send a DeviceCreateContext again
		 */
		spin_lock(&(connection->state_lock));
		connection->state = TF_CONN_STATE_NO_DEVICE_CONTEXT;
		spin_unlock(&(connection->state_lock));
		dprintk(KERN_ERR "tf_create_device_context failed with "
			"error_code 0x%08X\n",
			answer.create_device_context.error_code);
		if (answer.create_device_context.error_code ==
			S_ERROR_OUT_OF_MEMORY)
			error = -ENOMEM;
		else
			error = -EFAULT;
	}

	return error;
}

/* Check that the current application belongs to the
 * requested GID */
static bool tf_check_gid(gid_t requested_gid)
{
	if (requested_gid == current_egid()) {
		return true;
	} else {
		u32    size;
		u32    i;
		/* Look in the supplementary GIDs */
		get_group_info(GROUP_INFO);
		size = GROUP_INFO->ngroups;
		for (i = 0; i < size; i++)
			if (requested_gid == GROUP_AT(GROUP_INFO , i))
				return true;
	}
	return false;
}

/*
 * Opens a client session to the Secure World
 */
int tf_open_client_session(
	struct tf_connection *connection,
	union tf_command *command,
	union tf_answer *answer)
{
	int error = 0;
	struct tf_shmem_desc *shmem_desc[4] = {NULL};
	u32 i;

	dprintk(KERN_INFO "tf_open_client_session(%p)\n", connection);

	/*
	 * Initialize the message size with no login data. This will be later
	 * adjusted the the cases below
	 */
	command->open_client_session.message_size =
		(sizeof(struct tf_command_open_client_session) - 20
			- sizeof(struct tf_command_header))/4;

	switch (command->open_client_session.login_type) {
	case TF_LOGIN_PUBLIC:
		 /* Nothing to do */
		 break;

	case TF_LOGIN_USER:
		/*
		 * Send the EUID of the calling application in the login data.
		 * Update message size.
		 */
		*(u32 *) &command->open_client_session.login_data =
			current_euid();
#ifndef CONFIG_ANDROID
		command->open_client_session.login_type =
			(u32) TF_LOGIN_USER_LINUX_EUID;
#else
		command->open_client_session.login_type =
			(u32) TF_LOGIN_USER_ANDROID_EUID;
#endif

		/* Added one word */
		command->open_client_session.message_size += 1;
		break;

	case TF_LOGIN_GROUP: {
		/* Check requested GID */
		gid_t  requested_gid =
			*(u32 *) command->open_client_session.login_data;

		if (!tf_check_gid(requested_gid)) {
			dprintk(KERN_ERR "tf_open_client_session(%p) "
				"TF_LOGIN_GROUP: requested GID (0x%x) does "
				"not match real eGID (0x%x)"
				"or any of the supplementary GIDs\n",
				connection, requested_gid, current_egid());
			error = -EACCES;
			goto error;
		}
#ifndef CONFIG_ANDROID
		command->open_client_session.login_type =
			TF_LOGIN_GROUP_LINUX_GID;
#else
		command->open_client_session.login_type =
			TF_LOGIN_GROUP_ANDROID_GID;
#endif

		command->open_client_session.message_size += 1; /* GID */
		break;
	}

#ifndef CONFIG_ANDROID
	case TF_LOGIN_APPLICATION: {
		/*
		 * Compute SHA-1 hash of the application fully-qualified path
		 * name.  Truncate the hash to 16 bytes and send it as login
		 * data.  Update message size.
		 */
		u8 pSHA1Hash[SHA1_DIGEST_SIZE];

		error = tf_hash_application_path_and_data(pSHA1Hash,
			NULL, 0);
		if (error != 0) {
			dprintk(KERN_ERR "tf_open_client_session: "
				"error in tf_hash_application_path_and_data\n");
			goto error;
		}
		memcpy(&command->open_client_session.login_data,
			pSHA1Hash, 16);
		command->open_client_session.login_type =
			TF_LOGIN_APPLICATION_LINUX_PATH_SHA1_HASH;
		/* 16 bytes */
		command->open_client_session.message_size += 4;
		break;
	}
#else
	case TF_LOGIN_APPLICATION:
		/*
		 * Send the real UID of the calling application in the login
		 * data. Update message size.
		 */
		*(u32 *) &command->open_client_session.login_data =
			current_uid();

		command->open_client_session.login_type =
			(u32) TF_LOGIN_APPLICATION_ANDROID_UID;

		/* Added one word */
		command->open_client_session.message_size += 1;
		break;
#endif

#ifndef CONFIG_ANDROID
	case TF_LOGIN_APPLICATION_USER: {
		/*
		 * Compute SHA-1 hash of the concatenation of the application
		 * fully-qualified path name and the EUID of the calling
		 * application.  Truncate the hash to 16 bytes and send it as
		 * login data.  Update message size.
		 */
		u8 pSHA1Hash[SHA1_DIGEST_SIZE];

		error = tf_hash_application_path_and_data(pSHA1Hash,
			(u8 *) &(current_euid()), sizeof(current_euid()));
		if (error != 0) {
			dprintk(KERN_ERR "tf_open_client_session: "
				"error in tf_hash_application_path_and_data\n");
			goto error;
		}
		memcpy(&command->open_client_session.login_data,
			pSHA1Hash, 16);
		command->open_client_session.login_type =
			TF_LOGIN_APPLICATION_USER_LINUX_PATH_EUID_SHA1_HASH;

		/* 16 bytes */
		command->open_client_session.message_size += 4;

		break;
	}
#else
	case TF_LOGIN_APPLICATION_USER:
		/*
		 * Send the real UID and the EUID of the calling application in
		 * the login data. Update message size.
		 */
		*(u32 *) &command->open_client_session.login_data =
			current_uid();
		*(u32 *) &command->open_client_session.login_data[4] =
			current_euid();

		command->open_client_session.login_type =
			TF_LOGIN_APPLICATION_USER_ANDROID_UID_EUID;

		/* Added two words */
		command->open_client_session.message_size += 2;
		break;
#endif

#ifndef CONFIG_ANDROID
	case TF_LOGIN_APPLICATION_GROUP: {
		/*
		 * Check requested GID.  Compute SHA-1 hash of the concatenation
		 * of the application fully-qualified path name and the
		 * requested GID.  Update message size
		 */
		gid_t  requested_gid;
		u8     pSHA1Hash[SHA1_DIGEST_SIZE];

		requested_gid =	*(u32 *) &command->open_client_session.
			login_data;

		if (!tf_check_gid(requested_gid)) {
			dprintk(KERN_ERR "tf_open_client_session(%p) "
			"TF_LOGIN_APPLICATION_GROUP: requested GID (0x%x) "
			"does not match real eGID (0x%x)"
			"or any of the supplementary GIDs\n",
			connection, requested_gid, current_egid());
			error = -EACCES;
			goto error;
		}

		error = tf_hash_application_path_and_data(pSHA1Hash,
			&requested_gid, sizeof(u32));
		if (error != 0) {
			dprintk(KERN_ERR "tf_open_client_session: "
				"error in tf_hash_application_path_and_data\n");
			goto error;
		}

		memcpy(&command->open_client_session.login_data,
			pSHA1Hash, 16);
		command->open_client_session.login_type =
			TF_LOGIN_APPLICATION_GROUP_LINUX_PATH_GID_SHA1_HASH;

		/* 16 bytes */
		command->open_client_session.message_size += 4;
		break;
	}
#else
	case TF_LOGIN_APPLICATION_GROUP: {
		/*
		 * Check requested GID. Send the real UID and the requested GID
		 * in the login data. Update message size.
		 */
		gid_t requested_gid;

		requested_gid =	*(u32 *) &command->open_client_session.
			login_data;

		if (!tf_check_gid(requested_gid)) {
			dprintk(KERN_ERR "tf_open_client_session(%p) "
			"TF_LOGIN_APPLICATION_GROUP: requested GID (0x%x) "
			"does not match real eGID (0x%x)"
			"or any of the supplementary GIDs\n",
			connection, requested_gid, current_egid());
			error = -EACCES;
			goto error;
		}

		*(u32 *) &command->open_client_session.login_data =
			current_uid();
		*(u32 *) &command->open_client_session.login_data[4] =
			requested_gid;

		command->open_client_session.login_type =
			TF_LOGIN_APPLICATION_GROUP_ANDROID_UID_GID;

		/* Added two words */
		command->open_client_session.message_size += 2;

		break;
	}
#endif

	case TF_LOGIN_PRIVILEGED:
		/* A privileged login may be performed only on behalf of the
		   kernel itself or on behalf of a process with euid=0 or
		   egid=0 or euid=system or egid=system. */
		if (connection->owner == TF_CONNECTION_OWNER_KERNEL) {
			dprintk(KERN_DEBUG "tf_open_client_session: "
				"TF_LOGIN_PRIVILEGED for kernel API\n");
		} else if ((current_euid() != TF_PRIVILEGED_UID_GID) &&
			   (current_egid() != TF_PRIVILEGED_UID_GID) &&
			   (current_euid() != 0) && (current_egid() != 0)) {
			dprintk(KERN_ERR "tf_open_client_session: "
				" user %d, group %d not allowed to open "
				"session with TF_LOGIN_PRIVILEGED\n",
				current_euid(), current_egid());
			error = -EACCES;
			goto error;
		} else {
			dprintk(KERN_DEBUG "tf_open_client_session: "
				"TF_LOGIN_PRIVILEGED for %u:%u\n",
				current_euid(), current_egid());
		}
		command->open_client_session.login_type =
			TF_LOGIN_PRIVILEGED;
		break;

	case TF_LOGIN_AUTHENTICATION: {
		/*
		 * Compute SHA-1 hash of the application binary
		 * Send this hash as the login data (20 bytes)
		 */

		u8 *hash;
		hash = &(command->open_client_session.login_data[0]);

		error = tf_get_current_process_hash(hash);
		if (error != 0) {
			dprintk(KERN_ERR "tf_open_client_session: "
				"error in tf_get_current_process_hash\n");
			goto error;
		}
		command->open_client_session.login_type =
			TF_LOGIN_AUTHENTICATION_BINARY_SHA1_HASH;

		/* 20 bytes */
		command->open_client_session.message_size += 5;
		break;
	}

	case TF_LOGIN_PRIVILEGED_KERNEL:
		/* A kernel login may be performed only on behalf of the
		   kernel itself. */
		if (connection->owner == TF_CONNECTION_OWNER_KERNEL) {
			dprintk(KERN_DEBUG "tf_open_client_session: "
				"TF_LOGIN_PRIVILEGED_KERNEL for kernel API\n");
			command->open_client_session.login_type =
				TF_LOGIN_PRIVILEGED_KERNEL;
		} else {
			dprintk(KERN_ERR "tf_open_client_session: "
				" user %d, group %d not allowed to open "
				"session with TF_LOGIN_PRIVILEGED_KERNEL\n",
				current_euid(), current_egid());
			error = -EACCES;
			goto error;
		}
		command->open_client_session.login_type =
			TF_LOGIN_PRIVILEGED_KERNEL;
		break;

	default:
		 dprintk(KERN_ERR "tf_open_client_session: "
			"unknown login_type(%08X)\n",
			command->open_client_session.login_type);
		 error = -EOPNOTSUPP;
		 goto error;
	}

	/* Map the temporary memory references */
	for (i = 0; i < 4; i++) {
		int param_type;
		param_type = TF_GET_PARAM_TYPE(
			command->open_client_session.param_types, i);
		if ((param_type & (TF_PARAM_TYPE_MEMREF_FLAG |
				   TF_PARAM_TYPE_REGISTERED_MEMREF_FLAG))
				== TF_PARAM_TYPE_MEMREF_FLAG) {
			/* Map temp mem ref */
			error = tf_map_temp_shmem(connection,
				&command->open_client_session.
					params[i].temp_memref,
				param_type,
				&shmem_desc[i]);
			if (error != 0) {
				dprintk(KERN_ERR "tf_open_client_session: "
					"unable to map temporary memory block "
					"(%08X)\n", error);
				goto error;
			}
		}
	}

	/* Fill the handle of the Device Context */
	command->open_client_session.device_context =
		connection->device_context;

	error = tf_send_receive(
		&connection->dev->sm,
		command,
		answer,
		connection,
		true);

error:
	/* Unmap the temporary memory references */
	for (i = 0; i < 4; i++)
		if (shmem_desc[i] != NULL)
			tf_unmap_shmem(connection, shmem_desc[i], 0);

	if (error != 0)
		dprintk(KERN_ERR "tf_open_client_session returns %d\n",
			error);
	else
		dprintk(KERN_ERR "tf_open_client_session returns "
			"error_code 0x%08X\n",
			answer->open_client_session.error_code);

	return error;
}


/*
 * Closes a client session from the Secure World
 */
int tf_close_client_session(
	struct tf_connection *connection,
	union tf_command *command,
	union tf_answer *answer)
{
	int error = 0;

	dprintk(KERN_DEBUG "tf_close_client_session(%p)\n", connection);

	command->close_client_session.message_size =
		(sizeof(struct tf_command_close_client_session) -
			sizeof(struct tf_command_header)) / 4;
	command->close_client_session.device_context =
		connection->device_context;

	error = tf_send_receive(
		&connection->dev->sm,
		command,
		answer,
		connection,
		true);

	if (error != 0)
		dprintk(KERN_ERR "tf_close_client_session returns %d\n",
			error);
	else
		dprintk(KERN_ERR "tf_close_client_session returns "
			"error 0x%08X\n",
			answer->close_client_session.error_code);

	return error;
}


/*
 * Registers a shared memory to the Secure World
 */
int tf_register_shared_memory(
	struct tf_connection *connection,
	union tf_command *command,
	union tf_answer *answer)
{
	int error = 0;
	struct tf_shmem_desc *shmem_desc = NULL;
	bool in_user_space = connection->owner != TF_CONNECTION_OWNER_KERNEL;
	struct tf_command_register_shared_memory *msg =
		&command->register_shared_memory;

	dprintk(KERN_INFO "tf_register_shared_memory(%p) "
		"%p[0x%08X][0x%08x]\n",
		connection,
		(void *)msg->shared_mem_descriptors[0],
		msg->shared_mem_size,
		(u32)msg->memory_flags);

	if (in_user_space) {
		error = tf_validate_shmem_and_flags(
			msg->shared_mem_descriptors[0],
			msg->shared_mem_size,
			(u32)msg->memory_flags);
		if (error != 0)
			goto error;
	}

	/* Initialize message_size with no descriptors */
	msg->message_size
		= (offsetof(struct tf_command_register_shared_memory,
						shared_mem_descriptors) -
			sizeof(struct tf_command_header)) / 4;

	/* Map the shmem block and update the message */
	if (msg->shared_mem_size == 0) {
		/* Empty shared mem */
		msg->shared_mem_start_offset = msg->shared_mem_descriptors[0];
	} else {
		u32 descriptor_count;
		error = tf_map_shmem(
			connection,
			msg->shared_mem_descriptors[0],
			msg->memory_flags,
			in_user_space,
			msg->shared_mem_descriptors,
			&(msg->shared_mem_start_offset),
			msg->shared_mem_size,
			&shmem_desc,
			&descriptor_count);
		if (error != 0) {
			dprintk(KERN_ERR "tf_register_shared_memory: "
				"unable to map shared memory block\n");
			goto error;
		}
		msg->message_size += descriptor_count;
	}

	/*
	 * write the correct device context handle and the address of the shared
	 * memory descriptor in the message
	 */
	msg->device_context = connection->device_context;
	msg->block_id = (u32)shmem_desc;

	/* Send the updated message */
	error = tf_send_receive(
		&connection->dev->sm,
		command,
		answer,
		connection,
		true);

	if ((error != 0) ||
		(answer->register_shared_memory.error_code
			!= S_SUCCESS)) {
		dprintk(KERN_ERR "tf_register_shared_memory: "
			"operation failed. Unmap block\n");
		goto error;
	}

	/* Saves the block handle returned by the secure world */
	if (shmem_desc != NULL)
		shmem_desc->block_identifier =
			answer->register_shared_memory.block;

	/* successful completion */
	dprintk(KERN_INFO "tf_register_shared_memory(%p):"
		" block_id=0x%08x block=0x%08x\n",
		connection, msg->block_id,
		answer->register_shared_memory.block);
	return 0;

	/* error completion */
error:
	tf_unmap_shmem(
		connection,
		shmem_desc,
		0);

	if (error != 0)
		dprintk(KERN_ERR "tf_register_shared_memory returns %d\n",
			error);
	else
		dprintk(KERN_ERR "tf_register_shared_memory returns "
			"error_code 0x%08X\n",
			answer->register_shared_memory.error_code);

	return error;
}


/*
 * Releases a shared memory from the Secure World
 */
int tf_release_shared_memory(
	struct tf_connection *connection,
	union tf_command *command,
	union tf_answer *answer)
{
	int error = 0;

	dprintk(KERN_DEBUG "tf_release_shared_memory(%p)\n", connection);

	command->release_shared_memory.message_size =
		(sizeof(struct tf_command_release_shared_memory) -
			sizeof(struct tf_command_header)) / 4;
	command->release_shared_memory.device_context =
		connection->device_context;

	error = tf_send_receive(
		&connection->dev->sm,
		command,
		answer,
		connection,
		true);

	if ((error != 0) ||
		(answer->release_shared_memory.error_code != S_SUCCESS))
		goto error;

	/* Use block_id to get back the pointer to shmem_desc */
	tf_unmap_shmem(
		connection,
		(struct tf_shmem_desc *)
			answer->release_shared_memory.block_id,
		0);

	/* successful completion */
	dprintk(KERN_INFO "tf_release_shared_memory(%p):"
		" block_id=0x%08x block=0x%08x\n",
		connection, answer->release_shared_memory.block_id,
		command->release_shared_memory.block);
	return 0;


error:
	if (error != 0)
		dprintk(KERN_ERR "tf_release_shared_memory returns %d\n",
			error);
	else
		dprintk(KERN_ERR "tf_release_shared_memory returns "
			"nChannelStatus 0x%08X\n",
			answer->release_shared_memory.error_code);

	return error;

}


/*
 * Invokes a client command to the Secure World
 */
int tf_invoke_client_command(
	struct tf_connection *connection,
	union tf_command *command,
	union tf_answer *answer)
{
	int error = 0;
	struct tf_shmem_desc *shmem_desc[4] = {NULL};
	int i;

	dprintk(KERN_INFO "tf_invoke_client_command(%p)\n", connection);

	command->release_shared_memory.message_size =
		(sizeof(struct tf_command_invoke_client_command) -
			sizeof(struct tf_command_header)) / 4;

#ifdef CONFIG_TF_ZEBRA
	error = tf_crypto_try_shortcuted_update(connection,
		(struct tf_command_invoke_client_command *) command,
		(struct tf_answer_invoke_client_command *) answer);
	if (error == 0)
		return error;
#endif

	/* Map the tmprefs */
	for (i = 0; i < 4; i++) {
		int param_type = TF_GET_PARAM_TYPE(
			command->invoke_client_command.param_types, i);
		if ((param_type & (TF_PARAM_TYPE_MEMREF_FLAG |
				   TF_PARAM_TYPE_REGISTERED_MEMREF_FLAG))
				== TF_PARAM_TYPE_MEMREF_FLAG) {
			/* A temporary memref: map it */
			error = tf_map_temp_shmem(connection,
					&command->invoke_client_command.
						params[i].temp_memref,
					param_type, &shmem_desc[i]);
			if (error != 0) {
				dprintk(KERN_ERR
					"tf_invoke_client_command: "
					"unable to map temporary memory "
					"block\n (%08X)", error);
				goto error;
			}
		}
	}

	command->invoke_client_command.device_context =
		connection->device_context;

	error = tf_send_receive(&connection->dev->sm, command,
		answer, connection, true);

error:
	/* Unmap de temp mem refs */
	for (i = 0; i < 4; i++) {
		if (shmem_desc[i] != NULL) {
			dprintk(KERN_INFO "tf_invoke_client_command: "
				"UnMatemp_memref %d\n ", i);
			tf_unmap_shmem(connection, shmem_desc[i], 0);
		}
	}

	if (error != 0)
		dprintk(KERN_ERR "tf_invoke_client_command returns %d\n",
			error);
	else
		dprintk(KERN_ERR "tf_invoke_client_command returns "
			"error_code 0x%08X\n",
			answer->invoke_client_command.error_code);

	return error;
}


/*
 * Cancels a client command from the Secure World
 */
int tf_cancel_client_command(
	struct tf_connection *connection,
	union tf_command *command,
	union tf_answer *answer)
{
	int error = 0;

	dprintk(KERN_DEBUG "tf_cancel_client_command(%p)\n", connection);

	command->cancel_client_operation.device_context =
		connection->device_context;
	command->cancel_client_operation.message_size =
		(sizeof(struct tf_command_cancel_client_operation) -
			sizeof(struct tf_command_header)) / 4;

	error = tf_send_receive(
		&connection->dev->sm,
		command,
		answer,
		connection,
		true);

	if ((error != 0) ||
		(answer->cancel_client_operation.error_code != S_SUCCESS))
		goto error;


	/* successful completion */
	return 0;

error:
	if (error != 0)
		dprintk(KERN_ERR "tf_cancel_client_command returns %d\n",
			error);
	else
		dprintk(KERN_ERR "tf_cancel_client_command returns "
			"nChannelStatus 0x%08X\n",
			answer->cancel_client_operation.error_code);

	return error;
}



/*
 * Destroys a device context from the Secure World
 */
int tf_destroy_device_context(
	struct tf_connection *connection)
{
	int error;
	/*
	 * AFY: better use the specialized tf_command_destroy_device_context
	 * structure: this will save stack
	 */
	union tf_command command;
	union tf_answer answer;

	dprintk(KERN_INFO "tf_destroy_device_context(%p)\n", connection);

	BUG_ON(connection == NULL);

	command.header.message_type = TF_MESSAGE_TYPE_DESTROY_DEVICE_CONTEXT;
	command.header.message_size =
		(sizeof(struct tf_command_destroy_device_context) -
			sizeof(struct tf_command_header))/sizeof(u32);

	/*
	 * fill in the device context handler
	 * it is guarantied that the first shared memory descriptor describes
	 * the device context
	 */
	command.destroy_device_context.device_context =
		connection->device_context;

	error = tf_send_receive(
		&connection->dev->sm,
		&command,
		&answer,
		connection,
		false);

	if ((error != 0) ||
		(answer.destroy_device_context.error_code != S_SUCCESS))
		goto error;

	spin_lock(&(connection->state_lock));
	connection->state = TF_CONN_STATE_NO_DEVICE_CONTEXT;
	spin_unlock(&(connection->state_lock));

	/* successful completion */
	dprintk(KERN_INFO "tf_destroy_device_context(%p)\n",
		connection);
	return 0;

error:
	if (error != 0) {
		dprintk(KERN_ERR "tf_destroy_device_context failed with "
			"error %d\n", error);
	} else {
		dprintk(KERN_ERR "tf_destroy_device_context failed with "
			"error_code 0x%08X\n",
			answer.destroy_device_context.error_code);
		if (answer.destroy_device_context.error_code ==
			S_ERROR_OUT_OF_MEMORY)
			error = -ENOMEM;
		else
			error = -EFAULT;
	}

	return error;
}


/*----------------------------------------------------------------------------
 * Connection initialization and cleanup operations
 *----------------------------------------------------------------------------*/

/*
 * Opens a connection to the specified device.
 *
 * The placeholder referenced by connection is set to the address of the
 * new connection; it is set to NULL upon failure.
 *
 * Returns zero upon successful completion, or an appropriate error code upon
 * failure.
 */
int tf_open(struct tf_device *dev,
	struct file *file,
	struct tf_connection **connection)
{
	int error;
	struct tf_connection *conn = NULL;

	dprintk(KERN_INFO "tf_open(%p, %p)\n", file, connection);

	/*
	 * Allocate and initialize the conn.
	 * kmalloc only allocates sizeof(*conn) virtual memory
	 */
	conn = (struct tf_connection *) internal_kmalloc(sizeof(*conn),
		GFP_KERNEL);
	if (conn == NULL) {
		printk(KERN_ERR "tf_open(): "
			"Out of memory for conn!\n");
		error = -ENOMEM;
		goto error;
	}

	memset(conn, 0, sizeof(*conn));

	conn->state = TF_CONN_STATE_NO_DEVICE_CONTEXT;
	conn->dev = dev;
	spin_lock_init(&(conn->state_lock));
	atomic_set(&(conn->pending_op_count), 0);
	INIT_LIST_HEAD(&(conn->list));

	/*
	 * Initialize the shared memory
	 */
	error = tf_init_shared_memory(conn);
	if (error != 0)
		goto error;

#ifdef CONFIG_TF_ZEBRA
	/*
	 * Initialize CUS specifics
	 */
	tf_crypto_init_cus(conn);
#endif

	/*
	 * Attach the conn to the device.
	 */
	spin_lock(&(dev->connection_list_lock));
	list_add(&(conn->list), &(dev->connection_list));
	spin_unlock(&(dev->connection_list_lock));

	/*
	 * Successful completion.
	 */

	*connection = conn;

	dprintk(KERN_INFO "tf_open(): Success (conn=%p)\n", conn);
	return 0;

	/*
	 * Error handling.
	 */

error:
	dprintk(KERN_ERR "tf_open(): Failure (error %d)\n", error);
	/* Deallocate the descriptor pages if necessary */
	internal_kfree(conn);
	*connection = NULL;
	return error;
}


/*
 * Closes the specified connection.
 *
 * Upon return, the connection has been destroyed and cannot be used anymore.
 *
 * This function does nothing if connection is set to NULL.
 */
void tf_close(struct tf_connection *connection)
{
	int error;
	enum TF_CONN_STATE state;

	dprintk(KERN_DEBUG "tf_close(%p)\n", connection);

	if (connection == NULL)
		return;

	/*
	 * Assumption: Linux guarantees that no other operation is in progress
	 * and that no other operation will be started when close is called
	 */
	BUG_ON(atomic_read(&(connection->pending_op_count)) != 0);

	/*
	 * Exchange a Destroy Device Context message if needed.
	 */
	spin_lock(&(connection->state_lock));
	state = connection->state;
	spin_unlock(&(connection->state_lock));
	if (state == TF_CONN_STATE_VALID_DEVICE_CONTEXT) {
		/*
		 * A DestroyDeviceContext operation was not performed. Do it
		 * now.
		 */
		error = tf_destroy_device_context(connection);
		if (error != 0)
			/* avoid cleanup if destroy device context fails */
			goto error;
	}

	/*
	 * Clean up the shared memory
	 */
	tf_cleanup_shared_memories(connection);

	spin_lock(&(connection->dev->connection_list_lock));
	list_del(&(connection->list));
	spin_unlock(&(connection->dev->connection_list_lock));

	internal_kfree(connection);

	return;

error:
	dprintk(KERN_DEBUG "tf_close(%p) failed with error code %d\n",
		connection, error);
}