Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
/*-
 * Copyright (c) 2013-2015 Gleb Smirnoff <glebius@FreeBSD.org>
 * Copyright (c) 1998, David Greenman. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_kern_tls.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/capsicum.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/ktls.h>
#include <sys/mutex.h>
#include <sys/malloc.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/mbuf.h>
#include <sys/proc.h>
#include <sys/protosw.h>
#include <sys/rwlock.h>
#include <sys/sf_buf.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/syscallsubr.h>
#include <sys/sysctl.h>
#include <sys/sysproto.h>
#include <sys/vnode.h>

#include <net/vnet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>

#include <security/audit/audit.h>
#include <security/mac/mac_framework.h>

#include <vm/vm.h>
#include <vm/vm_object.h>
#include <vm/vm_pager.h>

static MALLOC_DEFINE(M_SENDFILE, "sendfile", "sendfile dynamic memory");

#define	EXT_FLAG_SYNC		EXT_FLAG_VENDOR1
#define	EXT_FLAG_NOCACHE	EXT_FLAG_VENDOR2
#define	EXT_FLAG_CACHE_LAST	EXT_FLAG_VENDOR3

/*
 * Structure describing a single sendfile(2) I/O, which may consist of
 * several underlying pager I/Os.
 *
 * The syscall context allocates the structure and initializes 'nios'
 * to 1.  As sendfile_swapin() runs through pages and starts asynchronous
 * paging operations, it increments 'nios'.
 *
 * Every I/O completion calls sendfile_iodone(), which decrements the 'nios',
 * and the syscall also calls sendfile_iodone() after allocating all mbufs,
 * linking them and sending to socket.  Whoever reaches zero 'nios' is
 * responsible to * call pru_ready on the socket, to notify it of readyness
 * of the data.
 */
struct sf_io {
	volatile u_int	nios;
	u_int		error;
	int		npages;
	struct socket	*so;
	struct mbuf	*m;
	vm_object_t	obj;
	vm_pindex_t	pindex0;
#ifdef KERN_TLS
	struct ktls_session *tls;
#endif
	vm_page_t	pa[];
};

/*
 * Structure used to track requests with SF_SYNC flag.
 */
struct sendfile_sync {
	struct mtx	mtx;
	struct cv	cv;
	unsigned	count;
	bool		waiting;
};

static void
sendfile_sync_destroy(struct sendfile_sync *sfs)
{
	KASSERT(sfs->count == 0, ("sendfile sync %p still busy", sfs));

	cv_destroy(&sfs->cv);
	mtx_destroy(&sfs->mtx);
	free(sfs, M_SENDFILE);
}

static void
sendfile_sync_signal(struct sendfile_sync *sfs)
{
	mtx_lock(&sfs->mtx);
	KASSERT(sfs->count > 0, ("sendfile sync %p not busy", sfs));
	if (--sfs->count == 0) {
		if (!sfs->waiting) {
			/* The sendfile() waiter was interrupted by a signal. */
			sendfile_sync_destroy(sfs);
			return;
		} else {
			cv_signal(&sfs->cv);
		}
	}
	mtx_unlock(&sfs->mtx);
}

counter_u64_t sfstat[sizeof(struct sfstat) / sizeof(uint64_t)];

static void
sfstat_init(const void *unused)
{

	COUNTER_ARRAY_ALLOC(sfstat, sizeof(struct sfstat) / sizeof(uint64_t),
	    M_WAITOK);
}
SYSINIT(sfstat, SI_SUB_MBUF, SI_ORDER_FIRST, sfstat_init, NULL);

static int
sfstat_sysctl(SYSCTL_HANDLER_ARGS)
{
	struct sfstat s;

	COUNTER_ARRAY_COPY(sfstat, &s, sizeof(s) / sizeof(uint64_t));
	if (req->newptr)
		COUNTER_ARRAY_ZERO(sfstat, sizeof(s) / sizeof(uint64_t));
	return (SYSCTL_OUT(req, &s, sizeof(s)));
}
SYSCTL_PROC(_kern_ipc, OID_AUTO, sfstat,
    CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
    sfstat_sysctl, "I",
    "sendfile statistics");

static void
sendfile_free_mext(struct mbuf *m)
{
	struct sf_buf *sf;
	vm_page_t pg;
	int flags;

	KASSERT(m->m_flags & M_EXT && m->m_ext.ext_type == EXT_SFBUF,
	    ("%s: m %p !M_EXT or !EXT_SFBUF", __func__, m));

	sf = m->m_ext.ext_arg1;
	pg = sf_buf_page(sf);
	flags = (m->m_ext.ext_flags & EXT_FLAG_NOCACHE) != 0 ? VPR_TRYFREE : 0;

	sf_buf_free(sf);
	vm_page_release(pg, flags);

	if (m->m_ext.ext_flags & EXT_FLAG_SYNC) {
		struct sendfile_sync *sfs = m->m_ext.ext_arg2;
		sendfile_sync_signal(sfs);
	}
}

static void
sendfile_free_mext_pg(struct mbuf *m)
{
	vm_page_t pg;
	int flags, i;
	bool cache_last;

	M_ASSERTEXTPG(m);

	cache_last = m->m_ext.ext_flags & EXT_FLAG_CACHE_LAST;
	flags = (m->m_ext.ext_flags & EXT_FLAG_NOCACHE) != 0 ? VPR_TRYFREE : 0;

	for (i = 0; i < m->m_epg_npgs; i++) {
		if (cache_last && i == m->m_epg_npgs - 1)
			flags = 0;
		pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
		vm_page_release(pg, flags);
	}

	if (m->m_ext.ext_flags & EXT_FLAG_SYNC) {
		struct sendfile_sync *sfs = m->m_ext.ext_arg1;
		sendfile_sync_signal(sfs);
	}
}

/*
 * Helper function to calculate how much data to put into page i of n.
 * Only first and last pages are special.
 */
static inline off_t
xfsize(int i, int n, off_t off, off_t len)
{

	if (i == 0)
		return (omin(PAGE_SIZE - (off & PAGE_MASK), len));

	if (i == n - 1 && ((off + len) & PAGE_MASK) > 0)
		return ((off + len) & PAGE_MASK);

	return (PAGE_SIZE);
}

/*
 * Helper function to get offset within object for i page.
 */
static inline vm_ooffset_t
vmoff(int i, off_t off)
{

	if (i == 0)
		return ((vm_ooffset_t)off);

	return (trunc_page(off + i * PAGE_SIZE));
}

/*
 * Helper function used when allocation of a page or sf_buf failed.
 * Pretend as if we don't have enough space, subtract xfsize() of
 * all pages that failed.
 */
static inline void
fixspace(int old, int new, off_t off, int *space)
{

	KASSERT(old > new, ("%s: old %d new %d", __func__, old, new));

	/* Subtract last one. */
	*space -= xfsize(old - 1, old, off, *space);
	old--;

	if (new == old)
		/* There was only one page. */
		return;

	/* Subtract first one. */
	if (new == 0) {
		*space -= xfsize(0, old, off, *space);
		new++;
	}

	/* Rest of pages are full sized. */
	*space -= (old - new) * PAGE_SIZE;

	KASSERT(*space >= 0, ("%s: space went backwards", __func__));
}

/*
 * Wait for all in-flight ios to complete, we must not unwire pages
 * under them.
 */
static void
sendfile_iowait(struct sf_io *sfio, const char *wmesg)
{
	while (atomic_load_int(&sfio->nios) != 1)
		pause(wmesg, 1);
}

/*
 * I/O completion callback.
 */
static void
sendfile_iodone(void *arg, vm_page_t *pa, int count, int error)
{
	struct sf_io *sfio = arg;
	struct socket *so;
	int i;

	if (error != 0)
		sfio->error = error;

	/*
	 * Restore the valid page pointers.  They are already
	 * unbusied, but still wired.
	 *
	 * XXXKIB since pages are only wired, and we do not
	 * own the object lock, other users might have
	 * invalidated them in meantime.  Similarly, after we
	 * unbusied the swapped-in pages, they can become
	 * invalid under us.
	 */
	MPASS(count == 0 || pa[0] != bogus_page);
	for (i = 0; i < count; i++) {
		if (pa[i] == bogus_page) {
			sfio->pa[(pa[0]->pindex - sfio->pindex0) + i] =
			    pa[i] = vm_page_relookup(sfio->obj,
			    pa[0]->pindex + i);
			KASSERT(pa[i] != NULL,
			    ("%s: page %p[%d] disappeared",
			    __func__, pa, i));
		} else {
			vm_page_xunbusy_unchecked(pa[i]);
		}
	}

	if (!refcount_release(&sfio->nios))
		return;

#ifdef INVARIANTS
	for (i = 1; i < sfio->npages; i++) {
		if (sfio->pa[i] == NULL)
			break;
		KASSERT(vm_page_wired(sfio->pa[i]),
		    ("sfio %p page %d %p not wired", sfio, i, sfio->pa[i]));
		if (i == 0)
			continue;
		KASSERT(sfio->pa[0]->object == sfio->pa[i]->object,
		    ("sfio %p page %d %p wrong owner %p %p", sfio, i,
		    sfio->pa[i], sfio->pa[0]->object, sfio->pa[i]->object));
		KASSERT(sfio->pa[0]->pindex + i == sfio->pa[i]->pindex,
		    ("sfio %p page %d %p wrong index %jx %jx", sfio, i,
		    sfio->pa[i], (uintmax_t)sfio->pa[0]->pindex,
		    (uintmax_t)sfio->pa[i]->pindex));
	}
#endif

	vm_object_pip_wakeup(sfio->obj);

	if (sfio->m == NULL) {
		/*
		 * Either I/O operation failed, or we failed to allocate
		 * buffers, or we bailed out on first busy page, or we
		 * succeeded filling the request without any I/Os. Anyway,
		 * pru_send hadn't been executed - nothing had been sent
		 * to the socket yet.
		 */
		MPASS((curthread->td_pflags & TDP_KTHREAD) == 0);
		free(sfio, M_SENDFILE);
		return;
	}

#if defined(KERN_TLS) && defined(INVARIANTS)
	if ((sfio->m->m_flags & M_EXTPG) != 0)
		KASSERT(sfio->tls == sfio->m->m_epg_tls,
		    ("TLS session mismatch"));
	else
		KASSERT(sfio->tls == NULL,
		    ("non-ext_pgs mbuf with TLS session"));
#endif
	so = sfio->so;
	CURVNET_SET(so->so_vnet);
	if (__predict_false(sfio->error)) {
		/*
		 * I/O operation failed.  The state of data in the socket
		 * is now inconsistent, and all what we can do is to tear
		 * it down. Protocol abort method would tear down protocol
		 * state, free all ready mbufs and detach not ready ones.
		 * We will free the mbufs corresponding to this I/O manually.
		 *
		 * The socket would be marked with EIO and made available
		 * for read, so that application receives EIO on next
		 * syscall and eventually closes the socket.
		 */
		so->so_proto->pr_usrreqs->pru_abort(so);
		so->so_error = EIO;

		mb_free_notready(sfio->m, sfio->npages);
#ifdef KERN_TLS
	} else if (sfio->tls != NULL && sfio->tls->mode == TCP_TLS_MODE_SW) {
		/*
		 * I/O operation is complete, but we still need to
		 * encrypt.  We cannot do this in the interrupt thread
		 * of the disk controller, so forward the mbufs to a
		 * different thread.
		 *
		 * Donate the socket reference from sfio to rather
		 * than explicitly invoking soref().
		 */
		ktls_enqueue(sfio->m, so, sfio->npages);
		goto out_with_ref;
#endif
	} else
		(void)(so->so_proto->pr_usrreqs->pru_ready)(so, sfio->m,
		    sfio->npages);

	SOCK_LOCK(so);
	sorele(so);
#ifdef KERN_TLS
out_with_ref:
#endif
	CURVNET_RESTORE();
	free(sfio, M_SENDFILE);
}

/*
 * Iterate through pages vector and request paging for non-valid pages.
 */
static int
sendfile_swapin(vm_object_t obj, struct sf_io *sfio, int *nios, off_t off,
    off_t len, int npages, int rhpages, int flags)
{
	vm_page_t *pa;
	int a, count, count1, grabbed, i, j, rv;

	pa = sfio->pa;
	*nios = 0;
	flags = (flags & SF_NODISKIO) ? VM_ALLOC_NOWAIT : 0;
	sfio->pindex0 = OFF_TO_IDX(off);

	/*
	 * First grab all the pages and wire them.  Note that we grab
	 * only required pages.  Readahead pages are dealt with later.
	 */
	grabbed = vm_page_grab_pages_unlocked(obj, OFF_TO_IDX(off),
	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED | flags, pa, npages);
	if (grabbed < npages) {
		for (int i = grabbed; i < npages; i++)
			pa[i] = NULL;
		npages = grabbed;
		rhpages = 0;
	}

	for (i = 0; i < npages;) {
		/* Skip valid pages. */
		if (vm_page_is_valid(pa[i], vmoff(i, off) & PAGE_MASK,
		    xfsize(i, npages, off, len))) {
			vm_page_xunbusy(pa[i]);
			SFSTAT_INC(sf_pages_valid);
			i++;
			continue;
		}

		/*
		 * Next page is invalid.  Check if it belongs to pager.  It
		 * may not be there, which is a regular situation for shmem
		 * pager.  For vnode pager this happens only in case of
		 * a sparse file.
		 *
		 * Important feature of vm_pager_has_page() is the hint
		 * stored in 'a', about how many pages we can pagein after
		 * this page in a single I/O.
		 */
		VM_OBJECT_RLOCK(obj);
		if (!vm_pager_has_page(obj, OFF_TO_IDX(vmoff(i, off)), NULL,
		    &a)) {
			VM_OBJECT_RUNLOCK(obj);
			pmap_zero_page(pa[i]);
			vm_page_valid(pa[i]);
			MPASS(pa[i]->dirty == 0);
			vm_page_xunbusy(pa[i]);
			i++;
			continue;
		}
		VM_OBJECT_RUNLOCK(obj);

		/*
		 * We want to pagein as many pages as possible, limited only
		 * by the 'a' hint and actual request.
		 */
		count = min(a + 1, npages - i);

		/*
		 * We should not pagein into a valid page because
		 * there might be still unfinished write tracked by
		 * e.g. a buffer, thus we substitute any valid pages
		 * with the bogus one.
		 *
		 * We must not leave around xbusy pages which are not
		 * part of the run passed to vm_pager_getpages(),
		 * otherwise pager might deadlock waiting for the busy
		 * status of the page, e.g. if it constitues the
		 * buffer needed to validate other page.
		 *
		 * First trim the end of the run consisting of the
		 * valid pages, then replace the rest of the valid
		 * with bogus.
		 */
		count1 = count;
		for (j = i + count - 1; j > i; j--) {
			if (vm_page_is_valid(pa[j], vmoff(j, off) & PAGE_MASK,
			    xfsize(j, npages, off, len))) {
				vm_page_xunbusy(pa[j]);
				SFSTAT_INC(sf_pages_valid);
				count--;
			} else {
				break;
			}
		}

		/*
		 * The last page in the run pa[i + count - 1] is
		 * guaranteed to be invalid by the trim above, so it
		 * is not replaced with bogus, thus -1 in the loop end
		 * condition.
		 */
		MPASS(pa[i + count - 1]->valid != VM_PAGE_BITS_ALL);
		for (j = i + 1; j < i + count - 1; j++) {
			if (vm_page_is_valid(pa[j], vmoff(j, off) & PAGE_MASK,
			    xfsize(j, npages, off, len))) {
				vm_page_xunbusy(pa[j]);
				SFSTAT_INC(sf_pages_valid);
				SFSTAT_INC(sf_pages_bogus);
				pa[j] = bogus_page;
			}
		}

		refcount_acquire(&sfio->nios);
		rv = vm_pager_get_pages_async(obj, pa + i, count, NULL,
		    i + count == npages ? &rhpages : NULL,
		    &sendfile_iodone, sfio);
		if (__predict_false(rv != VM_PAGER_OK)) {
			sendfile_iowait(sfio, "sferrio");

			/*
			 * Do remaining pages recovery before returning EIO.
			 * Pages from 0 to npages are wired.
			 * Pages from (i + count1) to npages are busied.
			 */
			for (j = 0; j < npages; j++) {
				if (j >= i + count1)
					vm_page_xunbusy(pa[j]);
				KASSERT(pa[j] != NULL && pa[j] != bogus_page,
				    ("%s: page %p[%d] I/O recovery failure",
				    __func__, pa, j));
				vm_page_unwire(pa[j], PQ_INACTIVE);
			}
			return (EIO);
		}

		SFSTAT_INC(sf_iocnt);
		SFSTAT_ADD(sf_pages_read, count);
		if (i + count == npages)
			SFSTAT_ADD(sf_rhpages_read, rhpages);

		i += count1;
		(*nios)++;
	}

	if (*nios == 0 && npages != 0)
		SFSTAT_INC(sf_noiocnt);

	return (0);
}

static int
sendfile_getobj(struct thread *td, struct file *fp, vm_object_t *obj_res,
    struct vnode **vp_res, struct shmfd **shmfd_res, off_t *obj_size,
    int *bsize)
{
	struct vattr va;
	vm_object_t obj;
	struct vnode *vp;
	struct shmfd *shmfd;
	int error;

	vp = *vp_res = NULL;
	obj = NULL;
	shmfd = *shmfd_res = NULL;
	*bsize = 0;

	/*
	 * The file descriptor must be a regular file and have a
	 * backing VM object.
	 */
	if (fp->f_type == DTYPE_VNODE) {
		vp = fp->f_vnode;
		vn_lock(vp, LK_SHARED | LK_RETRY);
		if (vp->v_type != VREG) {
			error = EINVAL;
			goto out;
		}
		*bsize = vp->v_mount->mnt_stat.f_iosize;
		error = VOP_GETATTR(vp, &va, td->td_ucred);
		if (error != 0)
			goto out;
		*obj_size = va.va_size;
		obj = vp->v_object;
		if (obj == NULL) {
			error = EINVAL;
			goto out;
		}
	} else if (fp->f_type == DTYPE_SHM) {
		error = 0;
		shmfd = fp->f_data;
		obj = shmfd->shm_object;
		*obj_size = shmfd->shm_size;
	} else {
		error = EINVAL;
		goto out;
	}

	VM_OBJECT_WLOCK(obj);
	if ((obj->flags & OBJ_DEAD) != 0) {
		VM_OBJECT_WUNLOCK(obj);
		error = EBADF;
		goto out;
	}

	/*
	 * Temporarily increase the backing VM object's reference
	 * count so that a forced reclamation of its vnode does not
	 * immediately destroy it.
	 */
	vm_object_reference_locked(obj);
	VM_OBJECT_WUNLOCK(obj);
	*obj_res = obj;
	*vp_res = vp;
	*shmfd_res = shmfd;

out:
	if (vp != NULL)
		VOP_UNLOCK(vp);
	return (error);
}

static int
sendfile_getsock(struct thread *td, int s, struct file **sock_fp,
    struct socket **so)
{
	int error;

	*sock_fp = NULL;
	*so = NULL;

	/*
	 * The socket must be a stream socket and connected.
	 */
	error = getsock_cap(td, s, &cap_send_rights,
	    sock_fp, NULL, NULL);
	if (error != 0)
		return (error);
	*so = (*sock_fp)->f_data;
	if ((*so)->so_type != SOCK_STREAM)
		return (EINVAL);
	/*
	 * SCTP one-to-one style sockets currently don't work with
	 * sendfile(). So indicate EINVAL for now.
	 */
	if ((*so)->so_proto->pr_protocol == IPPROTO_SCTP)
		return (EINVAL);
	if (SOLISTENING(*so))
		return (ENOTCONN);
	return (0);
}

int
vn_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
    struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
    struct thread *td)
{
	struct file *sock_fp;
	struct vnode *vp;
	struct vm_object *obj;
	vm_page_t pga;
	struct socket *so;
#ifdef KERN_TLS
	struct ktls_session *tls;
#endif
	struct mbuf *m, *mh, *mhtail;
	struct sf_buf *sf;
	struct shmfd *shmfd;
	struct sendfile_sync *sfs;
	struct vattr va;
	off_t off, sbytes, rem, obj_size;
	int bsize, error, ext_pgs_idx, hdrlen, max_pgs, softerr;
#ifdef KERN_TLS
	int tls_enq_cnt;
#endif
	bool use_ext_pgs;

	obj = NULL;
	so = NULL;
	m = mh = NULL;
	sfs = NULL;
#ifdef KERN_TLS
	tls = NULL;
#endif
	hdrlen = sbytes = 0;
	softerr = 0;
	use_ext_pgs = false;

	error = sendfile_getobj(td, fp, &obj, &vp, &shmfd, &obj_size, &bsize);
	if (error != 0)
		return (error);

	error = sendfile_getsock(td, sockfd, &sock_fp, &so);
	if (error != 0)
		goto out;

#ifdef MAC
	error = mac_socket_check_send(td->td_ucred, so);
	if (error != 0)
		goto out;
#endif

	SFSTAT_INC(sf_syscalls);
	SFSTAT_ADD(sf_rhpages_requested, SF_READAHEAD(flags));

	if (flags & SF_SYNC) {
		sfs = malloc(sizeof(*sfs), M_SENDFILE, M_WAITOK | M_ZERO);
		mtx_init(&sfs->mtx, "sendfile", NULL, MTX_DEF);
		cv_init(&sfs->cv, "sendfile");
		sfs->waiting = true;
	}

	rem = nbytes ? omin(nbytes, obj_size - offset) : obj_size - offset;

	/*
	 * Protect against multiple writers to the socket.
	 *
	 * XXXRW: Historically this has assumed non-interruptibility, so now
	 * we implement that, but possibly shouldn't.
	 */
	(void)sblock(&so->so_snd, SBL_WAIT | SBL_NOINTR);
#ifdef KERN_TLS
	tls = ktls_hold(so->so_snd.sb_tls_info);
#endif

	/*
	 * Loop through the pages of the file, starting with the requested
	 * offset. Get a file page (do I/O if necessary), map the file page
	 * into an sf_buf, attach an mbuf header to the sf_buf, and queue
	 * it on the socket.
	 * This is done in two loops.  The inner loop turns as many pages
	 * as it can, up to available socket buffer space, without blocking
	 * into mbufs to have it bulk delivered into the socket send buffer.
	 * The outer loop checks the state and available space of the socket
	 * and takes care of the overall progress.
	 */
	for (off = offset; rem > 0; ) {
		struct sf_io *sfio;
		vm_page_t *pa;
		struct mbuf *m0, *mtail;
		int nios, space, npages, rhpages;

		mtail = NULL;
		/*
		 * Check the socket state for ongoing connection,
		 * no errors and space in socket buffer.
		 * If space is low allow for the remainder of the
		 * file to be processed if it fits the socket buffer.
		 * Otherwise block in waiting for sufficient space
		 * to proceed, or if the socket is nonblocking, return
		 * to userland with EAGAIN while reporting how far
		 * we've come.
		 * We wait until the socket buffer has significant free
		 * space to do bulk sends.  This makes good use of file
		 * system read ahead and allows packet segmentation
		 * offloading hardware to take over lots of work.  If
		 * we were not careful here we would send off only one
		 * sfbuf at a time.
		 */
		SOCKBUF_LOCK(&so->so_snd);
		if (so->so_snd.sb_lowat < so->so_snd.sb_hiwat / 2)
			so->so_snd.sb_lowat = so->so_snd.sb_hiwat / 2;
retry_space:
		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
			error = EPIPE;
			SOCKBUF_UNLOCK(&so->so_snd);
			goto done;
		} else if (so->so_error) {
			error = so->so_error;
			so->so_error = 0;
			SOCKBUF_UNLOCK(&so->so_snd);
			goto done;
		}
		if ((so->so_state & SS_ISCONNECTED) == 0) {
			SOCKBUF_UNLOCK(&so->so_snd);
			error = ENOTCONN;
			goto done;
		}

		space = sbspace(&so->so_snd);
		if (space < rem &&
		    (space <= 0 ||
		     space < so->so_snd.sb_lowat)) {
			if (so->so_state & SS_NBIO) {
				SOCKBUF_UNLOCK(&so->so_snd);
				error = EAGAIN;
				goto done;
			}
			/*
			 * sbwait drops the lock while sleeping.
			 * When we loop back to retry_space the
			 * state may have changed and we retest
			 * for it.
			 */
			error = sbwait(&so->so_snd);
			/*
			 * An error from sbwait usually indicates that we've
			 * been interrupted by a signal. If we've sent anything
			 * then return bytes sent, otherwise return the error.
			 */
			if (error != 0) {
				SOCKBUF_UNLOCK(&so->so_snd);
				goto done;
			}
			goto retry_space;
		}
		SOCKBUF_UNLOCK(&so->so_snd);

		/*
		 * At the beginning of the first loop check if any headers
		 * are specified and copy them into mbufs.  Reduce space in
		 * the socket buffer by the size of the header mbuf chain.
		 * Clear hdr_uio here and hdrlen at the end of the first loop.
		 */
		if (hdr_uio != NULL && hdr_uio->uio_resid > 0) {
			hdr_uio->uio_td = td;
			hdr_uio->uio_rw = UIO_WRITE;
#ifdef KERN_TLS
			if (tls != NULL)
				mh = m_uiotombuf(hdr_uio, M_WAITOK, space,
				    tls->params.max_frame_len, M_EXTPG);
			else
#endif
				mh = m_uiotombuf(hdr_uio, M_WAITOK,
				    space, 0, 0);
			hdrlen = m_length(mh, &mhtail);
			space -= hdrlen;
			/*
			 * If header consumed all the socket buffer space,
			 * don't waste CPU cycles and jump to the end.
			 */
			if (space == 0) {
				sfio = NULL;
				nios = 0;
				goto prepend_header;
			}
			hdr_uio = NULL;
		}

		if (vp != NULL) {
			error = vn_lock(vp, LK_SHARED);
			if (error != 0)
				goto done;
			error = VOP_GETATTR(vp, &va, td->td_ucred);
			if (error != 0 || off >= va.va_size) {
				VOP_UNLOCK(vp);
				goto done;
			}
			if (va.va_size != obj_size) {
				obj_size = va.va_size;
				rem = nbytes ?
				    omin(nbytes + offset, obj_size) : obj_size;
				rem -= off;
			}
		}

		if (space > rem)
			space = rem;
		else if (space > PAGE_SIZE) {
			/*
			 * Use page boundaries when possible for large
			 * requests.
			 */
			if (off & PAGE_MASK)
				space -= (PAGE_SIZE - (off & PAGE_MASK));
			space = trunc_page(space);
			if (off & PAGE_MASK)
				space += (PAGE_SIZE - (off & PAGE_MASK));
		}

		npages = howmany(space + (off & PAGE_MASK), PAGE_SIZE);

		/*
		 * Calculate maximum allowed number of pages for readahead
		 * at this iteration.  If SF_USER_READAHEAD was set, we don't
		 * do any heuristics and use exactly the value supplied by
		 * application.  Otherwise, we allow readahead up to "rem".
		 * If application wants more, let it be, but there is no
		 * reason to go above MAXPHYS.  Also check against "obj_size",
		 * since vm_pager_has_page() can hint beyond EOF.
		 */
		if (flags & SF_USER_READAHEAD) {
			rhpages = SF_READAHEAD(flags);
		} else {
			rhpages = howmany(rem + (off & PAGE_MASK), PAGE_SIZE) -
			    npages;
			rhpages += SF_READAHEAD(flags);
		}
		rhpages = min(howmany(MAXPHYS, PAGE_SIZE), rhpages);
		rhpages = min(howmany(obj_size - trunc_page(off), PAGE_SIZE) -
		    npages, rhpages);

		sfio = malloc(sizeof(struct sf_io) +
		    npages * sizeof(vm_page_t), M_SENDFILE, M_WAITOK);
		refcount_init(&sfio->nios, 1);
		sfio->obj = obj;
		sfio->error = 0;
		sfio->m = NULL;
#ifdef KERN_TLS
		/*
		 * This doesn't use ktls_hold() because sfio->m will
		 * also have a reference on 'tls' that will be valid
		 * for all of sfio's lifetime.
		 */
		sfio->tls = tls;
#endif
		vm_object_pip_add(obj, 1);
		error = sendfile_swapin(obj, sfio, &nios, off, space, npages,
		    rhpages, flags);
		if (error != 0) {
			if (vp != NULL)
				VOP_UNLOCK(vp);
			sendfile_iodone(sfio, NULL, 0, error);
			goto done;
		}

		/*
		 * Loop and construct maximum sized mbuf chain to be bulk
		 * dumped into socket buffer.
		 */
		pa = sfio->pa;

		/*
		 * Use unmapped mbufs if enabled for TCP.  Unmapped
		 * bufs are restricted to TCP as that is what has been
		 * tested.  In particular, unmapped mbufs have not
		 * been tested with UNIX-domain sockets.
		 *
		 * TLS frames always require unmapped mbufs.
		 */
		if ((mb_use_ext_pgs &&
		    so->so_proto->pr_protocol == IPPROTO_TCP)
#ifdef KERN_TLS
		    || tls != NULL
#endif
		    ) {
			use_ext_pgs = true;
#ifdef KERN_TLS
			if (tls != NULL)
				max_pgs = num_pages(tls->params.max_frame_len);
			else
#endif
				max_pgs = MBUF_PEXT_MAX_PGS;

			/* Start at last index, to wrap on first use. */
			ext_pgs_idx = max_pgs - 1;
		}

		for (int i = 0; i < npages; i++) {
			/*
			 * If a page wasn't grabbed successfully, then
			 * trim the array. Can happen only with SF_NODISKIO.
			 */
			if (pa[i] == NULL) {
				SFSTAT_INC(sf_busy);
				fixspace(npages, i, off, &space);
				npages = i;
				softerr = EBUSY;
				break;
			}
			pga = pa[i];
			if (pga == bogus_page)
				pga = vm_page_relookup(obj, sfio->pindex0 + i);

			if (use_ext_pgs) {
				off_t xfs;

				ext_pgs_idx++;
				if (ext_pgs_idx == max_pgs) {
					m0 = mb_alloc_ext_pgs(M_WAITOK,
					    sendfile_free_mext_pg);

					if (flags & SF_NOCACHE) {
						m0->m_ext.ext_flags |=
						    EXT_FLAG_NOCACHE;

						/*
						 * See comment below regarding
						 * ignoring SF_NOCACHE for the
						 * last page.
						 */
						if ((npages - i <= max_pgs) &&
						    ((off + space) & PAGE_MASK) &&
						    (rem > space || rhpages > 0))
							m0->m_ext.ext_flags |=
							    EXT_FLAG_CACHE_LAST;
					}
					if (sfs != NULL) {
						m0->m_ext.ext_flags |=
						    EXT_FLAG_SYNC;
						m0->m_ext.ext_arg1 = sfs;
						mtx_lock(&sfs->mtx);
						sfs->count++;
						mtx_unlock(&sfs->mtx);
					}
					ext_pgs_idx = 0;

					/* Append to mbuf chain. */
					if (mtail != NULL)
						mtail->m_next = m0;
					else
						m = m0;
					mtail = m0;
					m0->m_epg_1st_off =
					    vmoff(i, off) & PAGE_MASK;
				}
				if (nios) {
					mtail->m_flags |= M_NOTREADY;
					m0->m_epg_nrdy++;
				}

				m0->m_epg_pa[ext_pgs_idx] = VM_PAGE_TO_PHYS(pga);
				m0->m_epg_npgs++;
				xfs = xfsize(i, npages, off, space);
				m0->m_epg_last_len = xfs;
				MBUF_EXT_PGS_ASSERT_SANITY(m0);
				mtail->m_len += xfs;
				mtail->m_ext.ext_size += PAGE_SIZE;
				continue;
			}

			/*
			 * Get a sendfile buf.  When allocating the
			 * first buffer for mbuf chain, we usually
			 * wait as long as necessary, but this wait
			 * can be interrupted.  For consequent
			 * buffers, do not sleep, since several
			 * threads might exhaust the buffers and then
			 * deadlock.
			 */
			sf = sf_buf_alloc(pga,
			    m != NULL ? SFB_NOWAIT : SFB_CATCH);
			if (sf == NULL) {
				SFSTAT_INC(sf_allocfail);
				sendfile_iowait(sfio, "sfnosf");
				for (int j = i; j < npages; j++)
					vm_page_unwire(pa[j], PQ_INACTIVE);
				if (m == NULL)
					softerr = ENOBUFS;
				fixspace(npages, i, off, &space);
				npages = i;
				break;
			}

			m0 = m_get(M_WAITOK, MT_DATA);
			m0->m_ext.ext_buf = (char *)sf_buf_kva(sf);
			m0->m_ext.ext_size = PAGE_SIZE;
			m0->m_ext.ext_arg1 = sf;
			m0->m_ext.ext_type = EXT_SFBUF;
			m0->m_ext.ext_flags = EXT_FLAG_EMBREF;
			m0->m_ext.ext_free = sendfile_free_mext;
			/*
			 * SF_NOCACHE sets the page as being freed upon send.
			 * However, we ignore it for the last page in 'space',
			 * if the page is truncated, and we got more data to
			 * send (rem > space), or if we have readahead
			 * configured (rhpages > 0).
			 */
			if ((flags & SF_NOCACHE) &&
			    (i != npages - 1 ||
			    !((off + space) & PAGE_MASK) ||
			    !(rem > space || rhpages > 0)))
				m0->m_ext.ext_flags |= EXT_FLAG_NOCACHE;
			if (sfs != NULL) {
				m0->m_ext.ext_flags |= EXT_FLAG_SYNC;
				m0->m_ext.ext_arg2 = sfs;
				mtx_lock(&sfs->mtx);
				sfs->count++;
				mtx_unlock(&sfs->mtx);
			}
			m0->m_ext.ext_count = 1;
			m0->m_flags |= (M_EXT | M_RDONLY);
			if (nios)
				m0->m_flags |= M_NOTREADY;
			m0->m_data = (char *)sf_buf_kva(sf) +
			    (vmoff(i, off) & PAGE_MASK);
			m0->m_len = xfsize(i, npages, off, space);

			/* Append to mbuf chain. */
			if (mtail != NULL)
				mtail->m_next = m0;
			else
				m = m0;
			mtail = m0;
		}

		if (vp != NULL)
			VOP_UNLOCK(vp);

		/* Keep track of bytes processed. */
		off += space;
		rem -= space;

		/*
		 * Prepend header, if any.  Save pointer to first mbuf
		 * with a page.
		 */
		if (hdrlen) {
prepend_header:
			m0 = mhtail->m_next = m;
			m = mh;
			mh = NULL;
		} else
			m0 = m;

		if (m == NULL) {
			KASSERT(softerr, ("%s: m NULL, no error", __func__));
			error = softerr;
			sendfile_iodone(sfio, NULL, 0, 0);
			goto done;
		}

		/* Add the buffer chain to the socket buffer. */
		KASSERT(m_length(m, NULL) == space + hdrlen,
		    ("%s: mlen %u space %d hdrlen %d",
		    __func__, m_length(m, NULL), space, hdrlen));

		CURVNET_SET(so->so_vnet);
#ifdef KERN_TLS
		if (tls != NULL)
			ktls_frame(m, tls, &tls_enq_cnt, TLS_RLTYPE_APP);
#endif
		if (nios == 0) {
			/*
			 * If sendfile_swapin() didn't initiate any I/Os,
			 * which happens if all data is cached in VM, or if
			 * the header consumed all socket buffer space and
			 * sfio is NULL, then we can send data right now
			 * without the PRUS_NOTREADY flag.
			 */
			if (sfio != NULL)
				sendfile_iodone(sfio, NULL, 0, 0);
#ifdef KERN_TLS
			if (tls != NULL && tls->mode == TCP_TLS_MODE_SW) {
				error = (*so->so_proto->pr_usrreqs->pru_send)
				    (so, PRUS_NOTREADY, m, NULL, NULL, td);
				soref(so);
				ktls_enqueue(m, so, tls_enq_cnt);
			} else
#endif
				error = (*so->so_proto->pr_usrreqs->pru_send)
				    (so, 0, m, NULL, NULL, td);
		} else {
			sfio->so = so;
			sfio->m = m0;
			sfio->npages = npages;
			soref(so);
			error = (*so->so_proto->pr_usrreqs->pru_send)
			    (so, PRUS_NOTREADY, m, NULL, NULL, td);
			sendfile_iodone(sfio, NULL, 0, 0);
		}
		CURVNET_RESTORE();

		m = NULL;	/* pru_send always consumes */
		if (error)
			goto done;
		sbytes += space + hdrlen;
		if (hdrlen)
			hdrlen = 0;
		if (softerr) {
			error = softerr;
			goto done;
		}
	}

	/*
	 * Send trailers. Wimp out and use writev(2).
	 */
	if (trl_uio != NULL) {
		sbunlock(&so->so_snd);
		error = kern_writev(td, sockfd, trl_uio);
		if (error == 0)
			sbytes += td->td_retval[0];
		goto out;
	}

done:
	sbunlock(&so->so_snd);
out:
	/*
	 * If there was no error we have to clear td->td_retval[0]
	 * because it may have been set by writev.
	 */
	if (error == 0) {
		td->td_retval[0] = 0;
	}
	if (sent != NULL) {
		(*sent) = sbytes;
	}
	if (obj != NULL)
		vm_object_deallocate(obj);
	if (so)
		fdrop(sock_fp, td);
	if (m)
		m_freem(m);
	if (mh)
		m_freem(mh);

	if (sfs != NULL) {
		mtx_lock(&sfs->mtx);
		if (sfs->count != 0)
			error = cv_wait_sig(&sfs->cv, &sfs->mtx);
		if (sfs->count == 0) {
			sendfile_sync_destroy(sfs);
		} else {
			sfs->waiting = false;
			mtx_unlock(&sfs->mtx);
		}
	}
#ifdef KERN_TLS
	if (tls != NULL)
		ktls_free(tls);
#endif

	if (error == ERESTART)
		error = EINTR;

	return (error);
}

static int
sendfile(struct thread *td, struct sendfile_args *uap, int compat)
{
	struct sf_hdtr hdtr;
	struct uio *hdr_uio, *trl_uio;
	struct file *fp;
	off_t sbytes;
	int error;

	/*
	 * File offset must be positive.  If it goes beyond EOF
	 * we send only the header/trailer and no payload data.
	 */
	if (uap->offset < 0)
		return (EINVAL);

	sbytes = 0;
	hdr_uio = trl_uio = NULL;

	if (uap->hdtr != NULL) {
		error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
		if (error != 0)
			goto out;
		if (hdtr.headers != NULL) {
			error = copyinuio(hdtr.headers, hdtr.hdr_cnt,
			    &hdr_uio);
			if (error != 0)
				goto out;
#ifdef COMPAT_FREEBSD4
			/*
			 * In FreeBSD < 5.0 the nbytes to send also included
			 * the header.  If compat is specified subtract the
			 * header size from nbytes.
			 */
			if (compat) {
				if (uap->nbytes > hdr_uio->uio_resid)
					uap->nbytes -= hdr_uio->uio_resid;
				else
					uap->nbytes = 0;
			}
#endif
		}
		if (hdtr.trailers != NULL) {
			error = copyinuio(hdtr.trailers, hdtr.trl_cnt,
			    &trl_uio);
			if (error != 0)
				goto out;
		}
	}

	AUDIT_ARG_FD(uap->fd);

	/*
	 * sendfile(2) can start at any offset within a file so we require
	 * CAP_READ+CAP_SEEK = CAP_PREAD.
	 */
	if ((error = fget_read(td, uap->fd, &cap_pread_rights, &fp)) != 0)
		goto out;

	error = fo_sendfile(fp, uap->s, hdr_uio, trl_uio, uap->offset,
	    uap->nbytes, &sbytes, uap->flags, td);
	fdrop(fp, td);

	if (uap->sbytes != NULL)
		copyout(&sbytes, uap->sbytes, sizeof(off_t));

out:
	free(hdr_uio, M_IOV);
	free(trl_uio, M_IOV);
	return (error);
}

/*
 * sendfile(2)
 * 
 * int sendfile(int fd, int s, off_t offset, size_t nbytes,
 *       struct sf_hdtr *hdtr, off_t *sbytes, int flags)
 * 
 * Send a file specified by 'fd' and starting at 'offset' to a socket
 * specified by 's'. Send only 'nbytes' of the file or until EOF if nbytes ==
 * 0.  Optionally add a header and/or trailer to the socket output.  If
 * specified, write the total number of bytes sent into *sbytes.
 */
int
sys_sendfile(struct thread *td, struct sendfile_args *uap)
{

	return (sendfile(td, uap, 0));
}

#ifdef COMPAT_FREEBSD4
int
freebsd4_sendfile(struct thread *td, struct freebsd4_sendfile_args *uap)
{
	struct sendfile_args args;

	args.fd = uap->fd;
	args.s = uap->s;
	args.offset = uap->offset;
	args.nbytes = uap->nbytes;
	args.hdtr = uap->hdtr;
	args.sbytes = uap->sbytes;
	args.flags = uap->flags;

	return (sendfile(td, &args, 1));
}
#endif /* COMPAT_FREEBSD4 */