summaryrefslogtreecommitdiff
path: root/usr/src/uts/common/io/ib/adapters/hermon/hermon_mr.c
blob: 709403564c7f2342e40ec8056180c4abbf8802f9 (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
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
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * hermon_mr.c
 *    Hermon Memory Region/Window Routines
 *
 *    Implements all the routines necessary to provide the requisite memory
 *    registration verbs.  These include operations like RegisterMemRegion(),
 *    DeregisterMemRegion(), ReregisterMemRegion, RegisterSharedMemRegion,
 *    etc., that affect Memory Regions.  It also includes the verbs that
 *    affect Memory Windows, including AllocMemWindow(), FreeMemWindow(),
 *    and QueryMemWindow().
 */

#include <sys/types.h>
#include <sys/conf.h>
#include <sys/ddi.h>
#include <sys/sunddi.h>
#include <sys/modctl.h>
#include <sys/esunddi.h>

#include <sys/ib/adapters/hermon/hermon.h>

extern uint32_t hermon_kernel_data_ro;
extern uint32_t hermon_user_data_ro;
extern int hermon_rdma_debug;

/*
 * Used by hermon_mr_keycalc() below to fill in the "unconstrained" portion
 * of Hermon memory keys (LKeys and RKeys)
 */
static	uint_t hermon_memkey_cnt = 0x00;
#define	HERMON_MEMKEY_SHIFT	24

/* initial state of an MPT */
#define	HERMON_MPT_SW_OWNERSHIP	0xF	/* memory regions */
#define	HERMON_MPT_FREE		0x3	/* allocate lkey */

static int hermon_mr_common_reg(hermon_state_t *state, hermon_pdhdl_t pd,
    hermon_bind_info_t *bind, hermon_mrhdl_t *mrhdl, hermon_mr_options_t *op,
    hermon_mpt_rsrc_type_t mpt_type);
static int hermon_mr_common_rereg(hermon_state_t *state, hermon_mrhdl_t mr,
    hermon_pdhdl_t pd, hermon_bind_info_t *bind, hermon_mrhdl_t *mrhdl_new,
    hermon_mr_options_t *op);
static int hermon_mr_rereg_xlat_helper(hermon_state_t *state, hermon_mrhdl_t mr,
    hermon_bind_info_t *bind, hermon_mr_options_t *op, uint64_t *mtt_addr,
    uint_t sleep, uint_t *dereg_level);
static uint64_t hermon_mr_nummtt_needed(hermon_state_t *state,
    hermon_bind_info_t *bind, uint_t *mtt_pgsize);
static int hermon_mr_mem_bind(hermon_state_t *state, hermon_bind_info_t *bind,
    ddi_dma_handle_t dmahdl, uint_t sleep, uint_t is_buffer);
static void hermon_mr_mem_unbind(hermon_state_t *state,
    hermon_bind_info_t *bind);
static int hermon_mr_fast_mtt_write(hermon_state_t *state, hermon_rsrc_t *mtt,
    hermon_bind_info_t *bind, uint32_t mtt_pgsize_bits);
static int hermon_mr_fast_mtt_write_fmr(hermon_state_t *state,
    hermon_rsrc_t *mtt, ibt_pmr_attr_t *mem_pattr, uint32_t mtt_pgsize_bits);
static uint_t hermon_mtt_refcnt_inc(hermon_rsrc_t *rsrc);
static uint_t hermon_mtt_refcnt_dec(hermon_rsrc_t *rsrc);


/*
 * The Hermon umem_lockmemory() callback ops.  When userland memory is
 * registered, these callback ops are specified.  The hermon_umap_umemlock_cb()
 * callback will be called whenever the memory for the corresponding
 * ddi_umem_cookie_t is being freed.
 */
static struct umem_callback_ops hermon_umem_cbops = {
	UMEM_CALLBACK_VERSION,
	hermon_umap_umemlock_cb,
};



/*
 * hermon_mr_register()
 *    Context: Can be called from interrupt or base context.
 */
int
hermon_mr_register(hermon_state_t *state, hermon_pdhdl_t pd,
    ibt_mr_attr_t *mr_attr, hermon_mrhdl_t *mrhdl, hermon_mr_options_t *op,
    hermon_mpt_rsrc_type_t mpt_type)
{
	hermon_bind_info_t	bind;
	int			status;

	/*
	 * Fill in the "bind" struct.  This struct provides the majority
	 * of the information that will be used to distinguish between an
	 * "addr" binding (as is the case here) and a "buf" binding (see
	 * below).  The "bind" struct is later passed to hermon_mr_mem_bind()
	 * which does most of the "heavy lifting" for the Hermon memory
	 * registration routines.
	 */
	bind.bi_type  = HERMON_BINDHDL_VADDR;
	bind.bi_addr  = mr_attr->mr_vaddr;
	bind.bi_len   = mr_attr->mr_len;
	bind.bi_as    = mr_attr->mr_as;
	bind.bi_flags = mr_attr->mr_flags;
	status = hermon_mr_common_reg(state, pd, &bind, mrhdl, op,
	    mpt_type);
	return (status);
}


/*
 * hermon_mr_register_buf()
 *    Context: Can be called from interrupt or base context.
 */
int
hermon_mr_register_buf(hermon_state_t *state, hermon_pdhdl_t pd,
    ibt_smr_attr_t *mr_attr, struct buf *buf, hermon_mrhdl_t *mrhdl,
    hermon_mr_options_t *op, hermon_mpt_rsrc_type_t mpt_type)
{
	hermon_bind_info_t	bind;
	int			status;

	/*
	 * Fill in the "bind" struct.  This struct provides the majority
	 * of the information that will be used to distinguish between an
	 * "addr" binding (see above) and a "buf" binding (as is the case
	 * here).  The "bind" struct is later passed to hermon_mr_mem_bind()
	 * which does most of the "heavy lifting" for the Hermon memory
	 * registration routines.  Note: We have chosen to provide
	 * "b_un.b_addr" as the IB address (when the IBT_MR_PHYS_IOVA flag is
	 * not set).  It is not critical what value we choose here as it need
	 * only be unique for the given RKey (which will happen by default),
	 * so the choice here is somewhat arbitrary.
	 */
	bind.bi_type  = HERMON_BINDHDL_BUF;
	bind.bi_buf   = buf;
	if (mr_attr->mr_flags & IBT_MR_PHYS_IOVA) {
		bind.bi_addr  = mr_attr->mr_vaddr;
	} else {
		bind.bi_addr  = (uint64_t)(uintptr_t)buf->b_un.b_addr;
	}
	bind.bi_as    = NULL;
	bind.bi_len   = (uint64_t)buf->b_bcount;
	bind.bi_flags = mr_attr->mr_flags;
	status = hermon_mr_common_reg(state, pd, &bind, mrhdl, op, mpt_type);
	return (status);
}


/*
 * hermon_mr_register_shared()
 *    Context: Can be called from interrupt or base context.
 */
int
hermon_mr_register_shared(hermon_state_t *state, hermon_mrhdl_t mrhdl,
    hermon_pdhdl_t pd, ibt_smr_attr_t *mr_attr, hermon_mrhdl_t *mrhdl_new)
{
	hermon_rsrc_t		*mpt, *mtt, *rsrc;
	hermon_umap_db_entry_t	*umapdb;
	hermon_hw_dmpt_t	mpt_entry;
	hermon_mrhdl_t		mr;
	hermon_bind_info_t	*bind;
	ddi_umem_cookie_t	umem_cookie;
	size_t			umem_len;
	caddr_t			umem_addr;
	uint64_t		mtt_addr, pgsize_msk;
	uint_t			sleep, mr_is_umem;
	int			status, umem_flags;

	/*
	 * Check the sleep flag.  Ensure that it is consistent with the
	 * current thread context (i.e. if we are currently in the interrupt
	 * context, then we shouldn't be attempting to sleep).
	 */
	sleep = (mr_attr->mr_flags & IBT_MR_NOSLEEP) ? HERMON_NOSLEEP :
	    HERMON_SLEEP;
	if ((sleep == HERMON_SLEEP) &&
	    (sleep != HERMON_SLEEPFLAG_FOR_CONTEXT())) {
		status = IBT_INVALID_PARAM;
		goto mrshared_fail;
	}

	/* Increment the reference count on the protection domain (PD) */
	hermon_pd_refcnt_inc(pd);

	/*
	 * Allocate an MPT entry.  This will be filled in with all the
	 * necessary parameters to define the shared memory region.
	 * Specifically, it will be made to reference the currently existing
	 * MTT entries and ownership of the MPT will be passed to the hardware
	 * in the last step below.  If we fail here, we must undo the
	 * protection domain reference count.
	 */
	status = hermon_rsrc_alloc(state, HERMON_DMPT, 1, sleep, &mpt);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto mrshared_fail1;
	}

	/*
	 * Allocate the software structure for tracking the shared memory
	 * region (i.e. the Hermon Memory Region handle).  If we fail here, we
	 * must undo the protection domain reference count and the previous
	 * resource allocation.
	 */
	status = hermon_rsrc_alloc(state, HERMON_MRHDL, 1, sleep, &rsrc);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto mrshared_fail2;
	}
	mr = (hermon_mrhdl_t)rsrc->hr_addr;
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mr))

	/*
	 * Setup and validate the memory region access flags.  This means
	 * translating the IBTF's enable flags into the access flags that
	 * will be used in later operations.
	 */
	mr->mr_accflag = 0;
	if (mr_attr->mr_flags & IBT_MR_ENABLE_WINDOW_BIND)
		mr->mr_accflag |= IBT_MR_WINDOW_BIND;
	if (mr_attr->mr_flags & IBT_MR_ENABLE_LOCAL_WRITE)
		mr->mr_accflag |= IBT_MR_LOCAL_WRITE;
	if (mr_attr->mr_flags & IBT_MR_ENABLE_REMOTE_READ)
		mr->mr_accflag |= IBT_MR_REMOTE_READ;
	if (mr_attr->mr_flags & IBT_MR_ENABLE_REMOTE_WRITE)
		mr->mr_accflag |= IBT_MR_REMOTE_WRITE;
	if (mr_attr->mr_flags & IBT_MR_ENABLE_REMOTE_ATOMIC)
		mr->mr_accflag |= IBT_MR_REMOTE_ATOMIC;

	/*
	 * Calculate keys (Lkey, Rkey) from MPT index.  Each key is formed
	 * from a certain number of "constrained" bits (the least significant
	 * bits) and some number of "unconstrained" bits.  The constrained
	 * bits must be set to the index of the entry in the MPT table, but
	 * the unconstrained bits can be set to any value we wish.  Note:
	 * if no remote access is required, then the RKey value is not filled
	 * in.  Otherwise both Rkey and LKey are given the same value.
	 */
	mr->mr_rkey = mr->mr_lkey = hermon_mr_keycalc(mpt->hr_indx);

	/* Grab the MR lock for the current memory region */
	mutex_enter(&mrhdl->mr_lock);

	/*
	 * Check here to see if the memory region has already been partially
	 * deregistered as a result of a hermon_umap_umemlock_cb() callback.
	 * If so, this is an error, return failure.
	 */
	if ((mrhdl->mr_is_umem) && (mrhdl->mr_umemcookie == NULL)) {
		mutex_exit(&mrhdl->mr_lock);
		status = IBT_MR_HDL_INVALID;
		goto mrshared_fail3;
	}

	/*
	 * Determine if the original memory was from userland and, if so, pin
	 * the pages (again) with umem_lockmemory().  This will guarantee a
	 * separate callback for each of this shared region's MR handles.
	 * If this is userland memory, then allocate an entry in the
	 * "userland resources database".  This will later be added to
	 * the database (after all further memory registration operations are
	 * successful).  If we fail here, we must undo all the above setup.
	 */
	mr_is_umem = mrhdl->mr_is_umem;
	if (mr_is_umem) {
		umem_len   = ptob(btopr(mrhdl->mr_bindinfo.bi_len));
		umem_addr  = (caddr_t)((uintptr_t)mrhdl->mr_bindinfo.bi_addr &
		    ~PAGEOFFSET);
		umem_flags = (DDI_UMEMLOCK_WRITE | DDI_UMEMLOCK_READ |
		    DDI_UMEMLOCK_LONGTERM);
		status = umem_lockmemory(umem_addr, umem_len, umem_flags,
		    &umem_cookie, &hermon_umem_cbops, NULL);
		if (status != 0) {
			mutex_exit(&mrhdl->mr_lock);
			status = IBT_INSUFF_RESOURCE;
			goto mrshared_fail3;
		}

		umapdb = hermon_umap_db_alloc(state->hs_instance,
		    (uint64_t)(uintptr_t)umem_cookie, MLNX_UMAP_MRMEM_RSRC,
		    (uint64_t)(uintptr_t)rsrc);
		if (umapdb == NULL) {
			mutex_exit(&mrhdl->mr_lock);
			status = IBT_INSUFF_RESOURCE;
			goto mrshared_fail4;
		}
	}

	/*
	 * Copy the MTT resource pointer (and additional parameters) from
	 * the original Hermon Memory Region handle.  Note: this is normally
	 * where the hermon_mr_mem_bind() routine would be called, but because
	 * we already have bound and filled-in MTT entries it is simply a
	 * matter here of managing the MTT reference count and grabbing the
	 * address of the MTT table entries (for filling in the shared region's
	 * MPT entry).
	 */
	mr->mr_mttrsrcp	  = mrhdl->mr_mttrsrcp;
	mr->mr_logmttpgsz = mrhdl->mr_logmttpgsz;
	mr->mr_bindinfo	  = mrhdl->mr_bindinfo;
	mr->mr_mttrefcntp = mrhdl->mr_mttrefcntp;
	mutex_exit(&mrhdl->mr_lock);
	bind = &mr->mr_bindinfo;
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*bind))
	mtt = mr->mr_mttrsrcp;

	/*
	 * Increment the MTT reference count (to reflect the fact that
	 * the MTT is now shared)
	 */
	(void) hermon_mtt_refcnt_inc(mr->mr_mttrefcntp);

	/*
	 * Update the new "bind" virtual address.  Do some extra work here
	 * to ensure proper alignment.  That is, make sure that the page
	 * offset for the beginning of the old range is the same as the
	 * offset for this new mapping
	 */
	pgsize_msk = (((uint64_t)1 << mr->mr_logmttpgsz) - 1);
	bind->bi_addr = ((mr_attr->mr_vaddr & ~pgsize_msk) |
	    (mr->mr_bindinfo.bi_addr & pgsize_msk));

	/*
	 * Fill in the MPT entry.  This is the final step before passing
	 * ownership of the MPT entry to the Hermon hardware.  We use all of
	 * the information collected/calculated above to fill in the
	 * requisite portions of the MPT.
	 */
	bzero(&mpt_entry, sizeof (hermon_hw_dmpt_t));
	mpt_entry.en_bind = (mr->mr_accflag & IBT_MR_WINDOW_BIND)   ? 1 : 0;
	mpt_entry.atomic  = (mr->mr_accflag & IBT_MR_REMOTE_ATOMIC) ? 1 : 0;
	mpt_entry.rw	  = (mr->mr_accflag & IBT_MR_REMOTE_WRITE)  ? 1 : 0;
	mpt_entry.rr	  = (mr->mr_accflag & IBT_MR_REMOTE_READ)   ? 1 : 0;
	mpt_entry.lw	  = (mr->mr_accflag & IBT_MR_LOCAL_WRITE)   ? 1 : 0;
	mpt_entry.lr	  = 1;
	mpt_entry.reg_win = HERMON_MPT_IS_REGION;
	mpt_entry.entity_sz	= mr->mr_logmttpgsz;
	mpt_entry.mem_key	= mr->mr_lkey;
	mpt_entry.pd		= pd->pd_pdnum;
	mpt_entry.start_addr	= bind->bi_addr;
	mpt_entry.reg_win_len	= bind->bi_len;
	mtt_addr = (mtt->hr_indx << HERMON_MTT_SIZE_SHIFT);
	mpt_entry.mtt_addr_h = mtt_addr >> 32;
	mpt_entry.mtt_addr_l = mtt_addr >> 3;

	/*
	 * Write the MPT entry to hardware.  Lastly, we pass ownership of
	 * the entry to the hardware.  Note: in general, this operation
	 * shouldn't fail.  But if it does, we have to undo everything we've
	 * done above before returning error.
	 */
	status = hermon_cmn_ownership_cmd_post(state, SW2HW_MPT, &mpt_entry,
	    sizeof (hermon_hw_dmpt_t), mpt->hr_indx, sleep);
	if (status != HERMON_CMD_SUCCESS) {
		cmn_err(CE_CONT, "Hermon: SW2HW_MPT command failed: %08x\n",
		    status);
		if (status == HERMON_CMD_INVALID_STATUS) {
			hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
		}
		status = ibc_get_ci_failure(0);
		goto mrshared_fail5;
	}

	/*
	 * Fill in the rest of the Hermon Memory Region handle.  Having
	 * successfully transferred ownership of the MPT, we can update the
	 * following fields for use in further operations on the MR.
	 */
	mr->mr_mptrsrcp	  = mpt;
	mr->mr_mttrsrcp	  = mtt;
	mr->mr_mpt_type	  = HERMON_MPT_DMPT;
	mr->mr_pdhdl	  = pd;
	mr->mr_rsrcp	  = rsrc;
	mr->mr_is_umem	  = mr_is_umem;
	mr->mr_is_fmr	  = 0;
	mr->mr_umemcookie = (mr_is_umem != 0) ? umem_cookie : NULL;
	mr->mr_umem_cbfunc = NULL;
	mr->mr_umem_cbarg1 = NULL;
	mr->mr_umem_cbarg2 = NULL;
	mr->mr_lkey	   = hermon_mr_key_swap(mr->mr_lkey);
	mr->mr_rkey	   = hermon_mr_key_swap(mr->mr_rkey);

	/*
	 * If this is userland memory, then we need to insert the previously
	 * allocated entry into the "userland resources database".  This will
	 * allow for later coordination between the hermon_umap_umemlock_cb()
	 * callback and hermon_mr_deregister().
	 */
	if (mr_is_umem) {
		hermon_umap_db_add(umapdb);
	}

	*mrhdl_new = mr;

	return (DDI_SUCCESS);

/*
 * The following is cleanup for all possible failure cases in this routine
 */
mrshared_fail5:
	(void) hermon_mtt_refcnt_dec(mr->mr_mttrefcntp);
	if (mr_is_umem) {
		hermon_umap_db_free(umapdb);
	}
mrshared_fail4:
	if (mr_is_umem) {
		ddi_umem_unlock(umem_cookie);
	}
mrshared_fail3:
	hermon_rsrc_free(state, &rsrc);
mrshared_fail2:
	hermon_rsrc_free(state, &mpt);
mrshared_fail1:
	hermon_pd_refcnt_dec(pd);
mrshared_fail:
	return (status);
}

/*
 * hermon_mr_alloc_fmr()
 *    Context: Can be called from interrupt or base context.
 */
int
hermon_mr_alloc_fmr(hermon_state_t *state, hermon_pdhdl_t pd,
    hermon_fmrhdl_t fmr_pool, hermon_mrhdl_t *mrhdl)
{
	hermon_rsrc_t		*mpt, *mtt, *rsrc;
	hermon_hw_dmpt_t	mpt_entry;
	hermon_mrhdl_t		mr;
	hermon_bind_info_t	bind;
	uint64_t		mtt_addr;
	uint64_t		nummtt;
	uint_t			sleep, mtt_pgsize_bits;
	int			status;
	offset_t		i;
	hermon_icm_table_t	*icm_table;
	hermon_dma_info_t	*dma_info;
	uint32_t		index1, index2, rindx;

	/*
	 * Check the sleep flag.  Ensure that it is consistent with the
	 * current thread context (i.e. if we are currently in the interrupt
	 * context, then we shouldn't be attempting to sleep).
	 */
	sleep = (fmr_pool->fmr_flags & IBT_MR_SLEEP) ? HERMON_SLEEP :
	    HERMON_NOSLEEP;
	if ((sleep == HERMON_SLEEP) &&
	    (sleep != HERMON_SLEEPFLAG_FOR_CONTEXT())) {
		return (IBT_INVALID_PARAM);
	}

	/* Increment the reference count on the protection domain (PD) */
	hermon_pd_refcnt_inc(pd);

	/*
	 * Allocate an MPT entry.  This will be filled in with all the
	 * necessary parameters to define the FMR.  Specifically, it will be
	 * made to reference the currently existing MTT entries and ownership
	 * of the MPT will be passed to the hardware in the last step below.
	 * If we fail here, we must undo the protection domain reference count.
	 */

	status = hermon_rsrc_alloc(state, HERMON_DMPT, 1, sleep, &mpt);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto fmralloc_fail1;
	}

	/*
	 * Allocate the software structure for tracking the fmr memory
	 * region (i.e. the Hermon Memory Region handle).  If we fail here, we
	 * must undo the protection domain reference count and the previous
	 * resource allocation.
	 */
	status = hermon_rsrc_alloc(state, HERMON_MRHDL, 1, sleep, &rsrc);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto fmralloc_fail2;
	}
	mr = (hermon_mrhdl_t)rsrc->hr_addr;
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mr))

	/*
	 * Setup and validate the memory region access flags.  This means
	 * translating the IBTF's enable flags into the access flags that
	 * will be used in later operations.
	 */
	mr->mr_accflag = 0;
	if (fmr_pool->fmr_flags & IBT_MR_ENABLE_LOCAL_WRITE)
		mr->mr_accflag |= IBT_MR_LOCAL_WRITE;
	if (fmr_pool->fmr_flags & IBT_MR_ENABLE_REMOTE_READ)
		mr->mr_accflag |= IBT_MR_REMOTE_READ;
	if (fmr_pool->fmr_flags & IBT_MR_ENABLE_REMOTE_WRITE)
		mr->mr_accflag |= IBT_MR_REMOTE_WRITE;
	if (fmr_pool->fmr_flags & IBT_MR_ENABLE_REMOTE_ATOMIC)
		mr->mr_accflag |= IBT_MR_REMOTE_ATOMIC;

	/*
	 * Calculate keys (Lkey, Rkey) from MPT index.  Each key is formed
	 * from a certain number of "constrained" bits (the least significant
	 * bits) and some number of "unconstrained" bits.  The constrained
	 * bits must be set to the index of the entry in the MPT table, but
	 * the unconstrained bits can be set to any value we wish.  Note:
	 * if no remote access is required, then the RKey value is not filled
	 * in.  Otherwise both Rkey and LKey are given the same value.
	 */
	mr->mr_fmr_key = 1;	/* ready for the next reload */
	mr->mr_rkey = mr->mr_lkey = mpt->hr_indx;

	/*
	 * Determine number of pages spanned.  This routine uses the
	 * information in the "bind" struct to determine the required
	 * number of MTT entries needed (and returns the suggested page size -
	 * as a "power-of-2" - for each MTT entry).
	 */
	/* Assume address will be page aligned later */
	bind.bi_addr = 0;
	/* Calculate size based on given max pages */
	bind.bi_len = fmr_pool->fmr_max_pages << PAGESHIFT;
	nummtt = hermon_mr_nummtt_needed(state, &bind, &mtt_pgsize_bits);

	/*
	 * Allocate the MTT entries.  Use the calculations performed above to
	 * allocate the required number of MTT entries.  If we fail here, we
	 * must not only undo all the previous resource allocation (and PD
	 * reference count), but we must also unbind the memory.
	 */
	status = hermon_rsrc_alloc(state, HERMON_MTT, nummtt, sleep, &mtt);
	if (status != DDI_SUCCESS) {
		IBTF_DPRINTF_L2("FMR", "FATAL: too few MTTs");
		status = IBT_INSUFF_RESOURCE;
		goto fmralloc_fail3;
	}
	mr->mr_logmttpgsz = mtt_pgsize_bits;

	/*
	 * Fill in the MPT entry.  This is the final step before passing
	 * ownership of the MPT entry to the Hermon hardware.  We use all of
	 * the information collected/calculated above to fill in the
	 * requisite portions of the MPT.
	 */
	bzero(&mpt_entry, sizeof (hermon_hw_dmpt_t));
	mpt_entry.en_bind = 0;
	mpt_entry.atomic  = (mr->mr_accflag & IBT_MR_REMOTE_ATOMIC) ? 1 : 0;
	mpt_entry.rw	  = (mr->mr_accflag & IBT_MR_REMOTE_WRITE)  ? 1 : 0;
	mpt_entry.rr	  = (mr->mr_accflag & IBT_MR_REMOTE_READ)   ? 1 : 0;
	mpt_entry.lw	  = (mr->mr_accflag & IBT_MR_LOCAL_WRITE)   ? 1 : 0;
	mpt_entry.lr	  = 1;
	mpt_entry.reg_win = HERMON_MPT_IS_REGION;
	mpt_entry.pd		= pd->pd_pdnum;

	mpt_entry.entity_sz	= mr->mr_logmttpgsz;
	mtt_addr = (mtt->hr_indx << HERMON_MTT_SIZE_SHIFT);
	mpt_entry.fast_reg_en = 1;
	mpt_entry.mtt_size = (uint_t)nummtt;
	mpt_entry.mtt_addr_h = mtt_addr >> 32;
	mpt_entry.mtt_addr_l = mtt_addr >> 3;
	mpt_entry.mem_key = mr->mr_lkey;

	/*
	 * FMR sets these to 0 for now.  Later during actual fmr registration
	 * these values are filled in.
	 */
	mpt_entry.start_addr	= 0;
	mpt_entry.reg_win_len	= 0;

	/*
	 * Write the MPT entry to hardware.  Lastly, we pass ownership of
	 * the entry to the hardware.  Note: in general, this operation
	 * shouldn't fail.  But if it does, we have to undo everything we've
	 * done above before returning error.
	 */
	status = hermon_cmn_ownership_cmd_post(state, SW2HW_MPT, &mpt_entry,
	    sizeof (hermon_hw_dmpt_t), mpt->hr_indx, sleep);
	if (status != HERMON_CMD_SUCCESS) {
		cmn_err(CE_CONT, "Hermon: SW2HW_MPT command failed: %08x\n",
		    status);
		if (status == HERMON_CMD_INVALID_STATUS) {
			hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
		}
		status = ibc_get_ci_failure(0);
		goto fmralloc_fail4;
	}

	/*
	 * Fill in the rest of the Hermon Memory Region handle.  Having
	 * successfully transferred ownership of the MPT, we can update the
	 * following fields for use in further operations on the MR.  Also, set
	 * that this is an FMR region.
	 */
	mr->mr_mptrsrcp	  = mpt;
	mr->mr_mttrsrcp	  = mtt;

	mr->mr_mpt_type   = HERMON_MPT_DMPT;
	mr->mr_pdhdl	  = pd;
	mr->mr_rsrcp	  = rsrc;
	mr->mr_is_fmr	  = 1;
	mr->mr_lkey	   = hermon_mr_key_swap(mr->mr_lkey);
	mr->mr_rkey	   = hermon_mr_key_swap(mr->mr_rkey);
	mr->mr_mttaddr	   = mtt_addr;
	(void) memcpy(&mr->mr_bindinfo, &bind, sizeof (hermon_bind_info_t));

	/* initialize hr_addr for use during register/deregister/invalidate */
	icm_table = &state->hs_icm[HERMON_DMPT];
	rindx = mpt->hr_indx;
	hermon_index(index1, index2, rindx, icm_table, i);
	dma_info = icm_table->icm_dma[index1] + index2;
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mpt))
	mpt->hr_addr = (void *)((uintptr_t)(dma_info->vaddr + i * mpt->hr_len));

	*mrhdl = mr;

	return (DDI_SUCCESS);

/*
 * The following is cleanup for all possible failure cases in this routine
 */
fmralloc_fail4:
	kmem_free(mtt, sizeof (hermon_rsrc_t) * nummtt);
fmralloc_fail3:
	hermon_rsrc_free(state, &rsrc);
fmralloc_fail2:
	hermon_rsrc_free(state, &mpt);
fmralloc_fail1:
	hermon_pd_refcnt_dec(pd);
fmralloc_fail:
	return (status);
}


/*
 * hermon_mr_register_physical_fmr()
 *    Context: Can be called from interrupt or base context.
 */
/*ARGSUSED*/
int
hermon_mr_register_physical_fmr(hermon_state_t *state,
    ibt_pmr_attr_t *mem_pattr_p, hermon_mrhdl_t mr, ibt_pmr_desc_t *mem_desc_p)
{
	hermon_rsrc_t		*mpt;
	uint64_t		*mpt_table;
	int			status;
	uint32_t		key;

	mutex_enter(&mr->mr_lock);
	mpt = mr->mr_mptrsrcp;
	mpt_table = (uint64_t *)mpt->hr_addr;

	/* Write MPT status to SW bit */
	*(uint8_t *)mpt_table = 0xF0;

	membar_producer();

	/*
	 * Write the mapped addresses into the MTT entries.  FMR needs to do
	 * this a little differently, so we call the fmr specific fast mtt
	 * write here.
	 */
	status = hermon_mr_fast_mtt_write_fmr(state, mr->mr_mttrsrcp,
	    mem_pattr_p, mr->mr_logmttpgsz);
	if (status != DDI_SUCCESS) {
		mutex_exit(&mr->mr_lock);
		status = ibc_get_ci_failure(0);
		goto fmr_reg_fail1;
	}

	/*
	 * Calculate keys (Lkey, Rkey) from MPT index.  Each key is formed
	 * from a certain number of "constrained" bits (the least significant
	 * bits) and some number of "unconstrained" bits.  The constrained
	 * bits must be set to the index of the entry in the MPT table, but
	 * the unconstrained bits can be set to any value we wish.  Note:
	 * if no remote access is required, then the RKey value is not filled
	 * in.  Otherwise both Rkey and LKey are given the same value.
	 */
	key = mpt->hr_indx | (mr->mr_fmr_key++ << HERMON_MEMKEY_SHIFT);
	mr->mr_lkey = mr->mr_rkey = hermon_mr_key_swap(key);

	/* write mem key value */
	*(uint32_t *)&mpt_table[1] = htonl(key);

	/* write length value */
	mpt_table[3] = htonll(mem_pattr_p->pmr_len);

	/* write start addr value */
	mpt_table[2] = htonll(mem_pattr_p->pmr_iova);

	/* write lkey value */
	*(uint32_t *)&mpt_table[4] = htonl(key);

	membar_producer();

	/* Write MPT status to HW bit */
	*(uint8_t *)mpt_table = 0x00;

	/* Fill in return parameters */
	mem_desc_p->pmd_lkey = mr->mr_lkey;
	mem_desc_p->pmd_rkey = mr->mr_rkey;
	mem_desc_p->pmd_iova = mem_pattr_p->pmr_iova;
	mem_desc_p->pmd_phys_buf_list_sz = mem_pattr_p->pmr_len;

	/* Fill in MR bindinfo struct for later sync or query operations */
	mr->mr_bindinfo.bi_addr = mem_pattr_p->pmr_iova;
	mr->mr_bindinfo.bi_flags = mem_pattr_p->pmr_flags & IBT_MR_NONCOHERENT;

	mutex_exit(&mr->mr_lock);

	return (DDI_SUCCESS);

fmr_reg_fail1:
	/*
	 * Note, we fail here, and purposely leave the memory ownership in
	 * software.  The memory tables may be corrupt, so we leave the region
	 * unregistered.
	 */
	return (status);
}


/*
 * hermon_mr_deregister()
 *    Context: Can be called from interrupt or base context.
 */
/* ARGSUSED */
int
hermon_mr_deregister(hermon_state_t *state, hermon_mrhdl_t *mrhdl, uint_t level,
    uint_t sleep)
{
	hermon_rsrc_t		*mpt, *mtt, *rsrc, *mtt_refcnt;
	hermon_umap_db_entry_t	*umapdb;
	hermon_pdhdl_t		pd;
	hermon_mrhdl_t		mr;
	hermon_bind_info_t	*bind;
	uint64_t		value;
	int			status;
	uint_t			shared_mtt;

	/*
	 * Check the sleep flag.  Ensure that it is consistent with the
	 * current thread context (i.e. if we are currently in the interrupt
	 * context, then we shouldn't be attempting to sleep).
	 */
	if ((sleep == HERMON_SLEEP) &&
	    (sleep != HERMON_SLEEPFLAG_FOR_CONTEXT())) {
		status = IBT_INVALID_PARAM;
		return (status);
	}

	/*
	 * Pull all the necessary information from the Hermon Memory Region
	 * handle.  This is necessary here because the resource for the
	 * MR handle is going to be freed up as part of the this
	 * deregistration
	 */
	mr	= *mrhdl;
	mutex_enter(&mr->mr_lock);
	mpt	= mr->mr_mptrsrcp;
	mtt	= mr->mr_mttrsrcp;
	mtt_refcnt = mr->mr_mttrefcntp;
	rsrc	= mr->mr_rsrcp;
	pd	= mr->mr_pdhdl;
	bind	= &mr->mr_bindinfo;

	/*
	 * Check here if the memory region is really an FMR.  If so, this is a
	 * bad thing and we shouldn't be here.  Return failure.
	 */
	if (mr->mr_is_fmr) {
		mutex_exit(&mr->mr_lock);
		return (IBT_INVALID_PARAM);
	}

	/*
	 * Check here to see if the memory region has already been partially
	 * deregistered as a result of the hermon_umap_umemlock_cb() callback.
	 * If so, then jump to the end and free the remaining resources.
	 */
	if ((mr->mr_is_umem) && (mr->mr_umemcookie == NULL)) {
		goto mrdereg_finish_cleanup;
	}
	if (hermon_rdma_debug & 0x4)
		IBTF_DPRINTF_L2("mr", "dereg: mr %p  key %x",
		    mr, mr->mr_rkey);

	/*
	 * We must drop the "mr_lock" here to ensure that both SLEEP and
	 * NOSLEEP calls into the firmware work as expected.  Also, if two
	 * threads are attemping to access this MR (via de-register,
	 * re-register, or otherwise), then we allow the firmware to enforce
	 * the checking, that only one deregister is valid.
	 */
	mutex_exit(&mr->mr_lock);

	/*
	 * Reclaim MPT entry from hardware (if necessary).  Since the
	 * hermon_mr_deregister() routine is used in the memory region
	 * reregistration process as well, it is possible that we will
	 * not always wish to reclaim ownership of the MPT.  Check the
	 * "level" arg and, if necessary, attempt to reclaim it.  If
	 * the ownership transfer fails for any reason, we check to see
	 * what command status was returned from the hardware.  The only
	 * "expected" error status is the one that indicates an attempt to
	 * deregister a memory region that has memory windows bound to it
	 */
	if (level >= HERMON_MR_DEREG_ALL) {
		if (mr->mr_mpt_type >= HERMON_MPT_DMPT) {
			status = hermon_cmn_ownership_cmd_post(state, HW2SW_MPT,
			    NULL, 0, mpt->hr_indx, sleep);
			if (status != HERMON_CMD_SUCCESS) {
				if (status == HERMON_CMD_REG_BOUND) {
					return (IBT_MR_IN_USE);
				} else {
					cmn_err(CE_CONT, "Hermon: HW2SW_MPT "
					    "command failed: %08x\n", status);
					if (status ==
					    HERMON_CMD_INVALID_STATUS) {
						hermon_fm_ereport(state,
						    HCA_SYS_ERR,
						    DDI_SERVICE_LOST);
					}
					return (IBT_INVALID_PARAM);
				}
			}
		}
	}

	/*
	 * Re-grab the mr_lock here.  Since further access to the protected
	 * 'mr' structure is needed, and we would have returned previously for
	 * the multiple deregistration case, we can safely grab the lock here.
	 */
	mutex_enter(&mr->mr_lock);

	/*
	 * If the memory had come from userland, then we do a lookup in the
	 * "userland resources database".  On success, we free the entry, call
	 * ddi_umem_unlock(), and continue the cleanup.  On failure (which is
	 * an indication that the umem_lockmemory() callback has called
	 * hermon_mr_deregister()), we call ddi_umem_unlock() and invalidate
	 * the "mr_umemcookie" field in the MR handle (this will be used
	 * later to detect that only partial cleaup still remains to be done
	 * on the MR handle).
	 */
	if (mr->mr_is_umem) {
		status = hermon_umap_db_find(state->hs_instance,
		    (uint64_t)(uintptr_t)mr->mr_umemcookie,
		    MLNX_UMAP_MRMEM_RSRC, &value, HERMON_UMAP_DB_REMOVE,
		    &umapdb);
		if (status == DDI_SUCCESS) {
			hermon_umap_db_free(umapdb);
			ddi_umem_unlock(mr->mr_umemcookie);
		} else {
			ddi_umem_unlock(mr->mr_umemcookie);
			mr->mr_umemcookie = NULL;
		}
	}

	/* mtt_refcnt is NULL in the case of hermon_dma_mr_register() */
	if (mtt_refcnt != NULL) {
		/*
		 * Decrement the MTT reference count.  Since the MTT resource
		 * may be shared between multiple memory regions (as a result
		 * of a "RegisterSharedMR" verb) it is important that we not
		 * free up or unbind resources prematurely.  If it's not shared
		 * (as indicated by the return status), then free the resource.
		 */
		shared_mtt = hermon_mtt_refcnt_dec(mtt_refcnt);
		if (!shared_mtt) {
			hermon_rsrc_free(state, &mtt_refcnt);
		}

		/*
		 * Free up the MTT entries and unbind the memory.  Here,
		 * as above, we attempt to free these resources only if
		 * it is appropriate to do so.
		 * Note, 'bind' is NULL in the alloc_lkey case.
		 */
		if (!shared_mtt) {
			if (level >= HERMON_MR_DEREG_NO_HW2SW_MPT) {
				hermon_mr_mem_unbind(state, bind);
			}
			hermon_rsrc_free(state, &mtt);
		}
	}

	/*
	 * If the MR handle has been invalidated, then drop the
	 * lock and return success.  Note: This only happens because
	 * the umem_lockmemory() callback has been triggered.  The
	 * cleanup here is partial, and further cleanup (in a
	 * subsequent hermon_mr_deregister() call) will be necessary.
	 */
	if ((mr->mr_is_umem) && (mr->mr_umemcookie == NULL)) {
		mutex_exit(&mr->mr_lock);
		return (DDI_SUCCESS);
	}

mrdereg_finish_cleanup:
	mutex_exit(&mr->mr_lock);

	/* Free the Hermon Memory Region handle */
	hermon_rsrc_free(state, &rsrc);

	/* Free up the MPT entry resource */
	if (mpt != NULL)
		hermon_rsrc_free(state, &mpt);

	/* Decrement the reference count on the protection domain (PD) */
	hermon_pd_refcnt_dec(pd);

	/* Set the mrhdl pointer to NULL and return success */
	*mrhdl = NULL;

	return (DDI_SUCCESS);
}

/*
 * hermon_mr_dealloc_fmr()
 *    Context: Can be called from interrupt or base context.
 */
/* ARGSUSED */
int
hermon_mr_dealloc_fmr(hermon_state_t *state, hermon_mrhdl_t *mrhdl)
{
	hermon_rsrc_t		*mpt, *mtt, *rsrc;
	hermon_pdhdl_t		pd;
	hermon_mrhdl_t		mr;

	/*
	 * Pull all the necessary information from the Hermon Memory Region
	 * handle.  This is necessary here because the resource for the
	 * MR handle is going to be freed up as part of the this
	 * deregistration
	 */
	mr	= *mrhdl;
	mutex_enter(&mr->mr_lock);
	mpt	= mr->mr_mptrsrcp;
	mtt	= mr->mr_mttrsrcp;
	rsrc	= mr->mr_rsrcp;
	pd	= mr->mr_pdhdl;
	mutex_exit(&mr->mr_lock);

	/* Free the MTT entries */
	hermon_rsrc_free(state, &mtt);

	/* Free the Hermon Memory Region handle */
	hermon_rsrc_free(state, &rsrc);

	/* Free up the MPT entry resource */
	hermon_rsrc_free(state, &mpt);

	/* Decrement the reference count on the protection domain (PD) */
	hermon_pd_refcnt_dec(pd);

	/* Set the mrhdl pointer to NULL and return success */
	*mrhdl = NULL;

	return (DDI_SUCCESS);
}


/*
 * hermon_mr_query()
 *    Context: Can be called from interrupt or base context.
 */
/* ARGSUSED */
int
hermon_mr_query(hermon_state_t *state, hermon_mrhdl_t mr,
    ibt_mr_query_attr_t *attr)
{
	int			status;
	hermon_hw_dmpt_t	mpt_entry;
	uint32_t		lkey;

	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*attr))

	mutex_enter(&mr->mr_lock);

	/*
	 * Check here to see if the memory region has already been partially
	 * deregistered as a result of a hermon_umap_umemlock_cb() callback.
	 * If so, this is an error, return failure.
	 */
	if ((mr->mr_is_umem) && (mr->mr_umemcookie == NULL)) {
		mutex_exit(&mr->mr_lock);
		return (IBT_MR_HDL_INVALID);
	}

	status = hermon_cmn_query_cmd_post(state, QUERY_MPT, 0,
	    mr->mr_lkey >> 8, &mpt_entry, sizeof (hermon_hw_dmpt_t),
	    HERMON_NOSLEEP);
	if (status != HERMON_CMD_SUCCESS) {
		cmn_err(CE_CONT, "Hermon: QUERY_MPT failed: status %x", status);
		mutex_exit(&mr->mr_lock);
		return (ibc_get_ci_failure(0));
	}

	/* Update the mr sw struct from the hw struct. */
	lkey = mpt_entry.mem_key;
	mr->mr_lkey = mr->mr_rkey = (lkey >> 8) | (lkey << 24);
	mr->mr_bindinfo.bi_addr = mpt_entry.start_addr;
	mr->mr_bindinfo.bi_len = mpt_entry.reg_win_len;
	mr->mr_accflag = (mr->mr_accflag & IBT_MR_RO_DISABLED) |
	    (mpt_entry.lw ? IBT_MR_LOCAL_WRITE : 0) |
	    (mpt_entry.rr ? IBT_MR_REMOTE_READ : 0) |
	    (mpt_entry.rw ? IBT_MR_REMOTE_WRITE : 0) |
	    (mpt_entry.atomic ? IBT_MR_REMOTE_ATOMIC : 0) |
	    (mpt_entry.en_bind ? IBT_MR_WINDOW_BIND : 0);
	mr->mr_mttaddr = ((uint64_t)mpt_entry.mtt_addr_h << 32) |
	    (mpt_entry.mtt_addr_l << 3);
	mr->mr_logmttpgsz = mpt_entry.entity_sz;

	/* Fill in the queried attributes */
	attr->mr_lkey_state =
	    (mpt_entry.status == HERMON_MPT_FREE) ? IBT_KEY_FREE :
	    (mpt_entry.status == HERMON_MPT_SW_OWNERSHIP) ? IBT_KEY_INVALID :
	    IBT_KEY_VALID;
	attr->mr_phys_buf_list_sz = mpt_entry.mtt_size;
	attr->mr_attr_flags = mr->mr_accflag;
	attr->mr_pd = (ibt_pd_hdl_t)mr->mr_pdhdl;

	/* Fill in the "local" attributes */
	attr->mr_lkey = (ibt_lkey_t)mr->mr_lkey;
	attr->mr_lbounds.pb_addr = (ib_vaddr_t)mr->mr_bindinfo.bi_addr;
	attr->mr_lbounds.pb_len  = (size_t)mr->mr_bindinfo.bi_len;

	/*
	 * Fill in the "remote" attributes (if necessary).  Note: the
	 * remote attributes are only valid if the memory region has one
	 * or more of the remote access flags set.
	 */
	if ((mr->mr_accflag & IBT_MR_REMOTE_READ) ||
	    (mr->mr_accflag & IBT_MR_REMOTE_WRITE) ||
	    (mr->mr_accflag & IBT_MR_REMOTE_ATOMIC)) {
		attr->mr_rkey = (ibt_rkey_t)mr->mr_rkey;
		attr->mr_rbounds.pb_addr = (ib_vaddr_t)mr->mr_bindinfo.bi_addr;
		attr->mr_rbounds.pb_len  = (size_t)mr->mr_bindinfo.bi_len;
	}

	/*
	 * If region is mapped for streaming (i.e. noncoherent), then set sync
	 * is required
	 */
	attr->mr_sync_required = (mr->mr_bindinfo.bi_flags &
	    IBT_MR_NONCOHERENT) ? B_TRUE : B_FALSE;

	mutex_exit(&mr->mr_lock);
	return (DDI_SUCCESS);
}


/*
 * hermon_mr_reregister()
 *    Context: Can be called from interrupt or base context.
 */
int
hermon_mr_reregister(hermon_state_t *state, hermon_mrhdl_t mr,
    hermon_pdhdl_t pd, ibt_mr_attr_t *mr_attr, hermon_mrhdl_t *mrhdl_new,
    hermon_mr_options_t *op)
{
	hermon_bind_info_t	bind;
	int			status;

	/*
	 * Fill in the "bind" struct.  This struct provides the majority
	 * of the information that will be used to distinguish between an
	 * "addr" binding (as is the case here) and a "buf" binding (see
	 * below).  The "bind" struct is later passed to hermon_mr_mem_bind()
	 * which does most of the "heavy lifting" for the Hermon memory
	 * registration (and reregistration) routines.
	 */
	bind.bi_type  = HERMON_BINDHDL_VADDR;
	bind.bi_addr  = mr_attr->mr_vaddr;
	bind.bi_len   = mr_attr->mr_len;
	bind.bi_as    = mr_attr->mr_as;
	bind.bi_flags = mr_attr->mr_flags;
	status = hermon_mr_common_rereg(state, mr, pd, &bind, mrhdl_new, op);
	return (status);
}


/*
 * hermon_mr_reregister_buf()
 *    Context: Can be called from interrupt or base context.
 */
int
hermon_mr_reregister_buf(hermon_state_t *state, hermon_mrhdl_t mr,
    hermon_pdhdl_t pd, ibt_smr_attr_t *mr_attr, struct buf *buf,
    hermon_mrhdl_t *mrhdl_new, hermon_mr_options_t *op)
{
	hermon_bind_info_t	bind;
	int			status;

	/*
	 * Fill in the "bind" struct.  This struct provides the majority
	 * of the information that will be used to distinguish between an
	 * "addr" binding (see above) and a "buf" binding (as is the case
	 * here).  The "bind" struct is later passed to hermon_mr_mem_bind()
	 * which does most of the "heavy lifting" for the Hermon memory
	 * registration routines.  Note: We have chosen to provide
	 * "b_un.b_addr" as the IB address (when the IBT_MR_PHYS_IOVA flag is
	 * not set).  It is not critical what value we choose here as it need
	 * only be unique for the given RKey (which will happen by default),
	 * so the choice here is somewhat arbitrary.
	 */
	bind.bi_type  = HERMON_BINDHDL_BUF;
	bind.bi_buf   = buf;
	if (mr_attr->mr_flags & IBT_MR_PHYS_IOVA) {
		bind.bi_addr  = mr_attr->mr_vaddr;
	} else {
		bind.bi_addr  = (uint64_t)(uintptr_t)buf->b_un.b_addr;
	}
	bind.bi_len   = (uint64_t)buf->b_bcount;
	bind.bi_flags = mr_attr->mr_flags;
	bind.bi_as    = NULL;
	status = hermon_mr_common_rereg(state, mr, pd, &bind, mrhdl_new, op);
	return (status);
}


/*
 * hermon_mr_sync()
 *    Context: Can be called from interrupt or base context.
 */
/* ARGSUSED */
int
hermon_mr_sync(hermon_state_t *state, ibt_mr_sync_t *mr_segs, size_t num_segs)
{
	hermon_mrhdl_t		mrhdl;
	uint64_t		seg_vaddr, seg_len, seg_end;
	uint64_t		mr_start, mr_end;
	uint_t			type;
	int			status, i;

	/* Process each of the ibt_mr_sync_t's */
	for (i = 0; i < num_segs; i++) {
		mrhdl = (hermon_mrhdl_t)mr_segs[i].ms_handle;

		/* Check for valid memory region handle */
		if (mrhdl == NULL) {
			status = IBT_MR_HDL_INVALID;
			goto mrsync_fail;
		}

		mutex_enter(&mrhdl->mr_lock);

		/*
		 * Check here to see if the memory region has already been
		 * partially deregistered as a result of a
		 * hermon_umap_umemlock_cb() callback.  If so, this is an
		 * error, return failure.
		 */
		if ((mrhdl->mr_is_umem) && (mrhdl->mr_umemcookie == NULL)) {
			mutex_exit(&mrhdl->mr_lock);
			status = IBT_MR_HDL_INVALID;
			goto mrsync_fail;
		}

		/* Check for valid bounds on sync request */
		seg_vaddr = mr_segs[i].ms_vaddr;
		seg_len	  = mr_segs[i].ms_len;
		seg_end	  = seg_vaddr + seg_len - 1;
		mr_start  = mrhdl->mr_bindinfo.bi_addr;
		mr_end	  = mr_start + mrhdl->mr_bindinfo.bi_len - 1;
		if ((seg_vaddr < mr_start) || (seg_vaddr > mr_end)) {
			mutex_exit(&mrhdl->mr_lock);
			status = IBT_MR_VA_INVALID;
			goto mrsync_fail;
		}
		if ((seg_end < mr_start) || (seg_end > mr_end)) {
			mutex_exit(&mrhdl->mr_lock);
			status = IBT_MR_LEN_INVALID;
			goto mrsync_fail;
		}

		/* Determine what type (i.e. direction) for sync */
		if (mr_segs[i].ms_flags & IBT_SYNC_READ) {
			type = DDI_DMA_SYNC_FORDEV;
		} else if (mr_segs[i].ms_flags & IBT_SYNC_WRITE) {
			type = DDI_DMA_SYNC_FORCPU;
		} else {
			mutex_exit(&mrhdl->mr_lock);
			status = IBT_INVALID_PARAM;
			goto mrsync_fail;
		}

		(void) ddi_dma_sync(mrhdl->mr_bindinfo.bi_dmahdl,
		    (off_t)(seg_vaddr - mr_start), (size_t)seg_len, type);

		mutex_exit(&mrhdl->mr_lock);
	}

	return (DDI_SUCCESS);

mrsync_fail:
	return (status);
}


/*
 * hermon_mw_alloc()
 *    Context: Can be called from interrupt or base context.
 */
int
hermon_mw_alloc(hermon_state_t *state, hermon_pdhdl_t pd, ibt_mw_flags_t flags,
    hermon_mwhdl_t *mwhdl)
{
	hermon_rsrc_t		*mpt, *rsrc;
	hermon_hw_dmpt_t		mpt_entry;
	hermon_mwhdl_t		mw;
	uint_t			sleep;
	int			status;

	if (state != NULL)	/* XXX - bogus test that is always TRUE */
		return (IBT_INSUFF_RESOURCE);

	/*
	 * Check the sleep flag.  Ensure that it is consistent with the
	 * current thread context (i.e. if we are currently in the interrupt
	 * context, then we shouldn't be attempting to sleep).
	 */
	sleep = (flags & IBT_MW_NOSLEEP) ? HERMON_NOSLEEP : HERMON_SLEEP;
	if ((sleep == HERMON_SLEEP) &&
	    (sleep != HERMON_SLEEPFLAG_FOR_CONTEXT())) {
		status = IBT_INVALID_PARAM;
		goto mwalloc_fail;
	}

	/* Increment the reference count on the protection domain (PD) */
	hermon_pd_refcnt_inc(pd);

	/*
	 * Allocate an MPT entry (for use as a memory window).  Since the
	 * Hermon hardware uses the MPT entry for memory regions and for
	 * memory windows, we will fill in this MPT with all the necessary
	 * parameters for the memory window.  And then (just as we do for
	 * memory regions) ownership will be passed to the hardware in the
	 * final step below.  If we fail here, we must undo the protection
	 * domain reference count.
	 */
	status = hermon_rsrc_alloc(state, HERMON_DMPT, 1, sleep, &mpt);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto mwalloc_fail1;
	}

	/*
	 * Allocate the software structure for tracking the memory window (i.e.
	 * the Hermon Memory Window handle).  Note: This is actually the same
	 * software structure used for tracking memory regions, but since many
	 * of the same properties are needed, only a single structure is
	 * necessary.  If we fail here, we must undo the protection domain
	 * reference count and the previous resource allocation.
	 */
	status = hermon_rsrc_alloc(state, HERMON_MRHDL, 1, sleep, &rsrc);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto mwalloc_fail2;
	}
	mw = (hermon_mwhdl_t)rsrc->hr_addr;
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mw))

	/*
	 * Calculate an "unbound" RKey from MPT index.  In much the same way
	 * as we do for memory regions (above), this key is constructed from
	 * a "constrained" (which depends on the MPT index) and an
	 * "unconstrained" portion (which may be arbitrarily chosen).
	 */
	mw->mr_rkey = hermon_mr_keycalc(mpt->hr_indx);

	/*
	 * Fill in the MPT entry.  This is the final step before passing
	 * ownership of the MPT entry to the Hermon hardware.  We use all of
	 * the information collected/calculated above to fill in the
	 * requisite portions of the MPT.  Note: fewer entries in the MPT
	 * entry are necessary to allocate a memory window.
	 */
	bzero(&mpt_entry, sizeof (hermon_hw_dmpt_t));
	mpt_entry.reg_win	= HERMON_MPT_IS_WINDOW;
	mpt_entry.mem_key	= mw->mr_rkey;
	mpt_entry.pd		= pd->pd_pdnum;
	mpt_entry.lr		= 1;

	/*
	 * Write the MPT entry to hardware.  Lastly, we pass ownership of
	 * the entry to the hardware.  Note: in general, this operation
	 * shouldn't fail.  But if it does, we have to undo everything we've
	 * done above before returning error.
	 */
	status = hermon_cmn_ownership_cmd_post(state, SW2HW_MPT, &mpt_entry,
	    sizeof (hermon_hw_dmpt_t), mpt->hr_indx, sleep);
	if (status != HERMON_CMD_SUCCESS) {
		cmn_err(CE_CONT, "Hermon: SW2HW_MPT command failed: %08x\n",
		    status);
		if (status == HERMON_CMD_INVALID_STATUS) {
			hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
		}
		status = ibc_get_ci_failure(0);
		goto mwalloc_fail3;
	}

	/*
	 * Fill in the rest of the Hermon Memory Window handle.  Having
	 * successfully transferred ownership of the MPT, we can update the
	 * following fields for use in further operations on the MW.
	 */
	mw->mr_mptrsrcp	= mpt;
	mw->mr_pdhdl	= pd;
	mw->mr_rsrcp	= rsrc;
	mw->mr_rkey	= hermon_mr_key_swap(mw->mr_rkey);
	*mwhdl = mw;

	return (DDI_SUCCESS);

mwalloc_fail3:
	hermon_rsrc_free(state, &rsrc);
mwalloc_fail2:
	hermon_rsrc_free(state, &mpt);
mwalloc_fail1:
	hermon_pd_refcnt_dec(pd);
mwalloc_fail:
	return (status);
}


/*
 * hermon_mw_free()
 *    Context: Can be called from interrupt or base context.
 */
int
hermon_mw_free(hermon_state_t *state, hermon_mwhdl_t *mwhdl, uint_t sleep)
{
	hermon_rsrc_t		*mpt, *rsrc;
	hermon_mwhdl_t		mw;
	int			status;
	hermon_pdhdl_t		pd;

	/*
	 * Check the sleep flag.  Ensure that it is consistent with the
	 * current thread context (i.e. if we are currently in the interrupt
	 * context, then we shouldn't be attempting to sleep).
	 */
	if ((sleep == HERMON_SLEEP) &&
	    (sleep != HERMON_SLEEPFLAG_FOR_CONTEXT())) {
		status = IBT_INVALID_PARAM;
		return (status);
	}

	/*
	 * Pull all the necessary information from the Hermon Memory Window
	 * handle.  This is necessary here because the resource for the
	 * MW handle is going to be freed up as part of the this operation.
	 */
	mw	= *mwhdl;
	mutex_enter(&mw->mr_lock);
	mpt	= mw->mr_mptrsrcp;
	rsrc	= mw->mr_rsrcp;
	pd	= mw->mr_pdhdl;
	mutex_exit(&mw->mr_lock);
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mw))

	/*
	 * Reclaim the MPT entry from hardware.  Note: in general, it is
	 * unexpected for this operation to return an error.
	 */
	status = hermon_cmn_ownership_cmd_post(state, HW2SW_MPT, NULL,
	    0, mpt->hr_indx, sleep);
	if (status != HERMON_CMD_SUCCESS) {
		cmn_err(CE_CONT, "Hermon: HW2SW_MPT command failed: %08x\n",
		    status);
		if (status == HERMON_CMD_INVALID_STATUS) {
			hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
		}
		return (ibc_get_ci_failure(0));
	}

	/* Free the Hermon Memory Window handle */
	hermon_rsrc_free(state, &rsrc);

	/* Free up the MPT entry resource */
	hermon_rsrc_free(state, &mpt);

	/* Decrement the reference count on the protection domain (PD) */
	hermon_pd_refcnt_dec(pd);

	/* Set the mwhdl pointer to NULL and return success */
	*mwhdl = NULL;

	return (DDI_SUCCESS);
}


/*
 * hermon_mr_keycalc()
 *    Context: Can be called from interrupt or base context.
 *    NOTE:  Produces a key in the form of
 *		KKKKKKKK IIIIIIII IIIIIIII IIIIIIIII
 *    where K == the arbitrary bits and I == the index
 */
uint32_t
hermon_mr_keycalc(uint32_t indx)
{
	uint32_t tmp_key, tmp_indx;

	/*
	 * Generate a simple key from counter.  Note:  We increment this
	 * static variable _intentionally_ without any kind of mutex around
	 * it.  First, single-threading all operations through a single lock
	 * would be a bad idea (from a performance point-of-view).  Second,
	 * the upper "unconstrained" bits don't really have to be unique
	 * because the lower bits are guaranteed to be (although we do make a
	 * best effort to ensure that they are).  Third, the window for the
	 * race (where both threads read and update the counter at the same
	 * time) is incredibly small.
	 * And, lastly, we'd like to make this into a "random" key
	 */
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(hermon_memkey_cnt))
	tmp_key = (hermon_memkey_cnt++) << HERMON_MEMKEY_SHIFT;
	tmp_indx = indx & 0xffffff;
	return (tmp_key | tmp_indx);
}


/*
 * hermon_mr_key_swap()
 *    Context: Can be called from interrupt or base context.
 *    NOTE:  Produces a key in the form of
 *		IIIIIIII IIIIIIII IIIIIIIII KKKKKKKK
 *    where K == the arbitrary bits and I == the index
 */
uint32_t
hermon_mr_key_swap(uint32_t indx)
{
	/*
	 * The memory key format to pass down to the hardware is
	 * (key[7:0],index[23:0]), which defines the index to the
	 * hardware resource. When the driver passes this as a memory
	 * key, (i.e. to retrieve a resource) the format is
	 * (index[23:0],key[7:0]).
	 */
	return (((indx >> 24) & 0x000000ff) | ((indx << 8) & 0xffffff00));
}

/*
 * hermon_mr_common_reg()
 *    Context: Can be called from interrupt or base context.
 */
static int
hermon_mr_common_reg(hermon_state_t *state, hermon_pdhdl_t pd,
    hermon_bind_info_t *bind, hermon_mrhdl_t *mrhdl, hermon_mr_options_t *op,
    hermon_mpt_rsrc_type_t mpt_type)
{
	hermon_rsrc_t		*mpt, *mtt, *rsrc, *mtt_refcnt;
	hermon_umap_db_entry_t	*umapdb;
	hermon_sw_refcnt_t	*swrc_tmp;
	hermon_hw_dmpt_t	mpt_entry;
	hermon_mrhdl_t		mr;
	ibt_mr_flags_t		flags;
	hermon_bind_info_t	*bh;
	ddi_dma_handle_t	bind_dmahdl;
	ddi_umem_cookie_t	umem_cookie;
	size_t			umem_len;
	caddr_t			umem_addr;
	uint64_t		mtt_addr, max_sz;
	uint_t			sleep, mtt_pgsize_bits, bind_type, mr_is_umem;
	int			status, umem_flags, bind_override_addr;

	/*
	 * Check the "options" flag.  Currently this flag tells the driver
	 * whether or not the region should be bound normally (i.e. with
	 * entries written into the PCI IOMMU), whether it should be
	 * registered to bypass the IOMMU, and whether or not the resulting
	 * address should be "zero-based" (to aid the alignment restrictions
	 * for QPs).
	 */
	if (op == NULL) {
		bind_type   = HERMON_BINDMEM_NORMAL;
		bind_dmahdl = NULL;
		bind_override_addr = 0;
	} else {
		bind_type	   = op->mro_bind_type;
		bind_dmahdl	   = op->mro_bind_dmahdl;
		bind_override_addr = op->mro_bind_override_addr;
	}

	/* check what kind of mpt to use */

	/* Extract the flags field from the hermon_bind_info_t */
	flags = bind->bi_flags;

	/*
	 * Check for invalid length.  Check is the length is zero or if the
	 * length is larger than the maximum configured value.  Return error
	 * if it is.
	 */
	max_sz = ((uint64_t)1 << state->hs_cfg_profile->cp_log_max_mrw_sz);
	if ((bind->bi_len == 0) || (bind->bi_len > max_sz)) {
		status = IBT_MR_LEN_INVALID;
		goto mrcommon_fail;
	}

	/*
	 * Check the sleep flag.  Ensure that it is consistent with the
	 * current thread context (i.e. if we are currently in the interrupt
	 * context, then we shouldn't be attempting to sleep).
	 */
	sleep = (flags & IBT_MR_NOSLEEP) ? HERMON_NOSLEEP: HERMON_SLEEP;
	if ((sleep == HERMON_SLEEP) &&
	    (sleep != HERMON_SLEEPFLAG_FOR_CONTEXT())) {
		status = IBT_INVALID_PARAM;
		goto mrcommon_fail;
	}

	/* Increment the reference count on the protection domain (PD) */
	hermon_pd_refcnt_inc(pd);

	/*
	 * Allocate an MPT entry.  This will be filled in with all the
	 * necessary parameters to define the memory region.  And then
	 * ownership will be passed to the hardware in the final step
	 * below.  If we fail here, we must undo the protection domain
	 * reference count.
	 */
	if (mpt_type == HERMON_MPT_DMPT) {
		status = hermon_rsrc_alloc(state, HERMON_DMPT, 1, sleep, &mpt);
		if (status != DDI_SUCCESS) {
			status = IBT_INSUFF_RESOURCE;
			goto mrcommon_fail1;
		}
	} else {
		mpt = NULL;
	}

	/*
	 * Allocate the software structure for tracking the memory region (i.e.
	 * the Hermon Memory Region handle).  If we fail here, we must undo
	 * the protection domain reference count and the previous resource
	 * allocation.
	 */
	status = hermon_rsrc_alloc(state, HERMON_MRHDL, 1, sleep, &rsrc);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto mrcommon_fail2;
	}
	mr = (hermon_mrhdl_t)rsrc->hr_addr;
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mr))

	/*
	 * Setup and validate the memory region access flags.  This means
	 * translating the IBTF's enable flags into the access flags that
	 * will be used in later operations.
	 */
	mr->mr_accflag = 0;
	if (flags & IBT_MR_ENABLE_WINDOW_BIND)
		mr->mr_accflag |= IBT_MR_WINDOW_BIND;
	if (flags & IBT_MR_ENABLE_LOCAL_WRITE)
		mr->mr_accflag |= IBT_MR_LOCAL_WRITE;
	if (flags & IBT_MR_ENABLE_REMOTE_READ)
		mr->mr_accflag |= IBT_MR_REMOTE_READ;
	if (flags & IBT_MR_ENABLE_REMOTE_WRITE)
		mr->mr_accflag |= IBT_MR_REMOTE_WRITE;
	if (flags & IBT_MR_ENABLE_REMOTE_ATOMIC)
		mr->mr_accflag |= IBT_MR_REMOTE_ATOMIC;

	/*
	 * Calculate keys (Lkey, Rkey) from MPT index.  Each key is formed
	 * from a certain number of "constrained" bits (the least significant
	 * bits) and some number of "unconstrained" bits.  The constrained
	 * bits must be set to the index of the entry in the MPT table, but
	 * the unconstrained bits can be set to any value we wish.  Note:
	 * if no remote access is required, then the RKey value is not filled
	 * in.  Otherwise both Rkey and LKey are given the same value.
	 */
	if (mpt)
		mr->mr_rkey = mr->mr_lkey = hermon_mr_keycalc(mpt->hr_indx);

	/*
	 * Determine if the memory is from userland and pin the pages
	 * with umem_lockmemory() if necessary.
	 * Then, if this is userland memory, allocate an entry in the
	 * "userland resources database".  This will later be added to
	 * the database (after all further memory registration operations are
	 * successful).  If we fail here, we must undo the reference counts
	 * and the previous resource allocations.
	 */
	mr_is_umem = (((bind->bi_as != NULL) && (bind->bi_as != &kas)) ? 1 : 0);
	if (mr_is_umem) {
		umem_len   = ptob(btopr(bind->bi_len +
		    ((uintptr_t)bind->bi_addr & PAGEOFFSET)));
		umem_addr  = (caddr_t)((uintptr_t)bind->bi_addr & ~PAGEOFFSET);
		umem_flags = (DDI_UMEMLOCK_WRITE | DDI_UMEMLOCK_READ |
		    DDI_UMEMLOCK_LONGTERM);
		status = umem_lockmemory(umem_addr, umem_len, umem_flags,
		    &umem_cookie, &hermon_umem_cbops, NULL);
		if (status != 0) {
			status = IBT_INSUFF_RESOURCE;
			goto mrcommon_fail3;
		}

		_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*bind))
		_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*bind->bi_buf))

		bind->bi_buf = ddi_umem_iosetup(umem_cookie, 0, umem_len,
		    B_WRITE, 0, 0, NULL, DDI_UMEM_SLEEP);
		if (bind->bi_buf == NULL) {
			status = IBT_INSUFF_RESOURCE;
			goto mrcommon_fail3;
		}
		bind->bi_type = HERMON_BINDHDL_UBUF;
		bind->bi_buf->b_flags |= B_READ;

		_NOTE(NOW_VISIBLE_TO_OTHER_THREADS(*bind->bi_buf))
		_NOTE(NOW_VISIBLE_TO_OTHER_THREADS(*bind))

		umapdb = hermon_umap_db_alloc(state->hs_instance,
		    (uint64_t)(uintptr_t)umem_cookie, MLNX_UMAP_MRMEM_RSRC,
		    (uint64_t)(uintptr_t)rsrc);
		if (umapdb == NULL) {
			status = IBT_INSUFF_RESOURCE;
			goto mrcommon_fail4;
		}
	}

	/*
	 * Setup the bindinfo for the mtt bind call
	 */
	bh = &mr->mr_bindinfo;
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*bh))
	bcopy(bind, bh, sizeof (hermon_bind_info_t));
	bh->bi_bypass = bind_type;
	status = hermon_mr_mtt_bind(state, bh, bind_dmahdl, &mtt,
	    &mtt_pgsize_bits, mpt != NULL);
	if (status != DDI_SUCCESS) {
		/*
		 * When mtt_bind fails, freerbuf has already been done,
		 * so make sure not to call it again.
		 */
		bind->bi_type = bh->bi_type;
		goto mrcommon_fail5;
	}
	mr->mr_logmttpgsz = mtt_pgsize_bits;

	/*
	 * Allocate MTT reference count (to track shared memory regions).
	 * This reference count resource may never be used on the given
	 * memory region, but if it is ever later registered as "shared"
	 * memory region then this resource will be necessary.  If we fail
	 * here, we do pretty much the same as above to clean up.
	 */
	status = hermon_rsrc_alloc(state, HERMON_REFCNT, 1, sleep,
	    &mtt_refcnt);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto mrcommon_fail6;
	}
	mr->mr_mttrefcntp = mtt_refcnt;
	swrc_tmp = (hermon_sw_refcnt_t *)mtt_refcnt->hr_addr;
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*swrc_tmp))
	HERMON_MTT_REFCNT_INIT(swrc_tmp);

	mtt_addr = (mtt->hr_indx << HERMON_MTT_SIZE_SHIFT);

	/*
	 * Fill in the MPT entry.  This is the final step before passing
	 * ownership of the MPT entry to the Hermon hardware.  We use all of
	 * the information collected/calculated above to fill in the
	 * requisite portions of the MPT.  Do this ONLY for DMPTs.
	 */
	if (mpt == NULL)
		goto no_passown;

	bzero(&mpt_entry, sizeof (hermon_hw_dmpt_t));

	mpt_entry.status  = HERMON_MPT_SW_OWNERSHIP;
	mpt_entry.en_bind = (mr->mr_accflag & IBT_MR_WINDOW_BIND)   ? 1 : 0;
	mpt_entry.atomic  = (mr->mr_accflag & IBT_MR_REMOTE_ATOMIC) ? 1 : 0;
	mpt_entry.rw	  = (mr->mr_accflag & IBT_MR_REMOTE_WRITE)  ? 1 : 0;
	mpt_entry.rr	  = (mr->mr_accflag & IBT_MR_REMOTE_READ)   ? 1 : 0;
	mpt_entry.lw	  = (mr->mr_accflag & IBT_MR_LOCAL_WRITE)   ? 1 : 0;
	mpt_entry.lr	  = 1;
	mpt_entry.phys_addr = 0;
	mpt_entry.reg_win = HERMON_MPT_IS_REGION;

	mpt_entry.entity_sz	= mr->mr_logmttpgsz;
	mpt_entry.mem_key	= mr->mr_lkey;
	mpt_entry.pd		= pd->pd_pdnum;
	mpt_entry.rem_acc_en = 0;
	mpt_entry.fast_reg_en = 0;
	mpt_entry.en_inval = 0;
	mpt_entry.lkey = 0;
	mpt_entry.win_cnt = 0;

	if (bind_override_addr == 0) {
		mpt_entry.start_addr = bh->bi_addr;
	} else {
		bh->bi_addr = bh->bi_addr & ((1 << mr->mr_logmttpgsz) - 1);
		mpt_entry.start_addr = bh->bi_addr;
	}
	mpt_entry.reg_win_len	= bh->bi_len;

	mpt_entry.mtt_addr_h = mtt_addr >> 32;  /* only 8 more bits */
	mpt_entry.mtt_addr_l = mtt_addr >> 3;	/* only 29 bits */

	/*
	 * Write the MPT entry to hardware.  Lastly, we pass ownership of
	 * the entry to the hardware if needed.  Note: in general, this
	 * operation shouldn't fail.  But if it does, we have to undo
	 * everything we've done above before returning error.
	 *
	 * For Hermon, this routine (which is common to the contexts) will only
	 * set the ownership if needed - the process of passing the context
	 * itself to HW will take care of setting up the MPT (based on type
	 * and index).
	 */

	mpt_entry.bnd_qp = 0;	/* dMPT for a qp, check for window */
	status = hermon_cmn_ownership_cmd_post(state, SW2HW_MPT, &mpt_entry,
	    sizeof (hermon_hw_dmpt_t), mpt->hr_indx, sleep);
	if (status != HERMON_CMD_SUCCESS) {
		cmn_err(CE_CONT, "Hermon: SW2HW_MPT command failed: %08x\n",
		    status);
		if (status == HERMON_CMD_INVALID_STATUS) {
			hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
		}
		status = ibc_get_ci_failure(0);
		goto mrcommon_fail7;
	}
	if (hermon_rdma_debug & 0x4)
		IBTF_DPRINTF_L2("mr", "  reg: mr %p  key %x",
		    mr, hermon_mr_key_swap(mr->mr_rkey));
no_passown:

	/*
	 * Fill in the rest of the Hermon Memory Region handle.  Having
	 * successfully transferred ownership of the MPT, we can update the
	 * following fields for use in further operations on the MR.
	 */
	mr->mr_mttaddr	   = mtt_addr;

	mr->mr_log2_pgsz   = (mr->mr_logmttpgsz - HERMON_PAGESHIFT);
	mr->mr_mptrsrcp	   = mpt;
	mr->mr_mttrsrcp	   = mtt;
	mr->mr_pdhdl	   = pd;
	mr->mr_rsrcp	   = rsrc;
	mr->mr_is_umem	   = mr_is_umem;
	mr->mr_is_fmr	   = 0;
	mr->mr_umemcookie  = (mr_is_umem != 0) ? umem_cookie : NULL;
	mr->mr_umem_cbfunc = NULL;
	mr->mr_umem_cbarg1 = NULL;
	mr->mr_umem_cbarg2 = NULL;
	mr->mr_lkey	   = hermon_mr_key_swap(mr->mr_lkey);
	mr->mr_rkey	   = hermon_mr_key_swap(mr->mr_rkey);
	mr->mr_mpt_type	   = mpt_type;

	/*
	 * If this is userland memory, then we need to insert the previously
	 * allocated entry into the "userland resources database".  This will
	 * allow for later coordination between the hermon_umap_umemlock_cb()
	 * callback and hermon_mr_deregister().
	 */
	if (mr_is_umem) {
		hermon_umap_db_add(umapdb);
	}

	*mrhdl = mr;

	return (DDI_SUCCESS);

/*
 * The following is cleanup for all possible failure cases in this routine
 */
mrcommon_fail7:
	hermon_rsrc_free(state, &mtt_refcnt);
mrcommon_fail6:
	hermon_mr_mem_unbind(state, bh);
	bind->bi_type = bh->bi_type;
mrcommon_fail5:
	if (mr_is_umem) {
		hermon_umap_db_free(umapdb);
	}
mrcommon_fail4:
	if (mr_is_umem) {
		/*
		 * Free up the memory ddi_umem_iosetup() allocates
		 * internally.
		 */
		if (bind->bi_type == HERMON_BINDHDL_UBUF) {
			freerbuf(bind->bi_buf);
			_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*bind))
			bind->bi_type = HERMON_BINDHDL_NONE;
			_NOTE(NOW_VISIBLE_TO_OTHER_THREADS(*bind))
		}
		ddi_umem_unlock(umem_cookie);
	}
mrcommon_fail3:
	hermon_rsrc_free(state, &rsrc);
mrcommon_fail2:
	if (mpt != NULL)
		hermon_rsrc_free(state, &mpt);
mrcommon_fail1:
	hermon_pd_refcnt_dec(pd);
mrcommon_fail:
	return (status);
}

/*
 * hermon_dma_mr_register()
 *    Context: Can be called from base context.
 */
int
hermon_dma_mr_register(hermon_state_t *state, hermon_pdhdl_t pd,
    ibt_dmr_attr_t *mr_attr, hermon_mrhdl_t *mrhdl)
{
	hermon_rsrc_t		*mpt, *rsrc;
	hermon_hw_dmpt_t	mpt_entry;
	hermon_mrhdl_t		mr;
	ibt_mr_flags_t		flags;
	uint_t			sleep;
	int			status;

	/* Extract the flags field */
	flags = mr_attr->dmr_flags;

	/*
	 * Check the sleep flag.  Ensure that it is consistent with the
	 * current thread context (i.e. if we are currently in the interrupt
	 * context, then we shouldn't be attempting to sleep).
	 */
	sleep = (flags & IBT_MR_NOSLEEP) ? HERMON_NOSLEEP: HERMON_SLEEP;
	if ((sleep == HERMON_SLEEP) &&
	    (sleep != HERMON_SLEEPFLAG_FOR_CONTEXT())) {
		status = IBT_INVALID_PARAM;
		goto mrcommon_fail;
	}

	/* Increment the reference count on the protection domain (PD) */
	hermon_pd_refcnt_inc(pd);

	/*
	 * Allocate an MPT entry.  This will be filled in with all the
	 * necessary parameters to define the memory region.  And then
	 * ownership will be passed to the hardware in the final step
	 * below.  If we fail here, we must undo the protection domain
	 * reference count.
	 */
	status = hermon_rsrc_alloc(state, HERMON_DMPT, 1, sleep, &mpt);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto mrcommon_fail1;
	}

	/*
	 * Allocate the software structure for tracking the memory region (i.e.
	 * the Hermon Memory Region handle).  If we fail here, we must undo
	 * the protection domain reference count and the previous resource
	 * allocation.
	 */
	status = hermon_rsrc_alloc(state, HERMON_MRHDL, 1, sleep, &rsrc);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto mrcommon_fail2;
	}
	mr = (hermon_mrhdl_t)rsrc->hr_addr;
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mr))
	bzero(mr, sizeof (*mr));

	/*
	 * Setup and validate the memory region access flags.  This means
	 * translating the IBTF's enable flags into the access flags that
	 * will be used in later operations.
	 */
	mr->mr_accflag = 0;
	if (flags & IBT_MR_ENABLE_WINDOW_BIND)
		mr->mr_accflag |= IBT_MR_WINDOW_BIND;
	if (flags & IBT_MR_ENABLE_LOCAL_WRITE)
		mr->mr_accflag |= IBT_MR_LOCAL_WRITE;
	if (flags & IBT_MR_ENABLE_REMOTE_READ)
		mr->mr_accflag |= IBT_MR_REMOTE_READ;
	if (flags & IBT_MR_ENABLE_REMOTE_WRITE)
		mr->mr_accflag |= IBT_MR_REMOTE_WRITE;
	if (flags & IBT_MR_ENABLE_REMOTE_ATOMIC)
		mr->mr_accflag |= IBT_MR_REMOTE_ATOMIC;

	/*
	 * Calculate keys (Lkey, Rkey) from MPT index.  Each key is formed
	 * from a certain number of "constrained" bits (the least significant
	 * bits) and some number of "unconstrained" bits.  The constrained
	 * bits must be set to the index of the entry in the MPT table, but
	 * the unconstrained bits can be set to any value we wish.  Note:
	 * if no remote access is required, then the RKey value is not filled
	 * in.  Otherwise both Rkey and LKey are given the same value.
	 */
	if (mpt)
		mr->mr_rkey = mr->mr_lkey = hermon_mr_keycalc(mpt->hr_indx);

	/*
	 * Fill in the MPT entry.  This is the final step before passing
	 * ownership of the MPT entry to the Hermon hardware.  We use all of
	 * the information collected/calculated above to fill in the
	 * requisite portions of the MPT.  Do this ONLY for DMPTs.
	 */
	bzero(&mpt_entry, sizeof (hermon_hw_dmpt_t));

	mpt_entry.status  = HERMON_MPT_SW_OWNERSHIP;
	mpt_entry.en_bind = (mr->mr_accflag & IBT_MR_WINDOW_BIND)   ? 1 : 0;
	mpt_entry.atomic  = (mr->mr_accflag & IBT_MR_REMOTE_ATOMIC) ? 1 : 0;
	mpt_entry.rw	  = (mr->mr_accflag & IBT_MR_REMOTE_WRITE)  ? 1 : 0;
	mpt_entry.rr	  = (mr->mr_accflag & IBT_MR_REMOTE_READ)   ? 1 : 0;
	mpt_entry.lw	  = (mr->mr_accflag & IBT_MR_LOCAL_WRITE)   ? 1 : 0;
	mpt_entry.lr	  = 1;
	mpt_entry.phys_addr = 1;	/* critical bit for this */
	mpt_entry.reg_win = HERMON_MPT_IS_REGION;

	mpt_entry.entity_sz	= mr->mr_logmttpgsz;
	mpt_entry.mem_key	= mr->mr_lkey;
	mpt_entry.pd		= pd->pd_pdnum;
	mpt_entry.rem_acc_en = 0;
	mpt_entry.fast_reg_en = 0;
	mpt_entry.en_inval = 0;
	mpt_entry.lkey = 0;
	mpt_entry.win_cnt = 0;

	mpt_entry.start_addr = mr_attr->dmr_paddr;
	mpt_entry.reg_win_len = mr_attr->dmr_len;
	if (mr_attr->dmr_len == 0)
		mpt_entry.len_b64 = 1;	/* needed for 2^^64 length */

	mpt_entry.mtt_addr_h = 0;
	mpt_entry.mtt_addr_l = 0;

	/*
	 * Write the MPT entry to hardware.  Lastly, we pass ownership of
	 * the entry to the hardware if needed.  Note: in general, this
	 * operation shouldn't fail.  But if it does, we have to undo
	 * everything we've done above before returning error.
	 *
	 * For Hermon, this routine (which is common to the contexts) will only
	 * set the ownership if needed - the process of passing the context
	 * itself to HW will take care of setting up the MPT (based on type
	 * and index).
	 */

	mpt_entry.bnd_qp = 0;	/* dMPT for a qp, check for window */
	status = hermon_cmn_ownership_cmd_post(state, SW2HW_MPT, &mpt_entry,
	    sizeof (hermon_hw_dmpt_t), mpt->hr_indx, sleep);
	if (status != HERMON_CMD_SUCCESS) {
		cmn_err(CE_CONT, "Hermon: SW2HW_MPT command failed: %08x\n",
		    status);
		if (status == HERMON_CMD_INVALID_STATUS) {
			hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
		}
		status = ibc_get_ci_failure(0);
		goto mrcommon_fail7;
	}

	/*
	 * Fill in the rest of the Hermon Memory Region handle.  Having
	 * successfully transferred ownership of the MPT, we can update the
	 * following fields for use in further operations on the MR.
	 */
	mr->mr_mttaddr	   = 0;

	mr->mr_log2_pgsz   = 0;
	mr->mr_mptrsrcp	   = mpt;
	mr->mr_mttrsrcp	   = NULL;
	mr->mr_pdhdl	   = pd;
	mr->mr_rsrcp	   = rsrc;
	mr->mr_is_umem	   = 0;
	mr->mr_is_fmr	   = 0;
	mr->mr_umemcookie  = NULL;
	mr->mr_umem_cbfunc = NULL;
	mr->mr_umem_cbarg1 = NULL;
	mr->mr_umem_cbarg2 = NULL;
	mr->mr_lkey	   = hermon_mr_key_swap(mr->mr_lkey);
	mr->mr_rkey	   = hermon_mr_key_swap(mr->mr_rkey);
	mr->mr_mpt_type	   = HERMON_MPT_DMPT;

	*mrhdl = mr;

	return (DDI_SUCCESS);

/*
 * The following is cleanup for all possible failure cases in this routine
 */
mrcommon_fail7:
	hermon_rsrc_free(state, &rsrc);
mrcommon_fail2:
	hermon_rsrc_free(state, &mpt);
mrcommon_fail1:
	hermon_pd_refcnt_dec(pd);
mrcommon_fail:
	return (status);
}

/*
 * hermon_mr_alloc_lkey()
 *    Context: Can be called from base context.
 */
int
hermon_mr_alloc_lkey(hermon_state_t *state, hermon_pdhdl_t pd,
    ibt_lkey_flags_t flags, uint_t nummtt, hermon_mrhdl_t *mrhdl)
{
	hermon_rsrc_t		*mpt, *mtt, *rsrc, *mtt_refcnt;
	hermon_sw_refcnt_t	*swrc_tmp;
	hermon_hw_dmpt_t	mpt_entry;
	hermon_mrhdl_t		mr;
	uint64_t		mtt_addr;
	uint_t			sleep;
	int			status;

	/* Increment the reference count on the protection domain (PD) */
	hermon_pd_refcnt_inc(pd);

	sleep = (flags & IBT_KEY_NOSLEEP) ? HERMON_NOSLEEP: HERMON_SLEEP;

	/*
	 * Allocate an MPT entry.  This will be filled in with "some" of the
	 * necessary parameters to define the memory region.  And then
	 * ownership will be passed to the hardware in the final step
	 * below.  If we fail here, we must undo the protection domain
	 * reference count.
	 *
	 * The MTTs will get filled in when the FRWR is processed.
	 */
	status = hermon_rsrc_alloc(state, HERMON_DMPT, 1, sleep, &mpt);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto alloclkey_fail1;
	}

	/*
	 * Allocate the software structure for tracking the memory region (i.e.
	 * the Hermon Memory Region handle).  If we fail here, we must undo
	 * the protection domain reference count and the previous resource
	 * allocation.
	 */
	status = hermon_rsrc_alloc(state, HERMON_MRHDL, 1, sleep, &rsrc);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto alloclkey_fail2;
	}
	mr = (hermon_mrhdl_t)rsrc->hr_addr;
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mr))
	bzero(mr, sizeof (*mr));
	mr->mr_bindinfo.bi_type = HERMON_BINDHDL_LKEY;

	mr->mr_lkey = hermon_mr_keycalc(mpt->hr_indx);

	status = hermon_rsrc_alloc(state, HERMON_MTT, nummtt, sleep, &mtt);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto alloclkey_fail3;
	}
	mr->mr_logmttpgsz = PAGESHIFT;

	/*
	 * Allocate MTT reference count (to track shared memory regions).
	 * This reference count resource may never be used on the given
	 * memory region, but if it is ever later registered as "shared"
	 * memory region then this resource will be necessary.  If we fail
	 * here, we do pretty much the same as above to clean up.
	 */
	status = hermon_rsrc_alloc(state, HERMON_REFCNT, 1, sleep,
	    &mtt_refcnt);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto alloclkey_fail4;
	}
	mr->mr_mttrefcntp = mtt_refcnt;
	swrc_tmp = (hermon_sw_refcnt_t *)mtt_refcnt->hr_addr;
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*swrc_tmp))
	HERMON_MTT_REFCNT_INIT(swrc_tmp);

	mtt_addr = (mtt->hr_indx << HERMON_MTT_SIZE_SHIFT);

	bzero(&mpt_entry, sizeof (hermon_hw_dmpt_t));
	mpt_entry.status = HERMON_MPT_FREE;
	mpt_entry.lw = 1;
	mpt_entry.lr = 1;
	mpt_entry.reg_win = HERMON_MPT_IS_REGION;
	mpt_entry.entity_sz = mr->mr_logmttpgsz;
	mpt_entry.mem_key = mr->mr_lkey;
	mpt_entry.pd = pd->pd_pdnum;
	mpt_entry.fast_reg_en = 1;
	mpt_entry.rem_acc_en = 1;
	mpt_entry.en_inval = 1;
	if (flags & IBT_KEY_REMOTE) {
		mpt_entry.ren_inval = 1;
	}
	mpt_entry.mtt_size = nummtt;
	mpt_entry.mtt_addr_h = mtt_addr >> 32;	/* only 8 more bits */
	mpt_entry.mtt_addr_l = mtt_addr >> 3;	/* only 29 bits */

	/*
	 * Write the MPT entry to hardware.  Lastly, we pass ownership of
	 * the entry to the hardware if needed.  Note: in general, this
	 * operation shouldn't fail.  But if it does, we have to undo
	 * everything we've done above before returning error.
	 *
	 * For Hermon, this routine (which is common to the contexts) will only
	 * set the ownership if needed - the process of passing the context
	 * itself to HW will take care of setting up the MPT (based on type
	 * and index).
	 */
	status = hermon_cmn_ownership_cmd_post(state, SW2HW_MPT, &mpt_entry,
	    sizeof (hermon_hw_dmpt_t), mpt->hr_indx, sleep);
	if (status != HERMON_CMD_SUCCESS) {
		cmn_err(CE_CONT, "Hermon: alloc_lkey: SW2HW_MPT command "
		    "failed: %08x\n", status);
		if (status == HERMON_CMD_INVALID_STATUS) {
			hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
		}
		status = ibc_get_ci_failure(0);
		goto alloclkey_fail5;
	}

	/*
	 * Fill in the rest of the Hermon Memory Region handle.  Having
	 * successfully transferred ownership of the MPT, we can update the
	 * following fields for use in further operations on the MR.
	 */
	mr->mr_accflag = IBT_MR_LOCAL_WRITE;
	mr->mr_mttaddr = mtt_addr;
	mr->mr_log2_pgsz = (mr->mr_logmttpgsz - HERMON_PAGESHIFT);
	mr->mr_mptrsrcp = mpt;
	mr->mr_mttrsrcp = mtt;
	mr->mr_pdhdl = pd;
	mr->mr_rsrcp = rsrc;
	mr->mr_lkey = hermon_mr_key_swap(mr->mr_lkey);
	mr->mr_rkey = mr->mr_lkey;
	mr->mr_mpt_type = HERMON_MPT_DMPT;

	*mrhdl = mr;
	return (DDI_SUCCESS);

alloclkey_fail5:
	hermon_rsrc_free(state, &mtt_refcnt);
alloclkey_fail4:
	hermon_rsrc_free(state, &mtt);
alloclkey_fail3:
	hermon_rsrc_free(state, &rsrc);
alloclkey_fail2:
	hermon_rsrc_free(state, &mpt);
alloclkey_fail1:
	hermon_pd_refcnt_dec(pd);
	return (status);
}

/*
 * hermon_mr_fexch_mpt_init()
 *    Context: Can be called from base context.
 *
 * This is the same as alloc_lkey, but not returning an mrhdl.
 */
int
hermon_mr_fexch_mpt_init(hermon_state_t *state, hermon_pdhdl_t pd,
    uint32_t mpt_indx, uint_t nummtt, uint64_t mtt_addr, uint_t sleep)
{
	hermon_hw_dmpt_t	mpt_entry;
	int			status;

	/*
	 * The MTTs will get filled in when the FRWR is processed.
	 */

	bzero(&mpt_entry, sizeof (hermon_hw_dmpt_t));
	mpt_entry.status = HERMON_MPT_FREE;
	mpt_entry.lw = 1;
	mpt_entry.lr = 1;
	mpt_entry.rw = 1;
	mpt_entry.rr = 1;
	mpt_entry.reg_win = HERMON_MPT_IS_REGION;
	mpt_entry.entity_sz = PAGESHIFT;
	mpt_entry.mem_key = mpt_indx;
	mpt_entry.pd = pd->pd_pdnum;
	mpt_entry.fast_reg_en = 1;
	mpt_entry.rem_acc_en = 1;
	mpt_entry.en_inval = 1;
	mpt_entry.ren_inval = 1;
	mpt_entry.mtt_size = nummtt;
	mpt_entry.mtt_addr_h = mtt_addr >> 32;	/* only 8 more bits */
	mpt_entry.mtt_addr_l = mtt_addr >> 3;	/* only 29 bits */

	/*
	 * Write the MPT entry to hardware.  Lastly, we pass ownership of
	 * the entry to the hardware if needed.  Note: in general, this
	 * operation shouldn't fail.  But if it does, we have to undo
	 * everything we've done above before returning error.
	 *
	 * For Hermon, this routine (which is common to the contexts) will only
	 * set the ownership if needed - the process of passing the context
	 * itself to HW will take care of setting up the MPT (based on type
	 * and index).
	 */
	status = hermon_cmn_ownership_cmd_post(state, SW2HW_MPT, &mpt_entry,
	    sizeof (hermon_hw_dmpt_t), mpt_indx, sleep);
	if (status != HERMON_CMD_SUCCESS) {
		cmn_err(CE_CONT, "Hermon: fexch_mpt_init: SW2HW_MPT command "
		    "failed: %08x\n", status);
		if (status == HERMON_CMD_INVALID_STATUS) {
			hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
		}
		status = ibc_get_ci_failure(0);
		return (status);
	}
	/* Increment the reference count on the protection domain (PD) */
	hermon_pd_refcnt_inc(pd);

	return (DDI_SUCCESS);
}

/*
 * hermon_mr_fexch_mpt_fini()
 *    Context: Can be called from base context.
 *
 * This is the same as deregister_mr, without an mrhdl.
 */
int
hermon_mr_fexch_mpt_fini(hermon_state_t *state, hermon_pdhdl_t pd,
    uint32_t mpt_indx, uint_t sleep)
{
	int			status;

	status = hermon_cmn_ownership_cmd_post(state, HW2SW_MPT,
	    NULL, 0, mpt_indx, sleep);
	if (status != DDI_SUCCESS) {
		cmn_err(CE_CONT, "Hermon: fexch_mpt_fini: HW2SW_MPT command "
		    "failed: %08x\n", status);
		if (status == HERMON_CMD_INVALID_STATUS) {
			hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
		}
		status = ibc_get_ci_failure(0);
		return (status);
	}

	/* Decrement the reference count on the protection domain (PD) */
	hermon_pd_refcnt_dec(pd);

	return (DDI_SUCCESS);
}

/*
 * hermon_mr_mtt_bind()
 *    Context: Can be called from interrupt or base context.
 */
int
hermon_mr_mtt_bind(hermon_state_t *state, hermon_bind_info_t *bind,
    ddi_dma_handle_t bind_dmahdl, hermon_rsrc_t **mtt, uint_t *mtt_pgsize_bits,
    uint_t is_buffer)
{
	uint64_t		nummtt;
	uint_t			sleep;
	int			status;

	/*
	 * Check the sleep flag.  Ensure that it is consistent with the
	 * current thread context (i.e. if we are currently in the interrupt
	 * context, then we shouldn't be attempting to sleep).
	 */
	sleep = (bind->bi_flags & IBT_MR_NOSLEEP) ?
	    HERMON_NOSLEEP : HERMON_SLEEP;
	if ((sleep == HERMON_SLEEP) &&
	    (sleep != HERMON_SLEEPFLAG_FOR_CONTEXT())) {
		status = IBT_INVALID_PARAM;
		goto mrmttbind_fail;
	}

	/*
	 * Bind the memory and determine the mapped addresses.  This is
	 * the first of two routines that do all the "heavy lifting" for
	 * the Hermon memory registration routines.  The hermon_mr_mem_bind()
	 * routine takes the "bind" struct with all its fields filled
	 * in and returns a list of DMA cookies (for the PCI mapped addresses
	 * corresponding to the specified address region) which are used by
	 * the hermon_mr_fast_mtt_write() routine below.  If we fail here, we
	 * must undo all the previous resource allocation (and PD reference
	 * count).
	 */
	status = hermon_mr_mem_bind(state, bind, bind_dmahdl, sleep, is_buffer);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto mrmttbind_fail;
	}

	/*
	 * Determine number of pages spanned.  This routine uses the
	 * information in the "bind" struct to determine the required
	 * number of MTT entries needed (and returns the suggested page size -
	 * as a "power-of-2" - for each MTT entry).
	 */
	nummtt = hermon_mr_nummtt_needed(state, bind, mtt_pgsize_bits);

	/*
	 * Allocate the MTT entries.  Use the calculations performed above to
	 * allocate the required number of MTT entries. If we fail here, we
	 * must not only undo all the previous resource allocation (and PD
	 * reference count), but we must also unbind the memory.
	 */
	status = hermon_rsrc_alloc(state, HERMON_MTT, nummtt, sleep, mtt);
	if (status != DDI_SUCCESS) {
		status = IBT_INSUFF_RESOURCE;
		goto mrmttbind_fail2;
	}

	/*
	 * Write the mapped addresses into the MTT entries.  This is part two
	 * of the "heavy lifting" routines that we talked about above.  Note:
	 * we pass the suggested page size from the earlier operation here.
	 * And if we fail here, we again do pretty much the same huge clean up.
	 */
	status = hermon_mr_fast_mtt_write(state, *mtt, bind, *mtt_pgsize_bits);
	if (status != DDI_SUCCESS) {
		/*
		 * hermon_mr_fast_mtt_write() returns DDI_FAILURE
		 * only if it detects a HW error during DMA.
		 */
		hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
		status = ibc_get_ci_failure(0);
		goto mrmttbind_fail3;
	}
	return (DDI_SUCCESS);

/*
 * The following is cleanup for all possible failure cases in this routine
 */
mrmttbind_fail3:
	hermon_rsrc_free(state, mtt);
mrmttbind_fail2:
	hermon_mr_mem_unbind(state, bind);
mrmttbind_fail:
	return (status);
}


/*
 * hermon_mr_mtt_unbind()
 *    Context: Can be called from interrupt or base context.
 */
int
hermon_mr_mtt_unbind(hermon_state_t *state, hermon_bind_info_t *bind,
    hermon_rsrc_t *mtt)
{
	/*
	 * Free up the MTT entries and unbind the memory.  Here, as above, we
	 * attempt to free these resources only if it is appropriate to do so.
	 */
	hermon_mr_mem_unbind(state, bind);
	hermon_rsrc_free(state, &mtt);

	return (DDI_SUCCESS);
}


/*
 * hermon_mr_common_rereg()
 *    Context: Can be called from interrupt or base context.
 */
static int
hermon_mr_common_rereg(hermon_state_t *state, hermon_mrhdl_t mr,
    hermon_pdhdl_t pd, hermon_bind_info_t *bind, hermon_mrhdl_t *mrhdl_new,
    hermon_mr_options_t *op)
{
	hermon_rsrc_t		*mpt;
	ibt_mr_attr_flags_t	acc_flags_to_use;
	ibt_mr_flags_t		flags;
	hermon_pdhdl_t		pd_to_use;
	hermon_hw_dmpt_t	mpt_entry;
	uint64_t		mtt_addr_to_use, vaddr_to_use, len_to_use;
	uint_t			sleep, dereg_level;
	int			status;

	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*bind))

	/*
	 * Check here to see if the memory region corresponds to a userland
	 * mapping.  Reregistration of userland memory regions is not
	 * currently supported.  Return failure.
	 */
	if (mr->mr_is_umem) {
		status = IBT_MR_HDL_INVALID;
		goto mrrereg_fail;
	}

	mutex_enter(&mr->mr_lock);

	/* Pull MPT resource pointer from the Hermon Memory Region handle */
	mpt = mr->mr_mptrsrcp;

	/* Extract the flags field from the hermon_bind_info_t */
	flags = bind->bi_flags;

	/*
	 * Check the sleep flag.  Ensure that it is consistent with the
	 * current thread context (i.e. if we are currently in the interrupt
	 * context, then we shouldn't be attempting to sleep).
	 */
	sleep = (flags & IBT_MR_NOSLEEP) ? HERMON_NOSLEEP: HERMON_SLEEP;
	if ((sleep == HERMON_SLEEP) &&
	    (sleep != HERMON_SLEEPFLAG_FOR_CONTEXT())) {
		mutex_exit(&mr->mr_lock);
		status = IBT_INVALID_PARAM;
		goto mrrereg_fail;
	}

	/*
	 * First step is to temporarily invalidate the MPT entry.  This
	 * regains ownership from the hardware, and gives us the opportunity
	 * to modify the entry.  Note: The HW2SW_MPT command returns the
	 * current MPT entry contents.  These are saved away here because
	 * they will be reused in a later step below.  If the region has
	 * bound memory windows that we fail returning an "in use" error code.
	 * Otherwise, this is an unexpected error and we deregister the
	 * memory region and return error.
	 *
	 * We use HERMON_CMD_NOSLEEP_SPIN here always because we must protect
	 * against holding the lock around this rereg call in all contexts.
	 */
	status = hermon_cmn_ownership_cmd_post(state, HW2SW_MPT, &mpt_entry,
	    sizeof (hermon_hw_dmpt_t), mpt->hr_indx, HERMON_CMD_NOSLEEP_SPIN);
	if (status != HERMON_CMD_SUCCESS) {
		mutex_exit(&mr->mr_lock);
		if (status == HERMON_CMD_REG_BOUND) {
			return (IBT_MR_IN_USE);
		} else {
			cmn_err(CE_CONT, "Hermon: HW2SW_MPT command failed: "
			    "%08x\n", status);
			if (status == HERMON_CMD_INVALID_STATUS) {
				hermon_fm_ereport(state, HCA_SYS_ERR,
				    HCA_ERR_SRV_LOST);
			}
			/*
			 * Call deregister and ensure that all current
			 * resources get freed up
			 */
			if (hermon_mr_deregister(state, &mr,
			    HERMON_MR_DEREG_ALL, sleep) != DDI_SUCCESS) {
				HERMON_WARNING(state, "failed to deregister "
				    "memory region");
			}
			return (ibc_get_ci_failure(0));
		}
	}

	/*
	 * If we're changing the protection domain, then validate the new one
	 */
	if (flags & IBT_MR_CHANGE_PD) {

		/* Check for valid PD handle pointer */
		if (pd == NULL) {
			mutex_exit(&mr->mr_lock);
			/*
			 * Call deregister and ensure that all current
			 * resources get properly freed up. Unnecessary
			 * here to attempt to regain software ownership
			 * of the MPT entry as that has already been
			 * done above.
			 */
			if (hermon_mr_deregister(state, &mr,
			    HERMON_MR_DEREG_NO_HW2SW_MPT, sleep) !=
			    DDI_SUCCESS) {
				HERMON_WARNING(state, "failed to deregister "
				    "memory region");
			}
			status = IBT_PD_HDL_INVALID;
			goto mrrereg_fail;
		}

		/* Use the new PD handle in all operations below */
		pd_to_use = pd;

	} else {
		/* Use the current PD handle in all operations below */
		pd_to_use = mr->mr_pdhdl;
	}

	/*
	 * If we're changing access permissions, then validate the new ones
	 */
	if (flags & IBT_MR_CHANGE_ACCESS) {
		/*
		 * Validate the access flags.  Both remote write and remote
		 * atomic require the local write flag to be set
		 */
		if (((flags & IBT_MR_ENABLE_REMOTE_WRITE) ||
		    (flags & IBT_MR_ENABLE_REMOTE_ATOMIC)) &&
		    !(flags & IBT_MR_ENABLE_LOCAL_WRITE)) {
			mutex_exit(&mr->mr_lock);
			/*
			 * Call deregister and ensure that all current
			 * resources get properly freed up. Unnecessary
			 * here to attempt to regain software ownership
			 * of the MPT entry as that has already been
			 * done above.
			 */
			if (hermon_mr_deregister(state, &mr,
			    HERMON_MR_DEREG_NO_HW2SW_MPT, sleep) !=
			    DDI_SUCCESS) {
				HERMON_WARNING(state, "failed to deregister "
				    "memory region");
			}
			status = IBT_MR_ACCESS_REQ_INVALID;
			goto mrrereg_fail;
		}

		/*
		 * Setup and validate the memory region access flags.  This
		 * means translating the IBTF's enable flags into the access
		 * flags that will be used in later operations.
		 */
		acc_flags_to_use = 0;
		if (flags & IBT_MR_ENABLE_WINDOW_BIND)
			acc_flags_to_use |= IBT_MR_WINDOW_BIND;
		if (flags & IBT_MR_ENABLE_LOCAL_WRITE)
			acc_flags_to_use |= IBT_MR_LOCAL_WRITE;
		if (flags & IBT_MR_ENABLE_REMOTE_READ)
			acc_flags_to_use |= IBT_MR_REMOTE_READ;
		if (flags & IBT_MR_ENABLE_REMOTE_WRITE)
			acc_flags_to_use |= IBT_MR_REMOTE_WRITE;
		if (flags & IBT_MR_ENABLE_REMOTE_ATOMIC)
			acc_flags_to_use |= IBT_MR_REMOTE_ATOMIC;

	} else {
		acc_flags_to_use = mr->mr_accflag;
	}

	/*
	 * If we're modifying the translation, then figure out whether
	 * we can reuse the current MTT resources.  This means calling
	 * hermon_mr_rereg_xlat_helper() which does most of the heavy lifting
	 * for the reregistration.  If the current memory region contains
	 * sufficient MTT entries for the new regions, then it will be
	 * reused and filled in.  Otherwise, new entries will be allocated,
	 * the old ones will be freed, and the new entries will be filled
	 * in.  Note:  If we're not modifying the translation, then we
	 * should already have all the information we need to update the MPT.
	 * Also note: If hermon_mr_rereg_xlat_helper() fails, it will return
	 * a "dereg_level" which is the level of cleanup that needs to be
	 * passed to hermon_mr_deregister() to finish the cleanup.
	 */
	if (flags & IBT_MR_CHANGE_TRANSLATION) {
		status = hermon_mr_rereg_xlat_helper(state, mr, bind, op,
		    &mtt_addr_to_use, sleep, &dereg_level);
		if (status != DDI_SUCCESS) {
			mutex_exit(&mr->mr_lock);
			/*
			 * Call deregister and ensure that all resources get
			 * properly freed up.
			 */
			if (hermon_mr_deregister(state, &mr, dereg_level,
			    sleep) != DDI_SUCCESS) {
				HERMON_WARNING(state, "failed to deregister "
				    "memory region");
			}
			goto mrrereg_fail;
		}
		vaddr_to_use = mr->mr_bindinfo.bi_addr;
		len_to_use   = mr->mr_bindinfo.bi_len;
	} else {
		mtt_addr_to_use = mr->mr_mttaddr;
		vaddr_to_use = mr->mr_bindinfo.bi_addr;
		len_to_use   = mr->mr_bindinfo.bi_len;
	}

	/*
	 * Calculate new keys (Lkey, Rkey) from MPT index.  Just like they were
	 * when the region was first registered, each key is formed from
	 * "constrained" bits and "unconstrained" bits.  Note:  If no remote
	 * access is required, then the RKey value is not filled in.  Otherwise
	 * both Rkey and LKey are given the same value.
	 */
	mr->mr_lkey = hermon_mr_keycalc(mpt->hr_indx);
	if ((acc_flags_to_use & IBT_MR_REMOTE_READ) ||
	    (acc_flags_to_use & IBT_MR_REMOTE_WRITE) ||
	    (acc_flags_to_use & IBT_MR_REMOTE_ATOMIC)) {
		mr->mr_rkey = mr->mr_lkey;
	} else
		mr->mr_rkey = 0;

	/*
	 * Fill in the MPT entry.  This is the final step before passing
	 * ownership of the MPT entry to the Hermon hardware.  We use all of
	 * the information collected/calculated above to fill in the
	 * requisite portions of the MPT.
	 */
	bzero(&mpt_entry, sizeof (hermon_hw_dmpt_t));

	mpt_entry.status  = HERMON_MPT_SW_OWNERSHIP;
	mpt_entry.en_bind = (acc_flags_to_use & IBT_MR_WINDOW_BIND)   ? 1 : 0;
	mpt_entry.atomic  = (acc_flags_to_use & IBT_MR_REMOTE_ATOMIC) ? 1 : 0;
	mpt_entry.rw	  = (acc_flags_to_use & IBT_MR_REMOTE_WRITE)  ? 1 : 0;
	mpt_entry.rr	  = (acc_flags_to_use & IBT_MR_REMOTE_READ)   ? 1 : 0;
	mpt_entry.lw	  = (acc_flags_to_use & IBT_MR_LOCAL_WRITE)   ? 1 : 0;
	mpt_entry.lr	  = 1;
	mpt_entry.phys_addr = 0;
	mpt_entry.reg_win = HERMON_MPT_IS_REGION;

	mpt_entry.entity_sz	= mr->mr_logmttpgsz;
	mpt_entry.mem_key	= mr->mr_lkey;
	mpt_entry.pd		= pd_to_use->pd_pdnum;

	mpt_entry.start_addr	= vaddr_to_use;
	mpt_entry.reg_win_len	= len_to_use;
	mpt_entry.mtt_addr_h = mtt_addr_to_use >> 32;
	mpt_entry.mtt_addr_l = mtt_addr_to_use >> 3;

	/*
	 * Write the updated MPT entry to hardware
	 *
	 * We use HERMON_CMD_NOSLEEP_SPIN here always because we must protect
	 * against holding the lock around this rereg call in all contexts.
	 */
	status = hermon_cmn_ownership_cmd_post(state, SW2HW_MPT, &mpt_entry,
	    sizeof (hermon_hw_dmpt_t), mpt->hr_indx, HERMON_CMD_NOSLEEP_SPIN);
	if (status != HERMON_CMD_SUCCESS) {
		mutex_exit(&mr->mr_lock);
		cmn_err(CE_CONT, "Hermon: SW2HW_MPT command failed: %08x\n",
		    status);
		if (status == HERMON_CMD_INVALID_STATUS) {
			hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
		}
		/*
		 * Call deregister and ensure that all current resources get
		 * properly freed up. Unnecessary here to attempt to regain
		 * software ownership of the MPT entry as that has already
		 * been done above.
		 */
		if (hermon_mr_deregister(state, &mr,
		    HERMON_MR_DEREG_NO_HW2SW_MPT, sleep) != DDI_SUCCESS) {
			HERMON_WARNING(state, "failed to deregister memory "
			    "region");
		}
		return (ibc_get_ci_failure(0));
	}

	/*
	 * If we're changing PD, then update their reference counts now.
	 * This means decrementing the reference count on the old PD and
	 * incrementing the reference count on the new PD.
	 */
	if (flags & IBT_MR_CHANGE_PD) {
		hermon_pd_refcnt_dec(mr->mr_pdhdl);
		hermon_pd_refcnt_inc(pd);
	}

	/*
	 * Update the contents of the Hermon Memory Region handle to reflect
	 * what has been changed.
	 */
	mr->mr_pdhdl	  = pd_to_use;
	mr->mr_accflag	  = acc_flags_to_use;
	mr->mr_is_umem	  = 0;
	mr->mr_is_fmr	  = 0;
	mr->mr_umemcookie = NULL;
	mr->mr_lkey	  = hermon_mr_key_swap(mr->mr_lkey);
	mr->mr_rkey	  = hermon_mr_key_swap(mr->mr_rkey);

	/* New MR handle is same as the old */
	*mrhdl_new = mr;
	mutex_exit(&mr->mr_lock);

	return (DDI_SUCCESS);

mrrereg_fail:
	return (status);
}


/*
 * hermon_mr_rereg_xlat_helper
 *    Context: Can be called from interrupt or base context.
 *    Note: This routine expects the "mr_lock" to be held when it
 *    is called.  Upon returning failure, this routine passes information
 *    about what "dereg_level" should be passed to hermon_mr_deregister().
 */
static int
hermon_mr_rereg_xlat_helper(hermon_state_t *state, hermon_mrhdl_t mr,
    hermon_bind_info_t *bind, hermon_mr_options_t *op, uint64_t *mtt_addr,
    uint_t sleep, uint_t *dereg_level)
{
	hermon_rsrc_t		*mtt, *mtt_refcnt;
	hermon_sw_refcnt_t	*swrc_old, *swrc_new;
	ddi_dma_handle_t	dmahdl;
	uint64_t		nummtt_needed, nummtt_in_currrsrc, max_sz;
	uint_t			mtt_pgsize_bits, bind_type, reuse_dmahdl;
	int			status;

	ASSERT(MUTEX_HELD(&mr->mr_lock));

	/*
	 * Check the "options" flag.  Currently this flag tells the driver
	 * whether or not the region should be bound normally (i.e. with
	 * entries written into the PCI IOMMU) or whether it should be
	 * registered to bypass the IOMMU.
	 */
	if (op == NULL) {
		bind_type = HERMON_BINDMEM_NORMAL;
	} else {
		bind_type = op->mro_bind_type;
	}

	/*
	 * Check for invalid length.  Check is the length is zero or if the
	 * length is larger than the maximum configured value.  Return error
	 * if it is.
	 */
	max_sz = ((uint64_t)1 << state->hs_cfg_profile->cp_log_max_mrw_sz);
	if ((bind->bi_len == 0) || (bind->bi_len > max_sz)) {
		/*
		 * Deregister will be called upon returning failure from this
		 * routine. This will ensure that all current resources get
		 * properly freed up. Unnecessary to attempt to regain
		 * software ownership of the MPT entry as that has already
		 * been done above (in hermon_mr_reregister())
		 */
		*dereg_level = HERMON_MR_DEREG_NO_HW2SW_MPT;

		status = IBT_MR_LEN_INVALID;
		goto mrrereghelp_fail;
	}

	/*
	 * Determine the number of pages necessary for new region and the
	 * number of pages supported by the current MTT resources
	 */
	nummtt_needed = hermon_mr_nummtt_needed(state, bind, &mtt_pgsize_bits);
	nummtt_in_currrsrc = mr->mr_mttrsrcp->hr_len >> HERMON_MTT_SIZE_SHIFT;

	/*
	 * Depending on whether we have enough pages or not, the next step is
	 * to fill in a set of MTT entries that reflect the new mapping.  In
	 * the first case below, we already have enough entries.  This means
	 * we need to unbind the memory from the previous mapping, bind the
	 * memory for the new mapping, write the new MTT entries, and update
	 * the mr to reflect the changes.
	 * In the second case below, we do not have enough entries in the
	 * current mapping.  So, in this case, we need not only to unbind the
	 * current mapping, but we need to free up the MTT resources associated
	 * with that mapping.  After we've successfully done that, we continue
	 * by binding the new memory, allocating new MTT entries, writing the
	 * new MTT entries, and updating the mr to reflect the changes.
	 */

	/*
	 * If this region is being shared (i.e. MTT refcount != 1), then we
	 * can't reuse the current MTT resources regardless of their size.
	 * Instead we'll need to alloc new ones (below) just as if there
	 * hadn't been enough room in the current entries.
	 */
	swrc_old = (hermon_sw_refcnt_t *)mr->mr_mttrefcntp->hr_addr;
	if (HERMON_MTT_IS_NOT_SHARED(swrc_old) &&
	    (nummtt_needed <= nummtt_in_currrsrc)) {

		/*
		 * Unbind the old mapping for this memory region, but retain
		 * the ddi_dma_handle_t (if possible) for reuse in the bind
		 * operation below.  Note:  If original memory region was
		 * bound for IOMMU bypass and the new region can not use
		 * bypass, then a new DMA handle will be necessary.
		 */
		if (HERMON_MR_REUSE_DMAHDL(mr, bind->bi_flags)) {
			mr->mr_bindinfo.bi_free_dmahdl = 0;
			hermon_mr_mem_unbind(state, &mr->mr_bindinfo);
			dmahdl = mr->mr_bindinfo.bi_dmahdl;
			reuse_dmahdl = 1;
		} else {
			hermon_mr_mem_unbind(state, &mr->mr_bindinfo);
			dmahdl = NULL;
			reuse_dmahdl = 0;
		}

		/*
		 * Bind the new memory and determine the mapped addresses.
		 * As described, this routine and hermon_mr_fast_mtt_write()
		 * do the majority of the work for the memory registration
		 * operations.  Note:  When we successfully finish the binding,
		 * we will set the "bi_free_dmahdl" flag to indicate that
		 * even though we may have reused the ddi_dma_handle_t we do
		 * wish it to be freed up at some later time.  Note also that
		 * if we fail, we may need to cleanup the ddi_dma_handle_t.
		 */
		bind->bi_bypass	= bind_type;
		status = hermon_mr_mem_bind(state, bind, dmahdl, sleep, 1);
		if (status != DDI_SUCCESS) {
			if (reuse_dmahdl) {
				ddi_dma_free_handle(&dmahdl);
			}

			/*
			 * Deregister will be called upon returning failure
			 * from this routine. This will ensure that all
			 * current resources get properly freed up.
			 * Unnecessary to attempt to regain software ownership
			 * of the MPT entry as that has already been done
			 * above (in hermon_mr_reregister()).  Also unnecessary
			 * to attempt to unbind the memory.
			 */
			*dereg_level = HERMON_MR_DEREG_NO_HW2SW_MPT_OR_UNBIND;

			status = IBT_INSUFF_RESOURCE;
			goto mrrereghelp_fail;
		}
		if (reuse_dmahdl) {
			bind->bi_free_dmahdl = 1;
		}

		/*
		 * Using the new mapping, but reusing the current MTT
		 * resources, write the updated entries to MTT
		 */
		mtt    = mr->mr_mttrsrcp;
		status = hermon_mr_fast_mtt_write(state, mtt, bind,
		    mtt_pgsize_bits);
		if (status != DDI_SUCCESS) {
			/*
			 * Deregister will be called upon returning failure
			 * from this routine. This will ensure that all
			 * current resources get properly freed up.
			 * Unnecessary to attempt to regain software ownership
			 * of the MPT entry as that has already been done
			 * above (in hermon_mr_reregister()).  Also unnecessary
			 * to attempt to unbind the memory.
			 *
			 * But we do need to unbind the newly bound memory
			 * before returning.
			 */
			hermon_mr_mem_unbind(state, bind);
			*dereg_level = HERMON_MR_DEREG_NO_HW2SW_MPT_OR_UNBIND;

			/*
			 * hermon_mr_fast_mtt_write() returns DDI_FAILURE
			 * only if it detects a HW error during DMA.
			 */
			hermon_fm_ereport(state, HCA_SYS_ERR, HCA_ERR_SRV_LOST);
			status = ibc_get_ci_failure(0);
			goto mrrereghelp_fail;
		}

		/* Put the updated information into the Mem Region handle */
		mr->mr_bindinfo	  = *bind;
		mr->mr_logmttpgsz = mtt_pgsize_bits;

	} else {
		/*
		 * Check if the memory region MTT is shared by any other MRs.
		 * Since the resource may be shared between multiple memory
		 * regions (as a result of a "RegisterSharedMR()" verb) it is
		 * important that we not unbind any resources prematurely.
		 */
		if (!HERMON_MTT_IS_SHARED(swrc_old)) {
			/*
			 * Unbind the old mapping for this memory region, but
			 * retain the ddi_dma_handle_t for reuse in the bind
			 * operation below. Note: This can only be done here
			 * because the region being reregistered is not
			 * currently shared.  Also if original memory region
			 * was bound for IOMMU bypass and the new region can
			 * not use bypass, then a new DMA handle will be
			 * necessary.
			 */
			if (HERMON_MR_REUSE_DMAHDL(mr, bind->bi_flags)) {
				mr->mr_bindinfo.bi_free_dmahdl = 0;
				hermon_mr_mem_unbind(state, &mr->mr_bindinfo);
				dmahdl = mr->mr_bindinfo.bi_dmahdl;
				reuse_dmahdl = 1;
			} else {
				hermon_mr_mem_unbind(state, &mr->mr_bindinfo);
				dmahdl = NULL;
				reuse_dmahdl = 0;
			}
		} else {
			dmahdl = NULL;
			reuse_dmahdl = 0;
		}

		/*
		 * Bind the new memory and determine the mapped addresses.
		 * As described, this routine and hermon_mr_fast_mtt_write()
		 * do the majority of the work for the memory registration
		 * operations.  Note:  When we successfully finish the binding,
		 * we will set the "bi_free_dmahdl" flag to indicate that
		 * even though we may have reused the ddi_dma_handle_t we do
		 * wish it to be freed up at some later time.  Note also that
		 * if we fail, we may need to cleanup the ddi_dma_handle_t.
		 */
		bind->bi_bypass	= bind_type;
		status = hermon_mr_mem_bind(state, bind, dmahdl, sleep, 1);
		if (status != DDI_SUCCESS) {
			if (reuse_dmahdl) {
				ddi_dma_free_handle(&dmahdl);
			}

			/*
			 * Deregister will be called upon returning failure
			 * from this routine. This will ensure that all
			 * current resources get properly freed up.
			 * Unnecessary to attempt to regain software ownership
			 * of the MPT entry as that has already been done
			 * above (in hermon_mr_reregister()).  Also unnecessary
			 * to attempt to unbind the memory.
			 */
			*dereg_level = HERMON_MR_DEREG_NO_HW2SW_MPT_OR_UNBIND;

			status = IBT_INSUFF_RESOURCE;
			goto mrrereghelp_fail;
		}
		if (reuse_dmahdl) {
			bind->bi_free_dmahdl = 1;
		}

		/*
		 * Allocate the new MTT entries resource
		 */
		status = hermon_rsrc_alloc(state, HERMON_MTT, nummtt_needed,
		    sleep, &mtt);
		if (status != DDI_SUCCESS) {
			/*
			 * Deregister will be called upon returning failure
			 * from this routine. This will ensure that all
			 * current resources get properly freed up.
			 * Unnecessary to attempt to regain software ownership
			 * of the MPT entry as that has already been done
			 * above (in hermon_mr_reregister()).  Also unnecessary
			 * to attempt to unbind the memory.
			 *
			 * But we do need to unbind the newly bound memory
			 * before returning.
			 */
			hermon_mr_mem_unbind(state, bind);
			*dereg_level = HERMON_MR_DEREG_NO_HW2SW_MPT_OR_UNBIND;

			status = IBT_INSUFF_RESOURCE;
			goto mrrereghelp_fail;
		}

		/*
		 * Allocate MTT reference count (to track shared memory
		 * regions).  As mentioned elsewhere above, this reference
		 * count resource may never be used on the given memory region,
		 * but if it is ever later registered as a "shared" memory
		 * region then this resource will be necessary.  Note:  This
		 * is only necessary here if the existing memory region is
		 * already being shared (because otherwise we already have
		 * a useable reference count resource).
		 */
		if (HERMON_MTT_IS_SHARED(swrc_old)) {
			status = hermon_rsrc_alloc(state, HERMON_REFCNT, 1,
			    sleep, &mtt_refcnt);
			if (status != DDI_SUCCESS) {
				/*
				 * Deregister will be called upon returning
				 * failure from this routine. This will ensure
				 * that all current resources get properly
				 * freed up.  Unnecessary to attempt to regain
				 * software ownership of the MPT entry as that
				 * has already been done above (in
				 * hermon_mr_reregister()).  Also unnecessary
				 * to attempt to unbind the memory.
				 *
				 * But we need to unbind the newly bound
				 * memory and free up the newly allocated MTT
				 * entries before returning.
				 */
				hermon_mr_mem_unbind(state, bind);
				hermon_rsrc_free(state, &mtt);
				*dereg_level =
				    HERMON_MR_DEREG_NO_HW2SW_MPT_OR_UNBIND;

				status = IBT_INSUFF_RESOURCE;
				goto mrrereghelp_fail;
			}
			swrc_new = (hermon_sw_refcnt_t *)mtt_refcnt->hr_addr;
			_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*swrc_new))
			HERMON_MTT_REFCNT_INIT(swrc_new);
		} else {
			mtt_refcnt = mr->mr_mttrefcntp;
		}

		/*
		 * Using the new mapping and the new MTT resources, write the
		 * updated entries to MTT
		 */
		status = hermon_mr_fast_mtt_write(state, mtt, bind,
		    mtt_pgsize_bits);
		if (status != DDI_SUCCESS) {
			/*
			 * Deregister will be called upon returning failure
			 * from this routine. This will ensure that all
			 * current resources get properly freed up.
			 * Unnecessary to attempt to regain software ownership
			 * of the MPT entry as that has already been done
			 * above (in hermon_mr_reregister()).  Also unnecessary
			 * to attempt to unbind the memory.
			 *
			 * But we need to unbind the newly bound memory,
			 * free up the newly allocated MTT entries, and
			 * (possibly) free the new MTT reference count
			 * resource before returning.
			 */
			if (HERMON_MTT_IS_SHARED(swrc_old)) {
				hermon_rsrc_free(state, &mtt_refcnt);
			}
			hermon_mr_mem_unbind(state, bind);
			hermon_rsrc_free(state, &mtt);
			*dereg_level = HERMON_MR_DEREG_NO_HW2SW_MPT_OR_UNBIND;

			status = IBT_INSUFF_RESOURCE;
			goto mrrereghelp_fail;
		}

		/*
		 * Check if the memory region MTT is shared by any other MRs.
		 * Since the resource may be shared between multiple memory
		 * regions (as a result of a "RegisterSharedMR()" verb) it is
		 * important that we not free up any resources prematurely.
		 */
		if (HERMON_MTT_IS_SHARED(swrc_old)) {
			/* Decrement MTT reference count for "old" region */
			(void) hermon_mtt_refcnt_dec(mr->mr_mttrefcntp);
		} else {
			/* Free up the old MTT entries resource */
			hermon_rsrc_free(state, &mr->mr_mttrsrcp);
		}

		/* Put the updated information into the mrhdl */
		mr->mr_bindinfo	  = *bind;
		mr->mr_logmttpgsz = mtt_pgsize_bits;
		mr->mr_mttrsrcp   = mtt;
		mr->mr_mttrefcntp = mtt_refcnt;
	}

	/*
	 * Calculate and return the updated MTT address (in the DDR address
	 * space).  This will be used by the caller (hermon_mr_reregister) in
	 * the updated MPT entry
	 */
	*mtt_addr = mtt->hr_indx << HERMON_MTT_SIZE_SHIFT;

	return (DDI_SUCCESS);

mrrereghelp_fail:
	return (status);
}


/*
 * hermon_mr_nummtt_needed()
 *    Context: Can be called from interrupt or base context.
 */
/* ARGSUSED */
static uint64_t
hermon_mr_nummtt_needed(hermon_state_t *state, hermon_bind_info_t *bind,
    uint_t *mtt_pgsize_bits)
{
	uint64_t	pg_offset_mask;
	uint64_t	pg_offset, tmp_length;

	/*
	 * For now we specify the page size as 8Kb (the default page size for
	 * the sun4u architecture), or 4Kb for x86.  Figure out optimal page
	 * size by examining the dmacookies
	 */
	*mtt_pgsize_bits = PAGESHIFT;

	pg_offset_mask = ((uint64_t)1 << *mtt_pgsize_bits) - 1;
	pg_offset = bind->bi_addr & pg_offset_mask;
	tmp_length = pg_offset + (bind->bi_len - 1);
	return ((tmp_length >> *mtt_pgsize_bits) + 1);
}


/*
 * hermon_mr_mem_bind()
 *    Context: Can be called from interrupt or base context.
 */
static int
hermon_mr_mem_bind(hermon_state_t *state, hermon_bind_info_t *bind,
    ddi_dma_handle_t dmahdl, uint_t sleep, uint_t is_buffer)
{
	ddi_dma_attr_t	dma_attr;
	int		(*callback)(caddr_t);
	int		status;

	/* bi_type must be set to a meaningful value to get a bind handle */
	ASSERT(bind->bi_type == HERMON_BINDHDL_VADDR ||
	    bind->bi_type == HERMON_BINDHDL_BUF ||
	    bind->bi_type == HERMON_BINDHDL_UBUF);

	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*bind))

	/* Set the callback flag appropriately */
	callback = (sleep == HERMON_SLEEP) ? DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;

	/*
	 * Initialize many of the default DMA attributes.  Then, if we're
	 * bypassing the IOMMU, set the DDI_DMA_FORCE_PHYSICAL flag.
	 */
	if (dmahdl == NULL) {
		hermon_dma_attr_init(state, &dma_attr);
#ifdef	__sparc
		if (bind->bi_bypass == HERMON_BINDMEM_BYPASS) {
			dma_attr.dma_attr_flags = DDI_DMA_FORCE_PHYSICAL;
		}
#endif

		/* set RO if needed - tunable set and 'is_buffer' is non-0 */
		if (is_buffer) {
			if (! (bind->bi_flags & IBT_MR_DISABLE_RO)) {
				if ((bind->bi_type != HERMON_BINDHDL_UBUF) &&
				    (hermon_kernel_data_ro ==
				    HERMON_RO_ENABLED)) {
					dma_attr.dma_attr_flags |=
					    DDI_DMA_RELAXED_ORDERING;
				}
				if (((bind->bi_type == HERMON_BINDHDL_UBUF) &&
				    (hermon_user_data_ro ==
				    HERMON_RO_ENABLED))) {
					dma_attr.dma_attr_flags |=
					    DDI_DMA_RELAXED_ORDERING;
				}
			}
		}

		/* Allocate a DMA handle for the binding */
		status = ddi_dma_alloc_handle(state->hs_dip, &dma_attr,
		    callback, NULL, &bind->bi_dmahdl);
		if (status != DDI_SUCCESS) {
			return (status);
		}
		bind->bi_free_dmahdl = 1;

	} else  {
		bind->bi_dmahdl = dmahdl;
		bind->bi_free_dmahdl = 0;
	}


	/*
	 * Bind the memory to get the PCI mapped addresses.  The decision
	 * to call ddi_dma_addr_bind_handle() or ddi_dma_buf_bind_handle()
	 * is determined by the "bi_type" flag.  Note: if the bind operation
	 * fails then we have to free up the DMA handle and return error.
	 */
	if (bind->bi_type == HERMON_BINDHDL_VADDR) {
		status = ddi_dma_addr_bind_handle(bind->bi_dmahdl, NULL,
		    (caddr_t)(uintptr_t)bind->bi_addr, bind->bi_len,
		    (DDI_DMA_RDWR | DDI_DMA_CONSISTENT), callback, NULL,
		    &bind->bi_dmacookie, &bind->bi_cookiecnt);

	} else {  /* HERMON_BINDHDL_BUF or HERMON_BINDHDL_UBUF */

		status = ddi_dma_buf_bind_handle(bind->bi_dmahdl,
		    bind->bi_buf, (DDI_DMA_RDWR | DDI_DMA_CONSISTENT), callback,
		    NULL, &bind->bi_dmacookie, &bind->bi_cookiecnt);
	}
	if (status != DDI_DMA_MAPPED) {
		if (bind->bi_free_dmahdl != 0) {
			ddi_dma_free_handle(&bind->bi_dmahdl);
		}
		return (status);
	}

	return (DDI_SUCCESS);
}


/*
 * hermon_mr_mem_unbind()
 *    Context: Can be called from interrupt or base context.
 */
static void
hermon_mr_mem_unbind(hermon_state_t *state, hermon_bind_info_t *bind)
{
	int	status;

	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*bind))
	/* there is nothing to unbind for alloc_lkey */
	if (bind->bi_type == HERMON_BINDHDL_LKEY)
		return;

	/*
	 * In case of HERMON_BINDHDL_UBUF, the memory bi_buf points to
	 * is actually allocated by ddi_umem_iosetup() internally, then
	 * it's required to free it here. Reset bi_type to HERMON_BINDHDL_NONE
	 * not to free it again later.
	 */
	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*bind))
	if (bind->bi_type == HERMON_BINDHDL_UBUF) {
		freerbuf(bind->bi_buf);
		bind->bi_type = HERMON_BINDHDL_NONE;
	}
	_NOTE(NOW_VISIBLE_TO_OTHER_THREADS(*bind))

	/*
	 * Unbind the DMA memory for the region
	 *
	 * Note: The only way ddi_dma_unbind_handle() currently
	 * can return an error is if the handle passed in is invalid.
	 * Since this should never happen, we choose to return void
	 * from this function!  If this does return an error, however,
	 * then we print a warning message to the console.
	 */
	status = ddi_dma_unbind_handle(bind->bi_dmahdl);
	if (status != DDI_SUCCESS) {
		HERMON_WARNING(state, "failed to unbind DMA mapping");
		return;
	}

	/* Free up the DMA handle */
	if (bind->bi_free_dmahdl != 0) {
		ddi_dma_free_handle(&bind->bi_dmahdl);
	}
}


/*
 * hermon_mr_fast_mtt_write()
 *    Context: Can be called from interrupt or base context.
 */
static int
hermon_mr_fast_mtt_write(hermon_state_t *state, hermon_rsrc_t *mtt,
    hermon_bind_info_t *bind, uint32_t mtt_pgsize_bits)
{
	hermon_icm_table_t	*icm_table;
	hermon_dma_info_t	*dma_info;
	uint32_t		index1, index2, rindx;
	ddi_dma_cookie_t	dmacookie;
	uint_t			cookie_cnt;
	uint64_t		*mtt_table;
	uint64_t		mtt_entry;
	uint64_t		addr, endaddr;
	uint64_t		pagesize;
	offset_t		i, start;
	uint_t			per_span;
	int			sync_needed;

	/*
	 * XXX According to the PRM, we are to use the WRITE_MTT
	 * command to write out MTTs. Tavor does not do this,
	 * instead taking advantage of direct access to the MTTs,
	 * and knowledge that Mellanox FMR relies on our ability
	 * to write directly to the MTTs without any further
	 * notification to the firmware. Likewise, we will choose
	 * to not use the WRITE_MTT command, but to simply write
	 * out the MTTs.
	 */

	/* Calculate page size from the suggested value passed in */
	pagesize = ((uint64_t)1 << mtt_pgsize_bits);

	/* Walk the "cookie list" and fill in the MTT table entries */
	dmacookie  = bind->bi_dmacookie;
	cookie_cnt = bind->bi_cookiecnt;

	icm_table = &state->hs_icm[HERMON_MTT];
	rindx = mtt->hr_indx;
	hermon_index(index1, index2, rindx, icm_table, i);
	start = i;

	per_span   = icm_table->span;
	dma_info   = icm_table->icm_dma[index1] + index2;
	mtt_table  = (uint64_t *)(uintptr_t)dma_info->vaddr;

	sync_needed = 0;
	while (cookie_cnt-- > 0) {
		addr    = dmacookie.dmac_laddress;
		endaddr = addr + (dmacookie.dmac_size - 1);
		addr    = addr & ~((uint64_t)pagesize - 1);

		while (addr <= endaddr) {

			/*
			 * Fill in the mapped addresses (calculated above) and
			 * set HERMON_MTT_ENTRY_PRESENT flag for each MTT entry.
			 */
			mtt_entry = addr | HERMON_MTT_ENTRY_PRESENT;
			mtt_table[i] = htonll(mtt_entry);
			i++;
			rindx++;

			if (i == per_span) {

				(void) ddi_dma_sync(dma_info->dma_hdl,
				    start * sizeof (hermon_hw_mtt_t),
				    (i - start) * sizeof (hermon_hw_mtt_t),
				    DDI_DMA_SYNC_FORDEV);

				if ((addr + pagesize > endaddr) &&
				    (cookie_cnt == 0))
					return (DDI_SUCCESS);

				hermon_index(index1, index2, rindx, icm_table,
				    i);
				start = i * sizeof (hermon_hw_mtt_t);
				dma_info = icm_table->icm_dma[index1] + index2;
				mtt_table =
				    (uint64_t *)(uintptr_t)dma_info->vaddr;

				sync_needed = 0;
			} else {
				sync_needed = 1;
			}

			addr += pagesize;
			if (addr == 0) {
				static int do_once = 1;
				_NOTE(SCHEME_PROTECTS_DATA("safe sharing",
				    do_once))
				if (do_once) {
					do_once = 0;
					cmn_err(CE_NOTE, "probable error in "
					    "dma_cookie address from caller\n");
				}
				break;
			}
		}

		/*
		 * When we've reached the end of the current DMA cookie,
		 * jump to the next cookie (if there are more)
		 */
		if (cookie_cnt != 0) {
			ddi_dma_nextcookie(bind->bi_dmahdl, &dmacookie);
		}
	}

	/* done all the cookies, now sync the memory for the device */
	if (sync_needed)
		(void) ddi_dma_sync(dma_info->dma_hdl,
		    start * sizeof (hermon_hw_mtt_t),
		    (i - start) * sizeof (hermon_hw_mtt_t),
		    DDI_DMA_SYNC_FORDEV);

	return (DDI_SUCCESS);
}

/*
 * hermon_mr_fast_mtt_write_fmr()
 *    Context: Can be called from interrupt or base context.
 */
/* ARGSUSED */
static int
hermon_mr_fast_mtt_write_fmr(hermon_state_t *state, hermon_rsrc_t *mtt,
    ibt_pmr_attr_t *mem_pattr, uint32_t mtt_pgsize_bits)
{
	hermon_icm_table_t	*icm_table;
	hermon_dma_info_t	*dma_info;
	uint32_t		index1, index2, rindx;
	uint64_t		*mtt_table;
	offset_t		i, j;
	uint_t			per_span;

	icm_table = &state->hs_icm[HERMON_MTT];
	rindx = mtt->hr_indx;
	hermon_index(index1, index2, rindx, icm_table, i);
	per_span   = icm_table->span;
	dma_info   = icm_table->icm_dma[index1] + index2;
	mtt_table  = (uint64_t *)(uintptr_t)dma_info->vaddr;

	/*
	 * Fill in the MTT table entries
	 */
	for (j = 0; j < mem_pattr->pmr_num_buf; j++) {
		mtt_table[i] = mem_pattr->pmr_addr_list[j].p_laddr;
		i++;
		rindx++;
		if (i == per_span) {
			hermon_index(index1, index2, rindx, icm_table, i);
			dma_info = icm_table->icm_dma[index1] + index2;
			mtt_table = (uint64_t *)(uintptr_t)dma_info->vaddr;
		}
	}

	return (DDI_SUCCESS);
}


/*
 * hermon_mtt_refcnt_inc()
 *    Context: Can be called from interrupt or base context.
 */
static uint_t
hermon_mtt_refcnt_inc(hermon_rsrc_t *rsrc)
{
	hermon_sw_refcnt_t *rc;

	rc = (hermon_sw_refcnt_t *)rsrc->hr_addr;
	return (atomic_inc_uint_nv(&rc->swrc_refcnt));
}


/*
 * hermon_mtt_refcnt_dec()
 *    Context: Can be called from interrupt or base context.
 */
static uint_t
hermon_mtt_refcnt_dec(hermon_rsrc_t *rsrc)
{
	hermon_sw_refcnt_t *rc;

	rc = (hermon_sw_refcnt_t *)rsrc->hr_addr;
	return (atomic_dec_uint_nv(&rc->swrc_refcnt));
}