xref: /linux/fs/smb/client/smb1ops.c (revision f43fa4b8522ba6038b77e86e5f0d94be35effcde)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  SMB1 (CIFS) version specific operations
4  *
5  *  Copyright (c) 2012, Jeff Layton <jlayton@redhat.com>
6  */
7 
8 #include <linux/pagemap.h>
9 #include <linux/vfs.h>
10 #include <linux/fs_struct.h>
11 #include <uapi/linux/magic.h>
12 #include "cifsglob.h"
13 #include "cifsproto.h"
14 #include "cifs_debug.h"
15 #include "cifs_unicode.h"
16 #include "fs_context.h"
17 #include "nterr.h"
18 #include "smberr.h"
19 #include "reparse.h"
20 
21 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
22 			  struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
23 {
24 	/*
25 	 * If we are reconnecting then should we check to see if
26 	 * any requested capabilities changed locally e.g. via
27 	 * remount but we can not do much about it here
28 	 * if they have (even if we could detect it by the following)
29 	 * Perhaps we could add a backpointer to array of sb from tcon
30 	 * or if we change to make all sb to same share the same
31 	 * sb as NFS - then we only have one backpointer to sb.
32 	 * What if we wanted to mount the server share twice once with
33 	 * and once without posixacls or posix paths?
34 	 */
35 	__u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
36 
37 	if (ctx && ctx->no_linux_ext) {
38 		tcon->fsUnixInfo.Capability = 0;
39 		tcon->unix_ext = 0; /* Unix Extensions disabled */
40 		cifs_dbg(FYI, "Linux protocol extensions disabled\n");
41 		return;
42 	} else if (ctx)
43 		tcon->unix_ext = 1; /* Unix Extensions supported */
44 
45 	if (!tcon->unix_ext) {
46 		cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
47 		return;
48 	}
49 
50 	if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
51 		__u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
52 
53 		cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
54 		/*
55 		 * check for reconnect case in which we do not
56 		 * want to change the mount behavior if we can avoid it
57 		 */
58 		if (ctx == NULL) {
59 			/*
60 			 * turn off POSIX ACL and PATHNAMES if not set
61 			 * originally at mount time
62 			 */
63 			if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
64 				cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
65 			if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
66 				if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
67 					cifs_dbg(VFS, "POSIXPATH support change\n");
68 				cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
69 			} else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
70 				cifs_dbg(VFS, "possible reconnect error\n");
71 				cifs_dbg(VFS, "server disabled POSIX path support\n");
72 			}
73 		}
74 
75 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
76 			cifs_dbg(VFS, "per-share encryption not supported yet\n");
77 
78 		cap &= CIFS_UNIX_CAP_MASK;
79 		if (ctx && ctx->no_psx_acl)
80 			cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
81 		else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
82 			cifs_dbg(FYI, "negotiated posix acl support\n");
83 			if (cifs_sb) {
84 				atomic_or(CIFS_MOUNT_POSIXACL,
85 					  &cifs_sb->mnt_cifs_flags);
86 			}
87 		}
88 
89 		if (ctx && ctx->posix_paths == 0)
90 			cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
91 		else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
92 			cifs_dbg(FYI, "negotiate posix pathnames\n");
93 			if (cifs_sb) {
94 				atomic_or(CIFS_MOUNT_POSIX_PATHS,
95 					  &cifs_sb->mnt_cifs_flags);
96 			}
97 		}
98 
99 		cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
100 #ifdef CONFIG_CIFS_DEBUG2
101 		if (cap & CIFS_UNIX_FCNTL_CAP)
102 			cifs_dbg(FYI, "FCNTL cap\n");
103 		if (cap & CIFS_UNIX_EXTATTR_CAP)
104 			cifs_dbg(FYI, "EXTATTR cap\n");
105 		if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
106 			cifs_dbg(FYI, "POSIX path cap\n");
107 		if (cap & CIFS_UNIX_XATTR_CAP)
108 			cifs_dbg(FYI, "XATTR cap\n");
109 		if (cap & CIFS_UNIX_POSIX_ACL_CAP)
110 			cifs_dbg(FYI, "POSIX ACL cap\n");
111 		if (cap & CIFS_UNIX_LARGE_READ_CAP)
112 			cifs_dbg(FYI, "very large read cap\n");
113 		if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
114 			cifs_dbg(FYI, "very large write cap\n");
115 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
116 			cifs_dbg(FYI, "transport encryption cap\n");
117 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
118 			cifs_dbg(FYI, "mandatory transport encryption cap\n");
119 #endif /* CIFS_DEBUG2 */
120 		if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
121 			if (ctx == NULL)
122 				cifs_dbg(FYI, "resetting capabilities failed\n");
123 			else
124 				cifs_dbg(VFS, "Negotiating Unix capabilities with the server failed. Consider mounting with the Unix Extensions disabled if problems are found by specifying the nounix mount option.\n");
125 
126 		}
127 	}
128 }
129 
130 /*
131  * An NT cancel request header looks just like the original request except:
132  *
133  * The Command is SMB_COM_NT_CANCEL
134  * The WordCount is zeroed out
135  * The ByteCount is zeroed out
136  *
137  * This function mangles an existing request buffer into a
138  * SMB_COM_NT_CANCEL request and then sends it.
139  */
140 static int
141 send_nt_cancel(struct cifs_ses *ses, struct TCP_Server_Info *server,
142 	       struct smb_rqst *rqst, struct mid_q_entry *mid,
143 	       unsigned int xid)
144 {
145 	struct smb_hdr *in_buf = (struct smb_hdr *)rqst->rq_iov[0].iov_base;
146 	struct kvec iov[1];
147 	struct smb_rqst crqst = { .rq_iov = iov, .rq_nvec = 1 };
148 	int rc = 0;
149 
150 	/* +2 for BCC field */
151 	in_buf->Command = SMB_COM_NT_CANCEL;
152 	in_buf->WordCount = 0;
153 	put_bcc(0, in_buf);
154 
155 	iov[0].iov_base = in_buf;
156 	iov[0].iov_len  = sizeof(struct smb_hdr) + 2;
157 
158 	cifs_server_lock(server);
159 	rc = cifs_sign_rqst(&crqst, server, &mid->sequence_number);
160 	if (rc) {
161 		cifs_server_unlock(server);
162 		return rc;
163 	}
164 
165 	/*
166 	 * The response to this call was already factored into the sequence
167 	 * number when the call went out, so we must adjust it back downward
168 	 * after signing here.
169 	 */
170 	--server->sequence_number;
171 	rc = __smb_send_rqst(server, 1, &crqst);
172 	if (rc < 0)
173 		server->sequence_number--;
174 
175 	cifs_server_unlock(server);
176 
177 	cifs_dbg(FYI, "issued NT_CANCEL for mid %u, rc = %d\n",
178 		 get_mid(in_buf), rc);
179 
180 	return rc;
181 }
182 
183 /*
184  * Send a LOCKINGX_CANCEL_LOCK to cause the Windows blocking lock to
185  * return.
186  */
187 static int
188 send_lock_cancel(struct cifs_ses *ses, struct TCP_Server_Info *server,
189 		 struct smb_rqst *rqst, struct mid_q_entry *mid,
190 		 unsigned int xid)
191 {
192 	struct smb_hdr *in_buf = (struct smb_hdr *)rqst->rq_iov[0].iov_base;
193 	unsigned int in_len = rqst->rq_iov[0].iov_len;
194 	LOCK_REQ *pSMB = (LOCK_REQ *)in_buf;
195 	int rc;
196 
197 	/* We just modify the current in_buf to change
198 	 * the type of lock from LOCKING_ANDX_SHARED_LOCK
199 	 * or LOCKING_ANDX_EXCLUSIVE_LOCK to
200 	 * LOCKING_ANDX_CANCEL_LOCK.
201 	 */
202 	pSMB->LockType = LOCKING_ANDX_CANCEL_LOCK|LOCKING_ANDX_LARGE_FILES;
203 	pSMB->Timeout = 0;
204 	pSMB->hdr.Mid = get_next_mid(ses->server);
205 
206 	rc = SendReceive(xid, ses, in_buf, in_len, NULL, NULL, 0);
207 	if (rc == -ENOLCK)
208 		rc = 0; /* If we get back -ENOLCK, it probably means we managed
209 			 * to cancel the lock command before it took effect.
210 			 */
211 	return rc;
212 }
213 
214 static int cifs_send_cancel(struct cifs_ses *ses, struct TCP_Server_Info *server,
215 			    struct smb_rqst *rqst, struct mid_q_entry *mid,
216 			    unsigned int xid)
217 {
218 	if (mid->sr_flags & CIFS_WINDOWS_LOCK)
219 		return send_lock_cancel(ses, server, rqst, mid, xid);
220 	return send_nt_cancel(ses, server, rqst, mid, xid);
221 }
222 
223 static bool
224 cifs_compare_fids(struct cifsFileInfo *ob1, struct cifsFileInfo *ob2)
225 {
226 	return ob1->fid.netfid == ob2->fid.netfid;
227 }
228 
229 static unsigned int
230 cifs_read_data_offset(char *buf)
231 {
232 	READ_RSP *rsp = (READ_RSP *)buf;
233 	return le16_to_cpu(rsp->DataOffset);
234 }
235 
236 static unsigned int
237 cifs_read_data_length(char *buf, bool in_remaining)
238 {
239 	READ_RSP *rsp = (READ_RSP *)buf;
240 	/* It's a bug reading remaining data for SMB1 packets */
241 	WARN_ON(in_remaining);
242 	return (le16_to_cpu(rsp->DataLengthHigh) << 16) +
243 	       le16_to_cpu(rsp->DataLength);
244 }
245 
246 static struct mid_q_entry *
247 cifs_find_mid(struct TCP_Server_Info *server, char *buffer)
248 {
249 	struct smb_hdr *buf = (struct smb_hdr *)buffer;
250 	struct mid_q_entry *mid;
251 
252 	spin_lock(&server->mid_queue_lock);
253 	list_for_each_entry(mid, &server->pending_mid_q, qhead) {
254 		if (compare_mid(mid->mid, buf) &&
255 		    mid->mid_state == MID_REQUEST_SUBMITTED &&
256 		    le16_to_cpu(mid->command) == buf->Command) {
257 			smb_get_mid(mid);
258 			spin_unlock(&server->mid_queue_lock);
259 			return mid;
260 		}
261 	}
262 	spin_unlock(&server->mid_queue_lock);
263 	return NULL;
264 }
265 
266 static void
267 cifs_add_credits(struct TCP_Server_Info *server,
268 		 struct cifs_credits *credits, const int optype)
269 {
270 	spin_lock(&server->req_lock);
271 	server->credits += credits->value;
272 	server->in_flight--;
273 	spin_unlock(&server->req_lock);
274 	wake_up(&server->request_q);
275 }
276 
277 static void
278 cifs_set_credits(struct TCP_Server_Info *server, const int val)
279 {
280 	spin_lock(&server->req_lock);
281 	server->credits = val;
282 	server->oplocks = val > 1 ? enable_oplocks : false;
283 	spin_unlock(&server->req_lock);
284 }
285 
286 static int *
287 cifs_get_credits_field(struct TCP_Server_Info *server, const int optype)
288 {
289 	return &server->credits;
290 }
291 
292 static unsigned int
293 cifs_get_credits(struct mid_q_entry *mid)
294 {
295 	return 1;
296 }
297 
298 /*
299  * Find a free multiplex id (SMB mid). Otherwise there could be
300  * mid collisions which might cause problems, demultiplexing the
301  * wrong response to this request. Multiplex ids could collide if
302  * one of a series requests takes much longer than the others, or
303  * if a very large number of long lived requests (byte range
304  * locks or FindNotify requests) are pending. No more than
305  * 64K-1 requests can be outstanding at one time. If no
306  * mids are available, return zero. A future optimization
307  * could make the combination of mids and uid the key we use
308  * to demultiplex on (rather than mid alone).
309  * In addition to the above check, the cifs demultiplex
310  * code already used the command code as a secondary
311  * check of the frame and if signing is negotiated the
312  * response would be discarded if the mid were the same
313  * but the signature was wrong. Since the mid is not put in the
314  * pending queue until later (when it is about to be dispatched)
315  * we do have to limit the number of outstanding requests
316  * to somewhat less than 64K-1 although it is hard to imagine
317  * so many threads being in the vfs at one time.
318  */
319 static __u64
320 cifs_get_next_mid(struct TCP_Server_Info *server)
321 {
322 	__u64 mid = 0;
323 	__u16 last_mid, cur_mid;
324 	bool collision, reconnect = false;
325 
326 	spin_lock(&server->mid_counter_lock);
327 	/* mid is 16 bit only for CIFS/SMB */
328 	cur_mid = (__u16)((server->current_mid) & 0xffff);
329 	/* we do not want to loop forever */
330 	last_mid = cur_mid;
331 	cur_mid++;
332 	/* avoid 0xFFFF MID */
333 	if (cur_mid == 0xffff)
334 		cur_mid++;
335 
336 	/*
337 	 * This nested loop looks more expensive than it is.
338 	 * In practice the list of pending requests is short,
339 	 * fewer than 50, and the mids are likely to be unique
340 	 * on the first pass through the loop unless some request
341 	 * takes longer than the 64 thousand requests before it
342 	 * (and it would also have to have been a request that
343 	 * did not time out).
344 	 */
345 	while (cur_mid != last_mid) {
346 		struct mid_q_entry *mid_entry;
347 		unsigned int num_mids;
348 
349 		collision = false;
350 		if (cur_mid == 0)
351 			cur_mid++;
352 
353 		num_mids = 0;
354 		spin_lock(&server->mid_queue_lock);
355 		list_for_each_entry(mid_entry, &server->pending_mid_q, qhead) {
356 			++num_mids;
357 			if (mid_entry->mid == cur_mid &&
358 			    mid_entry->mid_state == MID_REQUEST_SUBMITTED) {
359 				/* This mid is in use, try a different one */
360 				collision = true;
361 				break;
362 			}
363 		}
364 		spin_unlock(&server->mid_queue_lock);
365 
366 		/*
367 		 * if we have more than 32k mids in the list, then something
368 		 * is very wrong. Possibly a local user is trying to DoS the
369 		 * box by issuing long-running calls and SIGKILL'ing them. If
370 		 * we get to 2^16 mids then we're in big trouble as this
371 		 * function could loop forever.
372 		 *
373 		 * Go ahead and assign out the mid in this situation, but force
374 		 * an eventual reconnect to clean out the pending_mid_q.
375 		 */
376 		if (num_mids > 32768)
377 			reconnect = true;
378 
379 		if (!collision) {
380 			mid = (__u64)cur_mid;
381 			server->current_mid = mid;
382 			break;
383 		}
384 		cur_mid++;
385 	}
386 	spin_unlock(&server->mid_counter_lock);
387 
388 	if (reconnect) {
389 		cifs_signal_cifsd_for_reconnect(server, false);
390 	}
391 
392 	return mid;
393 }
394 
395 static void
396 cifs_downgrade_oplock(struct TCP_Server_Info *server,
397 		      struct cifsInodeInfo *cinode, __u32 oplock,
398 		      __u16 epoch, bool *purge_cache)
399 {
400 	lockdep_assert_held(&cinode->open_file_lock);
401 	cifs_set_oplock_level(cinode, oplock);
402 }
403 
404 static bool
405 cifs_need_neg(struct TCP_Server_Info *server)
406 {
407 	return server->maxBuf == 0;
408 }
409 
410 static int
411 cifs_negotiate(const unsigned int xid,
412 	       struct cifs_ses *ses,
413 	       struct TCP_Server_Info *server)
414 {
415 	int rc;
416 	rc = CIFSSMBNegotiate(xid, ses, server);
417 	return rc;
418 }
419 
420 static unsigned int
421 smb1_negotiate_wsize(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
422 {
423 	__u64 unix_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
424 	struct TCP_Server_Info *server = tcon->ses->server;
425 	unsigned int wsize;
426 
427 	/* start with specified wsize, or default */
428 	if (ctx->got_wsize)
429 		wsize = ctx->vol_wsize;
430 	else if (tcon->unix_ext && (unix_cap & CIFS_UNIX_LARGE_WRITE_CAP))
431 		wsize = CIFS_DEFAULT_IOSIZE;
432 	else
433 		wsize = CIFS_DEFAULT_NON_POSIX_WSIZE;
434 
435 	/* can server support 24-bit write sizes? (via UNIX extensions) */
436 	if (!tcon->unix_ext || !(unix_cap & CIFS_UNIX_LARGE_WRITE_CAP))
437 		wsize = min_t(unsigned int, wsize, CIFS_MAX_RFC1002_WSIZE);
438 
439 	/*
440 	 * no CAP_LARGE_WRITE_X or is signing enabled without CAP_UNIX set?
441 	 * Limit it to max buffer offered by the server, minus the size of the
442 	 * WRITEX header, not including the 4 byte RFC1001 length.
443 	 */
444 	if (!(server->capabilities & CAP_LARGE_WRITE_X) ||
445 	    (!(server->capabilities & CAP_UNIX) && server->sign))
446 		wsize = min_t(unsigned int, wsize,
447 				server->maxBuf - sizeof(WRITE_REQ));
448 
449 	/* hard limit of CIFS_MAX_WSIZE */
450 	wsize = min_t(unsigned int, wsize, CIFS_MAX_WSIZE);
451 
452 	return wsize;
453 }
454 
455 static unsigned int
456 smb1_negotiate_rsize(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
457 {
458 	__u64 unix_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
459 	struct TCP_Server_Info *server = tcon->ses->server;
460 	unsigned int rsize, defsize;
461 
462 	/*
463 	 * Set default value...
464 	 *
465 	 * HACK alert! Ancient servers have very small buffers. Even though
466 	 * MS-CIFS indicates that servers are only limited by the client's
467 	 * bufsize for reads, testing against win98se shows that it throws
468 	 * INVALID_PARAMETER errors if you try to request too large a read.
469 	 * OS/2 just sends back short reads.
470 	 *
471 	 * If the server doesn't advertise CAP_LARGE_READ_X, then assume that
472 	 * it can't handle a read request larger than its MaxBufferSize either.
473 	 */
474 	if (tcon->unix_ext && (unix_cap & CIFS_UNIX_LARGE_READ_CAP))
475 		defsize = CIFS_DEFAULT_IOSIZE;
476 	else if (server->capabilities & CAP_LARGE_READ_X)
477 		defsize = CIFS_DEFAULT_NON_POSIX_RSIZE;
478 	else
479 		defsize = server->maxBuf - sizeof(READ_RSP);
480 
481 	rsize = ctx->got_rsize ? ctx->vol_rsize : defsize;
482 
483 	/*
484 	 * no CAP_LARGE_READ_X? Then MS-CIFS states that we must limit this to
485 	 * the client's MaxBufferSize.
486 	 */
487 	if (!(server->capabilities & CAP_LARGE_READ_X))
488 		rsize = min_t(unsigned int, CIFSMaxBufSize, rsize);
489 
490 	/* hard limit of CIFS_MAX_RSIZE */
491 	rsize = min_t(unsigned int, rsize, CIFS_MAX_RSIZE);
492 
493 	return rsize;
494 }
495 
496 static void
497 cifs_qfs_tcon(const unsigned int xid, struct cifs_tcon *tcon,
498 	      struct cifs_sb_info *cifs_sb)
499 {
500 	CIFSSMBQFSDeviceInfo(xid, tcon);
501 	CIFSSMBQFSAttributeInfo(xid, tcon);
502 }
503 
504 static int
505 cifs_is_path_accessible(const unsigned int xid, struct cifs_tcon *tcon,
506 			struct cifs_sb_info *cifs_sb, const char *full_path)
507 {
508 	int rc = -EOPNOTSUPP;
509 	FILE_ALL_INFO file_info;
510 
511 	if (tcon->ses->capabilities & CAP_NT_SMBS)
512 		rc = CIFSSMBQPathInfo(xid, tcon, full_path, &file_info,
513 				      0 /* not legacy */, cifs_sb->local_nls,
514 				      cifs_remap(cifs_sb));
515 
516 	/*
517 	 * Non-UNICODE variant of fallback functions below expands wildcards,
518 	 * so they cannot be used for querying paths with wildcard characters.
519 	 * Therefore for such paths returns -ENOENT as they cannot exist.
520 	 */
521 	if ((rc == -EOPNOTSUPP || rc == -EINVAL) &&
522 	    !(tcon->ses->capabilities & CAP_UNICODE) &&
523 	    strpbrk(full_path, "*?\"><"))
524 		rc = -ENOENT;
525 
526 	if (rc == -EOPNOTSUPP || rc == -EINVAL)
527 		rc = SMBQueryInformation(xid, tcon, full_path, &file_info,
528 				cifs_sb->local_nls, cifs_remap(cifs_sb));
529 	return rc;
530 }
531 
532 static int cifs_query_path_info(const unsigned int xid,
533 				struct cifs_tcon *tcon,
534 				struct cifs_sb_info *cifs_sb,
535 				const char *full_path,
536 				struct cifs_open_info_data *data)
537 {
538 	int rc = -EOPNOTSUPP;
539 	FILE_ALL_INFO fi = {};
540 	struct cifs_search_info search_info = {};
541 	bool non_unicode_wildcard = false;
542 
543 	data->reparse_point = false;
544 	data->adjust_tz = false;
545 
546 	/*
547 	 * First try CIFSSMBQPathInfo() function which returns more info
548 	 * (NumberOfLinks) than CIFSFindFirst() fallback function.
549 	 * Some servers like Win9x do not support SMB_QUERY_FILE_ALL_INFO over
550 	 * TRANS2_QUERY_PATH_INFORMATION, but supports it with filehandle over
551 	 * TRANS2_QUERY_FILE_INFORMATION (function CIFSSMBQFileInfo(). But SMB
552 	 * Open command on non-NT servers works only for files, does not work
553 	 * for directories. And moreover Win9x SMB server returns bogus data in
554 	 * SMB_QUERY_FILE_ALL_INFO Attributes field. So for non-NT servers,
555 	 * do not even use CIFSSMBQPathInfo() or CIFSSMBQFileInfo() function.
556 	 */
557 	if (tcon->ses->capabilities & CAP_NT_SMBS)
558 		rc = CIFSSMBQPathInfo(xid, tcon, full_path, &fi, 0 /* not legacy */,
559 				      cifs_sb->local_nls, cifs_remap(cifs_sb));
560 
561 	/*
562 	 * Non-UNICODE variant of fallback functions below expands wildcards,
563 	 * so they cannot be used for querying paths with wildcard characters.
564 	 */
565 	if (rc && !(tcon->ses->capabilities & CAP_UNICODE) && strpbrk(full_path, "*?\"><"))
566 		non_unicode_wildcard = true;
567 
568 	/*
569 	 * Then fallback to CIFSFindFirst() which works also with non-NT servers
570 	 * but does not does not provide NumberOfLinks.
571 	 */
572 	if ((rc == -EOPNOTSUPP || rc == -EINVAL) &&
573 	    !non_unicode_wildcard) {
574 		if (!(tcon->ses->capabilities & tcon->ses->server->vals->cap_nt_find))
575 			search_info.info_level = SMB_FIND_FILE_INFO_STANDARD;
576 		else
577 			search_info.info_level = SMB_FIND_FILE_FULL_DIRECTORY_INFO;
578 		rc = CIFSFindFirst(xid, tcon, full_path, cifs_sb, NULL,
579 				   CIFS_SEARCH_CLOSE_ALWAYS | CIFS_SEARCH_CLOSE_AT_END,
580 				   &search_info, false);
581 		if (rc == 0) {
582 			if (!(tcon->ses->capabilities & tcon->ses->server->vals->cap_nt_find)) {
583 				FIND_FILE_STANDARD_INFO *di;
584 				int offset = tcon->ses->server->timeAdj;
585 
586 				di = (FIND_FILE_STANDARD_INFO *)search_info.srch_entries_start;
587 				fi.CreationTime = cpu_to_le64(cifs_UnixTimeToNT(cnvrtDosUnixTm(
588 						di->CreationDate, di->CreationTime, offset)));
589 				fi.LastAccessTime = cpu_to_le64(cifs_UnixTimeToNT(cnvrtDosUnixTm(
590 						di->LastAccessDate, di->LastAccessTime, offset)));
591 				fi.LastWriteTime = cpu_to_le64(cifs_UnixTimeToNT(cnvrtDosUnixTm(
592 						di->LastWriteDate, di->LastWriteTime, offset)));
593 				fi.ChangeTime = fi.LastWriteTime;
594 				fi.Attributes = cpu_to_le32(le16_to_cpu(di->Attributes));
595 				fi.AllocationSize = cpu_to_le64(le32_to_cpu(di->AllocationSize));
596 				fi.EndOfFile = cpu_to_le64(le32_to_cpu(di->DataSize));
597 			} else {
598 				FILE_FULL_DIRECTORY_INFO *di;
599 
600 				di = (FILE_FULL_DIRECTORY_INFO *)search_info.srch_entries_start;
601 				fi.CreationTime = di->CreationTime;
602 				fi.LastAccessTime = di->LastAccessTime;
603 				fi.LastWriteTime = di->LastWriteTime;
604 				fi.ChangeTime = di->ChangeTime;
605 				fi.Attributes = di->ExtFileAttributes;
606 				fi.AllocationSize = di->AllocationSize;
607 				fi.EndOfFile = di->EndOfFile;
608 				fi.EASize = di->EaSize;
609 			}
610 			fi.NumberOfLinks = cpu_to_le32(1);
611 			fi.DeletePending = 0;
612 			fi.Directory = !!(le32_to_cpu(fi.Attributes) & ATTR_DIRECTORY);
613 			cifs_buf_release(search_info.ntwrk_buf_start);
614 		} else if (!full_path[0]) {
615 			/*
616 			 * CIFSFindFirst() does not work on root path if the
617 			 * root path was exported on the server from the top
618 			 * level path (drive letter).
619 			 */
620 			rc = -EOPNOTSUPP;
621 		}
622 	}
623 
624 	/*
625 	 * If everything failed then fallback to the legacy SMB command
626 	 * SMB_COM_QUERY_INFORMATION which works with all servers, but
627 	 * provide just few information.
628 	 */
629 	if ((rc == -EOPNOTSUPP || rc == -EINVAL) && !non_unicode_wildcard) {
630 		rc = SMBQueryInformation(xid, tcon, full_path, &fi, cifs_sb->local_nls,
631 					 cifs_remap(cifs_sb));
632 		data->adjust_tz = true;
633 	} else if ((rc == -EOPNOTSUPP || rc == -EINVAL) && non_unicode_wildcard) {
634 		/* Path with non-UNICODE wildcard character cannot exist. */
635 		rc = -ENOENT;
636 	}
637 
638 	if (!rc) {
639 		move_cifs_info_to_smb2(&data->fi, &fi);
640 		data->reparse_point = le32_to_cpu(fi.Attributes) & ATTR_REPARSE_POINT;
641 	}
642 
643 #ifdef CONFIG_CIFS_XATTR
644 	/*
645 	 * For non-symlink WSL reparse points it is required to fetch
646 	 * EA $LXMOD which contains in its S_DT part the mandatory file type.
647 	 */
648 	if (!rc && data->reparse_point) {
649 		struct smb2_file_full_ea_info *ea;
650 		u32 next = 0;
651 
652 		ea = (struct smb2_file_full_ea_info *)data->wsl.eas;
653 		do {
654 			ea = (void *)((u8 *)ea + next);
655 			next = le32_to_cpu(ea->next_entry_offset);
656 		} while (next);
657 		if (le16_to_cpu(ea->ea_value_length)) {
658 			ea->next_entry_offset = cpu_to_le32(ALIGN(sizeof(*ea) +
659 						ea->ea_name_length + 1 +
660 						le16_to_cpu(ea->ea_value_length), 4));
661 			ea = (void *)((u8 *)ea + le32_to_cpu(ea->next_entry_offset));
662 		}
663 
664 		rc = CIFSSMBQAllEAs(xid, tcon, full_path, SMB2_WSL_XATTR_MODE,
665 				    &ea->ea_data[SMB2_WSL_XATTR_NAME_LEN + 1],
666 				    SMB2_WSL_XATTR_MODE_SIZE, cifs_sb);
667 		if (rc == SMB2_WSL_XATTR_MODE_SIZE) {
668 			ea->next_entry_offset = cpu_to_le32(0);
669 			ea->flags = 0;
670 			ea->ea_name_length = SMB2_WSL_XATTR_NAME_LEN;
671 			ea->ea_value_length = cpu_to_le16(SMB2_WSL_XATTR_MODE_SIZE);
672 			memcpy(&ea->ea_data[0], SMB2_WSL_XATTR_MODE, SMB2_WSL_XATTR_NAME_LEN + 1);
673 			data->wsl.eas_len += ALIGN(sizeof(*ea) + SMB2_WSL_XATTR_NAME_LEN + 1 +
674 						   SMB2_WSL_XATTR_MODE_SIZE, 4);
675 			rc = 0;
676 		} else if (rc >= 0) {
677 			/* It is an error if EA $LXMOD has wrong size. */
678 			rc = -EINVAL;
679 		} else {
680 			/*
681 			 * In all other cases ignore error if fetching
682 			 * of EA $LXMOD failed. It is needed only for
683 			 * non-symlink WSL reparse points and wsl_to_fattr()
684 			 * handle the case when EA is missing.
685 			 */
686 			rc = 0;
687 		}
688 	}
689 
690 	/*
691 	 * For WSL CHR and BLK reparse points it is required to fetch
692 	 * EA $LXDEV which contains major and minor device numbers.
693 	 */
694 	if (!rc && data->reparse_point) {
695 		struct smb2_file_full_ea_info *ea;
696 		u32 next = 0;
697 
698 		ea = (struct smb2_file_full_ea_info *)data->wsl.eas;
699 		do {
700 			ea = (void *)((u8 *)ea + next);
701 			next = le32_to_cpu(ea->next_entry_offset);
702 		} while (next);
703 		if (le16_to_cpu(ea->ea_value_length)) {
704 			ea->next_entry_offset = cpu_to_le32(ALIGN(sizeof(*ea) +
705 						ea->ea_name_length + 1 +
706 						le16_to_cpu(ea->ea_value_length), 4));
707 			ea = (void *)((u8 *)ea + le32_to_cpu(ea->next_entry_offset));
708 		}
709 
710 		rc = CIFSSMBQAllEAs(xid, tcon, full_path, SMB2_WSL_XATTR_DEV,
711 				    &ea->ea_data[SMB2_WSL_XATTR_NAME_LEN + 1],
712 				    SMB2_WSL_XATTR_DEV_SIZE, cifs_sb);
713 		if (rc == SMB2_WSL_XATTR_DEV_SIZE) {
714 			ea->next_entry_offset = cpu_to_le32(0);
715 			ea->flags = 0;
716 			ea->ea_name_length = SMB2_WSL_XATTR_NAME_LEN;
717 			ea->ea_value_length = cpu_to_le16(SMB2_WSL_XATTR_DEV_SIZE);
718 			memcpy(&ea->ea_data[0], SMB2_WSL_XATTR_DEV, SMB2_WSL_XATTR_NAME_LEN + 1);
719 			data->wsl.eas_len += ALIGN(sizeof(*ea) + SMB2_WSL_XATTR_NAME_LEN + 1 +
720 						   SMB2_WSL_XATTR_MODE_SIZE, 4);
721 			rc = 0;
722 		} else if (rc >= 0) {
723 			/* It is an error if EA $LXDEV has wrong size. */
724 			rc = -EINVAL;
725 		} else {
726 			/*
727 			 * In all other cases ignore error if fetching
728 			 * of EA $LXDEV failed. It is needed only for
729 			 * WSL CHR and BLK reparse points and wsl_to_fattr()
730 			 * handle the case when EA is missing.
731 			 */
732 			rc = 0;
733 		}
734 	}
735 #endif
736 
737 	return rc;
738 }
739 
740 static int cifs_get_srv_inum(const unsigned int xid, struct cifs_tcon *tcon,
741 			     struct cifs_sb_info *cifs_sb, const char *full_path,
742 			     u64 *uniqueid, struct cifs_open_info_data *unused)
743 {
744 	/*
745 	 * We can not use the IndexNumber field by default from Windows or
746 	 * Samba (in ALL_INFO buf) but we can request it explicitly. The SNIA
747 	 * CIFS spec claims that this value is unique within the scope of a
748 	 * share, and the windows docs hint that it's actually unique
749 	 * per-machine.
750 	 *
751 	 * There may be higher info levels that work but are there Windows
752 	 * server or network appliances for which IndexNumber field is not
753 	 * guaranteed unique?
754 	 *
755 	 * CIFSGetSrvInodeNumber() uses SMB_QUERY_FILE_INTERNAL_INFO
756 	 * which is SMB PASSTHROUGH level therefore check for capability.
757 	 * Note that this function can be called with tcon == NULL.
758 	 */
759 	if (tcon && !(tcon->ses->capabilities & CAP_INFOLEVEL_PASSTHRU))
760 		return -EOPNOTSUPP;
761 	return CIFSGetSrvInodeNumber(xid, tcon, full_path, uniqueid,
762 				     cifs_sb->local_nls,
763 				     cifs_remap(cifs_sb));
764 }
765 
766 static int cifs_query_file_info(const unsigned int xid, struct cifs_tcon *tcon,
767 				struct cifsFileInfo *cfile, struct cifs_open_info_data *data)
768 {
769 	int rc;
770 	FILE_ALL_INFO fi = {};
771 
772 	/*
773 	 * CIFSSMBQFileInfo() for non-NT servers returns bogus data in
774 	 * Attributes fields. So do not use this command for non-NT servers.
775 	 */
776 	if (!(tcon->ses->capabilities & CAP_NT_SMBS))
777 		return -EOPNOTSUPP;
778 
779 	if (cfile->symlink_target) {
780 		data->symlink_target = kstrdup(cfile->symlink_target, GFP_KERNEL);
781 		if (!data->symlink_target)
782 			return -ENOMEM;
783 	}
784 
785 	rc = CIFSSMBQFileInfo(xid, tcon, cfile->fid.netfid, &fi);
786 	if (!rc)
787 		move_cifs_info_to_smb2(&data->fi, &fi);
788 	return rc;
789 }
790 
791 static void
792 cifs_clear_stats(struct cifs_tcon *tcon)
793 {
794 	atomic_set(&tcon->stats.cifs_stats.num_writes, 0);
795 	atomic_set(&tcon->stats.cifs_stats.num_reads, 0);
796 	atomic_set(&tcon->stats.cifs_stats.num_flushes, 0);
797 	atomic_set(&tcon->stats.cifs_stats.num_oplock_brks, 0);
798 	atomic_set(&tcon->stats.cifs_stats.num_opens, 0);
799 	atomic_set(&tcon->stats.cifs_stats.num_posixopens, 0);
800 	atomic_set(&tcon->stats.cifs_stats.num_posixmkdirs, 0);
801 	atomic_set(&tcon->stats.cifs_stats.num_closes, 0);
802 	atomic_set(&tcon->stats.cifs_stats.num_deletes, 0);
803 	atomic_set(&tcon->stats.cifs_stats.num_mkdirs, 0);
804 	atomic_set(&tcon->stats.cifs_stats.num_rmdirs, 0);
805 	atomic_set(&tcon->stats.cifs_stats.num_renames, 0);
806 	atomic_set(&tcon->stats.cifs_stats.num_t2renames, 0);
807 	atomic_set(&tcon->stats.cifs_stats.num_ffirst, 0);
808 	atomic_set(&tcon->stats.cifs_stats.num_fnext, 0);
809 	atomic_set(&tcon->stats.cifs_stats.num_fclose, 0);
810 	atomic_set(&tcon->stats.cifs_stats.num_hardlinks, 0);
811 	atomic_set(&tcon->stats.cifs_stats.num_symlinks, 0);
812 	atomic_set(&tcon->stats.cifs_stats.num_locks, 0);
813 	atomic_set(&tcon->stats.cifs_stats.num_acl_get, 0);
814 	atomic_set(&tcon->stats.cifs_stats.num_acl_set, 0);
815 }
816 
817 static void
818 cifs_print_stats(struct seq_file *m, struct cifs_tcon *tcon)
819 {
820 	seq_printf(m, " Oplocks breaks: %d",
821 		   atomic_read(&tcon->stats.cifs_stats.num_oplock_brks));
822 	seq_printf(m, "\nReads:  %d Bytes: %llu",
823 		   atomic_read(&tcon->stats.cifs_stats.num_reads),
824 		   (long long)(tcon->bytes_read));
825 	seq_printf(m, "\nWrites: %d Bytes: %llu",
826 		   atomic_read(&tcon->stats.cifs_stats.num_writes),
827 		   (long long)(tcon->bytes_written));
828 	seq_printf(m, "\nFlushes: %d",
829 		   atomic_read(&tcon->stats.cifs_stats.num_flushes));
830 	seq_printf(m, "\nLocks: %d HardLinks: %d Symlinks: %d",
831 		   atomic_read(&tcon->stats.cifs_stats.num_locks),
832 		   atomic_read(&tcon->stats.cifs_stats.num_hardlinks),
833 		   atomic_read(&tcon->stats.cifs_stats.num_symlinks));
834 	seq_printf(m, "\nOpens: %d Closes: %d Deletes: %d",
835 		   atomic_read(&tcon->stats.cifs_stats.num_opens),
836 		   atomic_read(&tcon->stats.cifs_stats.num_closes),
837 		   atomic_read(&tcon->stats.cifs_stats.num_deletes));
838 	seq_printf(m, "\nPosix Opens: %d Posix Mkdirs: %d",
839 		   atomic_read(&tcon->stats.cifs_stats.num_posixopens),
840 		   atomic_read(&tcon->stats.cifs_stats.num_posixmkdirs));
841 	seq_printf(m, "\nMkdirs: %d Rmdirs: %d",
842 		   atomic_read(&tcon->stats.cifs_stats.num_mkdirs),
843 		   atomic_read(&tcon->stats.cifs_stats.num_rmdirs));
844 	seq_printf(m, "\nRenames: %d T2 Renames %d",
845 		   atomic_read(&tcon->stats.cifs_stats.num_renames),
846 		   atomic_read(&tcon->stats.cifs_stats.num_t2renames));
847 	seq_printf(m, "\nFindFirst: %d FNext %d FClose %d",
848 		   atomic_read(&tcon->stats.cifs_stats.num_ffirst),
849 		   atomic_read(&tcon->stats.cifs_stats.num_fnext),
850 		   atomic_read(&tcon->stats.cifs_stats.num_fclose));
851 }
852 
853 static void
854 cifs_mkdir_setinfo(struct inode *inode, const char *full_path,
855 		   struct cifs_sb_info *cifs_sb, struct cifs_tcon *tcon,
856 		   const unsigned int xid)
857 {
858 	FILE_BASIC_INFO info;
859 	struct cifsInodeInfo *cifsInode;
860 	u32 dosattrs;
861 	int rc;
862 
863 	memset(&info, 0, sizeof(info));
864 	cifsInode = CIFS_I(inode);
865 	dosattrs = cifsInode->cifsAttrs|ATTR_READONLY;
866 	info.Attributes = cpu_to_le32(dosattrs);
867 	rc = CIFSSMBSetPathInfo(xid, tcon, full_path, &info, cifs_sb->local_nls,
868 				cifs_sb);
869 	if (rc == -EOPNOTSUPP || rc == -EINVAL)
870 		rc = SMBSetInformation(xid, tcon, full_path,
871 				       info.Attributes,
872 				       0 /* do not change write time */,
873 				       cifs_sb->local_nls, cifs_sb);
874 	if (rc == 0)
875 		cifsInode->cifsAttrs = dosattrs;
876 }
877 
878 static int cifs_open_file(const unsigned int xid, struct cifs_open_parms *oparms, __u32 *oplock,
879 			  void *buf)
880 {
881 	struct cifs_open_info_data *data = buf;
882 	FILE_ALL_INFO fi = {};
883 	int rc;
884 
885 	if (!(oparms->tcon->ses->capabilities & CAP_NT_SMBS))
886 		rc = SMBLegacyOpen(xid, oparms->tcon, oparms->path,
887 				   oparms->disposition,
888 				   oparms->desired_access,
889 				   oparms->create_options,
890 				   &oparms->fid->netfid, oplock, &fi,
891 				   oparms->cifs_sb->local_nls,
892 				   cifs_remap(oparms->cifs_sb));
893 	else
894 		rc = CIFS_open(xid, oparms, oplock, &fi);
895 
896 	if (!rc && data)
897 		move_cifs_info_to_smb2(&data->fi, &fi);
898 
899 	return rc;
900 }
901 
902 static void
903 cifs_set_fid(struct cifsFileInfo *cfile, struct cifs_fid *fid, __u32 oplock)
904 {
905 	struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
906 
907 	lockdep_assert_held(&cinode->open_file_lock);
908 
909 	cfile->fid.netfid = fid->netfid;
910 	cifs_set_oplock_level(cinode, oplock);
911 	cinode->can_cache_brlcks = CIFS_CACHE_WRITE(cinode);
912 }
913 
914 static int
915 cifs_close_file(const unsigned int xid, struct cifs_tcon *tcon,
916 		struct cifs_fid *fid)
917 {
918 	return CIFSSMBClose(xid, tcon, fid->netfid);
919 }
920 
921 static int
922 cifs_flush_file(const unsigned int xid, struct cifs_tcon *tcon,
923 		struct cifs_fid *fid)
924 {
925 	return CIFSSMBFlush(xid, tcon, fid->netfid);
926 }
927 
928 static int
929 cifs_sync_read(const unsigned int xid, struct cifs_fid *pfid,
930 	       struct cifs_io_parms *parms, unsigned int *bytes_read,
931 	       char **buf, int *buf_type)
932 {
933 	parms->netfid = pfid->netfid;
934 	return CIFSSMBRead(xid, parms, bytes_read, buf, buf_type);
935 }
936 
937 static int
938 cifs_sync_write(const unsigned int xid, struct cifs_fid *pfid,
939 		struct cifs_io_parms *parms, unsigned int *written,
940 		struct kvec *iov, unsigned long nr_segs)
941 {
942 
943 	parms->netfid = pfid->netfid;
944 	return CIFSSMBWrite2(xid, parms, written, iov, nr_segs);
945 }
946 
947 static int
948 smb_set_file_info(struct inode *inode, const char *full_path,
949 		  FILE_BASIC_INFO *buf, const unsigned int xid)
950 {
951 	int oplock = 0;
952 	int rc;
953 	__u32 netpid;
954 	struct cifs_fid fid;
955 	struct cifs_open_parms oparms;
956 	struct cifsFileInfo *open_file;
957 	FILE_BASIC_INFO new_buf;
958 	struct cifs_open_info_data query_data = {};
959 	__le64 write_time = buf->LastWriteTime;
960 	struct cifsInodeInfo *cinode = CIFS_I(inode);
961 	struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
962 	struct tcon_link *tlink = NULL;
963 	struct cifs_tcon *tcon;
964 
965 	/* if the file is already open for write, just use that fileid */
966 	open_file = find_writable_file(cinode, FIND_FSUID_ONLY);
967 
968 	if (open_file) {
969 		fid.netfid = open_file->fid.netfid;
970 		netpid = open_file->pid;
971 		tcon = tlink_tcon(open_file->tlink);
972 	} else {
973 		tlink = cifs_sb_tlink(cifs_sb);
974 		if (IS_ERR(tlink)) {
975 			rc = PTR_ERR(tlink);
976 			tlink = NULL;
977 			goto out;
978 		}
979 		tcon = tlink_tcon(tlink);
980 	}
981 
982 	/*
983 	 * Non-NT servers interprets zero time value in SMB_SET_FILE_BASIC_INFO
984 	 * over TRANS2_SET_FILE_INFORMATION as a valid time value. NT servers
985 	 * interprets zero time value as do not change existing value on server.
986 	 * API of ->set_file_info() callback expects that zero time value has
987 	 * the NT meaning - do not change. Therefore if server is non-NT and
988 	 * some time values in "buf" are zero, then fetch missing time values.
989 	 */
990 	if (!(tcon->ses->capabilities & CAP_NT_SMBS) &&
991 	    (!buf->CreationTime || !buf->LastAccessTime ||
992 	     !buf->LastWriteTime || !buf->ChangeTime)) {
993 		rc = cifs_query_path_info(xid, tcon, cifs_sb, full_path, &query_data);
994 		if (rc) {
995 			if (open_file) {
996 				cifsFileInfo_put(open_file);
997 				open_file = NULL;
998 			}
999 			goto out;
1000 		}
1001 		/*
1002 		 * Original write_time from buf->LastWriteTime is preserved
1003 		 * as SMBSetInformation() interprets zero as do not change.
1004 		 */
1005 		new_buf = *buf;
1006 		buf = &new_buf;
1007 		if (!buf->CreationTime)
1008 			buf->CreationTime = query_data.fi.CreationTime;
1009 		if (!buf->LastAccessTime)
1010 			buf->LastAccessTime = query_data.fi.LastAccessTime;
1011 		if (!buf->LastWriteTime)
1012 			buf->LastWriteTime = query_data.fi.LastWriteTime;
1013 		if (!buf->ChangeTime)
1014 			buf->ChangeTime = query_data.fi.ChangeTime;
1015 	}
1016 
1017 	if (open_file)
1018 		goto set_via_filehandle;
1019 
1020 	rc = CIFSSMBSetPathInfo(xid, tcon, full_path, buf, cifs_sb->local_nls,
1021 				cifs_sb);
1022 	if (rc == 0) {
1023 		cinode->cifsAttrs = le32_to_cpu(buf->Attributes);
1024 		goto out;
1025 	} else if (rc != -EOPNOTSUPP && rc != -EINVAL) {
1026 		goto out;
1027 	}
1028 
1029 	oparms = (struct cifs_open_parms) {
1030 		.tcon = tcon,
1031 		.cifs_sb = cifs_sb,
1032 		.desired_access = SYNCHRONIZE | FILE_WRITE_ATTRIBUTES,
1033 		.create_options = cifs_create_options(cifs_sb, 0),
1034 		.disposition = FILE_OPEN,
1035 		.path = full_path,
1036 		.fid = &fid,
1037 	};
1038 
1039 	if (S_ISDIR(inode->i_mode) && !(tcon->ses->capabilities & CAP_NT_SMBS)) {
1040 		/* Opening directory path is not possible on non-NT servers. */
1041 		rc = -EOPNOTSUPP;
1042 	} else {
1043 		/*
1044 		 * Use cifs_open_file() instead of CIFS_open() as the
1045 		 * cifs_open_file() selects the correct function which
1046 		 * works also on non-NT servers.
1047 		 */
1048 		rc = cifs_open_file(xid, &oparms, &oplock, NULL);
1049 		/*
1050 		 * Opening path for writing on non-NT servers is not
1051 		 * possible when the read-only attribute is already set.
1052 		 * Non-NT server in this case returns -EACCES. For those
1053 		 * servers the only possible way how to clear the read-only
1054 		 * bit is via SMB_COM_SETATTR command.
1055 		 */
1056 		if (rc == -EACCES &&
1057 		    (cinode->cifsAttrs & ATTR_READONLY) &&
1058 		     le32_to_cpu(buf->Attributes) != 0 && /* 0 = do not change attrs */
1059 		     !(le32_to_cpu(buf->Attributes) & ATTR_READONLY) &&
1060 		     !(tcon->ses->capabilities & CAP_NT_SMBS))
1061 			rc = -EOPNOTSUPP;
1062 	}
1063 
1064 	/* Fallback to SMB_COM_SETATTR command when absolutely needed. */
1065 	if (rc == -EOPNOTSUPP) {
1066 		cifs_dbg(FYI, "calling SetInformation since SetPathInfo for attrs/times not supported by this server\n");
1067 		rc = SMBSetInformation(xid, tcon, full_path,
1068 				       buf->Attributes != 0 ? buf->Attributes : cpu_to_le32(cinode->cifsAttrs),
1069 				       write_time,
1070 				       cifs_sb->local_nls, cifs_sb);
1071 		if (rc == 0)
1072 			cinode->cifsAttrs = le32_to_cpu(buf->Attributes);
1073 		else
1074 			rc = -EACCES;
1075 		goto out;
1076 	}
1077 
1078 	if (rc != 0) {
1079 		if (rc == -EIO)
1080 			rc = -EINVAL;
1081 		goto out;
1082 	}
1083 
1084 	netpid = current->tgid;
1085 	cifs_dbg(FYI, "calling SetFileInfo since SetPathInfo for attrs/times not supported by this server\n");
1086 
1087 set_via_filehandle:
1088 	rc = CIFSSMBSetFileInfo(xid, tcon, buf, fid.netfid, netpid);
1089 	if (!rc)
1090 		cinode->cifsAttrs = le32_to_cpu(buf->Attributes);
1091 
1092 	if (open_file == NULL)
1093 		CIFSSMBClose(xid, tcon, fid.netfid);
1094 	else
1095 		cifsFileInfo_put(open_file);
1096 
1097 	/*
1098 	* Setting the read-only bit is not honored on non-NT servers when done
1099 	 * via open-semantics. So for setting it, use SMB_COM_SETATTR command.
1100 	 * This command works only after the file is closed, so use it only when
1101 	 * operation was called without the filehandle.
1102 	 */
1103 	if (open_file == NULL &&
1104 	    !(tcon->ses->capabilities & CAP_NT_SMBS) &&
1105 	    le32_to_cpu(buf->Attributes) & ATTR_READONLY) {
1106 		SMBSetInformation(xid, tcon, full_path,
1107 				  buf->Attributes,
1108 				  0 /* do not change write time */,
1109 				  cifs_sb->local_nls, cifs_sb);
1110 	}
1111 out:
1112 	if (tlink != NULL)
1113 		cifs_put_tlink(tlink);
1114 	return rc;
1115 }
1116 
1117 static int
1118 cifs_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
1119 		   struct cifsFileInfo *cfile, __u16 compression_state)
1120 {
1121 	return CIFSSMB_set_compression(xid, tcon, cfile->fid.netfid,
1122 				       compression_state);
1123 }
1124 
1125 static int
1126 cifs_query_dir_first(const unsigned int xid, struct cifs_tcon *tcon,
1127 		     const char *path, struct cifs_sb_info *cifs_sb,
1128 		     struct cifs_fid *fid, __u16 search_flags,
1129 		     struct cifs_search_info *srch_inf)
1130 {
1131 	int rc;
1132 
1133 	rc = CIFSFindFirst(xid, tcon, path, cifs_sb,
1134 			   &fid->netfid, search_flags, srch_inf, true);
1135 	if (rc)
1136 		cifs_dbg(FYI, "find first failed=%d\n", rc);
1137 	return rc;
1138 }
1139 
1140 static int
1141 cifs_query_dir_next(const unsigned int xid, struct cifs_tcon *tcon,
1142 		    struct cifs_fid *fid, __u16 search_flags,
1143 		    struct cifs_search_info *srch_inf)
1144 {
1145 	return CIFSFindNext(xid, tcon, fid->netfid, search_flags, srch_inf);
1146 }
1147 
1148 static int
1149 cifs_close_dir(const unsigned int xid, struct cifs_tcon *tcon,
1150 	       struct cifs_fid *fid)
1151 {
1152 	return CIFSFindClose(xid, tcon, fid->netfid);
1153 }
1154 
1155 static int cifs_oplock_response(struct cifs_tcon *tcon, __u64 persistent_fid,
1156 				__u64 volatile_fid, __u16 net_fid,
1157 				struct cifsInodeInfo *cinode, unsigned int oplock)
1158 {
1159 	unsigned int sbflags = cifs_sb_flags(CIFS_SB(cinode));
1160 	__u8 op;
1161 
1162 	op = !!((oplock & CIFS_CACHE_READ_FLG) || (sbflags & CIFS_MOUNT_RO_CACHE));
1163 	return CIFSSMBLock(0, tcon, net_fid, current->tgid, 0, 0, 0, 0,
1164 			   LOCKING_ANDX_OPLOCK_RELEASE, false, op);
1165 }
1166 
1167 static int
1168 cifs_queryfs(const unsigned int xid, struct cifs_tcon *tcon,
1169 	     const char *path, struct cifs_sb_info *cifs_sb, struct kstatfs *buf)
1170 {
1171 	int rc = -EOPNOTSUPP;
1172 
1173 	buf->f_type = CIFS_SUPER_MAGIC;
1174 
1175 	/*
1176 	 * We could add a second check for a QFS Unix capability bit
1177 	 */
1178 	if ((tcon->ses->capabilities & CAP_UNIX) &&
1179 	    (CIFS_POSIX_EXTENSIONS & le64_to_cpu(tcon->fsUnixInfo.Capability)))
1180 		rc = CIFSSMBQFSPosixInfo(xid, tcon, buf);
1181 
1182 	/*
1183 	 * Only need to call the old QFSInfo if failed on newer one,
1184 	 * e.g. by OS/2.
1185 	 **/
1186 	if (rc && (tcon->ses->capabilities & CAP_NT_SMBS))
1187 		rc = CIFSSMBQFSInfo(xid, tcon, buf);
1188 
1189 	/*
1190 	 * Some old Windows servers also do not support level 103, retry with
1191 	 * older level one if old server failed the previous call or we
1192 	 * bypassed it because we detected that this was an older LANMAN sess
1193 	 */
1194 	if (rc)
1195 		rc = SMBOldQFSInfo(xid, tcon, buf);
1196 	return rc;
1197 }
1198 
1199 static int
1200 cifs_mand_lock(const unsigned int xid, struct cifsFileInfo *cfile, __u64 offset,
1201 	       __u64 length, __u32 type, int lock, int unlock, bool wait)
1202 {
1203 	return CIFSSMBLock(xid, tlink_tcon(cfile->tlink), cfile->fid.netfid,
1204 			   current->tgid, length, offset, unlock, lock,
1205 			   (__u8)type, wait, 0);
1206 }
1207 
1208 static int
1209 cifs_unix_dfs_readlink(const unsigned int xid, struct cifs_tcon *tcon,
1210 		       const unsigned char *searchName, char **symlinkinfo,
1211 		       const struct nls_table *nls_codepage)
1212 {
1213 #ifdef CONFIG_CIFS_DFS_UPCALL
1214 	int rc;
1215 	struct dfs_info3_param referral = {0};
1216 
1217 	rc = get_dfs_path(xid, tcon->ses, searchName, nls_codepage, &referral,
1218 			  0);
1219 
1220 	if (!rc) {
1221 		*symlinkinfo = kstrdup(referral.node_name, GFP_KERNEL);
1222 		free_dfs_info_param(&referral);
1223 		if (!*symlinkinfo)
1224 			rc = -ENOMEM;
1225 	}
1226 	return rc;
1227 #else /* No DFS support */
1228 	return -EREMOTE;
1229 #endif
1230 }
1231 
1232 static int cifs_query_symlink(const unsigned int xid,
1233 			      struct cifs_tcon *tcon,
1234 			      struct cifs_sb_info *cifs_sb,
1235 			      const char *full_path,
1236 			      char **target_path)
1237 {
1238 	int rc;
1239 
1240 	cifs_tcon_dbg(FYI, "%s: path=%s\n", __func__, full_path);
1241 
1242 	if (!cap_unix(tcon->ses))
1243 		return -EOPNOTSUPP;
1244 
1245 	rc = CIFSSMBUnixQuerySymLink(xid, tcon, full_path, target_path,
1246 				     cifs_sb->local_nls, cifs_remap(cifs_sb));
1247 	if (rc == -EREMOTE)
1248 		rc = cifs_unix_dfs_readlink(xid, tcon, full_path,
1249 					    target_path, cifs_sb->local_nls);
1250 	return rc;
1251 }
1252 
1253 static struct reparse_data_buffer *cifs_get_reparse_point_buffer(const struct kvec *rsp_iov,
1254 								 u32 *plen)
1255 {
1256 	TRANSACT_IOCTL_RSP *io = rsp_iov->iov_base;
1257 	*plen = le16_to_cpu(io->ByteCount);
1258 	return (struct reparse_data_buffer *)((__u8 *)&io->hdr.Protocol +
1259 					      le32_to_cpu(io->DataOffset));
1260 }
1261 
1262 static bool
1263 cifs_is_read_op(__u32 oplock)
1264 {
1265 	return oplock == OPLOCK_READ;
1266 }
1267 
1268 static unsigned int
1269 cifs_wp_retry_size(struct inode *inode)
1270 {
1271 	return CIFS_SB(inode->i_sb)->ctx->wsize;
1272 }
1273 
1274 static bool
1275 cifs_dir_needs_close(struct cifsFileInfo *cfile)
1276 {
1277 	return !cfile->srch_inf.endOfSearch && !cfile->invalidHandle;
1278 }
1279 
1280 static bool
1281 cifs_can_echo(struct TCP_Server_Info *server)
1282 {
1283 	if (server->tcpStatus == CifsGood)
1284 		return true;
1285 
1286 	return false;
1287 }
1288 
1289 static int
1290 cifs_make_node(unsigned int xid, struct inode *inode,
1291 	       struct dentry *dentry, struct cifs_tcon *tcon,
1292 	       const char *full_path, umode_t mode, dev_t dev)
1293 {
1294 	struct cifs_sb_info *cifs_sb = CIFS_SB(inode);
1295 	unsigned int sbflags = cifs_sb_flags(cifs_sb);
1296 	struct inode *newinode = NULL;
1297 	int rc;
1298 
1299 	if (tcon->unix_ext) {
1300 		/*
1301 		 * SMB1 Unix Extensions: requires server support but
1302 		 * works with all special files
1303 		 */
1304 		struct cifs_unix_set_info_args args = {
1305 			.mode	= mode & ~current_umask(),
1306 			.ctime	= NO_CHANGE_64,
1307 			.atime	= NO_CHANGE_64,
1308 			.mtime	= NO_CHANGE_64,
1309 			.device	= dev,
1310 		};
1311 		if (sbflags & CIFS_MOUNT_SET_UID) {
1312 			args.uid = current_fsuid();
1313 			args.gid = current_fsgid();
1314 		} else {
1315 			args.uid = INVALID_UID; /* no change */
1316 			args.gid = INVALID_GID; /* no change */
1317 		}
1318 		rc = CIFSSMBUnixSetPathInfo(xid, tcon, full_path, &args,
1319 					    cifs_sb->local_nls,
1320 					    cifs_remap(cifs_sb));
1321 		if (rc)
1322 			return rc;
1323 
1324 		rc = cifs_get_inode_info_unix(&newinode, full_path,
1325 					      inode->i_sb, xid);
1326 
1327 		if (rc == 0)
1328 			d_instantiate(dentry, newinode);
1329 		return rc;
1330 	} else if (sbflags & CIFS_MOUNT_UNX_EMUL) {
1331 		/*
1332 		 * Check if mounted with mount parm 'sfu' mount parm.
1333 		 * SFU emulation should work with all servers
1334 		 * and was used by default in earlier versions of Windows.
1335 		 */
1336 		return cifs_sfu_make_node(xid, inode, dentry, tcon,
1337 					  full_path, mode, dev);
1338 	} else if (CIFS_REPARSE_SUPPORT(tcon)) {
1339 		/*
1340 		 * mknod via reparse points requires server support for
1341 		 * storing reparse points, which is available since
1342 		 * Windows 2000, but was not widely used until release
1343 		 * of Windows Server 2012 by the Windows NFS server.
1344 		 */
1345 		return mknod_reparse(xid, inode, dentry, tcon,
1346 				     full_path, mode, dev);
1347 	} else {
1348 		return -EOPNOTSUPP;
1349 	}
1350 }
1351 
1352 static bool
1353 cifs_is_network_name_deleted(char *buf, struct TCP_Server_Info *server)
1354 {
1355 	struct smb_hdr *shdr = (struct smb_hdr *)buf;
1356 	struct TCP_Server_Info *pserver;
1357 	struct cifs_ses *ses;
1358 	struct cifs_tcon *tcon;
1359 
1360 	if (shdr->Flags2 & SMBFLG2_ERR_STATUS) {
1361 		if (shdr->Status.CifsError != cpu_to_le32(NT_STATUS_NETWORK_NAME_DELETED))
1362 			return false;
1363 	} else {
1364 		if (shdr->Status.DosError.ErrorClass != ERRSRV ||
1365 		    shdr->Status.DosError.Error != cpu_to_le16(ERRinvtid))
1366 			return false;
1367 	}
1368 
1369 	/* If server is a channel, select the primary channel */
1370 	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
1371 
1372 	spin_lock(&cifs_tcp_ses_lock);
1373 	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
1374 		if (cifs_ses_exiting(ses))
1375 			continue;
1376 		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
1377 			if (tcon->tid == shdr->Tid) {
1378 				spin_lock(&tcon->tc_lock);
1379 				tcon->need_reconnect = true;
1380 				spin_unlock(&tcon->tc_lock);
1381 				spin_unlock(&cifs_tcp_ses_lock);
1382 				pr_warn_once("Server share %s deleted.\n",
1383 					     tcon->tree_name);
1384 				return true;
1385 			}
1386 		}
1387 	}
1388 	spin_unlock(&cifs_tcp_ses_lock);
1389 
1390 	return false;
1391 }
1392 
1393 struct smb_version_operations smb1_operations = {
1394 	.send_cancel = cifs_send_cancel,
1395 	.compare_fids = cifs_compare_fids,
1396 	.setup_request = cifs_setup_request,
1397 	.setup_async_request = cifs_setup_async_request,
1398 	.check_receive = cifs_check_receive,
1399 	.add_credits = cifs_add_credits,
1400 	.set_credits = cifs_set_credits,
1401 	.get_credits_field = cifs_get_credits_field,
1402 	.get_credits = cifs_get_credits,
1403 	.wait_mtu_credits = cifs_wait_mtu_credits,
1404 	.get_next_mid = cifs_get_next_mid,
1405 	.read_data_offset = cifs_read_data_offset,
1406 	.read_data_length = cifs_read_data_length,
1407 	.map_error = map_smb_to_linux_error,
1408 	.find_mid = cifs_find_mid,
1409 	.check_message = checkSMB,
1410 	.dump_detail = cifs_dump_detail,
1411 	.clear_stats = cifs_clear_stats,
1412 	.print_stats = cifs_print_stats,
1413 	.is_oplock_break = is_valid_oplock_break,
1414 	.downgrade_oplock = cifs_downgrade_oplock,
1415 	.check_trans2 = cifs_check_trans2,
1416 	.need_neg = cifs_need_neg,
1417 	.negotiate = cifs_negotiate,
1418 	.negotiate_wsize = smb1_negotiate_wsize,
1419 	.negotiate_rsize = smb1_negotiate_rsize,
1420 	.sess_setup = CIFS_SessSetup,
1421 	.logoff = CIFSSMBLogoff,
1422 	.tree_connect = CIFSTCon,
1423 	.tree_disconnect = CIFSSMBTDis,
1424 	.get_dfs_refer = CIFSGetDFSRefer,
1425 	.qfs_tcon = cifs_qfs_tcon,
1426 	.is_path_accessible = cifs_is_path_accessible,
1427 	.can_echo = cifs_can_echo,
1428 	.query_path_info = cifs_query_path_info,
1429 	.query_reparse_point = cifs_query_reparse_point,
1430 	.query_file_info = cifs_query_file_info,
1431 	.get_srv_inum = cifs_get_srv_inum,
1432 	.set_path_size = CIFSSMBSetEOF,
1433 	.set_file_size = CIFSSMBSetFileSize,
1434 	.set_file_info = smb_set_file_info,
1435 	.set_compression = cifs_set_compression,
1436 	.echo = CIFSSMBEcho,
1437 	.mkdir = CIFSSMBMkDir,
1438 	.mkdir_setinfo = cifs_mkdir_setinfo,
1439 	.rmdir = CIFSSMBRmDir,
1440 	.unlink = CIFSSMBDelFile,
1441 	.rename_pending_delete = cifs_rename_pending_delete,
1442 	.rename = CIFSSMBRename,
1443 	.create_hardlink = CIFSCreateHardLink,
1444 	.query_symlink = cifs_query_symlink,
1445 	.get_reparse_point_buffer = cifs_get_reparse_point_buffer,
1446 	.create_reparse_inode = cifs_create_reparse_inode,
1447 	.open = cifs_open_file,
1448 	.set_fid = cifs_set_fid,
1449 	.close = cifs_close_file,
1450 	.flush = cifs_flush_file,
1451 	.async_readv = cifs_async_readv,
1452 	.async_writev = cifs_async_writev,
1453 	.sync_read = cifs_sync_read,
1454 	.sync_write = cifs_sync_write,
1455 	.query_dir_first = cifs_query_dir_first,
1456 	.query_dir_next = cifs_query_dir_next,
1457 	.close_dir = cifs_close_dir,
1458 	.calc_smb_size = smbCalcSize,
1459 	.oplock_response = cifs_oplock_response,
1460 	.queryfs = cifs_queryfs,
1461 	.mand_lock = cifs_mand_lock,
1462 	.mand_unlock_range = cifs_unlock_range,
1463 	.push_mand_locks = cifs_push_mandatory_locks,
1464 	.query_mf_symlink = cifs_query_mf_symlink,
1465 	.create_mf_symlink = cifs_create_mf_symlink,
1466 	.is_read_op = cifs_is_read_op,
1467 	.wp_retry_size = cifs_wp_retry_size,
1468 	.dir_needs_close = cifs_dir_needs_close,
1469 	.select_sectype = cifs_select_sectype,
1470 #ifdef CONFIG_CIFS_XATTR
1471 	.query_all_EAs = CIFSSMBQAllEAs,
1472 	.set_EA = CIFSSMBSetEA,
1473 #endif /* CIFS_XATTR */
1474 	.get_acl = get_cifs_acl,
1475 	.get_acl_by_fid = get_cifs_acl_by_fid,
1476 	.set_acl = set_cifs_acl,
1477 	.make_node = cifs_make_node,
1478 	.is_network_name_deleted = cifs_is_network_name_deleted,
1479 };
1480 
1481 struct smb_version_values smb1_values = {
1482 	.version_string = SMB1_VERSION_STRING,
1483 	.protocol_id = SMB10_PROT_ID,
1484 	.large_lock_type = LOCKING_ANDX_LARGE_FILES,
1485 	.exclusive_lock_type = 0,
1486 	.shared_lock_type = LOCKING_ANDX_SHARED_LOCK,
1487 	.unlock_lock_type = 0,
1488 	.header_size = sizeof(struct smb_hdr),
1489 	.max_header_size = MAX_CIFS_HDR_SIZE,
1490 	.read_rsp_size = sizeof(READ_RSP),
1491 	.lock_cmd = cpu_to_le16(SMB_COM_LOCKING_ANDX),
1492 	.cap_unix = CAP_UNIX,
1493 	.cap_nt_find = CAP_NT_SMBS | CAP_NT_FIND,
1494 	.cap_large_files = CAP_LARGE_FILES,
1495 	.cap_unicode = CAP_UNICODE,
1496 	.signing_enabled = SECMODE_SIGN_ENABLED,
1497 	.signing_required = SECMODE_SIGN_REQUIRED,
1498 };
1499