xref: /linux/fs/smb/client/transport.c (revision f14572c203d57492e1d4e5d7851a3b143e083b82)
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2008
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *   Jeremy Allison (jra@samba.org) 2006.
7  *
8  */
9 
10 #include <linux/fs.h>
11 #include <linux/list.h>
12 #include <linux/gfp.h>
13 #include <linux/wait.h>
14 #include <linux/net.h>
15 #include <linux/delay.h>
16 #include <linux/freezer.h>
17 #include <linux/tcp.h>
18 #include <linux/bvec.h>
19 #include <linux/highmem.h>
20 #include <linux/uaccess.h>
21 #include <linux/processor.h>
22 #include <linux/mempool.h>
23 #include <linux/sched/signal.h>
24 #include <linux/task_io_accounting_ops.h>
25 #include <linux/task_work.h>
26 #include "cifsglob.h"
27 #include "cifsproto.h"
28 #include "cifs_debug.h"
29 #include "smb2proto.h"
30 #include "smbdirect.h"
31 #include "compress.h"
32 
33 void
cifs_wake_up_task(struct TCP_Server_Info * server,struct mid_q_entry * mid)34 cifs_wake_up_task(struct TCP_Server_Info *server, struct mid_q_entry *mid)
35 {
36 	if (mid->mid_state == MID_RESPONSE_RECEIVED)
37 		mid->mid_state = MID_RESPONSE_READY;
38 	wake_up_process(mid->callback_data);
39 }
40 
__release_mid(struct TCP_Server_Info * server,struct mid_q_entry * midEntry)41 void __release_mid(struct TCP_Server_Info *server, struct mid_q_entry *midEntry)
42 {
43 #ifdef CONFIG_CIFS_STATS2
44 	__le16 command = server->vals->lock_cmd;
45 	__u16 smb_cmd = le16_to_cpu(midEntry->command);
46 	unsigned long now;
47 	unsigned long roundtrip_time;
48 #endif
49 
50 	if (midEntry->resp_buf && (midEntry->wait_cancelled) &&
51 	    (midEntry->mid_state == MID_RESPONSE_RECEIVED ||
52 	     midEntry->mid_state == MID_RESPONSE_READY) &&
53 	    server->ops->handle_cancelled_mid)
54 		server->ops->handle_cancelled_mid(midEntry, server);
55 
56 	midEntry->mid_state = MID_FREE;
57 	atomic_dec(&mid_count);
58 	if (midEntry->large_buf)
59 		cifs_buf_release(midEntry->resp_buf);
60 	else
61 		cifs_small_buf_release(midEntry->resp_buf);
62 #ifdef CONFIG_CIFS_STATS2
63 	now = jiffies;
64 	if (now < midEntry->when_alloc)
65 		cifs_server_dbg(VFS, "Invalid mid allocation time\n");
66 	roundtrip_time = now - midEntry->when_alloc;
67 
68 	if (smb_cmd < NUMBER_OF_SMB2_COMMANDS) {
69 		if (atomic_read(&server->num_cmds[smb_cmd]) == 0) {
70 			server->slowest_cmd[smb_cmd] = roundtrip_time;
71 			server->fastest_cmd[smb_cmd] = roundtrip_time;
72 		} else {
73 			if (server->slowest_cmd[smb_cmd] < roundtrip_time)
74 				server->slowest_cmd[smb_cmd] = roundtrip_time;
75 			else if (server->fastest_cmd[smb_cmd] > roundtrip_time)
76 				server->fastest_cmd[smb_cmd] = roundtrip_time;
77 		}
78 		cifs_stats_inc(&server->num_cmds[smb_cmd]);
79 		server->time_per_cmd[smb_cmd] += roundtrip_time;
80 	}
81 	/*
82 	 * commands taking longer than one second (default) can be indications
83 	 * that something is wrong, unless it is quite a slow link or a very
84 	 * busy server. Note that this calc is unlikely or impossible to wrap
85 	 * as long as slow_rsp_threshold is not set way above recommended max
86 	 * value (32767 ie 9 hours) and is generally harmless even if wrong
87 	 * since only affects debug counters - so leaving the calc as simple
88 	 * comparison rather than doing multiple conversions and overflow
89 	 * checks
90 	 */
91 	if ((slow_rsp_threshold != 0) &&
92 	    time_after(now, midEntry->when_alloc + (slow_rsp_threshold * HZ)) &&
93 	    (midEntry->command != command)) {
94 		/*
95 		 * smb2slowcmd[NUMBER_OF_SMB2_COMMANDS] counts by command
96 		 * NB: le16_to_cpu returns unsigned so can not be negative below
97 		 */
98 		if (smb_cmd < NUMBER_OF_SMB2_COMMANDS)
99 			cifs_stats_inc(&server->smb2slowcmd[smb_cmd]);
100 
101 		trace_smb3_slow_rsp(smb_cmd, midEntry->mid, midEntry->pid,
102 			       midEntry->when_sent, midEntry->when_received);
103 		if (cifsFYI & CIFS_TIMER) {
104 			pr_debug("slow rsp: cmd %d mid %llu A: 0x%lx S: 0x%lx R: 0x%lx\n",
105 				 midEntry->command, midEntry->mid,
106 				 now - midEntry->when_alloc,
107 				 now - midEntry->when_sent,
108 				 now - midEntry->when_received);
109 		}
110 	}
111 #endif
112 	put_task_struct(midEntry->creator);
113 
114 	mempool_free(midEntry, &cifs_mid_pool);
115 }
116 
117 void
delete_mid(struct TCP_Server_Info * server,struct mid_q_entry * mid)118 delete_mid(struct TCP_Server_Info *server, struct mid_q_entry *mid)
119 {
120 	spin_lock(&server->mid_queue_lock);
121 
122 	if (!mid->deleted_from_q) {
123 		list_del_init(&mid->qhead);
124 		mid->deleted_from_q = true;
125 	}
126 	spin_unlock(&server->mid_queue_lock);
127 
128 	release_mid(server, mid);
129 }
130 
131 /*
132  * smb_send_kvec - send an array of kvecs to the server
133  * @server:	Server to send the data to
134  * @smb_msg:	Message to send
135  * @sent:	amount of data sent on socket is stored here
136  *
137  * Our basic "send data to server" function. Should be called with srv_mutex
138  * held. The caller is responsible for handling the results.
139  */
140 int
smb_send_kvec(struct TCP_Server_Info * server,struct msghdr * smb_msg,size_t * sent)141 smb_send_kvec(struct TCP_Server_Info *server, struct msghdr *smb_msg,
142 	      size_t *sent)
143 {
144 	int rc = 0;
145 	int retries = 0;
146 	struct socket *ssocket = server->ssocket;
147 
148 	*sent = 0;
149 
150 	if (server->noblocksnd)
151 		smb_msg->msg_flags = MSG_DONTWAIT + MSG_NOSIGNAL;
152 	else
153 		smb_msg->msg_flags = MSG_NOSIGNAL;
154 
155 	while (msg_data_left(smb_msg)) {
156 		/*
157 		 * If blocking send, we try 3 times, since each can block
158 		 * for 5 seconds. For nonblocking  we have to try more
159 		 * but wait increasing amounts of time allowing time for
160 		 * socket to clear.  The overall time we wait in either
161 		 * case to send on the socket is about 15 seconds.
162 		 * Similarly we wait for 15 seconds for a response from
163 		 * the server in SendReceive[2] for the server to send
164 		 * a response back for most types of requests (except
165 		 * SMB Write past end of file which can be slow, and
166 		 * blocking lock operations). NFS waits slightly longer
167 		 * than CIFS, but this can make it take longer for
168 		 * nonresponsive servers to be detected and 15 seconds
169 		 * is more than enough time for modern networks to
170 		 * send a packet.  In most cases if we fail to send
171 		 * after the retries we will kill the socket and
172 		 * reconnect which may clear the network problem.
173 		 *
174 		 * Even if regular signals are masked, EINTR might be
175 		 * propagated from sk_stream_wait_memory() to here when
176 		 * TIF_NOTIFY_SIGNAL is used for task work. For example,
177 		 * certain io_uring completions will use that. Treat
178 		 * having EINTR with pending task work the same as EAGAIN
179 		 * to avoid unnecessary reconnects.
180 		 */
181 		rc = sock_sendmsg(ssocket, smb_msg);
182 		if (rc == -EAGAIN || unlikely(rc == -EINTR && task_work_pending(current))) {
183 			retries++;
184 			if (retries >= 14 ||
185 			    (!server->noblocksnd && (retries > 2))) {
186 				cifs_server_dbg(VFS, "sends on sock %p stuck for 15 seconds\n",
187 					 ssocket);
188 				return -EAGAIN;
189 			}
190 			msleep(1 << retries);
191 			continue;
192 		}
193 
194 		if (rc < 0)
195 			return rc;
196 
197 		if (rc == 0) {
198 			/* should never happen, letting socket clear before
199 			   retrying is our only obvious option here */
200 			cifs_server_dbg(VFS, "tcp sent no data\n");
201 			msleep(500);
202 			continue;
203 		}
204 
205 		/* send was at least partially successful */
206 		*sent += rc;
207 		retries = 0; /* in case we get ENOSPC on the next send */
208 	}
209 	return 0;
210 }
211 
212 unsigned long
smb_rqst_len(struct TCP_Server_Info * server,struct smb_rqst * rqst)213 smb_rqst_len(struct TCP_Server_Info *server, struct smb_rqst *rqst)
214 {
215 	unsigned int i;
216 	struct kvec *iov;
217 	int nvec;
218 	unsigned long buflen = 0;
219 
220 	if (!is_smb1(server) && rqst->rq_nvec >= 2 &&
221 	    rqst->rq_iov[0].iov_len == 4) {
222 		iov = &rqst->rq_iov[1];
223 		nvec = rqst->rq_nvec - 1;
224 	} else {
225 		iov = rqst->rq_iov;
226 		nvec = rqst->rq_nvec;
227 	}
228 
229 	/* total up iov array first */
230 	for (i = 0; i < nvec; i++)
231 		buflen += iov[i].iov_len;
232 
233 	buflen += iov_iter_count(&rqst->rq_iter);
234 	return buflen;
235 }
236 
__smb_send_rqst(struct TCP_Server_Info * server,int num_rqst,struct smb_rqst * rqst)237 int __smb_send_rqst(struct TCP_Server_Info *server, int num_rqst,
238 		    struct smb_rqst *rqst)
239 {
240 	int rc;
241 	struct kvec *iov;
242 	int n_vec;
243 	unsigned int send_length = 0;
244 	unsigned int i, j;
245 	sigset_t mask, oldmask;
246 	size_t total_len = 0, sent, size;
247 	struct socket *ssocket = server->ssocket;
248 	struct msghdr smb_msg = {};
249 	__be32 rfc1002_marker;
250 
251 	cifs_in_send_inc(server);
252 	if (cifs_rdma_enabled(server)) {
253 		/* return -EAGAIN when connecting or reconnecting */
254 		rc = -EAGAIN;
255 		if (server->smbd_conn)
256 			rc = smbd_send(server, num_rqst, rqst);
257 		goto smbd_done;
258 	}
259 
260 	rc = -EAGAIN;
261 	if (ssocket == NULL)
262 		goto out;
263 
264 	rc = -ERESTARTSYS;
265 	if (fatal_signal_pending(current)) {
266 		cifs_dbg(FYI, "signal pending before send request\n");
267 		goto out;
268 	}
269 
270 	rc = 0;
271 	/* cork the socket */
272 	tcp_sock_set_cork(ssocket->sk, true);
273 
274 	for (j = 0; j < num_rqst; j++)
275 		send_length += smb_rqst_len(server, &rqst[j]);
276 	rfc1002_marker = cpu_to_be32(send_length);
277 
278 	/*
279 	 * We should not allow signals to interrupt the network send because
280 	 * any partial send will cause session reconnects thus increasing
281 	 * latency of system calls and overload a server with unnecessary
282 	 * requests.
283 	 */
284 
285 	sigfillset(&mask);
286 	sigprocmask(SIG_BLOCK, &mask, &oldmask);
287 
288 	/* Generate a rfc1002 marker */
289 	{
290 		struct kvec hiov = {
291 			.iov_base = &rfc1002_marker,
292 			.iov_len  = 4
293 		};
294 		iov_iter_kvec(&smb_msg.msg_iter, ITER_SOURCE, &hiov, 1, 4);
295 		rc = smb_send_kvec(server, &smb_msg, &sent);
296 		if (rc < 0)
297 			goto unmask;
298 
299 		total_len += sent;
300 		send_length += 4;
301 	}
302 
303 	cifs_dbg(FYI, "Sending smb: smb_len=%u\n", send_length);
304 
305 	for (j = 0; j < num_rqst; j++) {
306 		iov = rqst[j].rq_iov;
307 		n_vec = rqst[j].rq_nvec;
308 
309 		size = 0;
310 		for (i = 0; i < n_vec; i++) {
311 			dump_smb(iov[i].iov_base, iov[i].iov_len);
312 			size += iov[i].iov_len;
313 		}
314 
315 		iov_iter_kvec(&smb_msg.msg_iter, ITER_SOURCE, iov, n_vec, size);
316 
317 		rc = smb_send_kvec(server, &smb_msg, &sent);
318 		if (rc < 0)
319 			goto unmask;
320 
321 		total_len += sent;
322 
323 		if (iov_iter_count(&rqst[j].rq_iter) > 0) {
324 			smb_msg.msg_iter = rqst[j].rq_iter;
325 			rc = smb_send_kvec(server, &smb_msg, &sent);
326 			if (rc < 0)
327 				break;
328 			total_len += sent;
329 		}
330 	}
331 
332 unmask:
333 	sigprocmask(SIG_SETMASK, &oldmask, NULL);
334 
335 	/*
336 	 * If signal is pending but we have already sent the whole packet to
337 	 * the server we need to return success status to allow a corresponding
338 	 * mid entry to be kept in the pending requests queue thus allowing
339 	 * to handle responses from the server by the client.
340 	 *
341 	 * If only part of the packet has been sent there is no need to hide
342 	 * interrupt because the session will be reconnected anyway, so there
343 	 * won't be any response from the server to handle.
344 	 */
345 
346 	if (signal_pending(current) && (total_len != send_length)) {
347 		cifs_dbg(FYI, "signal is pending after attempt to send\n");
348 		rc = -ERESTARTSYS;
349 	}
350 
351 	/* uncork it */
352 	tcp_sock_set_cork(ssocket->sk, false);
353 
354 	if ((total_len > 0) && (total_len != send_length)) {
355 		cifs_dbg(FYI, "partial send (wanted=%u sent=%zu): terminating session\n",
356 			 send_length, total_len);
357 		/*
358 		 * If we have only sent part of an SMB then the next SMB could
359 		 * be taken as the remainder of this one. We need to kill the
360 		 * socket so the server throws away the partial SMB
361 		 */
362 		cifs_signal_cifsd_for_reconnect(server, false);
363 		trace_smb3_partial_send_reconnect(server->current_mid,
364 						  server->conn_id, server->hostname);
365 	}
366 smbd_done:
367 	/*
368 	 * there's hardly any use for the layers above to know the
369 	 * actual error code here. All they should do at this point is
370 	 * to retry the connection and hope it goes away.
371 	 */
372 	if (rc < 0 && rc != -EINTR && rc != -EAGAIN) {
373 		cifs_server_dbg(VFS, "Error %d sending data on socket to server\n",
374 			 rc);
375 		rc = -ECONNABORTED;
376 		cifs_signal_cifsd_for_reconnect(server, false);
377 	} else if (rc > 0)
378 		rc = 0;
379 out:
380 	cifs_in_send_dec(server);
381 	return rc;
382 }
383 
384 static int
smb_send_rqst(struct TCP_Server_Info * server,int num_rqst,struct smb_rqst * rqst,int flags)385 smb_send_rqst(struct TCP_Server_Info *server, int num_rqst,
386 	      struct smb_rqst *rqst, int flags)
387 {
388 	struct smb2_transform_hdr tr_hdr;
389 	struct smb_rqst new_rqst[MAX_COMPOUND] = {};
390 	struct kvec iov = {
391 		.iov_base = &tr_hdr,
392 		.iov_len = sizeof(tr_hdr),
393 	};
394 	int rc;
395 
396 	if (flags & CIFS_COMPRESS_REQ)
397 		return smb_compress(server, &rqst[0], __smb_send_rqst);
398 
399 	if (!(flags & CIFS_TRANSFORM_REQ))
400 		return __smb_send_rqst(server, num_rqst, rqst);
401 
402 	if (WARN_ON_ONCE(num_rqst > MAX_COMPOUND - 1))
403 		return smb_EIO1(smb_eio_trace_tx_max_compound, num_rqst);
404 
405 	if (!server->ops->init_transform_rq) {
406 		cifs_server_dbg(VFS, "Encryption requested but transform callback is missing\n");
407 		return smb_EIO(smb_eio_trace_tx_need_transform);
408 	}
409 
410 	new_rqst[0].rq_iov = &iov;
411 	new_rqst[0].rq_nvec = 1;
412 
413 	rc = server->ops->init_transform_rq(server, num_rqst + 1,
414 					    new_rqst, rqst);
415 	if (!rc) {
416 		rc = __smb_send_rqst(server, num_rqst + 1, new_rqst);
417 		smb3_free_compound_rqst(num_rqst, &new_rqst[1]);
418 	}
419 	return rc;
420 }
421 
422 static int
wait_for_free_credits(struct TCP_Server_Info * server,const int num_credits,const int timeout,const int flags,unsigned int * instance)423 wait_for_free_credits(struct TCP_Server_Info *server, const int num_credits,
424 		      const int timeout, const int flags,
425 		      unsigned int *instance)
426 {
427 	long rc;
428 	int *credits;
429 	int optype;
430 	long int t;
431 	int scredits, in_flight;
432 
433 	if (timeout < 0)
434 		t = MAX_JIFFY_OFFSET;
435 	else
436 		t = msecs_to_jiffies(timeout);
437 
438 	optype = flags & CIFS_OP_MASK;
439 
440 	*instance = 0;
441 
442 	credits = server->ops->get_credits_field(server, optype);
443 	/* Since an echo is already inflight, no need to wait to send another */
444 	if (*credits <= 0 && optype == CIFS_ECHO_OP)
445 		return -EAGAIN;
446 
447 	spin_lock(&server->req_lock);
448 	if ((flags & CIFS_TIMEOUT_MASK) == CIFS_NON_BLOCKING) {
449 		/* oplock breaks must not be held up */
450 		server->in_flight++;
451 		if (server->in_flight > server->max_in_flight)
452 			server->max_in_flight = server->in_flight;
453 		*credits -= 1;
454 		*instance = server->reconnect_instance;
455 		scredits = *credits;
456 		in_flight = server->in_flight;
457 		spin_unlock(&server->req_lock);
458 
459 		trace_smb3_nblk_credits(server->current_mid,
460 				server->conn_id, server->hostname, scredits, -1, in_flight);
461 		cifs_dbg(FYI, "%s: remove %u credits total=%d\n",
462 				__func__, 1, scredits);
463 
464 		return 0;
465 	}
466 
467 	while (1) {
468 		spin_unlock(&server->req_lock);
469 
470 		spin_lock(&server->srv_lock);
471 		if (server->tcpStatus == CifsExiting) {
472 			spin_unlock(&server->srv_lock);
473 			return -ENOENT;
474 		}
475 		spin_unlock(&server->srv_lock);
476 
477 		spin_lock(&server->req_lock);
478 		if (*credits < num_credits) {
479 			scredits = *credits;
480 			spin_unlock(&server->req_lock);
481 
482 			cifs_num_waiters_inc(server);
483 			rc = wait_event_killable_timeout(server->request_q,
484 				has_credits(server, credits, num_credits), t);
485 			cifs_num_waiters_dec(server);
486 			if (!rc) {
487 				spin_lock(&server->req_lock);
488 				scredits = *credits;
489 				in_flight = server->in_flight;
490 				spin_unlock(&server->req_lock);
491 
492 				trace_smb3_credit_timeout(server->current_mid,
493 						server->conn_id, server->hostname, scredits,
494 						num_credits, in_flight);
495 				cifs_server_dbg(VFS, "wait timed out after %d ms\n",
496 						timeout);
497 				return -EBUSY;
498 			}
499 			if (rc == -ERESTARTSYS)
500 				return -ERESTARTSYS;
501 			spin_lock(&server->req_lock);
502 		} else {
503 			/*
504 			 * For normal commands, reserve the last MAX_COMPOUND
505 			 * credits to compound requests.
506 			 * Otherwise these compounds could be permanently
507 			 * starved for credits by single-credit requests.
508 			 *
509 			 * To prevent spinning CPU, block this thread until
510 			 * there are >MAX_COMPOUND credits available.
511 			 * But only do this is we already have a lot of
512 			 * credits in flight to avoid triggering this check
513 			 * for servers that are slow to hand out credits on
514 			 * new sessions.
515 			 */
516 			if (!optype && num_credits == 1 &&
517 			    server->in_flight > 2 * MAX_COMPOUND &&
518 			    *credits <= MAX_COMPOUND) {
519 				spin_unlock(&server->req_lock);
520 
521 				cifs_num_waiters_inc(server);
522 				rc = wait_event_killable_timeout(
523 					server->request_q,
524 					has_credits(server, credits,
525 						    MAX_COMPOUND + 1),
526 					t);
527 				cifs_num_waiters_dec(server);
528 				if (!rc) {
529 					spin_lock(&server->req_lock);
530 					scredits = *credits;
531 					in_flight = server->in_flight;
532 					spin_unlock(&server->req_lock);
533 
534 					trace_smb3_credit_timeout(
535 							server->current_mid,
536 							server->conn_id, server->hostname,
537 							scredits, num_credits, in_flight);
538 					cifs_server_dbg(VFS, "wait timed out after %d ms\n",
539 							timeout);
540 					return -EBUSY;
541 				}
542 				if (rc == -ERESTARTSYS)
543 					return -ERESTARTSYS;
544 				spin_lock(&server->req_lock);
545 				continue;
546 			}
547 
548 			/*
549 			 * Can not count locking commands against total
550 			 * as they are allowed to block on server.
551 			 */
552 
553 			/* update # of requests on the wire to server */
554 			if ((flags & CIFS_TIMEOUT_MASK) != CIFS_BLOCKING_OP) {
555 				*credits -= num_credits;
556 				server->in_flight += num_credits;
557 				if (server->in_flight > server->max_in_flight)
558 					server->max_in_flight = server->in_flight;
559 				*instance = server->reconnect_instance;
560 			}
561 			scredits = *credits;
562 			in_flight = server->in_flight;
563 			spin_unlock(&server->req_lock);
564 
565 			trace_smb3_waitff_credits(server->current_mid,
566 					server->conn_id, server->hostname, scredits,
567 					-(num_credits), in_flight);
568 			cifs_dbg(FYI, "%s: remove %u credits total=%d\n",
569 					__func__, num_credits, scredits);
570 			break;
571 		}
572 	}
573 	return 0;
574 }
575 
wait_for_free_request(struct TCP_Server_Info * server,const int flags,unsigned int * instance)576 int wait_for_free_request(struct TCP_Server_Info *server, const int flags,
577 			  unsigned int *instance)
578 {
579 	return wait_for_free_credits(server, 1, -1, flags,
580 				     instance);
581 }
582 
583 static int
wait_for_compound_request(struct TCP_Server_Info * server,int num,const int flags,unsigned int * instance)584 wait_for_compound_request(struct TCP_Server_Info *server, int num,
585 			  const int flags, unsigned int *instance)
586 {
587 	int *credits;
588 	int scredits, in_flight;
589 
590 	credits = server->ops->get_credits_field(server, flags & CIFS_OP_MASK);
591 
592 	spin_lock(&server->req_lock);
593 	scredits = *credits;
594 	in_flight = server->in_flight;
595 
596 	if (*credits < num) {
597 		/*
598 		 * If the server is tight on resources or just gives us less
599 		 * credits for other reasons (e.g. requests are coming out of
600 		 * order and the server delays granting more credits until it
601 		 * processes a missing mid) and we exhausted most available
602 		 * credits there may be situations when we try to send
603 		 * a compound request but we don't have enough credits. At this
604 		 * point the client needs to decide if it should wait for
605 		 * additional credits or fail the request. If at least one
606 		 * request is in flight there is a high probability that the
607 		 * server will return enough credits to satisfy this compound
608 		 * request.
609 		 *
610 		 * Return immediately if no requests in flight since we will be
611 		 * stuck on waiting for credits.
612 		 */
613 		if (server->in_flight == 0) {
614 			spin_unlock(&server->req_lock);
615 			trace_smb3_insufficient_credits(server->current_mid,
616 					server->conn_id, server->hostname, scredits,
617 					num, in_flight);
618 			cifs_dbg(FYI, "%s: %d requests in flight, needed %d total=%d\n",
619 					__func__, in_flight, num, scredits);
620 			return -EDEADLK;
621 		}
622 	}
623 	spin_unlock(&server->req_lock);
624 
625 	return wait_for_free_credits(server, num, 60000, flags,
626 				     instance);
627 }
628 
629 int
cifs_wait_mtu_credits(struct TCP_Server_Info * server,size_t size,size_t * num,struct cifs_credits * credits)630 cifs_wait_mtu_credits(struct TCP_Server_Info *server, size_t size,
631 		      size_t *num, struct cifs_credits *credits)
632 {
633 	*num = size;
634 	credits->value = 0;
635 	credits->instance = server->reconnect_instance;
636 	return 0;
637 }
638 
wait_for_response(struct TCP_Server_Info * server,struct mid_q_entry * mid)639 int wait_for_response(struct TCP_Server_Info *server, struct mid_q_entry *mid)
640 {
641 	unsigned int sleep_state = TASK_KILLABLE;
642 	int error;
643 
644 	if (mid->sr_flags & CIFS_INTERRUPTIBLE_WAIT)
645 		sleep_state = TASK_INTERRUPTIBLE;
646 
647 	error = wait_event_state(server->response_q,
648 				 mid->mid_state != MID_REQUEST_SUBMITTED &&
649 				 mid->mid_state != MID_RESPONSE_RECEIVED,
650 				 (sleep_state | TASK_FREEZABLE_UNSAFE));
651 	if (error < 0)
652 		return -ERESTARTSYS;
653 
654 	return 0;
655 }
656 
657 /*
658  * Send a SMB request and set the callback function in the mid to handle
659  * the result. Caller is responsible for dealing with timeouts.
660  */
661 int
cifs_call_async(struct TCP_Server_Info * server,struct smb_rqst * rqst,mid_receive_t receive,mid_callback_t callback,mid_handle_t handle,void * cbdata,const int flags,const struct cifs_credits * exist_credits)662 cifs_call_async(struct TCP_Server_Info *server, struct smb_rqst *rqst,
663 		mid_receive_t receive, mid_callback_t callback,
664 		mid_handle_t handle, void *cbdata, const int flags,
665 		const struct cifs_credits *exist_credits)
666 {
667 	int rc;
668 	struct mid_q_entry *mid;
669 	struct cifs_credits credits = { .value = 0, .instance = 0 };
670 	unsigned int instance;
671 	int optype;
672 
673 	optype = flags & CIFS_OP_MASK;
674 
675 	if ((flags & CIFS_HAS_CREDITS) == 0) {
676 		rc = wait_for_free_request(server, flags, &instance);
677 		if (rc)
678 			return rc;
679 		credits.value = 1;
680 		credits.instance = instance;
681 	} else
682 		instance = exist_credits->instance;
683 
684 	cifs_server_lock(server);
685 
686 	/*
687 	 * We can't use credits obtained from the previous session to send this
688 	 * request. Check if there were reconnects after we obtained credits and
689 	 * return -EAGAIN in such cases to let callers handle it.
690 	 */
691 	if (instance != server->reconnect_instance) {
692 		cifs_server_unlock(server);
693 		add_credits_and_wake_if(server, &credits, optype);
694 		return -EAGAIN;
695 	}
696 
697 	mid = server->ops->setup_async_request(server, rqst);
698 	if (IS_ERR(mid)) {
699 		cifs_server_unlock(server);
700 		add_credits_and_wake_if(server, &credits, optype);
701 		return PTR_ERR(mid);
702 	}
703 
704 	mid->sr_flags = flags;
705 	mid->receive = receive;
706 	mid->callback = callback;
707 	mid->callback_data = cbdata;
708 	mid->handle = handle;
709 	mid->mid_state = MID_REQUEST_SUBMITTED;
710 
711 	/* put it on the pending_mid_q */
712 	spin_lock(&server->mid_queue_lock);
713 	list_add_tail(&mid->qhead, &server->pending_mid_q);
714 	spin_unlock(&server->mid_queue_lock);
715 
716 	/*
717 	 * Need to store the time in mid before calling I/O. For call_async,
718 	 * I/O response may come back and free the mid entry on another thread.
719 	 */
720 	cifs_save_when_sent(mid);
721 	rc = smb_send_rqst(server, 1, rqst, flags);
722 
723 	if (rc < 0) {
724 		revert_current_mid(server, mid->credits);
725 		server->sequence_number -= 2;
726 		delete_mid(server, mid);
727 	}
728 
729 	cifs_server_unlock(server);
730 
731 	if (rc == 0)
732 		return 0;
733 
734 	add_credits_and_wake_if(server, &credits, optype);
735 	return rc;
736 }
737 
cifs_sync_mid_result(struct mid_q_entry * mid,struct TCP_Server_Info * server)738 int cifs_sync_mid_result(struct mid_q_entry *mid, struct TCP_Server_Info *server)
739 {
740 	int rc = 0;
741 
742 	cifs_dbg(FYI, "%s: cmd=%d mid=%llu state=%d\n",
743 		 __func__, le16_to_cpu(mid->command), mid->mid, mid->mid_state);
744 
745 	spin_lock(&server->mid_queue_lock);
746 	switch (mid->mid_state) {
747 	case MID_RESPONSE_READY:
748 		spin_unlock(&server->mid_queue_lock);
749 		return rc;
750 	case MID_RETRY_NEEDED:
751 		rc = -EAGAIN;
752 		break;
753 	case MID_RESPONSE_MALFORMED:
754 		rc = smb_EIO(smb_eio_trace_rx_sync_mid_malformed);
755 		break;
756 	case MID_SHUTDOWN:
757 		rc = -EHOSTDOWN;
758 		break;
759 	case MID_RC:
760 		rc = mid->mid_rc;
761 		break;
762 	default:
763 		if (mid->deleted_from_q == false) {
764 			list_del_init(&mid->qhead);
765 			mid->deleted_from_q = true;
766 		}
767 		spin_unlock(&server->mid_queue_lock);
768 		cifs_server_dbg(VFS, "%s: invalid mid state mid=%llu state=%d\n",
769 			 __func__, mid->mid, mid->mid_state);
770 		rc = smb_EIO1(smb_eio_trace_rx_sync_mid_invalid, mid->mid_state);
771 		goto sync_mid_done;
772 	}
773 	spin_unlock(&server->mid_queue_lock);
774 
775 sync_mid_done:
776 	release_mid(server, mid);
777 	return rc;
778 }
779 
780 static void
cifs_compound_callback(struct TCP_Server_Info * server,struct mid_q_entry * mid)781 cifs_compound_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
782 {
783 	struct cifs_credits credits = {
784 		.value = server->ops->get_credits(mid),
785 		.instance = server->reconnect_instance,
786 	};
787 
788 	add_credits(server, &credits, mid->optype);
789 
790 	if (mid->mid_state == MID_RESPONSE_RECEIVED)
791 		mid->mid_state = MID_RESPONSE_READY;
792 }
793 
794 static void
cifs_compound_last_callback(struct TCP_Server_Info * server,struct mid_q_entry * mid)795 cifs_compound_last_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
796 {
797 	cifs_compound_callback(server, mid);
798 	cifs_wake_up_task(server, mid);
799 }
800 
801 static void
cifs_cancelled_callback(struct TCP_Server_Info * server,struct mid_q_entry * mid)802 cifs_cancelled_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
803 {
804 	cifs_compound_callback(server, mid);
805 	release_mid(server, mid);
806 }
807 
808 static void
cifs_mark_compound_mids_cancelled(struct mid_q_entry ** mid,int count)809 cifs_mark_compound_mids_cancelled(struct mid_q_entry **mid, int count)
810 {
811 	int i;
812 
813 	for (i = 0; i < count; i++) {
814 		spin_lock(&mid[i]->mid_lock);
815 		mid[i]->wait_cancelled = true;
816 		spin_unlock(&mid[i]->mid_lock);
817 	}
818 }
819 
820 /*
821  * cifs_pick_channel - pick an eligible channel for network operations
822  *
823  * @ses: session reference
824  *
825  * Select an eligible channel (not terminating and not marked as needing
826  * reconnect), preferring the least loaded one. If no eligible channel is
827  * found, fall back to the primary channel (index 0).
828  *
829  * Return: TCP_Server_Info pointer for the chosen channel, or NULL if @ses is
830  * NULL.
831  */
cifs_pick_channel(struct cifs_ses * ses)832 struct TCP_Server_Info *cifs_pick_channel(struct cifs_ses *ses)
833 {
834 	uint index = 0;
835 	unsigned int min_in_flight = UINT_MAX;
836 	struct TCP_Server_Info *server = NULL;
837 	int i, start, cur;
838 
839 	if (!ses)
840 		return NULL;
841 
842 	spin_lock(&ses->chan_lock);
843 	start = atomic_inc_return(&ses->chan_seq);
844 	for (i = 0; i < ses->chan_count; i++) {
845 		cur = (start + i) % ses->chan_count;
846 		server = ses->chans[cur].server;
847 		if (!server || server->terminate)
848 			continue;
849 
850 		if (CIFS_CHAN_NEEDS_RECONNECT(ses, cur))
851 			continue;
852 
853 		/*
854 		 * strictly speaking, we should pick up req_lock to read
855 		 * server->in_flight. But it shouldn't matter much here if we
856 		 * race while reading this data. The worst that can happen is
857 		 * that we could use a channel that's not least loaded. Avoiding
858 		 * taking the lock could help reduce wait time, which is
859 		 * important for this function
860 		 */
861 		if (server->in_flight < min_in_flight) {
862 			min_in_flight = server->in_flight;
863 			index = cur;
864 		}
865 	}
866 
867 	server = ses->chans[index].server;
868 	spin_unlock(&ses->chan_lock);
869 
870 	return server;
871 }
872 
873 int
compound_send_recv(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server,const int flags,const int num_rqst,struct smb_rqst * rqst,int * resp_buf_type,struct kvec * resp_iov)874 compound_send_recv(const unsigned int xid, struct cifs_ses *ses,
875 		   struct TCP_Server_Info *server,
876 		   const int flags, const int num_rqst, struct smb_rqst *rqst,
877 		   int *resp_buf_type, struct kvec *resp_iov)
878 {
879 	int i, j, optype, rc = 0;
880 	int num_processed = 0;
881 	struct mid_q_entry *mid[MAX_COMPOUND];
882 	bool cancelled_mid[MAX_COMPOUND] = {false};
883 	struct cifs_credits credits[MAX_COMPOUND] = {
884 		{ .value = 0, .instance = 0 }
885 	};
886 	unsigned int instance;
887 	char *buf;
888 
889 	optype = flags & CIFS_OP_MASK;
890 
891 	for (i = 0; i < num_rqst; i++)
892 		resp_buf_type[i] = CIFS_NO_BUFFER;  /* no response buf yet */
893 
894 	if (!ses || !ses->server || !server) {
895 		cifs_dbg(VFS, "Null session\n");
896 		return smb_EIO(smb_eio_trace_null_pointers);
897 	}
898 
899 	spin_lock(&server->srv_lock);
900 	if (server->tcpStatus == CifsExiting) {
901 		spin_unlock(&server->srv_lock);
902 		return -ENOENT;
903 	}
904 	spin_unlock(&server->srv_lock);
905 
906 	/*
907 	 * Wait for all the requests to become available.
908 	 * This approach still leaves the possibility to be stuck waiting for
909 	 * credits if the server doesn't grant credits to the outstanding
910 	 * requests and if the client is completely idle, not generating any
911 	 * other requests.
912 	 * This can be handled by the eventual session reconnect.
913 	 */
914 	rc = wait_for_compound_request(server, num_rqst, flags,
915 				       &instance);
916 	if (rc)
917 		return rc;
918 
919 	for (i = 0; i < num_rqst; i++) {
920 		credits[i].value = 1;
921 		credits[i].instance = instance;
922 	}
923 
924 	/*
925 	 * Make sure that we sign in the same order that we send on this socket
926 	 * and avoid races inside tcp sendmsg code that could cause corruption
927 	 * of smb data.
928 	 */
929 
930 	cifs_server_lock(server);
931 
932 	/*
933 	 * All the parts of the compound chain belong obtained credits from the
934 	 * same session. We can not use credits obtained from the previous
935 	 * session to send this request. Check if there were reconnects after
936 	 * we obtained credits and return -EAGAIN in such cases to let callers
937 	 * handle it.
938 	 */
939 	if (instance != server->reconnect_instance) {
940 		cifs_server_unlock(server);
941 		for (j = 0; j < num_rqst; j++)
942 			add_credits(server, &credits[j], optype);
943 		return -EAGAIN;
944 	}
945 
946 	for (i = 0; i < num_rqst; i++) {
947 		mid[i] = server->ops->setup_request(ses, server, &rqst[i]);
948 		if (IS_ERR(mid[i])) {
949 			revert_current_mid(server, i);
950 			for (j = 0; j < i; j++)
951 				delete_mid(server, mid[j]);
952 			cifs_server_unlock(server);
953 
954 			/* Update # of requests on wire to server */
955 			for (j = 0; j < num_rqst; j++)
956 				add_credits(server, &credits[j], optype);
957 			return PTR_ERR(mid[i]);
958 		}
959 
960 		mid[i]->sr_flags = flags;
961 		mid[i]->mid_state = MID_REQUEST_SUBMITTED;
962 		mid[i]->optype = optype;
963 		/*
964 		 * Invoke callback for every part of the compound chain
965 		 * to calculate credits properly. Wake up this thread only when
966 		 * the last element is received.
967 		 */
968 		if (i < num_rqst - 1)
969 			mid[i]->callback = cifs_compound_callback;
970 		else
971 			mid[i]->callback = cifs_compound_last_callback;
972 	}
973 	rc = smb_send_rqst(server, num_rqst, rqst, flags);
974 
975 	for (i = 0; i < num_rqst; i++)
976 		cifs_save_when_sent(mid[i]);
977 
978 	if (rc < 0) {
979 		revert_current_mid(server, num_rqst);
980 		server->sequence_number -= 2;
981 		for (i = 0; i < num_rqst; i++) {
982 			delete_mid(server, mid[i]);
983 			cancelled_mid[i] = true;
984 		}
985 	}
986 
987 	cifs_server_unlock(server);
988 
989 	/*
990 	 * If sending failed for some reason or it is an oplock break that we
991 	 * will not receive a response to - return credits back
992 	 */
993 	if (rc < 0 || (flags & CIFS_NO_SRV_RSP)) {
994 		for (i = 0; i < num_rqst; i++)
995 			add_credits(server, &credits[i], optype);
996 		goto out;
997 	}
998 
999 	/*
1000 	 * At this point the request is passed to the network stack - we assume
1001 	 * that any credits taken from the server structure on the client have
1002 	 * been spent and we can't return them back. Once we receive responses
1003 	 * we will collect credits granted by the server in the mid callbacks
1004 	 * and add those credits to the server structure.
1005 	 */
1006 
1007 	/*
1008 	 * Compounding is never used during session establish.
1009 	 */
1010 	spin_lock(&ses->ses_lock);
1011 	if ((ses->ses_status == SES_NEW) || (optype & CIFS_NEG_OP) || (optype & CIFS_SESS_OP)) {
1012 		spin_unlock(&ses->ses_lock);
1013 
1014 		if (WARN_ON_ONCE(num_rqst != 1 || !resp_iov))
1015 			return -EINVAL;
1016 
1017 		cifs_server_lock(server);
1018 		smb311_update_preauth_hash(ses, server, rqst[0].rq_iov, rqst[0].rq_nvec);
1019 		cifs_server_unlock(server);
1020 
1021 		spin_lock(&ses->ses_lock);
1022 	}
1023 	spin_unlock(&ses->ses_lock);
1024 
1025 	for (i = 0; i < num_rqst; i++) {
1026 		rc = wait_for_response(server, mid[i]);
1027 		if (rc != 0)
1028 			break;
1029 	}
1030 	if (rc != 0) {
1031 		/*
1032 		 * A completed CREATE earlier in the compound chain may have
1033 		 * opened a remote handle even though a later wait was
1034 		 * interrupted. Mark it cancelled so __release_mid() invokes
1035 		 * the existing unmatched-open cleanup.
1036 		 */
1037 		cifs_mark_compound_mids_cancelled(mid, i);
1038 
1039 		for (; i < num_rqst; i++) {
1040 			cifs_server_dbg(FYI, "Cancelling wait for mid %llu cmd: %d\n",
1041 				 mid[i]->mid, le16_to_cpu(mid[i]->command));
1042 			send_cancel(ses, server, &rqst[i], mid[i], xid);
1043 			spin_lock(&mid[i]->mid_lock);
1044 			mid[i]->wait_cancelled = true;
1045 			if (mid[i]->mid_state == MID_REQUEST_SUBMITTED ||
1046 			    mid[i]->mid_state == MID_RESPONSE_RECEIVED) {
1047 				mid[i]->callback = cifs_cancelled_callback;
1048 				cancelled_mid[i] = true;
1049 				credits[i].value = 0;
1050 			}
1051 			spin_unlock(&mid[i]->mid_lock);
1052 		}
1053 	}
1054 
1055 	for (i = 0; i < num_rqst; i++) {
1056 		if (rc < 0)
1057 			goto out;
1058 
1059 		rc = cifs_sync_mid_result(mid[i], server);
1060 		if (rc != 0) {
1061 			/*
1062 			 * A previous CREATE may have completed before this
1063 			 * response failed. Mark it cancelled so its remote
1064 			 * handle is closed when the mid is released.
1065 			 */
1066 			cifs_mark_compound_mids_cancelled(mid, i);
1067 			/* Keep their response buffers for cancelled-mid cleanup. */
1068 			num_processed = 0;
1069 			/* mark this mid as cancelled to not free it below */
1070 			cancelled_mid[i] = true;
1071 			goto out;
1072 		}
1073 
1074 		if (!mid[i]->resp_buf ||
1075 		    mid[i]->mid_state != MID_RESPONSE_READY) {
1076 			rc = smb_EIO1(smb_eio_trace_rx_mid_unready, mid[i]->mid_state);
1077 			cifs_dbg(FYI, "Bad MID state?\n");
1078 			cifs_mark_compound_mids_cancelled(mid, i);
1079 			num_processed = 0;
1080 			goto out;
1081 		}
1082 
1083 		rc = server->ops->check_receive(mid[i], server,
1084 						flags & CIFS_LOG_ERROR);
1085 		num_processed = i + 1;
1086 	}
1087 
1088 out:
1089 	/*
1090 	 * Delay moving response buffers out of their mids until response
1091 	 * synchronization completes. This lets cancelled-mid cleanup inspect
1092 	 * an earlier CREATE response if a later MID fails.
1093 	 */
1094 	if (resp_iov) {
1095 		for (i = 0; i < num_processed; i++) {
1096 			buf = (char *)mid[i]->resp_buf;
1097 			resp_iov[i].iov_base = buf;
1098 			resp_iov[i].iov_len = mid[i]->resp_buf_size;
1099 
1100 			if (mid[i]->large_buf)
1101 				resp_buf_type[i] = CIFS_LARGE_BUFFER;
1102 			else
1103 				resp_buf_type[i] = CIFS_SMALL_BUFFER;
1104 
1105 			/* mark it so buf will not be freed by delete_mid */
1106 			if ((flags & CIFS_NO_RSP_BUF) == 0)
1107 				mid[i]->resp_buf = NULL;
1108 		}
1109 	}
1110 
1111 	/*
1112 	 * Compounding is never used during session establish.
1113 	 */
1114 	if (num_processed == num_rqst) {
1115 		spin_lock(&ses->ses_lock);
1116 		if ((ses->ses_status == SES_NEW) || (optype & CIFS_NEG_OP) || (optype & CIFS_SESS_OP)) {
1117 			struct kvec iov = {
1118 				.iov_base = resp_iov[0].iov_base,
1119 				.iov_len = resp_iov[0].iov_len
1120 			};
1121 			spin_unlock(&ses->ses_lock);
1122 			cifs_server_lock(server);
1123 			smb311_update_preauth_hash(ses, server, &iov, 1);
1124 			cifs_server_unlock(server);
1125 			spin_lock(&ses->ses_lock);
1126 		}
1127 		spin_unlock(&ses->ses_lock);
1128 	}
1129 
1130 	/*
1131 	 * This will dequeue all mids. After this it is important that the
1132 	 * demultiplex_thread will not process any of these mids any further.
1133 	 * This is prevented above by using a noop callback that will not
1134 	 * wake this thread except for the very last PDU.
1135 	 */
1136 	for (i = 0; i < num_rqst; i++) {
1137 		if (!cancelled_mid[i])
1138 			delete_mid(server, mid[i]);
1139 	}
1140 
1141 	return rc;
1142 }
1143 
1144 int
cifs_send_recv(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server,struct smb_rqst * rqst,int * resp_buf_type,const int flags,struct kvec * resp_iov)1145 cifs_send_recv(const unsigned int xid, struct cifs_ses *ses,
1146 	       struct TCP_Server_Info *server,
1147 	       struct smb_rqst *rqst, int *resp_buf_type, const int flags,
1148 	       struct kvec *resp_iov)
1149 {
1150 	return compound_send_recv(xid, ses, server, flags, 1,
1151 				  rqst, resp_buf_type, resp_iov);
1152 }
1153 
1154 
1155 /*
1156  * Discard any remaining data in the current SMB. To do this, we borrow the
1157  * current bigbuf.
1158  */
1159 int
cifs_discard_remaining_data(struct TCP_Server_Info * server)1160 cifs_discard_remaining_data(struct TCP_Server_Info *server)
1161 {
1162 	unsigned int rfclen = server->pdu_size;
1163 	size_t remaining = rfclen - server->total_read;
1164 
1165 	while (remaining > 0) {
1166 		ssize_t length;
1167 
1168 		length = cifs_discard_from_socket(server,
1169 				min_t(size_t, remaining,
1170 				      CIFSMaxBufSize + MAX_HEADER_SIZE(server)));
1171 		if (length < 0)
1172 			return length;
1173 		server->total_read += length;
1174 		remaining -= length;
1175 	}
1176 
1177 	return 0;
1178 }
1179 
1180 static int
__cifs_readv_discard(struct TCP_Server_Info * server,struct mid_q_entry * mid,bool malformed)1181 __cifs_readv_discard(struct TCP_Server_Info *server, struct mid_q_entry *mid,
1182 		     bool malformed)
1183 {
1184 	int length;
1185 
1186 	length = cifs_discard_remaining_data(server);
1187 	dequeue_mid(server, mid, malformed);
1188 	mid->resp_buf = server->smallbuf;
1189 	server->smallbuf = NULL;
1190 	return length;
1191 }
1192 
1193 static int
cifs_readv_discard(struct TCP_Server_Info * server,struct mid_q_entry * mid)1194 cifs_readv_discard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1195 {
1196 	struct cifs_io_subrequest *rdata = mid->callback_data;
1197 
1198 	return  __cifs_readv_discard(server, mid, rdata->result);
1199 }
1200 
1201 int
cifs_readv_receive(struct TCP_Server_Info * server,struct mid_q_entry * mid)1202 cifs_readv_receive(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1203 {
1204 	int length, len;
1205 	unsigned int data_offset, data_len, end_off;
1206 	struct cifs_io_subrequest *rdata = mid->callback_data;
1207 	char *buf = server->smallbuf;
1208 	unsigned int buflen = server->pdu_size;
1209 	bool use_rdma_mr = false;
1210 
1211 	cifs_dbg(FYI, "%s: mid=%llu offset=%llu bytes=%zu\n",
1212 		 __func__, mid->mid, rdata->subreq.start, rdata->subreq.len);
1213 
1214 	/*
1215 	 * read the rest of READ_RSP header (sans Data array), or whatever we
1216 	 * can if there's not enough data. At this point, we've read down to
1217 	 * the Mid.
1218 	 */
1219 	len = min_t(unsigned int, buflen, server->vals->read_rsp_size) -
1220 							HEADER_SIZE(server) + 1;
1221 
1222 	length = cifs_read_from_socket(server,
1223 				       buf + HEADER_SIZE(server) - 1, len);
1224 	if (length < 0)
1225 		return length;
1226 	server->total_read += length;
1227 
1228 	if (server->ops->is_session_expired &&
1229 	    server->ops->is_session_expired(buf)) {
1230 		cifs_reconnect(server, true);
1231 		return -1;
1232 	}
1233 
1234 	if (server->ops->is_status_pending &&
1235 	    server->ops->is_status_pending(buf, server)) {
1236 		cifs_discard_remaining_data(server);
1237 		return -1;
1238 	}
1239 
1240 	/* set up first two iov for signature check and to get credits */
1241 	rdata->iov[0].iov_base = buf;
1242 	rdata->iov[0].iov_len = server->total_read;
1243 	cifs_dbg(FYI, "0: iov_base=%p iov_len=%zu\n",
1244 		 rdata->iov[0].iov_base, rdata->iov[0].iov_len);
1245 
1246 	/* Was the SMB read successful? */
1247 	rdata->result = server->ops->map_error(buf, false);
1248 	if (rdata->result != 0) {
1249 		cifs_dbg(FYI, "%s: server returned error %d\n",
1250 			 __func__, rdata->result);
1251 		/* normal error on read response */
1252 		return __cifs_readv_discard(server, mid, false);
1253 	}
1254 
1255 	/* Is there enough to get to the rest of the READ_RSP header? */
1256 	if (server->total_read < server->vals->read_rsp_size) {
1257 		cifs_dbg(FYI, "%s: server returned short header. got=%u expected=%zu\n",
1258 			 __func__, server->total_read,
1259 			 server->vals->read_rsp_size);
1260 		rdata->result = smb_EIO2(smb_eio_trace_read_rsp_short,
1261 					 server->total_read, server->vals->read_rsp_size);
1262 		return cifs_readv_discard(server, mid);
1263 	}
1264 
1265 	data_offset = server->ops->read_data_offset(buf);
1266 	if (data_offset < server->total_read) {
1267 		/*
1268 		 * win2k8 sometimes sends an offset of 0 when the read
1269 		 * is beyond the EOF. Treat it as if the data starts just after
1270 		 * the header.
1271 		 */
1272 		cifs_dbg(FYI, "%s: data offset (%u) inside read response header\n",
1273 			 __func__, data_offset);
1274 		data_offset = server->total_read;
1275 	} else if (data_offset > MAX_CIFS_SMALL_BUFFER_SIZE) {
1276 		/* data_offset is beyond the end of smallbuf */
1277 		cifs_dbg(FYI, "%s: data offset (%u) beyond end of smallbuf\n",
1278 			 __func__, data_offset);
1279 		rdata->result = smb_EIO1(smb_eio_trace_read_overlarge,
1280 					 data_offset);
1281 		return cifs_readv_discard(server, mid);
1282 	}
1283 
1284 	cifs_dbg(FYI, "%s: total_read=%u data_offset=%u\n",
1285 		 __func__, server->total_read, data_offset);
1286 
1287 	len = data_offset - server->total_read;
1288 	if (len > 0) {
1289 		/* read any junk before data into the rest of smallbuf */
1290 		length = cifs_read_from_socket(server,
1291 					       buf + server->total_read, len);
1292 		if (length < 0)
1293 			return length;
1294 		server->total_read += length;
1295 		rdata->iov[0].iov_len = server->total_read;
1296 	}
1297 
1298 	/* how much data is in the response? */
1299 #ifdef CONFIG_CIFS_SMB_DIRECT
1300 	use_rdma_mr = rdata->mr;
1301 #endif
1302 	data_len = server->ops->read_data_length(buf, use_rdma_mr);
1303 	if (!use_rdma_mr) {
1304 		if (check_add_overflow(data_offset, data_len, &end_off) ||
1305 		    end_off > buflen) {
1306 			/* data_len is corrupt -- discard frame */
1307 			rdata->result = smb_EIO2(smb_eio_trace_read_rsp_malformed,
1308 						 end_off, buflen);
1309 			return cifs_readv_discard(server, mid);
1310 		}
1311 	}
1312 
1313 #ifdef CONFIG_CIFS_SMB_DIRECT
1314 	if (rdata->mr)
1315 		length = data_len; /* An RDMA read is already done. */
1316 	else
1317 #endif
1318 		length = cifs_read_iter_from_socket(server, &rdata->subreq.io_iter,
1319 						    data_len);
1320 	if (length > 0)
1321 		rdata->got_bytes += length;
1322 	server->total_read += length;
1323 
1324 	cifs_dbg(FYI, "total_read=%u buflen=%u remaining=%u\n",
1325 		 server->total_read, buflen, data_len);
1326 
1327 	/* discard anything left over */
1328 	if (server->total_read < buflen)
1329 		return cifs_readv_discard(server, mid);
1330 
1331 	dequeue_mid(server, mid, false);
1332 	mid->resp_buf = server->smallbuf;
1333 	server->smallbuf = NULL;
1334 	return length;
1335 }
1336