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
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2021-2022, NVIDIA CORPORATION & AFFILIATES
 */
#include <linux/iommu.h>
#include <linux/iommufd.h>
#include <linux/pci-ats.h>
#include <linux/slab.h>
#include <uapi/linux/iommufd.h>

#include "../iommu-priv.h"
#include "io_pagetable.h"
#include "iommufd_private.h"

static bool allow_unsafe_interrupts;
module_param(allow_unsafe_interrupts, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(
	allow_unsafe_interrupts,
	"Allow IOMMUFD to bind to devices even if the platform cannot isolate "
	"the MSI interrupt window. Enabling this is a security weakness.");

struct iommufd_attach {
	struct iommufd_hw_pagetable *hwpt;
	struct xarray device_array;
};

/*
 * Detect a noiommu device for the cdev path. We check dev->iommu rather than
 * using device_iommu_mapped() (which checks dev->iommu_group) because when
 * both group and cdev interfaces coexist, the group path assigns a fake
 * noiommu iommu_group to the device. That would cause device_iommu_mapped()
 * to return true and hide the noiommu case from the cdev path. dev->iommu is
 * reliably NULL when no IOMMU driver is managing the device.
 */
static bool iommufd_device_is_noiommu(struct iommufd_device *idev)
{
	return IS_ENABLED(CONFIG_IOMMUFD_NOIOMMU) && !idev->dev->iommu;
}

static void iommufd_group_release(struct kref *kref)
{
	struct iommufd_group *igroup =
		container_of(kref, struct iommufd_group, ref);

	WARN_ON(!xa_empty(&igroup->pasid_attach));

	if (igroup->group) {
		xa_cmpxchg(&igroup->ictx->groups, iommu_group_id(igroup->group),
			   igroup, NULL, GFP_KERNEL);
		iommu_group_put(igroup->group);
	}
	mutex_destroy(&igroup->lock);
	kfree(igroup);
}

static void iommufd_put_group(struct iommufd_group *group)
{
	kref_put(&group->ref, iommufd_group_release);
}

static bool iommufd_group_try_get(struct iommufd_group *igroup,
				  struct iommu_group *group)
{
	if (!igroup)
		return false;
	/*
	 * group ID's cannot be re-used until the group is put back which does
	 * not happen if we could get an igroup pointer under the xa_lock.
	 */
	if (WARN_ON(igroup->group != group))
		return false;
	return kref_get_unless_zero(&igroup->ref);
}

static struct iommufd_group *iommufd_alloc_group(struct iommufd_ctx *ictx,
						 struct iommu_group *group)
{
	struct iommufd_group *new_igroup;

	new_igroup = kzalloc_obj(*new_igroup, GFP_KERNEL);
	if (!new_igroup)
		return ERR_PTR(-ENOMEM);

	kref_init(&new_igroup->ref);
	mutex_init(&new_igroup->lock);
	xa_init(&new_igroup->pasid_attach);
	new_igroup->sw_msi_start = PHYS_ADDR_MAX;
	/* group reference moves into new_igroup */
	new_igroup->group = group;

	/*
	 * The ictx is not additionally refcounted here because all objects using
	 * an igroup must put it before their destroy completes.
	 */
	new_igroup->ictx = ictx;
	return new_igroup;
}

/*
 * iommufd needs to store some more data for each iommu_group, we keep a
 * parallel xarray indexed by iommu_group id to hold this instead of putting it
 * in the core structure. To keep things simple the iommufd_group memory is
 * unique within the iommufd_ctx. This makes it easy to check there are no
 * memory leaks.
 */
static struct iommufd_group *iommufd_get_group(struct iommufd_ctx *ictx,
					       struct device *dev)
{
	struct iommufd_group *new_igroup;
	struct iommufd_group *cur_igroup;
	struct iommufd_group *igroup;
	struct iommu_group *group;
	unsigned int id;

	group = iommu_group_get(dev);
	if (!group)
		return ERR_PTR(-ENODEV);

	id = iommu_group_id(group);

	xa_lock(&ictx->groups);
	igroup = xa_load(&ictx->groups, id);
	if (iommufd_group_try_get(igroup, group)) {
		xa_unlock(&ictx->groups);
		iommu_group_put(group);
		return igroup;
	}
	xa_unlock(&ictx->groups);

	new_igroup = iommufd_alloc_group(ictx, group);
	if (IS_ERR(new_igroup)) {
		iommu_group_put(group);
		return new_igroup;
	}

	/*
	 * We dropped the lock so igroup is invalid. NULL is a safe and likely
	 * value to assume for the xa_cmpxchg algorithm.
	 */
	cur_igroup = NULL;
	xa_lock(&ictx->groups);
	while (true) {
		igroup = __xa_cmpxchg(&ictx->groups, id, cur_igroup, new_igroup,
				      GFP_KERNEL);
		if (xa_is_err(igroup)) {
			xa_unlock(&ictx->groups);
			iommufd_put_group(new_igroup);
			return ERR_PTR(xa_err(igroup));
		}

		/* new_group was successfully installed */
		if (cur_igroup == igroup) {
			xa_unlock(&ictx->groups);
			return new_igroup;
		}

		/* Check again if the current group is any good */
		if (iommufd_group_try_get(igroup, group)) {
			xa_unlock(&ictx->groups);
			iommufd_put_group(new_igroup);
			return igroup;
		}
		cur_igroup = igroup;
	}
}

static void iommufd_device_remove_vdev(struct iommufd_device *idev)
{
	struct iommufd_vdevice *vdev;

	mutex_lock(&idev->igroup->lock);
	/* prevent new references from vdev */
	idev->destroying = true;
	/* vdev has been completely destroyed by userspace */
	if (!idev->vdev)
		goto out_unlock;

	vdev = idev->vdev;

	/*
	 * An ongoing vdev destroy ioctl has removed the vdev from the object
	 * xarray, but has not finished iommufd_vdevice_destroy() yet as it
	 * needs the same mutex. We exit the locking then wait on wait_cnt
	 * reference for the vdev destruction.
	 */
	if (iommufd_try_inc_users(idev->ictx, &vdev->obj))
		goto out_unlock;

	/*
	 * vdev is still alive. Hold a users refcount to prevent racing with
	 * userspace destruction, then use iommufd_object_tombstone_user() to
	 * destroy it and leave a tombstone.
	 */
	mutex_unlock(&idev->igroup->lock);
	iommufd_object_tombstone_user(idev->ictx, &vdev->obj);
	return;

out_unlock:
	mutex_unlock(&idev->igroup->lock);
}

void iommufd_device_pre_destroy(struct iommufd_object *obj)
{
	struct iommufd_device *idev =
		container_of(obj, struct iommufd_device, obj);

	/* Release the wait_cnt reference on this */
	iommufd_device_remove_vdev(idev);
}

void iommufd_device_destroy(struct iommufd_object *obj)
{
	struct iommufd_device *idev =
		container_of(obj, struct iommufd_device, obj);

	/* igroup is NULL when destroy called during bind error cleanup */
	if (!idev->igroup)
		return;
	if (!iommufd_device_is_noiommu(idev))
		iommu_device_release_dma_owner(idev->dev);
	iommufd_put_group(idev->igroup);
	if (!iommufd_selftest_is_mock_dev(idev->dev))
		iommufd_ctx_put(idev->ictx);
}

static int iommufd_bind_iommu(struct iommufd_device *idev)
{
	struct iommufd_ctx *ictx = idev->ictx;
	struct device *dev = idev->dev;
	struct iommufd_group *igroup;
	int rc;

	/*
	 * iommufd always sets IOMMU_CACHE because we offer no way for userspace
	 * to restore cache coherency.
	 */
	if (!device_iommu_capable(dev, IOMMU_CAP_CACHE_COHERENCY))
		return -EINVAL;

	igroup = iommufd_get_group(ictx, dev);
	if (IS_ERR(igroup))
		return PTR_ERR(igroup);

	/*
	 * For historical compat with VFIO the insecure interrupt path is
	 * allowed if the module parameter is set. Secure/Isolated means that a
	 * MemWr operation from the device (eg a simple DMA) cannot trigger an
	 * interrupt outside this iommufd context.
	 */
	if (!iommufd_selftest_is_mock_dev(dev) &&
	    !iommu_group_has_isolated_msi(igroup->group)) {
		if (!allow_unsafe_interrupts) {
			rc = -EPERM;
			goto out_group_put;
		}

		dev_warn(
			dev,
			"MSI interrupts are not secure, they cannot be isolated by the platform. "
			"Check that platform features like interrupt remapping are enabled. "
			"Use the \"allow_unsafe_interrupts\" module parameter to override\n");
	}

	rc = iommu_device_claim_dma_owner(dev, ictx);
	if (rc)
		goto out_group_put;

	/* igroup refcount moves into iommufd_device */
	idev->igroup = igroup;
	idev->enforce_cache_coherency =
		device_iommu_capable(dev, IOMMU_CAP_ENFORCE_CACHE_COHERENCY);
	return 0;

out_group_put:
	iommufd_put_group(igroup);
	return rc;
}

/*
 * Noiommu devices have no real IOMMU group. Create a dummy igroup so that
 * internal code paths that expect idev->igroup to be present still work.
 * A NULL igroup->group distinguishes this from a real IOMMU-backed group.
 */
static int iommufd_bind_noiommu(struct iommufd_device *idev)
{
	struct iommufd_group *igroup;

	igroup = iommufd_alloc_group(idev->ictx, NULL);
	if (IS_ERR(igroup))
		return PTR_ERR(igroup);
	idev->igroup = igroup;
	return 0;
}

/**
 * iommufd_device_bind - Bind a physical device to an iommu fd
 * @ictx: iommufd file descriptor
 * @dev: Pointer to a physical device struct
 * @id: Output ID number to return to userspace for this device
 *
 * A successful bind establishes an ownership over the device and returns
 * struct iommufd_device pointer, otherwise returns error pointer.
 *
 * A driver using this API must set driver_managed_dma and must not touch
 * the device until this routine succeeds and establishes ownership.
 *
 * Binding a PCI device places the entire RID under iommufd control.
 *
 * The caller must undo this with iommufd_device_unbind()
 */
struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,
					   struct device *dev, u32 *id)
{
	struct iommufd_device *idev;
	int rc;

	idev = iommufd_object_alloc(ictx, idev, IOMMUFD_OBJ_DEVICE);
	if (IS_ERR(idev))
		return idev;

	idev->ictx = ictx;
	idev->dev = dev;

	if (!iommufd_device_is_noiommu(idev))
		rc = iommufd_bind_iommu(idev);
	else
		rc = iommufd_bind_noiommu(idev);
	if (rc)
		goto err_out;

	/*
	 * Take a ctx reference after bind succeeds. This must happen here
	 * so that iommufd_device_destroy() can handle partial initialization
	 */
	if (!iommufd_selftest_is_mock_dev(dev))
		iommufd_ctx_get(ictx);
	/* The calling driver is a user until iommufd_device_unbind() */
	refcount_inc(&idev->obj.users);

	/*
	 * If the caller fails after this success it must call
	 * iommufd_unbind_device() which is safe since we hold this refcount.
	 * This also means the device is a leaf in the graph and no other object
	 * can take a reference on it.
	 */
	iommufd_object_finalize(ictx, &idev->obj);
	*id = idev->obj.id;
	return idev;

err_out:
	/*
	 * iommufd_device_destroy() handles partially initialized idev,
	 * so iommufd_object_abort_and_destroy() is safe to call here.
	 */
	iommufd_object_abort_and_destroy(ictx, &idev->obj);
	return ERR_PTR(rc);

}
EXPORT_SYMBOL_NS_GPL(iommufd_device_bind, "IOMMUFD");

/**
 * iommufd_ctx_has_group - True if any device within the group is bound
 *                         to the ictx
 * @ictx: iommufd file descriptor
 * @group: Pointer to a physical iommu_group struct
 *
 * True if any device within the group has been bound to this ictx, ex. via
 * iommufd_device_bind(), therefore implying ictx ownership of the group.
 */
bool iommufd_ctx_has_group(struct iommufd_ctx *ictx, struct iommu_group *group)
{
	struct iommufd_object *obj;
	unsigned long index;

	if (!ictx || !group)
		return false;

	xa_lock(&ictx->objects);
	xa_for_each(&ictx->objects, index, obj) {
		if (obj->type == IOMMUFD_OBJ_DEVICE &&
		    container_of(obj, struct iommufd_device, obj)
				    ->igroup->group == group) {
			xa_unlock(&ictx->objects);
			return true;
		}
	}
	xa_unlock(&ictx->objects);
	return false;
}
EXPORT_SYMBOL_NS_GPL(iommufd_ctx_has_group, "IOMMUFD");

/**
 * iommufd_device_unbind - Undo iommufd_device_bind()
 * @idev: Device returned by iommufd_device_bind()
 *
 * Release the device from iommufd control. The DMA ownership will return back
 * to unowned with DMA controlled by the DMA API. This invalidates the
 * iommufd_device pointer, other APIs that consume it must not be called
 * concurrently.
 */
void iommufd_device_unbind(struct iommufd_device *idev)
{
	iommufd_object_destroy_user(idev->ictx, &idev->obj);
}
EXPORT_SYMBOL_NS_GPL(iommufd_device_unbind, "IOMMUFD");

struct iommufd_ctx *iommufd_device_to_ictx(struct iommufd_device *idev)
{
	return idev->ictx;
}
EXPORT_SYMBOL_NS_GPL(iommufd_device_to_ictx, "IOMMUFD");

u32 iommufd_device_to_id(struct iommufd_device *idev)
{
	return idev->obj.id;
}
EXPORT_SYMBOL_NS_GPL(iommufd_device_to_id, "IOMMUFD");

static unsigned int iommufd_group_device_num(struct iommufd_group *igroup,
					     ioasid_t pasid)
{
	struct iommufd_attach *attach;
	struct iommufd_device *idev;
	unsigned int count = 0;
	unsigned long index;

	lockdep_assert_held(&igroup->lock);

	attach = xa_load(&igroup->pasid_attach, pasid);
	if (attach)
		xa_for_each(&attach->device_array, index, idev)
			count++;
	return count;
}

#ifdef CONFIG_IRQ_MSI_IOMMU
static int iommufd_group_setup_msi(struct iommufd_group *igroup,
				   struct iommufd_hwpt_paging *hwpt_paging)
{
	struct iommufd_ctx *ictx = igroup->ictx;
	struct iommufd_sw_msi_map *cur;

	if (igroup->sw_msi_start == PHYS_ADDR_MAX)
		return 0;

	/*
	 * Install all the MSI pages the device has been using into the domain
	 */
	guard(mutex)(&ictx->sw_msi_lock);
	list_for_each_entry(cur, &ictx->sw_msi_list, sw_msi_item) {
		int rc;

		if (cur->sw_msi_start != igroup->sw_msi_start ||
		    !test_bit(cur->id, igroup->required_sw_msi.bitmap))
			continue;

		rc = iommufd_sw_msi_install(ictx, hwpt_paging, cur);
		if (rc)
			return rc;
	}
	return 0;
}
#else
static inline int
iommufd_group_setup_msi(struct iommufd_group *igroup,
			struct iommufd_hwpt_paging *hwpt_paging)
{
	return 0;
}
#endif

static bool
iommufd_group_first_attach(struct iommufd_group *igroup, ioasid_t pasid)
{
	lockdep_assert_held(&igroup->lock);
	return !xa_load(&igroup->pasid_attach, pasid);
}

static int
iommufd_device_attach_reserved_iova(struct iommufd_device *idev,
				    struct iommufd_hwpt_paging *hwpt_paging)
{
	struct iommufd_group *igroup = idev->igroup;
	int rc;

	lockdep_assert_held(&igroup->lock);

	rc = iopt_table_enforce_dev_resv_regions(&hwpt_paging->ioas->iopt,
						 idev->dev,
						 &igroup->sw_msi_start);
	if (rc)
		return rc;

	if (iommufd_group_first_attach(igroup, IOMMU_NO_PASID)) {
		rc = iommufd_group_setup_msi(igroup, hwpt_paging);
		if (rc) {
			iopt_remove_reserved_iova(&hwpt_paging->ioas->iopt,
						  idev->dev);
			return rc;
		}
	}
	return 0;
}

/* The device attach/detach/replace helpers for attach_handle */

static bool iommufd_device_is_attached(struct iommufd_device *idev,
				       ioasid_t pasid)
{
	struct iommufd_attach *attach;

	attach = xa_load(&idev->igroup->pasid_attach, pasid);
	return xa_load(&attach->device_array, idev->obj.id);
}

static int iommufd_hwpt_pasid_compat(struct iommufd_hw_pagetable *hwpt,
				     struct iommufd_device *idev,
				     ioasid_t pasid)
{
	struct iommufd_group *igroup = idev->igroup;

	lockdep_assert_held(&igroup->lock);

	if (pasid == IOMMU_NO_PASID) {
		unsigned long start = IOMMU_NO_PASID;

		if (!hwpt->pasid_compat &&
		    xa_find_after(&igroup->pasid_attach,
				  &start, UINT_MAX, XA_PRESENT))
			return -EINVAL;
	} else {
		struct iommufd_attach *attach;

		if (!hwpt->pasid_compat)
			return -EINVAL;

		attach = xa_load(&igroup->pasid_attach, IOMMU_NO_PASID);
		if (attach && attach->hwpt && !attach->hwpt->pasid_compat)
			return -EINVAL;
	}

	return 0;
}

static bool iommufd_hwpt_compatible_device(struct iommufd_hw_pagetable *hwpt,
					   struct iommufd_device *idev)
{
	struct pci_dev *pdev;

	if (!hwpt->fault || !dev_is_pci(idev->dev))
		return true;

	/*
	 * Once we turn on PCI/PRI support for VF, the response failure code
	 * should not be forwarded to the hardware due to PRI being a shared
	 * resource between PF and VFs. There is no coordination for this
	 * shared capability. This waits for a vPRI reset to recover.
	 */
	pdev = to_pci_dev(idev->dev);

	return (!pdev->is_virtfn || !pci_pri_supported(pdev));
}

static int iommufd_hwpt_attach_device(struct iommufd_hw_pagetable *hwpt,
				      struct iommufd_device *idev,
				      ioasid_t pasid)
{
	struct iommufd_attach_handle *handle;
	int rc;

	if (!iommufd_hwpt_compatible_device(hwpt, idev))
		return -EINVAL;

	rc = iommufd_hwpt_pasid_compat(hwpt, idev, pasid);
	if (rc)
		return rc;

	if (iommufd_device_is_noiommu(idev))
		return 0;

	handle = kzalloc_obj(*handle);
	if (!handle)
		return -ENOMEM;

	handle->idev = idev;
	if (pasid == IOMMU_NO_PASID)
		rc = iommu_attach_group_handle(hwpt->domain, idev->igroup->group,
					       &handle->handle);
	else
		rc = iommu_attach_device_pasid(hwpt->domain, idev->dev, pasid,
					       &handle->handle);
	if (rc)
		goto out_free_handle;

	return 0;

out_free_handle:
	kfree(handle);
	return rc;
}

static struct iommufd_attach_handle *
iommufd_device_get_attach_handle(struct iommufd_device *idev, ioasid_t pasid)
{
	struct iommu_attach_handle *handle;

	lockdep_assert_held(&idev->igroup->lock);

	handle = iommu_attach_handle_get(idev->igroup->group, pasid, 0);
	if (IS_ERR(handle))
		return NULL;
	return to_iommufd_handle(handle);
}

static void iommufd_hwpt_detach_device(struct iommufd_hw_pagetable *hwpt,
				       struct iommufd_device *idev,
				       ioasid_t pasid)
{
	struct iommufd_attach_handle *handle;

	if (iommufd_device_is_noiommu(idev))
		return;

	handle = iommufd_device_get_attach_handle(idev, pasid);
	if (pasid == IOMMU_NO_PASID)
		iommu_detach_group_handle(hwpt->domain, idev->igroup->group);
	else
		iommu_detach_device_pasid(hwpt->domain, idev->dev, pasid);

	iommufd_auto_response_faults(hwpt, handle);
	kfree(handle);
}

static int iommufd_hwpt_replace_device(struct iommufd_device *idev,
				       ioasid_t pasid,
				       struct iommufd_hw_pagetable *hwpt,
				       struct iommufd_hw_pagetable *old)
{
	struct iommufd_attach_handle *handle, *old_handle;
	int rc;

	if (!iommufd_hwpt_compatible_device(hwpt, idev))
		return -EINVAL;

	rc = iommufd_hwpt_pasid_compat(hwpt, idev, pasid);
	if (rc)
		return rc;

	if (iommufd_device_is_noiommu(idev))
		return 0;

	old_handle = iommufd_device_get_attach_handle(idev, pasid);

	handle = kzalloc_obj(*handle);
	if (!handle)
		return -ENOMEM;

	handle->idev = idev;
	if (pasid == IOMMU_NO_PASID)
		rc = iommu_replace_group_handle(idev->igroup->group,
						hwpt->domain, &handle->handle);
	else
		rc = iommu_replace_device_pasid(hwpt->domain, idev->dev,
						pasid, &handle->handle);
	if (rc)
		goto out_free_handle;

	iommufd_auto_response_faults(old, old_handle);
	kfree(old_handle);

	return 0;

out_free_handle:
	kfree(handle);
	return rc;
}

int iommufd_hw_pagetable_attach(struct iommufd_hw_pagetable *hwpt,
				struct iommufd_device *idev, ioasid_t pasid)
{
	struct iommufd_hwpt_paging *hwpt_paging = find_hwpt_paging(hwpt);
	bool attach_resv = hwpt_paging && pasid == IOMMU_NO_PASID &&
			   !iommufd_device_is_noiommu(idev);
	struct iommufd_group *igroup = idev->igroup;
	struct iommufd_hw_pagetable *old_hwpt;
	struct iommufd_attach *attach;
	int rc;

	mutex_lock(&igroup->lock);

	attach = xa_cmpxchg(&igroup->pasid_attach, pasid, NULL,
			    XA_ZERO_ENTRY, GFP_KERNEL);
	if (xa_is_err(attach)) {
		rc = xa_err(attach);
		goto err_unlock;
	}

	if (!attach) {
		attach = kzalloc_obj(*attach);
		if (!attach) {
			rc = -ENOMEM;
			goto err_release_pasid;
		}
		xa_init(&attach->device_array);
	}

	old_hwpt = attach->hwpt;

	rc = xa_insert(&attach->device_array, idev->obj.id, XA_ZERO_ENTRY,
		       GFP_KERNEL);
	if (rc) {
		WARN_ON(rc == -EBUSY && !old_hwpt);
		goto err_free_attach;
	}

	if (old_hwpt && old_hwpt != hwpt) {
		rc = -EINVAL;
		goto err_release_devid;
	}

	if (attach_resv) {
		rc = iommufd_device_attach_reserved_iova(idev, hwpt_paging);
		if (rc)
			goto err_release_devid;
	}

	/*
	 * Only attach to the group once for the first device that is in the
	 * group. All the other devices will follow this attachment. The user
	 * should attach every device individually to the hwpt as the per-device
	 * reserved regions are only updated during individual device
	 * attachment.
	 */
	if (iommufd_group_first_attach(igroup, pasid)) {
		rc = iommufd_hwpt_attach_device(hwpt, idev, pasid);
		if (rc)
			goto err_unresv;
		attach->hwpt = hwpt;
		WARN_ON(xa_is_err(xa_store(&igroup->pasid_attach, pasid, attach,
					   GFP_KERNEL)));
	}
	refcount_inc(&hwpt->obj.users);
	WARN_ON(xa_is_err(xa_store(&attach->device_array, idev->obj.id,
				   idev, GFP_KERNEL)));
	mutex_unlock(&igroup->lock);
	return 0;
err_unresv:
	if (attach_resv)
		iopt_remove_reserved_iova(&hwpt_paging->ioas->iopt, idev->dev);
err_release_devid:
	xa_release(&attach->device_array, idev->obj.id);
err_free_attach:
	if (iommufd_group_first_attach(igroup, pasid))
		kfree(attach);
err_release_pasid:
	if (iommufd_group_first_attach(igroup, pasid))
		xa_release(&igroup->pasid_attach, pasid);
err_unlock:
	mutex_unlock(&igroup->lock);
	return rc;
}

struct iommufd_hw_pagetable *
iommufd_hw_pagetable_detach(struct iommufd_device *idev, ioasid_t pasid)
{
	struct iommufd_group *igroup = idev->igroup;
	struct iommufd_hwpt_paging *hwpt_paging;
	struct iommufd_hw_pagetable *hwpt;
	struct iommufd_attach *attach;

	mutex_lock(&igroup->lock);
	attach = xa_load(&igroup->pasid_attach, pasid);
	if (!attach) {
		mutex_unlock(&igroup->lock);
		return NULL;
	}

	hwpt = attach->hwpt;
	hwpt_paging = find_hwpt_paging(hwpt);

	xa_erase(&attach->device_array, idev->obj.id);
	if (xa_empty(&attach->device_array)) {
		iommufd_hwpt_detach_device(hwpt, idev, pasid);
		xa_erase(&igroup->pasid_attach, pasid);
		kfree(attach);
	}
	if (hwpt_paging && pasid == IOMMU_NO_PASID)
		iopt_remove_reserved_iova(&hwpt_paging->ioas->iopt, idev->dev);
	mutex_unlock(&igroup->lock);

	iommufd_hw_pagetable_put(idev->ictx, hwpt);

	/* Caller must destroy hwpt */
	return hwpt;
}

static struct iommufd_hw_pagetable *
iommufd_device_do_attach(struct iommufd_device *idev, ioasid_t pasid,
			 struct iommufd_hw_pagetable *hwpt)
{
	int rc;

	rc = iommufd_hw_pagetable_attach(hwpt, idev, pasid);
	if (rc)
		return ERR_PTR(rc);
	return NULL;
}

static void
iommufd_group_remove_reserved_iova(struct iommufd_group *igroup,
				   struct iommufd_hwpt_paging *hwpt_paging)
{
	struct iommufd_attach *attach;
	struct iommufd_device *cur;
	unsigned long index;

	lockdep_assert_held(&igroup->lock);

	attach = xa_load(&igroup->pasid_attach, IOMMU_NO_PASID);
	xa_for_each(&attach->device_array, index, cur)
		iopt_remove_reserved_iova(&hwpt_paging->ioas->iopt, cur->dev);
}

static int
iommufd_group_do_replace_reserved_iova(struct iommufd_group *igroup,
				       struct iommufd_hwpt_paging *hwpt_paging)
{
	struct iommufd_hwpt_paging *old_hwpt_paging;
	struct iommufd_attach *attach;
	struct iommufd_device *cur;
	unsigned long index;
	int rc;

	lockdep_assert_held(&igroup->lock);

	attach = xa_load(&igroup->pasid_attach, IOMMU_NO_PASID);
	old_hwpt_paging = find_hwpt_paging(attach->hwpt);
	if (!old_hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas) {
		xa_for_each(&attach->device_array, index, cur) {
			rc = iopt_table_enforce_dev_resv_regions(
				&hwpt_paging->ioas->iopt, cur->dev, NULL);
			if (rc)
				goto err_unresv;
		}
	}

	rc = iommufd_group_setup_msi(igroup, hwpt_paging);
	if (rc)
		goto err_unresv;
	return 0;

err_unresv:
	iommufd_group_remove_reserved_iova(igroup, hwpt_paging);
	return rc;
}

static struct iommufd_hw_pagetable *
iommufd_device_do_replace(struct iommufd_device *idev, ioasid_t pasid,
			  struct iommufd_hw_pagetable *hwpt)
{
	struct iommufd_hwpt_paging *hwpt_paging = find_hwpt_paging(hwpt);
	bool attach_resv = hwpt_paging && pasid == IOMMU_NO_PASID &&
			   !iommufd_device_is_noiommu(idev);
	struct iommufd_hwpt_paging *old_hwpt_paging;
	struct iommufd_group *igroup = idev->igroup;
	struct iommufd_hw_pagetable *old_hwpt;
	struct iommufd_attach *attach;
	unsigned int num_devices;
	int rc;

	mutex_lock(&igroup->lock);

	attach = xa_load(&igroup->pasid_attach, pasid);
	if (!attach) {
		rc = -EINVAL;
		goto err_unlock;
	}

	old_hwpt = attach->hwpt;

	WARN_ON(!old_hwpt || xa_empty(&attach->device_array));

	if (!iommufd_device_is_attached(idev, pasid)) {
		rc = -EINVAL;
		goto err_unlock;
	}

	if (hwpt == old_hwpt) {
		mutex_unlock(&igroup->lock);
		return NULL;
	}

	if (attach_resv) {
		rc = iommufd_group_do_replace_reserved_iova(igroup, hwpt_paging);
		if (rc)
			goto err_unlock;
	}

	rc = iommufd_hwpt_replace_device(idev, pasid, hwpt, old_hwpt);
	if (rc)
		goto err_unresv;

	old_hwpt_paging = find_hwpt_paging(old_hwpt);
	if (old_hwpt_paging && pasid == IOMMU_NO_PASID &&
	    (!hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas))
		iommufd_group_remove_reserved_iova(igroup, old_hwpt_paging);

	attach->hwpt = hwpt;

	num_devices = iommufd_group_device_num(igroup, pasid);
	/*
	 * Move the refcounts held by the device_array to the new hwpt. Retain a
	 * refcount for this thread as the caller will free it.
	 */
	refcount_add(num_devices, &hwpt->obj.users);
	if (num_devices > 1)
		WARN_ON(refcount_sub_and_test(num_devices - 1,
					      &old_hwpt->obj.users));
	mutex_unlock(&igroup->lock);

	/* Caller must destroy old_hwpt */
	return old_hwpt;
err_unresv:
	if (attach_resv)
		iommufd_group_remove_reserved_iova(igroup, hwpt_paging);
err_unlock:
	mutex_unlock(&igroup->lock);
	return ERR_PTR(rc);
}

typedef struct iommufd_hw_pagetable *(*attach_fn)(
	struct iommufd_device *idev, ioasid_t pasid,
	struct iommufd_hw_pagetable *hwpt);

/*
 * When automatically managing the domains we search for a compatible domain in
 * the iopt and if one is found use it, otherwise create a new domain.
 * Automatic domain selection will never pick a manually created domain.
 */
static struct iommufd_hw_pagetable *
iommufd_device_auto_get_domain(struct iommufd_device *idev, ioasid_t pasid,
			       struct iommufd_ioas *ioas, u32 *pt_id,
			       attach_fn do_attach)
{
	/*
	 * iommufd_hw_pagetable_attach() is called by
	 * iommufd_hwpt_paging_alloc() in immediate attachment mode, same as
	 * iommufd_device_do_attach(). So if we are in this mode then we prefer
	 * to use the immediate_attach path as it supports drivers that can't
	 * directly allocate a domain.
	 */
	bool immediate_attach = do_attach == iommufd_device_do_attach;
	struct iommufd_hw_pagetable *destroy_hwpt;
	struct iommufd_hwpt_paging *hwpt_paging;
	struct iommufd_hw_pagetable *hwpt;

	/*
	 * There is no differentiation when domains are allocated, so any domain
	 * that is willing to attach to the device is interchangeable with any
	 * other.
	 */
	mutex_lock(&ioas->mutex);
	list_for_each_entry(hwpt_paging, &ioas->hwpt_list, hwpt_item) {
		if (!hwpt_paging->auto_domain)
			continue;

		hwpt = &hwpt_paging->common;
		if (!iommufd_lock_obj(&hwpt->obj))
			continue;
		destroy_hwpt = (*do_attach)(idev, pasid, hwpt);
		if (IS_ERR(destroy_hwpt)) {
			iommufd_put_object(idev->ictx, &hwpt->obj);
			/*
			 * -EINVAL means the domain is incompatible with the
			 * device. Other error codes should propagate to
			 * userspace as failure. Success means the domain is
			 * attached.
			 */
			if (PTR_ERR(destroy_hwpt) == -EINVAL)
				continue;
			goto out_unlock;
		}
		*pt_id = hwpt->obj.id;
		iommufd_put_object(idev->ictx, &hwpt->obj);
		goto out_unlock;
	}

	hwpt_paging = iommufd_hwpt_paging_alloc(idev->ictx, ioas, idev, pasid,
						0, immediate_attach, NULL);
	if (IS_ERR(hwpt_paging)) {
		destroy_hwpt = ERR_CAST(hwpt_paging);
		goto out_unlock;
	}
	hwpt = &hwpt_paging->common;

	if (!immediate_attach) {
		destroy_hwpt = (*do_attach)(idev, pasid, hwpt);
		if (IS_ERR(destroy_hwpt))
			goto out_abort;
	} else {
		destroy_hwpt = NULL;
	}

	hwpt_paging->auto_domain = true;
	*pt_id = hwpt->obj.id;

	iommufd_object_finalize(idev->ictx, &hwpt->obj);
	mutex_unlock(&ioas->mutex);
	return destroy_hwpt;

out_abort:
	iommufd_object_abort_and_destroy(idev->ictx, &hwpt->obj);
out_unlock:
	mutex_unlock(&ioas->mutex);
	return destroy_hwpt;
}

static int iommufd_device_change_pt(struct iommufd_device *idev,
				    ioasid_t pasid,
				    u32 *pt_id, attach_fn do_attach)
{
	struct iommufd_hw_pagetable *destroy_hwpt;
	struct iommufd_object *pt_obj;

	pt_obj = iommufd_get_object(idev->ictx, *pt_id, IOMMUFD_OBJ_ANY);
	if (IS_ERR(pt_obj))
		return PTR_ERR(pt_obj);

	switch (pt_obj->type) {
	case IOMMUFD_OBJ_HWPT_NESTED:
	case IOMMUFD_OBJ_HWPT_PAGING: {
		struct iommufd_hw_pagetable *hwpt =
			container_of(pt_obj, struct iommufd_hw_pagetable, obj);

		destroy_hwpt = (*do_attach)(idev, pasid, hwpt);
		if (IS_ERR(destroy_hwpt))
			goto out_put_pt_obj;
		break;
	}
	case IOMMUFD_OBJ_IOAS: {
		struct iommufd_ioas *ioas =
			container_of(pt_obj, struct iommufd_ioas, obj);

		destroy_hwpt = iommufd_device_auto_get_domain(idev, pasid, ioas,
							      pt_id, do_attach);
		if (IS_ERR(destroy_hwpt))
			goto out_put_pt_obj;
		break;
	}
	default:
		destroy_hwpt = ERR_PTR(-EINVAL);
		goto out_put_pt_obj;
	}
	iommufd_put_object(idev->ictx, pt_obj);

	/* This destruction has to be after we unlock everything */
	if (destroy_hwpt)
		iommufd_hw_pagetable_put(idev->ictx, destroy_hwpt);
	return 0;

out_put_pt_obj:
	iommufd_put_object(idev->ictx, pt_obj);
	return PTR_ERR(destroy_hwpt);
}

/**
 * iommufd_device_attach - Connect a device/pasid to an iommu_domain
 * @idev: device to attach
 * @pasid: pasid to attach
 * @pt_id: Input an IOMMUFD_OBJ_IOAS, or IOMMUFD_OBJ_HWPT_PAGING
 *         Output the IOMMUFD_OBJ_HWPT_PAGING ID
 *
 * This connects the device/pasid to an iommu_domain, either automatically
 * or manually selected. Once this completes the device could do DMA with
 * @pasid. @pasid is IOMMU_NO_PASID if this attach is for no pasid usage.
 *
 * The caller should return the resulting pt_id back to userspace.
 * This function is undone by calling iommufd_device_detach().
 */
int iommufd_device_attach(struct iommufd_device *idev, ioasid_t pasid,
			  u32 *pt_id)
{
	int rc;

	rc = iommufd_device_change_pt(idev, pasid, pt_id,
				      &iommufd_device_do_attach);
	if (rc)
		return rc;

	/*
	 * Pairs with iommufd_device_detach() - catches caller bugs attempting
	 * to destroy a device with an attachment.
	 */
	refcount_inc(&idev->obj.users);
	return 0;
}
EXPORT_SYMBOL_NS_GPL(iommufd_device_attach, "IOMMUFD");

/**
 * iommufd_device_replace - Change the device/pasid's iommu_domain
 * @idev: device to change
 * @pasid: pasid to change
 * @pt_id: Input an IOMMUFD_OBJ_IOAS, or IOMMUFD_OBJ_HWPT_PAGING
 *         Output the IOMMUFD_OBJ_HWPT_PAGING ID
 *
 * This is the same as::
 *
 *   iommufd_device_detach();
 *   iommufd_device_attach();
 *
 * If it fails then no change is made to the attachment. The iommu driver may
 * implement this so there is no disruption in translation. This can only be
 * called if iommufd_device_attach() has already succeeded. @pasid is
 * IOMMU_NO_PASID for no pasid usage.
 */
int iommufd_device_replace(struct iommufd_device *idev, ioasid_t pasid,
			   u32 *pt_id)
{
	return iommufd_device_change_pt(idev, pasid, pt_id,
					&iommufd_device_do_replace);
}
EXPORT_SYMBOL_NS_GPL(iommufd_device_replace, "IOMMUFD");

/**
 * iommufd_device_detach - Disconnect a device/pasid from an iommu_domain
 * @idev: device to detach
 * @pasid: pasid to detach
 *
 * Undo iommufd_device_attach(). This disconnects the idev from the previously
 * attached pt_id. The device returns back to a blocked DMA translation.
 * @pasid is IOMMU_NO_PASID for no pasid usage.
 */
void iommufd_device_detach(struct iommufd_device *idev, ioasid_t pasid)
{
	struct iommufd_hw_pagetable *hwpt;

	hwpt = iommufd_hw_pagetable_detach(idev, pasid);
	if (!hwpt)
		return;
	refcount_dec(&idev->obj.users);
}
EXPORT_SYMBOL_NS_GPL(iommufd_device_detach, "IOMMUFD");

/*
 * On success, it will refcount_inc() at a valid new_ioas and refcount_dec() at
 * a valid cur_ioas (access->ioas). A caller passing in a valid new_ioas should
 * call iommufd_put_object() if it does an iommufd_get_object() for a new_ioas.
 */
static int iommufd_access_change_ioas(struct iommufd_access *access,
				      struct iommufd_ioas *new_ioas)
{
	u32 iopt_access_list_id = access->iopt_access_list_id;
	struct iommufd_ioas *cur_ioas = access->ioas;
	int rc;

	lockdep_assert_held(&access->ioas_lock);

	/* We are racing with a concurrent detach, bail */
	if (cur_ioas != access->ioas_unpin)
		return -EBUSY;

	if (cur_ioas == new_ioas)
		return 0;

	/*
	 * Set ioas to NULL to block any further iommufd_access_pin_pages().
	 * iommufd_access_unpin_pages() can continue using access->ioas_unpin.
	 */
	access->ioas = NULL;

	if (new_ioas) {
		rc = iopt_add_access(&new_ioas->iopt, access);
		if (rc) {
			access->ioas = cur_ioas;
			return rc;
		}
		refcount_inc(&new_ioas->obj.users);
	}

	if (cur_ioas) {
		if (!iommufd_access_is_internal(access) && access->ops->unmap) {
			mutex_unlock(&access->ioas_lock);
			access->ops->unmap(access->data, 0, ULONG_MAX);
			mutex_lock(&access->ioas_lock);
		}
		iopt_remove_access(&cur_ioas->iopt, access, iopt_access_list_id);
		refcount_dec(&cur_ioas->obj.users);
	}

	access->ioas = new_ioas;
	access->ioas_unpin = new_ioas;

	return 0;
}

static int iommufd_access_change_ioas_id(struct iommufd_access *access, u32 id)
{
	struct iommufd_ioas *ioas = iommufd_get_ioas(access->ictx, id);
	int rc;

	if (IS_ERR(ioas))
		return PTR_ERR(ioas);
	rc = iommufd_access_change_ioas(access, ioas);
	iommufd_put_object(access->ictx, &ioas->obj);
	return rc;
}

void iommufd_access_destroy_object(struct iommufd_object *obj)
{
	struct iommufd_access *access =
		container_of(obj, struct iommufd_access, obj);

	mutex_lock(&access->ioas_lock);
	if (access->ioas)
		WARN_ON(iommufd_access_change_ioas(access, NULL));
	mutex_unlock(&access->ioas_lock);
	if (!iommufd_access_is_internal(access))
		iommufd_ctx_put(access->ictx);
}

static struct iommufd_access *__iommufd_access_create(struct iommufd_ctx *ictx)
{
	struct iommufd_access *access;

	/*
	 * There is no uAPI for the access object, but to keep things symmetric
	 * use the object infrastructure anyhow.
	 */
	access = iommufd_object_alloc(ictx, access, IOMMUFD_OBJ_ACCESS);
	if (IS_ERR(access))
		return access;

	/* The calling driver is a user until iommufd_access_destroy() */
	refcount_inc(&access->obj.users);
	mutex_init(&access->ioas_lock);
	return access;
}

struct iommufd_access *iommufd_access_create_internal(struct iommufd_ctx *ictx)
{
	struct iommufd_access *access;

	access = __iommufd_access_create(ictx);
	if (IS_ERR(access))
		return access;
	access->iova_alignment = PAGE_SIZE;

	iommufd_object_finalize(ictx, &access->obj);
	return access;
}

/**
 * iommufd_access_create - Create an iommufd_access
 * @ictx: iommufd file descriptor
 * @ops: Driver's ops to associate with the access
 * @data: Opaque data to pass into ops functions
 * @id: Output ID number to return to userspace for this access
 *
 * An iommufd_access allows a driver to read/write to the IOAS without using
 * DMA. The underlying CPU memory can be accessed using the
 * iommufd_access_pin_pages() or iommufd_access_rw() functions.
 *
 * The provided ops are required to use iommufd_access_pin_pages().
 */
struct iommufd_access *
iommufd_access_create(struct iommufd_ctx *ictx,
		      const struct iommufd_access_ops *ops, void *data, u32 *id)
{
	struct iommufd_access *access;

	access = __iommufd_access_create(ictx);
	if (IS_ERR(access))
		return access;

	access->data = data;
	access->ops = ops;

	if (ops->needs_pin_pages)
		access->iova_alignment = PAGE_SIZE;
	else
		access->iova_alignment = 1;

	access->ictx = ictx;
	iommufd_ctx_get(ictx);
	iommufd_object_finalize(ictx, &access->obj);
	*id = access->obj.id;
	return access;
}
EXPORT_SYMBOL_NS_GPL(iommufd_access_create, "IOMMUFD");

/**
 * iommufd_access_destroy - Destroy an iommufd_access
 * @access: The access to destroy
 *
 * The caller must stop using the access before destroying it.
 */
void iommufd_access_destroy(struct iommufd_access *access)
{
	iommufd_object_destroy_user(access->ictx, &access->obj);
}
EXPORT_SYMBOL_NS_GPL(iommufd_access_destroy, "IOMMUFD");

void iommufd_access_detach(struct iommufd_access *access)
{
	mutex_lock(&access->ioas_lock);
	if (WARN_ON(!access->ioas)) {
		mutex_unlock(&access->ioas_lock);
		return;
	}
	WARN_ON(iommufd_access_change_ioas(access, NULL));
	mutex_unlock(&access->ioas_lock);
}
EXPORT_SYMBOL_NS_GPL(iommufd_access_detach, "IOMMUFD");

int iommufd_access_attach(struct iommufd_access *access, u32 ioas_id)
{
	int rc;

	mutex_lock(&access->ioas_lock);
	if (WARN_ON(access->ioas)) {
		mutex_unlock(&access->ioas_lock);
		return -EINVAL;
	}

	rc = iommufd_access_change_ioas_id(access, ioas_id);
	mutex_unlock(&access->ioas_lock);
	return rc;
}
EXPORT_SYMBOL_NS_GPL(iommufd_access_attach, "IOMMUFD");

int iommufd_access_attach_internal(struct iommufd_access *access,
				   struct iommufd_ioas *ioas)
{
	int rc;

	mutex_lock(&access->ioas_lock);
	if (WARN_ON(access->ioas)) {
		mutex_unlock(&access->ioas_lock);
		return -EINVAL;
	}

	rc = iommufd_access_change_ioas(access, ioas);
	mutex_unlock(&access->ioas_lock);
	return rc;
}

int iommufd_access_replace(struct iommufd_access *access, u32 ioas_id)
{
	int rc;

	mutex_lock(&access->ioas_lock);
	if (!access->ioas) {
		mutex_unlock(&access->ioas_lock);
		return -ENOENT;
	}
	rc = iommufd_access_change_ioas_id(access, ioas_id);
	mutex_unlock(&access->ioas_lock);
	return rc;
}
EXPORT_SYMBOL_NS_GPL(iommufd_access_replace, "IOMMUFD");

/**
 * iommufd_access_notify_unmap - Notify users of an iopt to stop using it
 * @iopt: iopt to work on
 * @iova: Starting iova in the iopt
 * @length: Number of bytes
 *
 * After this function returns there should be no users attached to the pages
 * linked to this iopt that intersect with iova,length. Anyone that has attached
 * a user through iopt_access_pages() needs to detach it through
 * iommufd_access_unpin_pages() before this function returns.
 *
 * iommufd_access_destroy() will wait for any outstanding unmap callback to
 * complete. Once iommufd_access_destroy() no unmap ops are running or will
 * run in the future. Due to this a driver must not create locking that prevents
 * unmap to complete while iommufd_access_destroy() is running.
 */
void iommufd_access_notify_unmap(struct io_pagetable *iopt, unsigned long iova,
				 unsigned long length)
{
	struct iommufd_ioas *ioas =
		container_of(iopt, struct iommufd_ioas, iopt);
	struct iommufd_access *access;
	unsigned long index;

	xa_lock(&ioas->iopt.access_list);
	xa_for_each(&ioas->iopt.access_list, index, access) {
		if (iommufd_access_is_internal(access) ||
		    !iommufd_lock_obj(&access->obj))
			continue;
		xa_unlock(&ioas->iopt.access_list);

		access->ops->unmap(access->data, iova, length);

		iommufd_put_object(access->ictx, &access->obj);
		xa_lock(&ioas->iopt.access_list);
	}
	xa_unlock(&ioas->iopt.access_list);
}

/**
 * iommufd_access_unpin_pages() - Undo iommufd_access_pin_pages
 * @access: IOAS access to act on
 * @iova: Starting IOVA
 * @length: Number of bytes to access
 *
 * Return the struct page's. The caller must stop accessing them before calling
 * this. The iova/length must exactly match the one provided to access_pages.
 */
void iommufd_access_unpin_pages(struct iommufd_access *access,
				unsigned long iova, unsigned long length)
{
	bool internal = iommufd_access_is_internal(access);
	struct iopt_area_contig_iter iter;
	struct io_pagetable *iopt;
	unsigned long last_iova;
	struct iopt_area *area;

	if (WARN_ON(!length) ||
	    WARN_ON(check_add_overflow(iova, length - 1, &last_iova)))
		return;

	mutex_lock(&access->ioas_lock);
	/*
	 * The driver must be doing something wrong if it calls this before an
	 * iommufd_access_attach() or after an iommufd_access_detach().
	 */
	if (WARN_ON(!access->ioas_unpin)) {
		mutex_unlock(&access->ioas_lock);
		return;
	}
	iopt = &access->ioas_unpin->iopt;

	down_read(&iopt->iova_rwsem);
	iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova)
		iopt_area_remove_access(
			area, iopt_area_iova_to_index(area, iter.cur_iova),
			iopt_area_iova_to_index(
				area,
				min(last_iova, iopt_area_last_iova(area))),
			internal);
	WARN_ON(!iopt_area_contig_done(&iter));
	up_read(&iopt->iova_rwsem);
	mutex_unlock(&access->ioas_lock);
}
EXPORT_SYMBOL_NS_GPL(iommufd_access_unpin_pages, "IOMMUFD");

static bool iopt_area_contig_is_aligned(struct iopt_area_contig_iter *iter)
{
	if (iopt_area_start_byte(iter->area, iter->cur_iova) % PAGE_SIZE)
		return false;

	if (!iopt_area_contig_done(iter) &&
	    (iopt_area_start_byte(iter->area, iopt_area_last_iova(iter->area)) %
	     PAGE_SIZE) != (PAGE_SIZE - 1))
		return false;
	return true;
}

static bool check_area_prot(struct iopt_area *area, unsigned int flags)
{
	if (flags & IOMMUFD_ACCESS_RW_WRITE)
		return area->iommu_prot & IOMMU_WRITE;
	return area->iommu_prot & IOMMU_READ;
}

/**
 * iommufd_access_pin_pages() - Return a list of pages under the iova
 * @access: IOAS access to act on
 * @iova: Starting IOVA
 * @length: Number of bytes to access
 * @out_pages: Output page list
 * @flags: IOPMMUFD_ACCESS_RW_* flags
 *
 * Reads @length bytes starting at iova and returns the struct page * pointers.
 * These can be kmap'd by the caller for CPU access.
 *
 * The caller must perform iommufd_access_unpin_pages() when done to balance
 * this.
 *
 * This API always requires a page aligned iova. This happens naturally if the
 * ioas alignment is >= PAGE_SIZE and the iova is PAGE_SIZE aligned. However
 * smaller alignments have corner cases where this API can fail on otherwise
 * aligned iova.
 */
int iommufd_access_pin_pages(struct iommufd_access *access, unsigned long iova,
			     unsigned long length, struct page **out_pages,
			     unsigned int flags)
{
	bool internal = iommufd_access_is_internal(access);
	struct iopt_area_contig_iter iter;
	struct io_pagetable *iopt;
	unsigned long last_iova;
	struct iopt_area *area;
	int rc;

	/* Driver's ops don't support pin_pages */
	if (IS_ENABLED(CONFIG_IOMMUFD_TEST) &&
	    WARN_ON(access->iova_alignment != PAGE_SIZE ||
		    (!internal && !access->ops->unmap)))
		return -EINVAL;

	if (!length)
		return -EINVAL;
	if (check_add_overflow(iova, length - 1, &last_iova))
		return -EOVERFLOW;

	mutex_lock(&access->ioas_lock);
	if (!access->ioas) {
		mutex_unlock(&access->ioas_lock);
		return -ENOENT;
	}
	iopt = &access->ioas->iopt;

	down_read(&iopt->iova_rwsem);
	iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova) {
		unsigned long last = min(last_iova, iopt_area_last_iova(area));
		unsigned long last_index = iopt_area_iova_to_index(area, last);
		unsigned long index =
			iopt_area_iova_to_index(area, iter.cur_iova);

		if (area->prevent_access ||
		    !iopt_area_contig_is_aligned(&iter)) {
			rc = -EINVAL;
			goto err_remove;
		}

		if (!check_area_prot(area, flags)) {
			rc = -EPERM;
			goto err_remove;
		}

		rc = iopt_area_add_access(area, index, last_index, out_pages,
					  flags, internal);
		if (rc)
			goto err_remove;
		out_pages += last_index - index + 1;
	}
	if (!iopt_area_contig_done(&iter)) {
		rc = -ENOENT;
		goto err_remove;
	}

	up_read(&iopt->iova_rwsem);
	mutex_unlock(&access->ioas_lock);
	return 0;

err_remove:
	if (iova < iter.cur_iova) {
		last_iova = iter.cur_iova - 1;
		iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova)
			iopt_area_remove_access(
				area,
				iopt_area_iova_to_index(area, iter.cur_iova),
				iopt_area_iova_to_index(
					area, min(last_iova,
						  iopt_area_last_iova(area))),
				internal);
	}
	up_read(&iopt->iova_rwsem);
	mutex_unlock(&access->ioas_lock);
	return rc;
}
EXPORT_SYMBOL_NS_GPL(iommufd_access_pin_pages, "IOMMUFD");

/**
 * iommufd_access_rw - Read or write data under the iova
 * @access: IOAS access to act on
 * @iova: Starting IOVA
 * @data: Kernel buffer to copy to/from
 * @length: Number of bytes to access
 * @flags: IOMMUFD_ACCESS_RW_* flags
 *
 * Copy kernel to/from data into the range given by IOVA/length. If flags
 * indicates IOMMUFD_ACCESS_RW_KTHREAD then a large copy can be optimized
 * by changing it into copy_to/from_user().
 */
int iommufd_access_rw(struct iommufd_access *access, unsigned long iova,
		      void *data, size_t length, unsigned int flags)
{
	struct iopt_area_contig_iter iter;
	struct io_pagetable *iopt;
	struct iopt_area *area;
	unsigned long last_iova;
	int rc = -EINVAL;

	if (!length)
		return -EINVAL;
	if (check_add_overflow(iova, length - 1, &last_iova))
		return -EOVERFLOW;

	mutex_lock(&access->ioas_lock);
	if (!access->ioas) {
		mutex_unlock(&access->ioas_lock);
		return -ENOENT;
	}
	iopt = &access->ioas->iopt;

	down_read(&iopt->iova_rwsem);
	iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova) {
		unsigned long last = min(last_iova, iopt_area_last_iova(area));
		unsigned long bytes = (last - iter.cur_iova) + 1;

		if (area->prevent_access) {
			rc = -EINVAL;
			goto err_out;
		}

		if (!check_area_prot(area, flags)) {
			rc = -EPERM;
			goto err_out;
		}

		rc = iopt_pages_rw_access(
			area->pages, iopt_area_start_byte(area, iter.cur_iova),
			data, bytes, flags);
		if (rc)
			goto err_out;
		data += bytes;
	}
	if (!iopt_area_contig_done(&iter))
		rc = -ENOENT;
err_out:
	up_read(&iopt->iova_rwsem);
	mutex_unlock(&access->ioas_lock);
	return rc;
}
EXPORT_SYMBOL_NS_GPL(iommufd_access_rw, "IOMMUFD");

int iommufd_get_hw_info(struct iommufd_ucmd *ucmd)
{
	const u32 SUPPORTED_FLAGS = IOMMU_HW_INFO_FLAG_INPUT_TYPE;
	struct iommu_hw_info *cmd = ucmd->cmd;
	void __user *user_ptr = u64_to_user_ptr(cmd->data_uptr);
	const struct iommu_ops *ops;
	struct iommufd_device *idev;
	unsigned int data_len;
	unsigned int copy_len;
	void *data;
	int rc;

	if (cmd->flags & ~SUPPORTED_FLAGS)
		return -EOPNOTSUPP;
	if (cmd->__reserved[0] || cmd->__reserved[1] || cmd->__reserved[2])
		return -EOPNOTSUPP;

	/* Clear the type field since drivers don't support a random input */
	if (!(cmd->flags & IOMMU_HW_INFO_FLAG_INPUT_TYPE))
		cmd->in_data_type = IOMMU_HW_INFO_TYPE_DEFAULT;

	idev = iommufd_get_device(ucmd, cmd->dev_id);
	if (IS_ERR(idev))
		return PTR_ERR(idev);

	if (iommufd_device_is_noiommu(idev)) {
		rc = -EOPNOTSUPP;
		goto out_put;
	}

	ops = dev_iommu_ops(idev->dev);
	if (ops->hw_info) {
		data = ops->hw_info(idev->dev, &data_len, &cmd->out_data_type);
		if (IS_ERR(data)) {
			rc = PTR_ERR(data);
			goto out_put;
		}

		/*
		 * drivers that have hw_info callback should have a unique
		 * iommu_hw_info_type.
		 */
		if (WARN_ON_ONCE(cmd->out_data_type ==
				 IOMMU_HW_INFO_TYPE_NONE)) {
			rc = -EOPNOTSUPP;
			goto out_free;
		}
	} else {
		cmd->out_data_type = IOMMU_HW_INFO_TYPE_NONE;
		data_len = 0;
		data = NULL;
	}

	copy_len = min(cmd->data_len, data_len);
	if (copy_to_user(user_ptr, data, copy_len)) {
		rc = -EFAULT;
		goto out_free;
	}

	/*
	 * Zero the trailing bytes if the user buffer is bigger than the
	 * data size kernel actually has.
	 */
	if (copy_len < cmd->data_len) {
		if (clear_user(user_ptr + copy_len, cmd->data_len - copy_len)) {
			rc = -EFAULT;
			goto out_free;
		}
	}

	/*
	 * We return the length the kernel supports so userspace may know what
	 * the kernel capability is. It could be larger than the input buffer.
	 */
	cmd->data_len = data_len;

	cmd->out_capabilities = 0;
	if (device_iommu_capable(idev->dev, IOMMU_CAP_DIRTY_TRACKING))
		cmd->out_capabilities |= IOMMU_HW_CAP_DIRTY_TRACKING;

	/* Report when ATS cannot be used for this device */
	if (!device_iommu_capable(idev->dev, IOMMU_CAP_PCI_ATS_SUPPORTED))
		cmd->out_capabilities |= IOMMU_HW_CAP_PCI_ATS_NOT_SUPPORTED;

	cmd->out_max_pasid_log2 = 0;
	/*
	 * Currently, all iommu drivers enable PASID in the probe_device()
	 * op if iommu and device supports it. So the max_pasids stored in
	 * dev->iommu indicates both PASID support and enable status. A
	 * non-zero dev->iommu->max_pasids means PASID is supported and
	 * enabled. The iommufd only reports PASID capability to userspace
	 * if it's enabled.
	 */
	if (idev->dev->iommu->max_pasids) {
		cmd->out_max_pasid_log2 = ilog2(idev->dev->iommu->max_pasids);

		if (dev_is_pci(idev->dev)) {
			struct pci_dev *pdev = to_pci_dev(idev->dev);
			int ctrl;

			ctrl = pci_pasid_status(pdev);

			WARN_ON_ONCE(ctrl < 0 ||
				     !(ctrl & PCI_PASID_CTRL_ENABLE));

			if (ctrl & PCI_PASID_CTRL_EXEC)
				cmd->out_capabilities |=
						IOMMU_HW_CAP_PCI_PASID_EXEC;
			if (ctrl & PCI_PASID_CTRL_PRIV)
				cmd->out_capabilities |=
						IOMMU_HW_CAP_PCI_PASID_PRIV;
		}
	}

	rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
out_free:
	kfree(data);
out_put:
	iommufd_put_object(ucmd->ictx, &idev->obj);
	return rc;
}